Cai
2026-08-16 2992aee3f9bb2eaa5dd4da28a598be3d67ea0ec0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {pathToFileURL} from 'node:url';
import * as prior from './detail_strengthening_p0_primary_source_discovery_runtime_repair001_20260730.mjs';
import {parseAuthorityCsv,serializeCsv,serializeManifestDataRows,validateAppendStableManifest} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
export const ROOT=process.cwd();
export const CASE_ID=prior.CASE_ID;
export const BASE=prior.BASE;
export const AUDIT_REPORT=prior.AUDIT_REPORT;
export const MANIFEST=prior.MANIFEST;
export const ANOMALY_AUTHORITY=prior.ANOMALY_AUTHORITY;
export const ORIGINAL_TRIAGE_RUN=prior.ORIGINAL_TRIAGE_RUN;
export const DESIGN_ID='DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-001';
export const DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-DESIGN-001';
export const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-DESIGN-001';
export const EXEC_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-001';
export const EXEC_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-001';
export const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-DESIGN-REREVIEW-001';
export const SOURCE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-GAP-CLOSURE-VERIFICATION-ORACLE-VALIDATION-REPAIR001-EXEC-OUTPUT-001';
export const EXEC_TOKEN='EXECUTE_DETAIL_STRENGTHENING_P0_OPEN_GAP_EVIDENCE_ACQUISITION_001';
export const SCRIPT='dev/ana-dev/detail_strengthening_p0_open_gap_evidence_acquisition_runtime_20260731.mjs';
 
export const TARGET_AUTHORITY=prior.TARGET_AUTHORITY;
export const PRIOR_GAP_AUTHORITY=prior.GAP_AUTHORITY;
export const NEXT_PLAN=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_next_evidence_plan_20260731.csv`;
export const DECISION=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_decision_20260731.csv`;
export const MAP=`${BASE}/evidence/case_evidence_map.csv`;
export const GAP_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_gap_authority_20260731.csv`;
export const QUERY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_query_authority_20260731.csv`;
export const SOURCE_POLICY=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_policy_20260731.csv`;
export const METHOD_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_method_authority_20260731.csv`;
export const FORMAL_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_formal_design_entry_authority_20260731.csv`;
export const CONTRACT=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_runtime_contract_20260731.csv`;
export const SCHEMA=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_schema_20260731.csv`;
export const EXEC_SET=`${BASE}/manifest/detail_strengthening_p0_open_gap_evidence_acquisition_execution_artifact_set_20260731.csv`;
export const EXEC_BASELINE=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_execution_baseline_20260731.csv`;
export const METHOD_PREFLIGHT=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_method_preflight_20260731.csv`;
export const RAW_ARCHIVE=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_raw_archive_20260731.jsonl`;
export const QUERY_LEDGER=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_query_execution_ledger_20260731.csv`;
export const SUPPLEMENT_LEDGER=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_supplement_ledger_20260731.csv`;
export const PROVENANCE_LEDGER=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_provenance_20260731.csv`;
export const CANDIDATE_REGISTER=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_candidate_register_20260731.csv`;
export const OCCURRENCE_DISPOSITION=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_occurrence_disposition_20260731.csv`;
export const GAP_SUMMARY=`${BASE}/outputs/数据表/robot_detail_p0_open_gap_evidence_acquisition_summary_v01_20260731.csv`;
export const APPLICATION=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_application_20260731.csv`;
export const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_open_gap_evidence_acquisition_execution_20260731.md`;
export const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_open_gap_evidence_acquisition_execution_validation_20260731.csv`;
export const PROTECTED_INVENTORY=`${BASE}/evidence/final_gate_output_inventory_rebuild_repair001_20260728.csv`;
 
export const QUERY_COLUMNS=prior.QUERY_COLUMNS;
export const POLICY_COLUMNS=prior.POLICY_COLUMNS;
export const METHOD_COLUMNS=prior.METHOD_COLUMNS;
export const FORMAL_ENTRY_COLUMNS=prior.FORMAL_ENTRY_COLUMNS;
export const CONTRACT_COLUMNS=prior.CONTRACT_COLUMNS;
export const SCHEMA_COLUMNS=prior.SCHEMA_COLUMNS;
export const EXEC_SET_COLUMNS=prior.EXEC_SET_COLUMNS;
export const BASELINE_COLUMNS=prior.BASELINE_COLUMNS;
export const METHOD_PREFLIGHT_COLUMNS=prior.METHOD_PREFLIGHT_COLUMNS;
export const QUERY_LEDGER_COLUMNS=prior.QUERY_LEDGER_COLUMNS;
export const SUPPLEMENT_COLUMNS=prior.SUPPLEMENT_COLUMNS;
export const PROVENANCE_COLUMNS=prior.PROVENANCE_COLUMNS;
export const CANDIDATE_COLUMNS=prior.CANDIDATE_COLUMNS;
export const DISPOSITION_COLUMNS=prior.DISPOSITION_COLUMNS;
export const SUMMARY_COLUMNS=prior.SUMMARY_COLUMNS;
export const APPLICATION_COLUMNS=prior.APPLICATION_COLUMNS;
export const VALIDATION_COLUMNS=prior.VALIDATION_COLUMNS;
export const RAW_FIELDS=prior.RAW_FIELDS;
export const GAP_COLUMNS=['gap_id','conceptual_gap_key','occurrence_count','source_occurrence_keys','object_ids','source_classes_required','query_ids','candidate_cap','gap_state_before','gap_state_after_discovery','claim_strength_ceiling','formal_pool_effect','evidence_strength_effect'];
 
export const GENERATED=[EXEC_BASELINE,METHOD_PREFLIGHT,RAW_ARCHIVE,QUERY_LEDGER,SUPPLEMENT_LEDGER,PROVENANCE_LEDGER,CANDIDATE_REGISTER,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
const DISCOVERY_STAGE=[RAW_ARCHIVE,QUERY_LEDGER,SUPPLEMENT_LEDGER,PROVENANCE_LEDGER,CANDIDATE_REGISTER];
const DERIVED_STAGE=[OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
const FROZEN_INPUTS=[SCRIPT,TARGET_AUTHORITY,GAP_AUTHORITY,NEXT_PLAN,DECISION,MAP,QUERY_AUTHORITY,SOURCE_POLICY,METHOD_AUTHORITY,FORMAL_ENTRY_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,ANOMALY_AUTHORITY];
const abs=value=>path.join(ROOT,...value.split('/'));
const sha=value=>crypto.createHash('sha256').update(value).digest('hex');
const normalize=value=>value.toString('utf8').replace(/^\uFEFF/,'').replace(/\r\n/g,'\n').replace(/\r/g,'\n');
const lineCount=value=>{const text=normalize(value);return text.split('\n').length-(text.endsWith('\n')?1:0);};
const readCsv=file=>{const parsed=parseAuthorityCsv(normalize(fs.readFileSync(abs(file))));if(parsed.errors.length)throw new Error(`CSV:${file}:${parsed.errors.join('|')}`);return parsed;};
const identity=file=>{const buffer=fs.readFileSync(abs(file)),stat=fs.statSync(abs(file));return{rows:file.endsWith('.csv')?readCsv(file).rows.length:lineCount(buffer),bytes:buffer.length,sha256:sha(buffer),mtime:new Date(Math.trunc(stat.mtimeMs)).toISOString(),mtimeMs:Math.trunc(stat.mtimeMs)};};
const write=(file,text)=>{fs.mkdirSync(path.dirname(abs(file)),{recursive:true});fs.writeFileSync(abs(file),text,'utf8');};
const exactColumns=(parsed,columns,code)=>parsed.header.join('|')===columns.join('|')?[]:[`${code}_COLUMNS`];
const equalRows=(actual,expected,columns,code)=>{const errors=[];if(actual.length!==expected.length)return[`${code}_COUNT:${actual.length}:${expected.length}`];for(let i=0;i<expected.length;i++)for(const column of columns)if(String(actual[i]?.[column]??'')!==String(expected[i]?.[column]??'')){errors.push(`${code}_FIELD:${i+1}:${column}`);break;}return errors;};
const iso=value=>/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(String(value))&&Number.isFinite(Date.parse(value));
 
function auditEntry(auditId){const lines=normalize(fs.readFileSync(abs(AUDIT_REPORT))).split('\n'),start=lines.findIndex(line=>line.startsWith('### ')&&line.includes(auditId));if(start<0)return null;let end=lines.length;for(let i=start+1;i<lines.length;i++)if(lines[i].startsWith('### ')){end=i;break;}while(end>start&&lines[end-1]==='')end--;const buffer=Buffer.from(`${lines.slice(start,end).join('\n')}\n`);return{start:start+1,end,lines:end-start,bytes:buffer.length,sha256:sha(buffer),text:buffer.toString('utf8')};}
 
export function queryRows(){const definitions=[
 ['CHAIN-001','ZH','人形机器人 具名客户 具名供应商 具体产品 正式定点 合同 主供 独供 公告','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0ACQ-DOMAIN-002'],
 ['CHAIN-001','EN','humanoid robot named customer supplier product nomination contract main sole supplier official','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0ACQ-DOMAIN-002'],
 ['CHAIN-002','ZH','机器人 BOM 原表 采购单价 供应份额 订单 收入确认 官方 合同 公告','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE|OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT','P0ACQ-DOMAIN-003'],
 ['CHAIN-002','EN','robot BOM original table procurement unit price supplier share order revenue recognition official','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE|OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT','P0ACQ-DOMAIN-003'],
 ['COMPANY-001','ZH','机器人 发行人 年报 业务收入 占比 毛利率 页码 官方 披露','EXCHANGE_OR_REGULATOR_FILING|COMPANY_IR_OR_ANNUAL_REPORT','P0ACQ-DOMAIN-002'],
 ['COMPANY-001','EN','robotics issuer annual report segment revenue share gross margin page official filing','EXCHANGE_OR_REGULATOR_FILING|COMPANY_IR_OR_ANNUAL_REPORT','P0ACQ-DOMAIN-002'],
 ['MARKET-001','ZH','IFR MIR GGII Omdia 机器人 市场 原始表格 页码 规模 份额 ASP 口径 官方','OFFICIAL_INDUSTRY_BODY_OR_REPORT_PUBLISHER','P0ACQ-DOMAIN-001'],
 ['MARKET-001','EN','IFR MIR Omdia robotics market original table page market definition shipments revenue ASP official','OFFICIAL_INDUSTRY_BODY_OR_REPORT_PUBLISHER','P0ACQ-DOMAIN-001'],
 ['MODEL-001','ZH','机器人 模型 任务成功率 接管率 部署台数 收费 官方 技术报告 客户','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|COMPANY_IR_OR_ANNUAL_REPORT','P0ACQ-DOMAIN-004'],
 ['MODEL-001','EN','robot foundation model task success intervention rate deployed units pricing official customer technical','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|COMPANY_IR_OR_ANNUAL_REPORT','P0ACQ-DOMAIN-004'],
 ['PRODUCT-001','ZH','机器人 产品 价格 ASP BOM 寿命 良率 产能利用率 交期 官方 招标 合同','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0ACQ-DOMAIN-005'],
 ['PRODUCT-001','EN','robot product price ASP BOM lifetime yield capacity utilization lead time official tender contract','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0ACQ-DOMAIN-005'],
 ['SUPPLY-001','ZH','机器人 具名客户 供应商 具体产品 中标 定点 采购合同 份额 官方','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0ACQ-DOMAIN-006'],
 ['SUPPLY-001','EN','robot named buyer supplier product tender award nomination procurement contract share official','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0ACQ-DOMAIN-006']
];return definitions.map((row,index)=>({query_id:`P0ACQ-QUERY-${String(index+1).padStart(3,'0')}`,conceptual_gap_key:`STRONG_FIELD:ROBOT-GAP-${row[0]}`,query_language:row[1],query_text:row[2],required_source_class:row[3],domain_policy_id:row[4],result_inspection_cap:'10',candidate_capture_cap:'3',secondary_source_policy:'SEARCH_LEAD_ONLY_NOT_ACCEPTED_AS_CANDIDATE',execution_order:String(index+1)}));}
 
export function policyRows(){const rows=[
 ['P0ACQ-DOMAIN-001','DOMAIN_CLASS','OFFICIAL_INDUSTRY_BODY_OR_REPORT_PUBLISHER','publisher owns report/table and identifies publication','aggregator or uncited reproduction','REJECT_SECONDARY_OR_UNATTRIBUTED'],
 ['P0ACQ-DOMAIN-002','DOMAIN_CLASS','EXCHANGE_OR_REGULATOR_FILING|COMPANY_IR_OR_ANNUAL_REPORT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','issuer/customer/supplier identity and covered product or financial field explicit','media paraphrase or anonymous supply-chain claim','REJECT_SECONDARY_OR_UNATTRIBUTED'],
 ['P0ACQ-DOMAIN-003','DOMAIN_CLASS','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE|OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT','official BOM/contract/filing with direct field carriage','estimate or third-party teardown without primary origin','REJECT_SECONDARY_OR_UNATTRIBUTED'],
 ['P0ACQ-DOMAIN-004','DOMAIN_CLASS','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|COMPANY_IR_OR_ANNUAL_REPORT','official technical/customer/deployment/pricing carriage','benchmark repost or promotional paraphrase','REJECT_SECONDARY_OR_UNATTRIBUTED'],
 ['P0ACQ-DOMAIN-005','DOMAIN_CLASS','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','official product/tender/contract field carriage','dealer quote or nonofficial specification','REJECT_SECONDARY_OR_UNATTRIBUTED'],
 ['P0ACQ-DOMAIN-006','DOMAIN_CLASS','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','named parties/product/award/nomination explicit','anonymous channel or media supply-chain claim','REJECT_SECONDARY_OR_UNATTRIBUTED'],
 ['P0ACQ-POLICY-007','NETWORK','PUBLIC_WEB_READ_ONLY_NO_LOGIN_NO_PAYWALL_BYPASS','search/open only after exact release','login, form, purchase, credential, paywall bypass','HELD_SCOPE_VIOLATION'],
 ['P0ACQ-POLICY-008','SECONDARY_SOURCE','SEARCH_LEAD_ONLY_NOT_ACCEPTED_AS_CANDIDATE','secondary may locate official URL then is discarded','secondary content captured as candidate','REJECT_SECONDARY'],
 ['P0ACQ-POLICY-009','URL','CANONICAL_HTTP_OR_HTTPS','canonical URL and lower-case host','tracking duplicate or unresolved redirect','REJECT_URL'],
 ['P0ACQ-POLICY-010','SNIPPET','MAX_800_UTF8_BYTES_WITH_EXACT_HASH','minimal exact relevance fragment and locator','full copyrighted document or paraphrase','REJECT_SNIPPET'],
 ['P0ACQ-POLICY-011','GAP_EFFECT','DISCOVERY_ONLY_GAP_REMAINS_OPEN','independent semantic+sufficiency review required','closure, confirmation or output rewrite','FAIL_CLOSED'],
 ['P0ACQ-POLICY-012','CLAIM_STRENGTH','PENDING_VERIFICATION_MAX_NO_UPGRADE','no acquisition-stage upgrade','strong or investment conclusion','FAIL_CLOSED'],
 ['P0ACQ-POLICY-013','FORMAL_POOL','NO_AUTOMATIC_FORMAL_POOL_CHANGE','candidate does not change pool','approval or promotion','FAIL_CLOSED'],
 ['P0ACQ-POLICY-014','EVIDENCE_STRENGTH','NO_UPGRADE','candidate registration only','map strength mutation','FAIL_CLOSED'],
 ['P0ACQ-POLICY-015','CANDIDATE_CAP','MAX_5_PER_CONCEPTUAL_GAP_AND_3_PER_QUERY','retain most direct official candidates','uncapped accumulation','FAIL_CLOSED']
];return rows.map(row=>Object.fromEntries(POLICY_COLUMNS.map((column,index)=>[column,row[index]])));}
 
export function gapRows(){const priorRows=readCsv(PRIOR_GAP_AUTHORITY).rows,queries=queryRows();return priorRows.map((row,index)=>({...row,gap_id:`P0ACQ-GAP-${String(index+1).padStart(3,'0')}`,source_classes_required:[...new Set(queries.filter(q=>q.conceptual_gap_key===row.conceptual_gap_key).flatMap(q=>q.required_source_class.split('|'))) ].sort().join('|'),query_ids:queries.filter(q=>q.conceptual_gap_key===row.conceptual_gap_key).map(q=>q.query_id).join('|')}));}
 
export function methodRows(){return[{method_id:'P0ACQ-METHOD-001',darkline_required:'NO_APPROVED_EQUIVALENT_ONLY',darkline_availability:'NOT_REQUIRED',approved_equivalent_method:'CODEX_WEB_SEARCH_QUERY_AND_OPEN',equivalent_tool_sequence:'web.search_query->web.open',task_mode:'14_TARGETED_AUTHORITY_QUERIES_PUBLIC_WEB_READ_ONLY',availability_preflight:'REQUIRED_AFTER_RELEASE_BEFORE_NETWORK',unavailable_status:'HELD_BY_REQUIRED_EXTERNAL_INFORMATION_METHOD_UNAVAILABLE',release_before_network:'REQUIRED_EXACT_AUDIT_LITERAL',raw_archive_path:RAW_ARCHIVE,query_log_path:QUERY_LEDGER,supplement_ledger_path:SUPPLEMENT_LEDGER,provenance_ledger_path:PROVENANCE_LEDGER,archive_identity_policy:'UTF8_NO_BOM_LF_JSONL_PER_RECORD_SHA256',network_boundary:'PUBLIC_WEB_READ_ONLY_NO_LOGIN_NO_FORM_SUBMISSION_NO_PURCHASE_NO_PAYWALL_BYPASS'}];}
 
export function contractRows(){const values=[
 ['RELEASE','AUDIT','exact PASS + exact release/batch/run/method/network/gap-effect literals'],['SCOPE','GAPS','7 exact open conceptual gaps'],['SCOPE','OCCURRENCES','10 exact source occurrences'],['SCOPE','QUERIES','14 targeted queries; exactly two per gap'],['PLAN','CROSS_BIND','every gap maps to exact next-evidence plan and prior decision'],['QUERY','POLICY','required source classes subset referenced domain policy'],['QUERY','ORDER','unique 1..14'],['NETWORK','BOUNDARY','PUBLIC_WEB_READ_ONLY_NO_LOGIN_NO_FORM_SUBMISSION_NO_PURCHASE_NO_PAYWALL_BYPASS'],['NETWORK','METHOD','CODEX_WEB_SEARCH_QUERY_AND_OPEN only'],['NETWORK','PREWRITE','release and method preflight before first query'],['RAW','ARCHIVE','JSONL exact field order and per-record SHA256'],['QUERY_LEDGER','BIJECTION','exact14 query_id and query-text hash'],['SUPPLEMENT','BIJECTION','one row per raw record'],['PROVENANCE','BIJECTION','one row per candidate and exact raw/query/url/hash mapping'],['CANDIDATE','SOURCE_CLASS','must belong to query required source classes and policy'],['CANDIDATE','URL','canonical HTTP/S; per-gap URL unique'],['CANDIDATE','SNIPPET','max800 UTF8 bytes and exact hash'],['CANDIDATE','CAP','max5 per gap and max3 per query'],['CANDIDATE','STATE','PRIMARY_CONFIRMED or PRIMARY_CANDIDATE_NEEDS_REVIEW'],['DERIVATION','OCCURRENCE','exact10 all-field deterministic from target+candidate-by-gap'],['DERIVATION','SUMMARY','exact7 all-field deterministic per gap'],['DERIVATION','APPLICATION','exact10 all-field deterministic candidate linkage'],['GAP','STATE','OPEN_RETAINED_GAP always'],['CLAIM','CEILING','PENDING_VERIFICATION_MAX_NO_UPGRADE'],['POOL','EFFECT','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],['EVIDENCE','EFFECT','NO_UPGRADE'],['MAP','EFFECT','READ_ONLY_MAP46_NO_MUTATION'],['OUTPUT','MUTATION','NO_BUSINESS_OUTPUT_OR_FORMAL_VIEW_MUTATION'],['EXECUTION','BASELINE','baseline first before network and exact current identities'],['EXECUTION','STAGING','raw/query/supplement/provenance/candidate all required before finalize'],['EXECUTION','VALIDATION','validation last generated output and no FAIL'],['EXECUTION','EXACT_SET','25 unique ordered artifacts'],['MANIFEST','ANOMALY','only enumerated L1605 legacy header'],['MANIFEST','APPEND','data-only exact25 rows'],['MANIFEST','SEVEN_FIELDS','case/run/batch/path/hash/bytes/filesystem-ms-mtime exact'],['MANIFEST','TRANSACTION','candidate validate, append, postvalidate, rollback derived files on failure'],['PROTECTED','IDENTITY','49 exact current paths unchanged'],['REVIEW','STATE','pending independent execution/output review'],['REVIEW','NEXT_GATE','candidate semantic+sufficiency review before any gap effect']
];return values.map((row,index)=>({contract_id:`P0ACQ-CON-${String(index+1).padStart(3,'0')}`,scope:row[0],field:row[1],required_value_or_rule:row[2],violation_status:'FAIL_CLOSED_OR_HELD'}));}
 
export function schemaRows(){const rows=[
 ['EXECUTION_BASELINE',EXEC_BASELINE,BASELINE_COLUMNS,'baseline_id','exact65','release+manifest+14 inputs+protected49','BASELINE_FIRST'],
 ['METHOD_PREFLIGHT',METHOD_PREFLIGHT,METHOD_PREFLIGHT_COLUMNS,'preflight_id','exact1','release-before-network method state','BEFORE_NETWORK'],
 ['RAW_ARCHIVE',RAW_ARCHIVE,RAW_FIELDS,'raw_record_id','dynamic','exact JSONL raw search/open/no-result records','DISCOVERY_ONLY_GAP_REMAINS_OPEN'],
 ['QUERY_EXECUTION_LEDGER',QUERY_LEDGER,QUERY_LEDGER_COLUMNS,'query_execution_id','exact14','query authority bijection','DISCOVERY_ONLY_GAP_REMAINS_OPEN'],
 ['SUPPLEMENT_LEDGER',SUPPLEMENT_LEDGER,SUPPLEMENT_COLUMNS,'supplement_id','equal_raw','raw disposition bijection','DISCOVERY_ONLY_GAP_REMAINS_OPEN'],
 ['PROVENANCE_LEDGER',PROVENANCE_LEDGER,PROVENANCE_COLUMNS,'provenance_id','equal_candidate','candidate/raw/query exact provenance','NO_UPGRADE'],
 ['CANDIDATE_REGISTER',CANDIDATE_REGISTER,CANDIDATE_COLUMNS,'candidate_id','0_to_35','official-source candidates only','PENDING_VERIFICATION_MAX_NO_UPGRADE'],
 ['OCCURRENCE_DISPOSITION',OCCURRENCE_DISPOSITION,DISPOSITION_COLUMNS,'disposition_id','exact10','deterministic all-field derivation','OPEN_RETAINED_GAP'],
 ['GAP_SUMMARY',GAP_SUMMARY,SUMMARY_COLUMNS,'summary_id','exact7','deterministic all-field derivation','OPEN_RETAINED_GAP'],
 ['APPLICATION',APPLICATION,APPLICATION_COLUMNS,'application_id','exact10','deterministic review-only application','NO_GAP_CLOSURE'],
 ['EXECUTION_REQUEST',EXEC_REQUEST,['MARKDOWN_UTF8_NO_BOM_LF'],'NOT_APPLICABLE','exact1','frozen request text','NO_UPGRADE'],
 ['EXECUTION_VALIDATION',EXEC_VALIDATION,VALIDATION_COLUMNS,'check_id','exact22','fail-closed runtime oracle','VALIDATION_LAST']
];return rows.map((row,index)=>({schema_id:`P0ACQ-SCHEMA-${String(index+1).padStart(3,'0')}`,artifact_role:row[0],artifact_path:row[1],column_order:row[2].join('|'),primary_key:row[3],row_count_rule:row[4],serialization:row[0]==='EXECUTION_REQUEST'?'UTF8_NO_BOM_LF_MARKDOWN':row[0]==='RAW_ARCHIVE'?'UTF8_NO_BOM_LF_JSONL':'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_CSV',derivation_rule:row[5],required_boundary:row[6]}));}
 
export function executionSetRows(){const paths=[SCRIPT,TARGET_AUTHORITY,GAP_AUTHORITY,NEXT_PLAN,DECISION,MAP,QUERY_AUTHORITY,SOURCE_POLICY,METHOD_AUTHORITY,FORMAL_ENTRY_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,EXEC_BASELINE,METHOD_PREFLIGHT,RAW_ARCHIVE,QUERY_LEDGER,SUPPLEMENT_LEDGER,PROVENANCE_LEDGER,CANDIDATE_REGISTER,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];const roles=['RUNTIME','TARGET_AUTHORITY','GAP_AUTHORITY','NEXT_EVIDENCE_PLAN','PRIOR_GAP_DECISION','FORMAL_MAP46_READ_ONLY','QUERY_AUTHORITY','SOURCE_POLICY','METHOD_AUTHORITY','FORMAL_DESIGN_ENTRY','RUNTIME_CONTRACT','OUTPUT_SCHEMA','EXECUTION_EXACT_SET','EXECUTION_BASELINE_FIRST','METHOD_PREFLIGHT','RAW_ARCHIVE','QUERY_LEDGER','SUPPLEMENT_LEDGER','PROVENANCE_LEDGER','CANDIDATE_REGISTER','OCCURRENCE_DISPOSITION','GAP_SUMMARY','APPLICATION','EXECUTION_REQUEST','VALIDATION_LAST'];return paths.map((artifactPath,index)=>({artifact_id:`P0ACQ-EXEC-SET-${String(index+1).padStart(3,'0')}`,batch_id:EXEC_BATCH,run_id:EXEC_RUN,generation_order:String(index+1),artifact_path:artifactPath,artifact_role:roles[index],identity_policy:'EXACT_SHA256_BYTES_FILESYSTEM_MTIME_MS'}));}
 
export function authorityBundle(){return{targets:readCsv(TARGET_AUTHORITY).rows,gaps:readCsv(GAP_AUTHORITY).rows,queries:readCsv(QUERY_AUTHORITY).rows,policies:readCsv(SOURCE_POLICY).rows,methods:readCsv(METHOD_AUTHORITY).rows,contracts:readCsv(CONTRACT).rows,schemas:readCsv(SCHEMA).rows,executionSet:readCsv(EXEC_SET).rows};}
 
export function releaseTextErrors(text){const required=['result=PASS','execution_release=EXPLICITLY_RELEASED',`released_batch_id=${EXEC_BATCH}`,`released_run_id=${EXEC_RUN}`,'external_information_method=CODEX_WEB_SEARCH_QUERY_AND_OPEN_APPROVED_EQUIVALENT','network_execution_scope=PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY','gap_effect=DISCOVERY_ONLY_GAP_REMAINS_OPEN'];const lines=text.split('\n').map(line=>line.trim().replace(/^[\-*]\s*/,'').replace(/`/g,'')),errors=[];for(const marker of required)if(!lines.includes(marker))errors.push(`RELEASE_MARKER:${marker}`);if(lines.some(line=>/^(?:result|conclusion)=FAIL(?:_|$)/.test(line))||lines.includes('execution_release=NOT_ALLOWED')||lines.includes('execution_release=NOT_RELEASED'))errors.push('RELEASE_CONTRADICTION');return errors;}
export function releaseErrors({required=true}={}){const entry=auditEntry(RELEASE_AUDIT);return entry?releaseTextErrors(entry.text):required?['RELEASE_AUDIT_MISSING']:[];}
 
export function queryPolicyErrors(bundle=authorityBundle()){const errors=[],policy=new Map(bundle.policies.map(row=>[row.policy_id,row])),plan=new Map(readCsv(NEXT_PLAN).rows.map(row=>[row.conceptual_gap_key,row])),decision=new Map(readCsv(DECISION).rows.map(row=>[row.conceptual_gap_key,row]));if(bundle.queries.length!==14||new Set(bundle.queries.map(row=>row.query_id)).size!==14)errors.push('QUERY_COUNT');if(new Set(bundle.queries.map(row=>row.execution_order)).size!==14||bundle.queries.some((row,index)=>row.execution_order!==String(index+1)))errors.push('QUERY_ORDER');for(const gap of bundle.gaps){const qs=bundle.queries.filter(row=>row.conceptual_gap_key===gap.conceptual_gap_key);if(qs.length!==2)errors.push(`QUERY_PER_GAP:${gap.conceptual_gap_key}`);if(gap.query_ids!==qs.map(row=>row.query_id).join('|'))errors.push(`GAP_QUERY_BIND:${gap.conceptual_gap_key}`);if(!plan.has(gap.conceptual_gap_key)||!decision.has(gap.conceptual_gap_key))errors.push(`PLAN_DECISION_BIND:${gap.conceptual_gap_key}`);}for(const query of bundle.queries){const p=policy.get(query.domain_policy_id);if(!p){errors.push(`POLICY_MISSING:${query.query_id}`);continue;}const allowed=new Set(p.allowed_value.split('|')),required=new Set(query.required_source_class.split('|'));for(const value of required)if(!allowed.has(value))errors.push(`QUERY_POLICY_CLASS:${query.query_id}:${value}`);}return[...new Set(errors)];}
 
export function methodAuthorityErrors(rows){if(rows.length!==1)return[`METHOD_COUNT:${rows.length}`];return equalRows(rows,methodRows(),METHOD_COLUMNS,'METHOD');}
export function methodPreflightErrors(rows){const errors=[];if(rows.length!==1)return[`PREFLIGHT_COUNT:${rows.length}`];const row=rows[0];if(row.method_id!=='P0ACQ-METHOD-001'||row.selected_method!=='CODEX_WEB_SEARCH_QUERY_AND_OPEN'||row.task_mode!=='14_TARGETED_AUTHORITY_QUERIES_PUBLIC_WEB_READ_ONLY'||row.release_gate_status!=='PASS_EXACT_RELEASE_BEFORE_NETWORK'||row.status!=='PASS'||!iso(row.checked_at))errors.push('PREFLIGHT_FIELDS');return errors;}
 
function formalEntryErrors(){const rows=readCsv(FORMAL_ENTRY_AUTHORITY).rows;if(rows.length!==1)return['FORMAL_ENTRY_COUNT'];const row=rows[0],all=normalize(fs.readFileSync(abs(row.artifact_path))).split('\n'),text=`${all.slice(Number(row.start_line)-1,Number(row.end_line)).join('\n')}\n`,errors=[];if(Buffer.byteLength(text)!==Number(row.bytes)||sha(Buffer.from(text))!==row.sha256||lineCount(Buffer.from(text))!==Number(row.lines))errors.push('FORMAL_ENTRY_IDENTITY');for(const marker of row.required_markers.split('|'))if(!text.includes(marker))errors.push(`FORMAL_ENTRY_MARKER:${marker}`);return errors;}
 
function manifestState({expectedRows=[],expectedRunId='',prefix=null,delta=null}={}){return validateAppendStableManifest(fs.readFileSync(abs(MANIFEST)),{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:prefix,originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:expectedRows,expectedRunId,expectedPhysicalDelta:delta,filesystemIdentity:{runIds:expectedRunId?[expectedRunId]:[],get:file=>fs.existsSync(abs(file))?identity(file):null}});}
function protectedRows(){const paths=readCsv(PROTECTED_INVENTORY).rows.map(row=>row.artifact_path);return paths.map(artifact_path=>({artifact_path,...identity(artifact_path)}));}
 
export function designInputErrors({requireRelease=false,expectNoExecution=true,expectDesignManifest=true}={}){const bundle=authorityBundle(),errors=[...queryPolicyErrors(bundle),...methodAuthorityErrors(bundle.methods),...formalEntryErrors(),...releaseErrors({required:requireRelease})];if(bundle.targets.length!==10||bundle.gaps.length!==7||readCsv(NEXT_PLAN).rows.length!==7||readCsv(DECISION).rows.length!==7||readCsv(MAP).rows.length!==46)errors.push('FROZEN_COUNTS');errors.push(...equalRows(bundle.queries,queryRows(),QUERY_COLUMNS,'QUERY'),...equalRows(bundle.policies,policyRows(),POLICY_COLUMNS,'POLICY'),...equalRows(bundle.methods,methodRows(),METHOD_COLUMNS,'METHOD'),...equalRows(bundle.gaps,gapRows(),GAP_COLUMNS,'GAP'),...equalRows(bundle.contracts,contractRows(),CONTRACT_COLUMNS,'CONTRACT'),...equalRows(bundle.schemas,schemaRows(),SCHEMA_COLUMNS,'SCHEMA'),...equalRows(bundle.executionSet,executionSetRows(),EXEC_SET_COLUMNS,'EXEC_SET'));if(protectedRows().length!==49)errors.push('PROTECTED_COUNT');if(expectDesignManifest){const rows=manifestState().logicalRows.filter(row=>row.run_id===DESIGN_RUN);if(rows.length!==15||new Set(rows.map(row=>row.artifact_path)).size!==15)errors.push(`DESIGN_MANIFEST:${rows.length}`);for(const row of rows){const id=identity(row.artifact_path);if(row.case_id!==CASE_ID||row.batch_id!==DESIGN_BATCH||row.sha256!==id.sha256||row.bytes!==String(id.bytes)||Date.parse(row.mtime)!==id.mtimeMs)errors.push(`DESIGN_IDENTITY:${row.artifact_path}`);}}if(expectNoExecution&&(GENERATED.some(file=>fs.existsSync(abs(file)))||manifestState().logicalRows.some(row=>row.run_id===EXEC_RUN)))errors.push('EXECUTION_STATE_NOT_EMPTY');return[...new Set(errors)];}
 
function baselineRows(){const release=auditEntry(RELEASE_AUDIT),manifest=fs.readFileSync(abs(MANIFEST));if(!release)throw new Error('RELEASE_AUDIT_MISSING');const rows=[{baseline_id:'P0ACQ-BASE-001',identity_type:'NORMALIZED_RELEASE_AUDIT_ENTRY',artifact_path:`${AUDIT_REPORT}#L${release.start}-L${release.end}`,rows:String(release.lines),bytes:String(release.bytes),sha256:release.sha256,mtime:'INFO_APPENDABLE_SHARED_FILE',required_state:'EXACT_PASS_RELEASE_ENTRY'},{baseline_id:'P0ACQ-BASE-002',identity_type:'RAW_MANIFEST_PREFIX',artifact_path:MANIFEST,rows:String(manifestState().logicalDataRows),bytes:String(manifest.length),sha256:sha(manifest),mtime:new Date(Math.trunc(fs.statSync(abs(MANIFEST)).mtimeMs)).toISOString(),required_state:'EXACT_APPEND_ONLY_PREFIX'}];for(const file of FROZEN_INPUTS){const id=identity(file);rows.push({baseline_id:`P0ACQ-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'FROZEN_EXECUTION_INPUT',artifact_path:file,rows:String(id.rows),bytes:String(id.bytes),sha256:id.sha256,mtime:id.mtime,required_state:'EXACT_NO_DRIFT'});}for(const item of protectedRows())rows.push({baseline_id:`P0ACQ-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'PROTECTED49_CURRENT_IDENTITY',artifact_path:item.artifact_path,rows:String(item.rows),bytes:String(item.bytes),sha256:item.sha256,mtime:item.mtime,required_state:'NO_MUTATION'});return rows;}
function baselineErrors(rows){const errors=[];if(rows.length!==65)return[`BASELINE_COUNT:${rows.length}`];const release=auditEntry(RELEASE_AUDIT);if(!release||rows[0].rows!==String(release.lines)||rows[0].bytes!==String(release.bytes)||rows[0].sha256!==release.sha256)errors.push('BASELINE_RELEASE');const manifest=fs.readFileSync(abs(MANIFEST)),prefix=rows[1];if(manifest.length<Number(prefix.bytes)||sha(manifest.subarray(0,Number(prefix.bytes)))!==prefix.sha256)errors.push('BASELINE_MANIFEST_PREFIX');for(const row of rows.slice(2)){if(!fs.existsSync(abs(row.artifact_path))){errors.push(`BASELINE_MISSING:${row.artifact_path}`);continue;}const id=identity(row.artifact_path);if(row.rows!==String(id.rows)||row.bytes!==String(id.bytes)||row.sha256!==id.sha256||Date.parse(row.mtime)!==id.mtimeMs)errors.push(`BASELINE_IDENTITY:${row.artifact_path}`);}return errors;}
 
function makePreflight(){return[{preflight_id:'P0ACQ-PREFLIGHT-001',method_id:'P0ACQ-METHOD-001',darkline_available:'NO',equivalent_method_available:'YES',selected_method:'CODEX_WEB_SEARCH_QUERY_AND_OPEN',task_mode:'14_TARGETED_AUTHORITY_QUERIES_PUBLIC_WEB_READ_ONLY',release_gate_status:'PASS_EXACT_RELEASE_BEFORE_NETWORK',checked_at:new Date().toISOString(),status:'PASS'}];}
export function beginAcquisition({token,method}={}){if(token!==EXEC_TOKEN)throw new Error('EXECUTION_TOKEN_MISMATCH');if(method!=='CODEX_WEB_SEARCH_QUERY_AND_OPEN')throw new Error('METHOD_NOT_ALLOWED');const errors=designInputErrors({requireRelease:true,expectNoExecution:true,expectDesignManifest:true});if(errors.length)throw new Error(`BEGIN_PREWRITE:${errors.join('|')}`);write(EXEC_BASELINE,serializeCsv(baselineRows(),BASELINE_COLUMNS));write(METHOD_PREFLIGHT,serializeCsv(makePreflight(),METHOD_PREFLIGHT_COLUMNS));return{status:'READY_FOR_EXACT_14_TARGETED_QUERY_ACQUISITION',network_allowed:true,baseline_rows:65};}
 
function discovery(){const raw=prior.parseRawArchive(fs.readFileSync(abs(RAW_ARCHIVE))),query=readCsv(QUERY_LEDGER),supplement=readCsv(SUPPLEMENT_LEDGER),provenance=readCsv(PROVENANCE_LEDGER),candidate=readCsv(CANDIDATE_REGISTER),method=readCsv(METHOD_PREFLIGHT),bundle=authorityBundle(),value={rawRows:raw.rows,queryLedger:query.rows,supplements:supplement.rows,provenance:provenance.rows,candidates:candidate.rows,methodPreflight:method.rows},errors=[...raw.errors,...exactColumns(query,QUERY_LEDGER_COLUMNS,'QUERY'),...exactColumns(supplement,SUPPLEMENT_COLUMNS,'SUPPLEMENT'),...exactColumns(provenance,PROVENANCE_COLUMNS,'PROVENANCE'),...exactColumns(candidate,CANDIDATE_COLUMNS,'CANDIDATE'),...exactColumns(method,METHOD_PREFLIGHT_COLUMNS,'METHOD'),...methodPreflightErrors(method.rows),...prior.provenanceErrors(value,bundle)];const queryById=new Map(bundle.queries.map(row=>[row.query_id,row]));for(const row of candidate.rows){const queryRow=queryById.get(row.query_id);if(queryRow&&!queryRow.required_source_class.split('|').includes(row.source_class))errors.push(`CANDIDATE_QUERY_SOURCE_CLASS:${row.candidate_id}`);}return{...value,errors:[...new Set(errors)]};}
 
export function validateStaging(){const errors=[...releaseErrors({required:true})];if(!fs.existsSync(abs(EXEC_BASELINE))||!fs.existsSync(abs(METHOD_PREFLIGHT)))errors.push('BEGIN_ARTIFACTS_MISSING');for(const file of DISCOVERY_STAGE)if(!fs.existsSync(abs(file)))errors.push(`DISCOVERY_MISSING:${file}`);if(errors.length)return errors;errors.push(...baselineErrors(readCsv(EXEC_BASELINE).rows),...discovery().errors);if(DERIVED_STAGE.some(file=>fs.existsSync(abs(file))))errors.push('DERIVED_STAGE_EXISTS');if(manifestState().logicalRows.some(row=>row.run_id===EXEC_RUN))errors.push('EXECUTION_MANIFEST_ROWS');return[...new Set(errors)];}
 
function requestText(status){return`# P0 开放缺口定向主来源证据采集执行复审请求\n\ncase_id=${CASE_ID}\nsource_audit=${SOURCE_AUDIT}\nrelease_audit=${RELEASE_AUDIT}\nbatch_id=${EXEC_BATCH}\nrun_id=${EXEC_RUN}\nmethod=CODEX_WEB_SEARCH_QUERY_AND_OPEN\nnetwork_scope=PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY\nquery_scope=14_TARGETED_FROZEN_AUTHORITY_QUERIES\nrun_status=${status}\ngap_effect=DISCOVERY_ONLY_GAP_REMAINS_OPEN\nclaim_strength_ceiling=PENDING_VERIFICATION_MAX_NO_UPGRADE\nformal_pool_effect=NO_AUTOMATIC_FORMAL_POOL_CHANGE\nevidence_strength_effect=NO_UPGRADE\nmap_effect=READ_ONLY_MAP46_NO_MUTATION\n`;} 
 
function validationRows(d,derived){const runtime=[...d.errors,...prior.derivedErrors({...d,...derived},authorityBundle())],checks=[['RUNTIME_ERRORS','0',String(runtime.length)],['TARGETS','10','10'],['GAPS','7','7'],['NEXT_PLAN','7','7'],['DECISION','7','7'],['MAP','46','46'],['QUERIES','14',String(d.queryLedger.length)],['RAW_QUERY_COVERAGE','14',String(new Set(d.rawRows.map(row=>row.query_id)).size)],['SUPPLEMENT_BIJECTION',String(d.rawRows.length),String(d.supplements.length)],['PROVENANCE_BIJECTION',String(d.candidates.length),String(d.provenance.length)],['OCCURRENCES','10',String(derived.dispositions.length)],['SUMMARY','7',String(derived.summary.length)],['APPLICATION','10',String(derived.applications.length)],['OPEN_GAP','OPEN_RETAINED_GAP',derived.dispositions.every(row=>row.gap_state_after==='OPEN_RETAINED_GAP')?'OPEN_RETAINED_GAP':'MISMATCH'],['CLAIM_CEILING','PENDING_VERIFICATION_MAX_NO_UPGRADE',derived.dispositions.every(row=>row.claim_strength_after==='PENDING_VERIFICATION_MAX_NO_UPGRADE')?'PENDING_VERIFICATION_MAX_NO_UPGRADE':'MISMATCH'],['POOL','NO_AUTOMATIC_FORMAL_POOL_CHANGE',derived.applications.every(row=>row.formal_pool_effect==='NO_AUTOMATIC_FORMAL_POOL_CHANGE')?'NO_AUTOMATIC_FORMAL_POOL_CHANGE':'MISMATCH'],['EVIDENCE','NO_UPGRADE',derived.applications.every(row=>row.evidence_strength_effect==='NO_UPGRADE')?'NO_UPGRADE':'MISMATCH'],['MAP_EFFECT','READ_ONLY_MAP46_NO_MUTATION','READ_ONLY_MAP46_NO_MUTATION'],['PROTECTED','49','49'],['EXACT_SET','25','25'],['METHOD','CODEX_WEB_SEARCH_QUERY_AND_OPEN',d.methodPreflight[0]?.selected_method??''],['REVIEW_STATE','PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW','PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW']];const rows=checks.map((item,index)=>({check_id:`P0ACQ-EXEC-VAL-${String(index+1).padStart(3,'0')}`,check_description:item[0],expected:item[1],actual:item[2],status:item[1]===item[2]?'PASS':'FAIL',evidence:'P0ACQ_SHARED_FAIL_CLOSED_RUNTIME_ORACLE'}));rows.push({check_id:'P0ACQ-EXEC-VAL-023',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identity postchecked'});return rows;}
 
function manifestRowsFor(paths){return paths.map(file=>{const id=identity(file);return{case_id:CASE_ID,run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:file,sha256:id.sha256,bytes:String(id.bytes),mtime:id.mtime};});}
function manifestMutationErrors(field){const before=fs.readFileSync(abs(MANIFEST)),correct=manifestRowsFor([SCRIPT])[0],mutated={...correct};if(field==='case_id')mutated[field]='WRONG-CASE';else if(field==='run_id')mutated[field]='WRONG-RUN';else if(field==='batch_id')mutated[field]='WRONG-BATCH';else if(field==='artifact_path')mutated[field]=`${SCRIPT}.wrong`;else if(field==='sha256')mutated[field]='0'.repeat(64);else if(field==='bytes')mutated[field]=String(Number(correct.bytes)+1);else if(field==='mtime')mutated[field]='NOT-A-TIMESTAMP';const errors=[];if(mutated[field]!==correct[field])errors.push(`MANIFEST_${field.toUpperCase()}`);const candidate=Buffer.concat([before,Buffer.from(serializeManifestDataRows([mutated]),'utf8')]),state=validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:before.length,sha256:sha(before)},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:[correct],expectedRunId:EXEC_RUN,expectedPhysicalDelta:1,filesystemIdentity:{runIds:[EXEC_RUN],get:file=>fs.existsSync(abs(file))?identity(file):null}});errors.push(...state.errors.map(code=>`PARSER:${code}`));return errors;}
export function finalizeAcquisition({token}={}){if(token!==EXEC_TOKEN)throw new Error('EXECUTION_TOKEN_MISMATCH');const pre=validateStaging();if(pre.length)throw new Error(`FINALIZE_PREWRITE:${pre.join('|')}`);const before=fs.readFileSync(abs(MANIFEST)),d=discovery(),derived=prior.deriveOutputs(d.queryLedger,d.candidates,d.methodPreflight,authorityBundle());try{write(OCCURRENCE_DISPOSITION,serializeCsv(derived.dispositions,DISPOSITION_COLUMNS));write(GAP_SUMMARY,serializeCsv(derived.summary,SUMMARY_COLUMNS));write(APPLICATION,serializeCsv(derived.applications,APPLICATION_COLUMNS));write(EXEC_REQUEST,requestText(derived.runStatus));const validation=validationRows(d,derived);write(EXEC_VALIDATION,serializeCsv(validation,VALIDATION_COLUMNS));if(validation.some(row=>row.status==='FAIL'))throw new Error('VALIDATION_FAIL');const rows=manifestRowsFor(executionSetRows().map(row=>row.artifact_path)),candidate=Buffer.concat([before,Buffer.from(serializeManifestDataRows(rows),'utf8')]),state=validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:before.length,sha256:sha(before)},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:EXEC_RUN,expectedPhysicalDelta:25});if(state.errors.length)throw new Error(`MANIFEST_CANDIDATE:${state.errors.join('|')}`);fs.writeFileSync(abs(MANIFEST),candidate);const post=validateExecution();if(post.length)throw new Error(`POSTWRITE:${post.join('|')}`);return{status:'EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW',queries:14,raw_records:d.rawRows.length,candidates:d.candidates.length,gaps_open:7,manifest_rows:25};}catch(error){const cleanup=[];try{fs.writeFileSync(abs(MANIFEST),before);}catch(failure){cleanup.push(`MANIFEST:${failure.message}`);}for(const file of DERIVED_STAGE)if(fs.existsSync(abs(file)))try{fs.rmSync(abs(file));}catch(failure){cleanup.push(`REMOVE:${file}:${failure.message}`);}if(cleanup.length)throw new Error(`ROLLBACK_INCOMPLETE_HELD:${cleanup.join('|')}:${error.message}`);throw error;}}
 
export function validateExecution(){const errors=[];for(const file of GENERATED)if(!fs.existsSync(abs(file)))errors.push(`MISSING:${file}`);if(errors.length)return errors;const baseline=readCsv(EXEC_BASELINE),d=discovery(),disp=readCsv(OCCURRENCE_DISPOSITION),summary=readCsv(GAP_SUMMARY),apps=readCsv(APPLICATION),validation=readCsv(EXEC_VALIDATION);errors.push(...exactColumns(baseline,BASELINE_COLUMNS,'BASELINE'),...baselineErrors(baseline.rows),...d.errors,...exactColumns(disp,DISPOSITION_COLUMNS,'DISPOSITION'),...exactColumns(summary,SUMMARY_COLUMNS,'SUMMARY'),...exactColumns(apps,APPLICATION_COLUMNS,'APPLICATION'),...exactColumns(validation,VALIDATION_COLUMNS,'VALIDATION'),...prior.derivedErrors({...d,dispositions:disp.rows,summary:summary.rows,applications:apps.rows},authorityBundle()));if(validation.rows.length!==23||validation.rows.some(row=>row.status==='FAIL'))errors.push('VALIDATION_STATUS');const expected=manifestRowsFor(executionSetRows().map(row=>row.artifact_path)),prefix=baseline.rows[1],state=manifestState({expectedRows:expected,expectedRunId:EXEC_RUN,prefix:{bytes:Number(prefix.bytes),sha256:prefix.sha256},delta:25});errors.push(...state.errors.map(code=>`MANIFEST:${code}`));return[...new Set(errors)];}
 
function synthetic(){const bundle={targets:readCsv(TARGET_AUTHORITY).rows,gaps:gapRows(),queries:queryRows(),policies:policyRows()},time='2026-07-31T00:00:00.000Z',queryLedger=bundle.queries.map((query,index)=>({query_execution_id:`P0ACQ-QEXEC-${String(index+1).padStart(3,'0')}`,query_id:query.query_id,conceptual_gap_key:query.conceptual_gap_key,query_text_sha256:sha(Buffer.from(query.query_text)),searched_at:time,result_count_inspected:'0',candidate_count_captured:'0',execution_status:'COMPLETED_NO_PRIMARY_CANDIDATE',tool_boundary:'PUBLIC_WEB_READ_ONLY_NO_LOGIN_NO_PAYWALL_BYPASS',gap_effect:'DISCOVERY_ONLY_GAP_REMAINS_OPEN'}));return{bundle,queryLedger,candidates:[],methodPreflight:makePreflight()};}
export function negativeRows(){const good=['result=PASS','execution_release=EXPLICITLY_RELEASED',`released_batch_id=${EXEC_BATCH}`,`released_run_id=${EXEC_RUN}`,'external_information_method=CODEX_WEB_SEARCH_QUERY_AND_OPEN_APPROVED_EQUIVALENT','network_execution_scope=PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY','gap_effect=DISCOVERY_ONLY_GAP_REMAINS_OPEN'].join('\n'),tests=[];const add=(name,oracle,expectedCode,fn)=>{const errors=fn(),actual=errors.length?'REJECT':'ACCEPT';tests.push({test_id:`P0ACQ-NEG-${String(tests.length+1).padStart(3,'0')}-${name}`,mutation_applied:name==='CLEAN'?'NO_CLEAN_CONTROL':'YES',oracle,expected:name==='CLEAN'?'ACCEPT':'REJECT',expected_code:expectedCode,actual,actual_codes:errors.join('|')||'NONE',result:(name==='CLEAN'?actual==='ACCEPT':actual==='REJECT'&&errors.some(code=>code.startsWith(expectedCode)))?'PASS':'FAIL'});};add('CLEAN','releaseTextErrors','NONE',()=>releaseTextErrors(good));add('FAIL_MENTIONS_PASS','releaseTextErrors','RELEASE_',()=>releaseTextErrors(`result=FAIL\nnotes=${good.replace(/\n/g,' ')}`));add('WRONG_BATCH','releaseTextErrors','RELEASE_MARKER',()=>releaseTextErrors(good.replace(EXEC_BATCH,'WRONG')));add('QUERY_GAP_SWAP','queryPolicyErrors','GAP_QUERY_BIND',()=>{const b={gaps:gapRows().map(row=>({...row})),queries:queryRows().map(row=>({...row})),policies:policyRows()};[b.queries[0].conceptual_gap_key,b.queries[2].conceptual_gap_key]=[b.queries[2].conceptual_gap_key,b.queries[0].conceptual_gap_key];return queryPolicyErrors(b);});add('QUERY_CLASS','queryPolicyErrors','QUERY_POLICY_CLASS',()=>{const b={gaps:gapRows(),queries:queryRows().map(row=>({...row})),policies:policyRows()};b.queries[0].required_source_class='OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT';return queryPolicyErrors(b);});add('QUERY_ORDER','queryPolicyErrors','QUERY_ORDER',()=>{const b={gaps:gapRows(),queries:queryRows().map(row=>({...row})),policies:policyRows()};b.queries[1].execution_order='1';return queryPolicyErrors(b);});add('METHOD_MODE','methodAuthorityErrors','METHOD_FIELD',()=>{const rows=methodRows().map(row=>({...row,task_mode:'WRONG'}));return methodAuthorityErrors(rows);});const clean=synthetic(),derived=prior.deriveOutputs(clean.queryLedger,clean.candidates,clean.methodPreflight,clean.bundle);add('LEDGER_GAP','provenanceErrors','QUERY_LEDGER_GAP',()=>{const ledger=clean.queryLedger.map(row=>({...row}));ledger[0].conceptual_gap_key='WRONG';return prior.provenanceErrors({rawRows:[],queryLedger:ledger,supplements:[],provenance:[],candidates:[]},clean.bundle);});add('SUMMARY_FIELD','derivedErrors','SUMMARY_FIELD',()=>{const summary=derived.summary.map(row=>({...row}));summary[0].gap_state_after='CLOSED';return prior.derivedErrors({queryLedger:clean.queryLedger,candidates:[],methodPreflight:clean.methodPreflight,dispositions:derived.dispositions,summary,applications:derived.applications},clean.bundle);});add('APPLICATION_FIELD','derivedErrors','APPLICATION_FIELD',()=>{const applications=derived.applications.map(row=>({...row}));applications[0].application_result='CLOSED';return prior.derivedErrors({queryLedger:clean.queryLedger,candidates:[],methodPreflight:clean.methodPreflight,dispositions:derived.dispositions,summary:derived.summary,applications},clean.bundle);});add('DISPOSITION_FIELD','derivedErrors','DISPOSITION_FIELD',()=>{const dispositions=derived.dispositions.map(row=>({...row}));dispositions[0].claim_strength_after='STRONG';return prior.derivedErrors({queryLedger:clean.queryLedger,candidates:[],methodPreflight:clean.methodPreflight,dispositions,summary:derived.summary,applications:derived.applications},clean.bundle);});for(const field of ['case_id','run_id','batch_id','artifact_path','sha256','bytes','mtime'])add(`MANIFEST_${field.toUpperCase()}`,'validateAppendStableManifest',`MANIFEST_${field.toUpperCase()}`,()=>manifestMutationErrors(field));return tests;}
 
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){const mode=process.argv[2]??'--preview',token=process.argv.find(value=>value.startsWith('--token='))?.slice(8),method=process.argv.find(value=>value.startsWith('--method='))?.slice(9);if(mode==='--preview'){const errors=[];if(fs.existsSync(abs(QUERY_AUTHORITY)))errors.push(...queryPolicyErrors());console.log(JSON.stringify({status:'PREVIEW',gaps:7,occurrences:10,queries:14,contracts:contractRows().length,schemas:schemaRows().length,exact_set:executionSetRows().length,negative:negativeRows().length,errors},null,2));if(errors.length)process.exitCode=1;}else if(mode==='--self-test'){const rows=negativeRows();console.log(JSON.stringify(rows,null,2));if(rows.some(row=>row.result!=='PASS'))process.exitCode=1;}else if(mode==='--validate-design-inputs'){const errors=designInputErrors({requireRelease:false,expectNoExecution:true,expectDesignManifest:true});console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_DESIGN_INPUTS',errors},null,2));if(errors.length)process.exitCode=1;}else if(mode==='--validate-release'){const errors=designInputErrors({requireRelease:true,expectNoExecution:true,expectDesignManifest:true});console.log(JSON.stringify({status:errors.length?'HELD':'PASS_RELEASE_BEFORE_NETWORK',errors},null,2));if(errors.length)process.exitCode=1;}else if(mode==='--begin-acquisition')console.log(JSON.stringify(beginAcquisition({token,method}),null,2));else if(mode==='--validate-staging'){const errors=validateStaging();console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_STAGING',errors},null,2));if(errors.length)process.exitCode=1;}else if(mode==='--finalize')console.log(JSON.stringify(finalizeAcquisition({token}),null,2));else if(mode==='--validate-execution'){const errors=validateExecution();console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_APPEND_STABLE_EXECUTION_STATE',errors},null,2));if(errors.length)process.exitCode=1;}else throw new Error(`UNKNOWN_MODE:${mode}`);}