"""Immutable versioned Stage B candidate export; no model loading or training.""" from __future__ import annotations import argparse import hashlib import json import platform import re import sys from collections import defaultdict from importlib.metadata import version from pathlib import Path from .expanded_generator import VERSION, generate_expanded, inventory from .family_library import MAX_PROFILES from .generator import SEED, CLASS_TARGETS from .reporting import build_reports, read_jsonl, write_jsonl, write_manifest, write_reports, write_review_queue from .validation import check_schema_definitions ROOT = Path(__file__).resolve().parents[2] OUTPUT_ROOT = ROOT / 'data' / 'candidates' def source_manifest(): paths = [*sorted((ROOT/'src'/'jitai_training').glob('*.py')), *sorted((ROOT/'schemas').glob('*.json')), ROOT/'requirements-stage-b.txt'] entries = {p.relative_to(ROOT).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in paths} digest = hashlib.sha256(json.dumps(entries, sort_keys=True).encode()).hexdigest() return dict(source_digest=digest, files=entries, python=platform.python_version(), packages={name: version(name) for name in ('jsonschema', 'pydantic', 'tzdata')}) def sample_gate(sample_dir, seed, digest): try: report = json.loads((sample_dir/'reports'/'stage_b_report.json').read_text(encoding='utf-8')) manifest = json.loads((sample_dir/'manifest.json').read_text(encoding='utf-8')) if report.get('source_digest') != digest or report.get('seed') != seed or report.get('automated_status') != 'passed': return False, 'sample status, seed or source/schema digest does not match' required = {'train.jsonl', 'validation.jsonl', 'test.jsonl', 'review_queue.csv', 'family_inventory.json', 'source_manifest.json', 'reports/stage_b_report.json', 'reports/stage_b_report.md', 'DATASET_CARD.md'} if required != {entry['path'] for entry in manifest['artifacts']}: return False, 'sample artifact inventory does not match the export contract' for entry in manifest['artifacts']: path = sample_dir/entry['path'] if hashlib.sha256(path.read_bytes()).hexdigest() != entry['sha256']: return False, 'sample artifact checksum mismatch: ' + entry['path'] rows = [] for split in ('train', 'validation', 'test'): partition = read_jsonl(sample_dir/f'{split}.jsonl') if any(row['split'] != split for row in partition): return False, 'sample split file mismatch' rows.extend(partition) if rows != [r for split in ('train', 'validation', 'test') for r in generate_expanded(seed=seed) if r['split'] == split]: return False, 'sample rows do not reproduce from this source and seed' actual = build_reports(rows) if actual['automated_status'] != 'passed': return False, 'sample revalidation failed' return True, 'verified source, seed, hashes, deterministic rows and all sample gates' except (OSError, ValueError, KeyError, TypeError) as error: return False, str(error) def generate(mode, seed=SEED, run_version='v3'): if not re.fullmatch(r'v[0-9]+(?:-[a-z0-9]+)*', run_version): raise ValueError('run version must look like v3 or v3-rerun1') output_dir = OUTPUT_ROOT/('sample-' + run_version if mode == 'sample' else run_version) # Refuse an existing directory before any writes or expensive work. if output_dir.exists(): print('FAIL: preserving existing dataset directory: ' + str(output_dir)) return 5 check_schema_definitions() sources = source_manifest() gate_evidence = None if mode == 'full': passed, gate_evidence = sample_gate(OUTPUT_ROOT/('sample-' + run_version), seed, sources['source_digest']) if not passed: print('FAIL: full generation requires a verified passing sample: ' + gate_evidence) return 4 records = generate_expanded(seed=seed, profiles=1 if mode == 'sample' else MAX_PROFILES) reports = build_reports(records) reports.update(source_digest=sources['source_digest'], seed=seed, generator_version=VERSION, sample_gate_evidence=gate_evidence, planning_target=15000, planning_class_targets=CLASS_TARGETS, capacity_status='reduced_to_authored_capacity', target_shortfall=15000-len(records), capacity_explanation='76 authored scenario definitions in 59 related-family groups; at most two context profiles and one meaningful counterfactual per profile. Two empty/missing-store cases permit one profile only. No repeated title-only scaling to 15,000.') output_dir.mkdir(parents=True, exist_ok=False) partitions = defaultdict(list) for record in records: partitions[record['split']].append(record) artifacts = [] for split in ('train', 'validation', 'test'): path = output_dir/f'{split}.jsonl' write_jsonl(path, partitions[split]); artifacts.append(path) queue = output_dir/'review_queue.csv' write_review_queue(queue, records); artifacts.append(queue) for filename, data in [('family_inventory.json', inventory(seed)), ('source_manifest.json', sources)]: path = output_dir/filename path.write_text(json.dumps(data, ensure_ascii=False, indent=2)+'\n', encoding='utf-8'); artifacts.append(path) write_reports(output_dir, records, reports) artifacts += [output_dir/'reports'/'stage_b_report.json', output_dir/'reports'/'stage_b_report.md'] card = output_dir/'DATASET_CARD.md' card.write_text( f'# Authored synthetic JITAI candidates {run_version}\n\n' f'Candidate count: {len(records)}. Automated status: {reports["automated_status"]}. Human-review status: pending; zero reviewed or accepted.\n\n' 'This is a bounded authored-library export, not the planned 15,000-example dataset. ' 'The current library supports 300 candidates at its conservative repetition cap. ' 'There are 76 scenario definitions and 59 independent split groups; closely related lifecycle and quiet-hour counterfactual cases share groups. ' 'Each primary class has 11 or 12 groups, with two groups per primary class in each evaluation split. ' 'Counterfactuals and context profiles never count as independent families.\n\n' 'Two context profiles test current user/safety requests with quiet hours and cooldowns active versus inactive, ' 'or vary proactive task timing. Empty/missing task-store scenarios use one profile because changing absent titles cannot add diversity. ' 'Related counterfactuals intentionally repeat utterances. See the report for related similarities, class counts, coverage and actual split sizes.\n\n' 'All text is newly authored synthetic content. No local language model was loaded and no external dataset examples were incorporated. ' 'Safety cases describe immediate danger without procedural harm details or guessed contact numbers. ' 'The assistant only proposes actions; the host application owns execution and safety controls.\n\n' 'Automated evidence rules cover this finite authored library, not unrestricted language understanding. ' 'Exact lexical and normalized structural screens cannot prove semantic independence. ' 'The family distinctions, emotional/safety judgments, privacy cases, messages and tool arguments require actual human review. ' 'These small evaluation sets support preparation checks, not reliable model evaluation estimates. ' 'Do not train from these candidates or claim Stage B acceptance. No Stage C or training work has run.\n\n' 'Reproduce with the source hashes and package versions in source_manifest.json; checksum every exported artifact using manifest.json. ' 'The test families are fixed by the recorded seed and are not tuning data. ' 'Use review_queue.csv and docs/stage-b-review-guide.md for actual review.\n', encoding='utf-8') artifacts.append(card) write_manifest(output_dir, records, artifacts, seed) print(json.dumps(dict(output_dir=str(output_dir), candidate_count=len(records), automated_status=reports['automated_status'], automated_checks=reports['automated_checks'], split_counts=reports['split_counts'], class_distribution=reports['class_distribution'], human_review=reports['human_review'], planning_target=15000, bounded_capacity=reports['diversity']['authored_capacity_examples']), indent=2)) return 0 if reports['automated_status'] == 'passed' else 4 def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('mode', choices=['sample', 'full']) parser.add_argument('--seed', type=int, default=SEED) parser.add_argument('--run-version', default='v3', help='New immutable export version; existing directories are never overwritten') args = parser.parse_args() sys.exit(generate(args.mode, args.seed, args.run_version)) if __name__ == '__main__': main()