"""Compact final receipts; preserve pilots, failed attempts and frozen queue versions."""
import collections,hashlib,json,time
from pathlib import Path
P=Path(__file__).resolve().parent;L=P.parent;B=L/'full-corpus'
def jl(p):return [json.loads(l) for l in p.open()]
def dump(p,x):p.write_text(json.dumps(x,indent=2,sort_keys=True)+'\n')
sha=lambda b:hashlib.sha256(b).hexdigest()
r=json.loads((P/'RESULTS.json').read_text());q=json.loads((P/'QUEUE-READY.json').read_text());fit=json.loads((P/'FIT-READY.json').read_text());evaluation=json.loads((P/'EVALUATION-READY.json').read_text());migration=json.loads((B/'span-resolved-v1/MIGRATION-RECEIPT.json').read_text());integrity=json.loads((P/'INTEGRITY-RECEIPT.json').read_text());assert integrity['status']=='PASS';assert q['version']=='learned-v2-fafb465ea706b37c'
dump(P/'paired-summary.json',dict(schema=1,units='Exact lineage/background scope units; canonical pairs/families separate coverage counts; never independent pooled trials',records=r['records']))
dump(P/'coverage.json',dict(schema=1,**r['coverage'],feature_coverage=r['feature_coverage'],all_rows='all-row-coverage.jsonl',scope_profiles='coverage-rows.jsonl',source_policy_exceptions=str(B/'span-resolved-v1/remaining-source-exceptions.jsonl'),declarations_separate=4,excluded_overlay='reopened-CF-C02.json',backgrounds=79))
compact=[{k:x[k] for k in ['profile','label','arm','reference','intersection','matched','reference_funded','arm_funded','wins','losses','descriptive_repository_component_net_fraction_p025_p975']} for x in r['records'] if x['intersection']=='arm-reference' and x['arm'].startswith(('logistic','hgb'))]
dump(P/'PAYOFF-RECEIPT.json',dict(schema=1,status='BOUNDED RUN COMPLETE; no demonstrated new reportable-family gain',reason='Default logistic matches fixed matched-cap RRF on source-positive funding; boosting loses one. Balanced utility learners lose more useful positives than they gain. Protection preserves baseline but adds negative exposures. No provider/source acceptance was inferred from model probabilities.',comparison=compact,denominators='579 accepted function records,561 canonical pair IDs,206 families; positives200 records/185 pairs/103 families. All mapped, but unknown source/prompt campaigns remain unknown.',novel_queue=q,source_acceptance='Pending independent Root review; newly confirmed emitted/reportable useful families=0 in this worker evidence, unjudged discovery is unknown',profiles_pooled=False))
runtime=dict(schema=1,fixed_replay=json.loads((B/'span-resolved-v1/runtime-total.json').read_text()),learned_fit=fit,learned_fit_measurement_scope='Final resume33.15s/45.38 CPU excludes first2 completed folds and failed all-NaN attempt, retained in initial log. Initial2 completed fold fit portions2.214s wall; total first-attempt CPU/wall not captured. Do not treat final resume as total physical training cost.',learned_budget_replay=evaluation,feature_preparation=dict(initial_completed_backgrounds=len(jl(P/'prepare.log')),resume_completed_backgrounds=len(jl(P/'prepare-resume.log')),initial_wall_seconds=None,resume_wall_seconds=json.loads((P/'FEATURE-COVERAGE.json').read_text())['elapsed_seconds'],cpu_seconds=None,execution_note='Initial exec remained active across compaction; an unnecessary idempotent resume overlapped feature preparation for remaining55 backgrounds. Both completed; no heavy representation refits. Final1438 feature views and5752 cached signal values independently checked before handoff. Exclusive preparation lock now prevents recurrence. Per-process numerical threads were2; total overlapping thread use was not measured and is not claimed <=2.',all_feature_values_frozen_before_fit=True),queue_v1_wall_seconds=json.loads((P/'queues/learned-v1-901827b10778c8f9/FROZEN.json').read_text())['wall_seconds'],queue_v2_wall_seconds=q['wall_seconds'],feature_and_queue_cpu_measurement='Not captured; unknown, not zero. Fit/replay CPU measured above. Original partial/failed attempts retained in logs, not charged as fresh models or providers.',external_vector_caches_reused=len(list(B.glob('bg-*/reused-vector-receipt.json'))),representation_refits_for_learned=0,coordinate_migration_original77_vector_refits=0,additional2_background_initial_fits=2,worker_provider_calls=0,worker_physical_usd=0,root_prior_intake_usd=.01674792)
dump(P/'RUNTIME-RECEIPT.json',runtime)
dump(P/'EXECUTION-CORRECTIONS.json',dict(schema=1,algorithm_and_registered_arms_unchanged=True,all_missing_hgb='Installed sklearn1.9.1 binning errors on an all-NaN column. Applied preregistered all-missing-train impute0, retained native NaNs in other columns; completed fold caches reused, failed log preserved.',shared_test_routing='Copied unchanged shared tests initially lacked relative archive and ingestion utility; explicit read-only archive route and byte-identical utility snapshot corrected harness; final30 tests pass. Earlier failures preserved.',queue_v1='One control shared a family/source component. Preserved original frozen queue, reselected controls with explicit component guard; all8 novel Candidate payload hashes unchanged, v2 distinct IDs and frozen hash; independent receipt0 overlaps.',feature_resume=runtime['feature_preparation']['execution_note'],old_complementarity='249 original positive scope units were repeated background views, not independent pairs. Original audit retained. New receipt reports matched denominators and treats supported known non-retrieval as definite unfunded while selected source-incomplete funding remains unknown. No missing judge answers became negatives.'))
(L/'CURRENT-LEARNED-QUEUE.json').write_bytes((P/'QUEUE-READY.json').read_bytes())
old=L/'HANDOFF.json';previous=L/'HANDOFF-pre-completion.json'
if old.exists() and not previous.exists():previous.write_bytes(old.read_bytes())
handoff=dict(schema=2,worker='experiment-signal-ensemble / GPT-6.1-Sol high',base_commit='15567ee22a662208e8e6ad66b2439c10c08584cf',worktree=str(L.parent),status='FIXED79/79 COMPLETE AND FROZEN; REGISTERED LEARNED15-FOLD RUN COMPLETE; NOVEL V2 QUEUE FROZEN AWAITING CENTRAL ALLOCATION/REVIEW',main_result='No demonstrated reportable-family payoff from learned combination. Default logistic adds no positive funding over matched-cap RRF; balanced logistic2wins/3losses, HGB1win/2losses versus matched-cap RRF. Protection prevents baseline losses but adds negative exposures. Seen DEVELOPMENT/REGRESSION only.',records=617,exact_backgrounds=79,learned_eligible_accepted_function_records=579,learned_positive_inventory={'lineage_records':200,'canonical_pairs':185,'families':103},declarations_separate=4,reopened_overlay='learned-ensemble-v1/reopened-CF-C02.json',complementarity='learned-ensemble-v1/COMPLEMENTARITY-RECEIPT.json',fixed_frozen='full-corpus/FIXED-COMPLETION-FROZEN.json',learned='learned-ensemble-v1/RESULTS.json',concise_payoff='learned-ensemble-v1/PAYOFF-RECEIPT.json',all_row_coverage='learned-ensemble-v1/all-row-coverage.jsonl',oof='learned-ensemble-v1/oof-predictions.jsonl',per_family='learned-ensemble-v1/per-family-outcomes.jsonl',paired_changes='learned-ensemble-v1/paired-changes.jsonl',protocol_sha256=fit['protocol_sha256'],integrity='learned-ensemble-v1/INTEGRITY-RECEIPT.json',migration='full-corpus/span-resolved-v1/MIGRATION-RECEIPT.json',migration_denominators='full-corpus/MIGRATION-DENOMINATOR-ADDENDUM.json',source_exceptions={'native_endpoint_occurrences_resolved':446,'native_unique_background_function_identities':382,'missing_commit_occurrences':670,'missing_source_occurrences':504,'original_before_native_unresolved_total':'not serialized; unknown. Matched coordinate audit1278 missing/invalid=>104 resolved;338 supplied-valid=>338 resolved; remaining1174 unresolved. Not111 unique gold pairs.'},provider_intake='intake-seven-frozen/SUMMARY.json',provider_observations={'root_selected_novel':2,'root_control':1,'novel_policy_emitted':0,'control_policy_emitted':0,'unanswered_original_queue_cases':13,'actual_root_usd':.01674792,'source_acceptance':'pending; no gold relabel'},root_action={'queue':q['queue'],'sha256':q['sha256'],'novel':8,'independent_controls':4,'requested_normal_estimated_usd':q['requested_normal_estimated_usd'],'allocation':'Root must allocate central discovery budget and relay v2 to judge-operations; no execution authorization inferred','do_not_execute_old_version':'learned-v1-901827b10778c8f9','canonical_request_cache_owner':'judge-operations','source_acceptance':'independent source reviewer/Root only'},shared_contracts={'import':'lab-contracts/IMPORT-RECEIPT.json','tests_passed':30,'new_queue_typed_boundaries':12},runtime='learned-ensemble-v1/RUNTIME-RECEIPT.json',corrections='learned-ensemble-v1/EXECUTION-CORRECTIONS.json',commands='commands.sh',worker_provider_calls=0,credentials_read=False,production_CI_config_changes=False,publication=False,additional_agents=0,firecrawl_curator='untouched',created_utc=time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()))
dump(L/'HANDOFF.json',handoff)
text='''The fixed comparison is complete for all79 exact backgrounds in the shared617 snapshot. The learned screen is complete for15 held-out repositories, with default and balanced profiles kept separate. All579 eligible accepted function records map;4 declarations and reopenedCF-C02 remain separate. Positive inventory means200 lineage records,185 canonical pairs and103 families. Repeated background views are scope units, never extra independent positives.

Learning has not demonstrated a payoff over the matched-cap fixed fusion. Against that control, default logistic has0 positive funding wins/0 losses over130 matched scope units (111 canonical pairs,87 families); HGB0/1 over126 (109 pairs,86 families). Balanced logistic has2/3 over97 (90 pairs,75 families); HGB1/2 over98 matched control-intersection units. These descriptive development results do not establish a newly reportable family. Protection retains the full baseline funded set where source-complete, but adds negative exposures. Exposure is not an emitted false report.

The original complementarity audit and all pilot/partial/failed results are preserved. COMPLEMENTARITY-RECEIPT.json separates units and matched funding denominators. A supported non-retrieved target is definitely unfunded even where the old raw funding field was null; selected source-incomplete campaigns remain unknown. This corrects the earlier apparent zero funding-win count without inventing judge answers or tuning retrieval. Frozen RRF’s broad loss cases include defaultLL-S074 and balancedCF-LL-C10/LL-S010, all budget displacement. Learned balanced losses include the$0.03209 T3 server-update-state case. Exact family/scope/first-loss cases are in paired-changes.jsonl.

The shared native resolver is adopted with real structure/context. Across1620 endpoint/background occurrences,446 resolve natively (382 unique background/function identities);670 lack the pinned commit and504 lack source.1606 cached directional score/rank comparisons are unchanged. The matched original coordinate audit has104 missing-span recoveries, not104 unique pairs; the old native unresolved total was not serialized and stays unknown.32 frozen original-queue endpoint occurrences remain32 native with0 changes. Actual adapter19, shared helper21, and shared boundary30 tests pass.

Only3 original queue cases have root provider observations:2 novel and1 control, all below the frozen emission threshold, yielding0 emissions.13 remain unanswered; independent source acceptance is pending. The worker called no providers and changed no labels.

Current judging handoff is learned-v2-fafb465ea706b37c:8 novel funded disagreements plus4 controls with0 source-component overlap. All8 novel payloads are unchanged from preserved v1; v1’s control-family overlap is corrected in v2, which has distinct IDs and a frozen hash. Root must allocate central budget (normal estimate$0.0797371) and relay to judge-operations. No providers are authorized or run by this worker. All rejected/reserved leads remain in novel-ranked-inventory.jsonl. Shared typed Candidate/source/span/funding boundaries validated all12 cases.

Runtime: final learned fitting resume33.15s wall/45.38s CPU, plus2 completed cached folds and failed-attempt overhead not fully captured; replay6.49s wall/6.49s CPU; no new heavy representation fits. Fixed source replay1005.26s wall-sum/801.37s CPU-sum; all79 vectors warm in migration. Feature preparation had an unnecessary overlapping resume; both completed and5752 cached feature values were independently verified. Its CPU and aggregate overlapping thread use were not measured; no <=2 aggregate claim is made for that incident. Per-process numerical threads were2, and a preparation lock prevents recurrence. Execution corrections, original logs and exact commands are preserved.
'''
(P/'REPORT.md').write_text(text)
print(json.dumps(dict(status=handoff['status'],handoff=str(L/'HANDOFF.json'),queue=q['version'],provider_calls=0),indent=2))
