Cai
2026-08-14 85bbcb99dbd54f3fba3420832736670e9da60cc3
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {spawnSync} from 'node:child_process';
import {pathToFileURL} from 'node:url';
import {
  ROOT,CASE_ID,BASE,AUDIT_REPORT,MANIFEST,ANOMALY_AUTHORITY,ORIGINAL_TRIAGE_RUN,
  DESIGN_RUN,DESIGN_BATCH,EXEC_RUN,EXEC_BATCH,RELEASE_AUDIT,SCRIPT,
  TARGET_AUTHORITY,GAP_AUTHORITY,QUERY_AUTHORITY,SOURCE_POLICY,CONTRACT,SCHEMA,EXEC_SET,
  EXEC_BASELINE,QUERY_LEDGER,CANDIDATE_REGISTER,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION,
  TARGET_COLUMNS,GAP_COLUMNS,QUERY_COLUMNS,POLICY_COLUMNS,CONTRACT_COLUMNS,SCHEMA_COLUMNS,EXEC_SET_COLUMNS,BASELINE_COLUMNS,VALIDATION_COLUMNS,
  abs,sha,normalizeText,lineCount,readCsv,fileIdentity,auditEntry,authorityBundle,contractRows,schemaRows,executionSetRows,negativeRows,prewriteErrors,
} from './detail_strengthening_p0_primary_source_discovery_runtime_20260730.mjs';
import {hashBuffer,parseAuthorityCsv,serializeCsv,serializeManifestDataRows,validateAppendStableManifest} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
const PREDECESSOR_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-MANIFEST-INTEGRITY-REPAIR001-EXEC-OUTPUT-001';
const PREDECESSOR_ENTRY={lines:56,bytes:6734,sha256:'22500d5979b090710000fb5c4111e66339ef2ea3563e1f5a8db90c1d58d8c137'};
const TRIAGE_REGISTER=`${BASE}/outputs/数据表/robot_detail_gap_triage_register_v01_repair002_20260730.csv`;
const TRIAGE_SUMMARY=`${BASE}/outputs/数据表/robot_detail_gap_workstream_summary_v01_repair002_20260730.csv`;
const TRIAGE_APPLICATION=`${BASE}/evidence/detail_strengthening_gap_triage_application_repair002_20260730.csv`;
const PROTECTED_INVENTORY=`${BASE}/evidence/final_gate_output_inventory_rebuild_repair001_20260728.csv`;
const BUILDER='dev/ana-dev/detail_strengthening_p0_primary_source_discovery_design_20260730.mjs';
const NEG_RESULTS=`${BASE}/evidence/detail_strengthening_p0_primary_source_discovery_negative_results_20260730.csv`;
const DESIGN_BASELINE=`${BASE}/evidence/detail_strengthening_p0_primary_source_discovery_design_baseline_20260730.csv`;
const DESIGN_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_primary_source_discovery_design_20260730.md`;
const DESIGN_SET=`${BASE}/manifest/detail_strengthening_p0_primary_source_discovery_design_artifact_set_20260730.csv`;
const DESIGN_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_primary_source_discovery_design_validation_20260730.csv`;
const MANIFEST_PREFIX={physicalRecords:1639,logicalRows:1637,bytes:586870,sha256:'3b93d6ae9b821db5db91bc7c30f737ecaace5852d9ced8fdcc060c1e544ad350'};
const DESIGN_PATHS=[SCRIPT,BUILDER,TARGET_AUTHORITY,GAP_AUTHORITY,QUERY_AUTHORITY,SOURCE_POLICY,CONTRACT,SCHEMA,EXEC_SET,NEG_RESULTS,DESIGN_BASELINE,DESIGN_REQUEST,DESIGN_SET,DESIGN_VALIDATION];
const DESIGN_SET_COLUMNS=['artifact_id','batch_id','run_id','generation_order','artifact_path','artifact_role','identity_policy'];
const NEG_COLUMNS=['test_id','mutation_applied','oracle','expected','expected_code','actual','actual_codes','result'];
 
const esc=value=>`"${String(value??'').replace(/"/g,'""')}"`;
const writeText=(file,text)=>{fs.mkdirSync(path.dirname(abs(file)),{recursive:true});fs.writeFileSync(abs(file),text,'utf8');};
 
function currentManifestState() {
  const buffer=fs.readFileSync(abs(MANIFEST));
  return validateAppendStableManifest(buffer,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:MANIFEST_PREFIX.bytes,sha256:MANIFEST_PREFIX.sha256},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11});
}
 
function sourceRows() {
  const register=readCsv(TRIAGE_REGISTER);
  const p0=register.rows.filter(row=>row.priority==='P0'&&row.workstream==='STRONG_FIELD_PRIMARY_EVIDENCE');
  if(p0.length!==10)throw new Error(`P0_SOURCE_COUNT:${p0.length}`);
  return p0;
}
 
function targetRows() {
  return sourceRows().map((row,index)=>({
    target_id:`P0DISC-TARGET-${String(index+1).padStart(3,'0')}`,
    triage_id:row.triage_id,
    detail_item_id:row.detail_item_id,
    source_authority_id:row.source_authority_id,
    source_row_id:row.source_row_id,
    source_occurrence_key:row.source_occurrence_key,
    conceptual_gap_key:row.conceptual_gap_key,
    object_type:row.object_type,
    object_id:row.object_id,
    priority:row.priority,
    workstream:row.workstream,
    current_status:row.current_status,
    required_evidence_or_next_action:row.required_evidence_or_next_action,
    claim_strength_ceiling:row.claim_strength_ceiling,
    formal_pool_effect:row.formal_pool_effect,
    evidence_strength_effect:row.evidence_strength_effect,
    discovery_effect:'DISCOVERY_ONLY_GAP_REMAINS_OPEN',
  }));
}
 
const querySpecs={
  'STRONG_FIELD:ROBOT-GAP-MARKET-001':[
    ['ZH','机器人 市场规模 出货量 2024 2025 IFR MIR GGII Omdia 官方报告','OFFICIAL_INDUSTRY_BODY_OR_REPORT_PUBLISHER','P0DISC-DOMAIN-001'],
    ['EN','robot market shipments 2024 2025 official report IFR Interact Analysis Omdia','OFFICIAL_INDUSTRY_BODY_OR_REPORT_PUBLISHER','P0DISC-DOMAIN-001'],
  ],
  'STRONG_FIELD:ROBOT-GAP-CHAIN-001':[
    ['ZH','人形机器人 供应链 定点 客户认证 合同 公告 招股书 官方','EXCHANGE_OR_REGULATOR_FILING|COMPANY_IR_OR_ANNUAL_REPORT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0DISC-DOMAIN-002'],
    ['EN','humanoid robot supplier contract customer certification filing official','EXCHANGE_OR_REGULATOR_FILING|COMPANY_IR_OR_ANNUAL_REPORT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0DISC-DOMAIN-002'],
  ],
  'STRONG_FIELD:ROBOT-GAP-COMPANY-001':[
    ['ZH','机器人 业务收入 分部 年报 公告 投资者关系 官方','EXCHANGE_OR_REGULATOR_FILING|COMPANY_IR_OR_ANNUAL_REPORT','P0DISC-DOMAIN-002'],
    ['EN','robotics revenue annual report segment filing investor relations official','EXCHANGE_OR_REGULATOR_FILING|COMPANY_IR_OR_ANNUAL_REPORT','P0DISC-DOMAIN-002'],
  ],
  'STRONG_FIELD:ROBOT-GAP-PRODUCT-001':[
    ['ZH','机器人 产品手册 价格 ASP BOM 产销 官方 产品页 招投标','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0DISC-DOMAIN-003'],
    ['EN','robot product datasheet price ASP BOM tender official','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','P0DISC-DOMAIN-003'],
  ],
  'STRONG_FIELD:ROBOT-GAP-MODEL-001':[
    ['ZH','机器人 大模型 技术报告 产品文档 部署 收费 官方','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|COMPANY_IR_OR_ANNUAL_REPORT','P0DISC-DOMAIN-003'],
    ['EN','robot foundation model technical report documentation deployment pricing official','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|COMPANY_IR_OR_ANNUAL_REPORT','P0DISC-DOMAIN-003'],
  ],
  'STRONG_FIELD:ROBOT-GAP-SUPPLY-001':[
    ['ZH','机器人 供应 定点 采购 合同 招投标 客户公告 供应商公告','OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE|EXCHANGE_OR_REGULATOR_FILING','P0DISC-DOMAIN-002'],
    ['EN','robot supplier nomination procurement contract tender customer announcement official','OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE|EXCHANGE_OR_REGULATOR_FILING','P0DISC-DOMAIN-002'],
  ],
  'STRONG_FIELD:ROBOT-GAP-CHAIN-002':[
    ['ZH','机器人 BOM 采购价 供应份额 订单 收入确认 官方','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE|OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT','P0DISC-DOMAIN-002'],
    ['EN','robot BOM procurement price supplier share order revenue filing official','EXCHANGE_OR_REGULATOR_FILING|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE|OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT','P0DISC-DOMAIN-002'],
  ],
};
 
function queryRows() {
  const keys=Object.keys(querySpecs).sort();
  const rows=[];
  for(const key of keys)for(const spec of querySpecs[key])rows.push({query_id:`P0DISC-QUERY-${String(rows.length+1).padStart(3,'0')}`,conceptual_gap_key:key,query_language:spec[0],query_text:spec[1],required_source_class:spec[2],domain_policy_id:spec[3],result_inspection_cap:'10',candidate_capture_cap:'3',secondary_source_policy:'SEARCH_LEAD_ONLY_NOT_ACCEPTED_AS_CANDIDATE',execution_order:String(rows.length+1)});
  return rows;
}
 
function gapRows() {
  const targets=targetRows(),queries=queryRows();
  const keys=[...new Set(targets.map(row=>row.conceptual_gap_key))].sort();
  return keys.map((key,index)=>{
    const occurrences=targets.filter(row=>row.conceptual_gap_key===key);
    const q=queries.filter(row=>row.conceptual_gap_key===key);
    return {gap_id:`P0DISC-GAP-${String(index+1).padStart(3,'0')}`,conceptual_gap_key:key,occurrence_count:String(occurrences.length),source_occurrence_keys:occurrences.map(row=>row.source_occurrence_key).sort().join('|'),object_ids:[...new Set(occurrences.map(row=>row.object_id))].sort().join('|'),source_classes_required:[...new Set(q.flatMap(row=>row.required_source_class.split('|')))].sort().join('|'),query_ids:q.map(row=>row.query_id).join('|'),candidate_cap:'5',gap_state_before:'OPEN_RETAINED_GAP',gap_state_after_discovery:'OPEN_RETAINED_GAP',claim_strength_ceiling:'PENDING_VERIFICATION_MAX_NO_UPGRADE',formal_pool_effect:'NO_AUTOMATIC_FORMAL_POOL_CHANGE',evidence_strength_effect:'NO_UPGRADE'};
  });
}
 
function policyRows() {
  const specs=[
    ['P0DISC-DOMAIN-001','DOMAIN_CLASS','OFFICIAL_INDUSTRY_BODY_OR_REPORT_PUBLISHER','publisher owns report/dataset and page identifies publication','aggregator or uncited reproduction','REJECT_SECONDARY_OR_UNATTRIBUTED'],
    ['P0DISC-DOMAIN-002','DOMAIN_CLASS','EXCHANGE_OR_REGULATOR_FILING|COMPANY_IR_OR_ANNUAL_REPORT|OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','issuer/regulator/customer/supplier identity is explicit','media paraphrase or anonymous supply-chain claim','REJECT_SECONDARY_OR_UNATTRIBUTED'],
    ['P0DISC-DOMAIN-003','DOMAIN_CLASS','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|COMPANY_IR_OR_ANNUAL_REPORT','official product/technical/IR publisher identity is explicit','dealer page or repost without official provenance','REJECT_SECONDARY_OR_UNATTRIBUTED'],
    ['P0DISC-POLICY-004','NETWORK','PUBLIC_WEB_READ_ONLY_NO_LOGIN_NO_PAYWALL_BYPASS','GET/search/open only after exact release','login, form submission, purchase, credential or paywall bypass','HELD_SCOPE_VIOLATION'],
    ['P0DISC-POLICY-005','SECONDARY_SOURCE','SEARCH_LEAD_ONLY_NOT_ACCEPTED_AS_CANDIDATE','may identify official source URL then discard secondary row','candidate capture from media/blog/broker research without primary origin','REJECT_SECONDARY'],
    ['P0DISC-POLICY-006','URL','CANONICAL_HTTP_OR_HTTPS','strip fragment and tracking params; lowercase host; trim trailing slash','non-http, tracking-only duplicate or unresolved redirect','REJECT_URL'],
    ['P0DISC-POLICY-007','SNIPPET','MAX_800_UTF8_BYTES_WITH_EXACT_HASH','minimal relevance fragment plus locator','full copyrighted document or unverifiable paraphrase','REJECT_SNIPPET'],
    ['P0DISC-POLICY-008','GAP_EFFECT','DISCOVERY_ONLY_GAP_REMAINS_OPEN','candidate requires independent source+semantic review','any closure, confirmation or output rewrite','FAIL_CLOSED'],
    ['P0DISC-POLICY-009','CLAIM_STRENGTH','PENDING_VERIFICATION_MAX_NO_UPGRADE','no discovery-stage upgrade','confirmed/strong/business conclusion','FAIL_CLOSED'],
    ['P0DISC-POLICY-010','FORMAL_POOL','NO_AUTOMATIC_FORMAL_POOL_CHANGE','no candidate changes company pool','formal-view approval or pool promotion','FAIL_CLOSED'],
    ['P0DISC-POLICY-011','EVIDENCE_STRENGTH','NO_UPGRADE','candidate registration only','evidence-map strength mutation','FAIL_CLOSED'],
    ['P0DISC-POLICY-012','CANDIDATE_CAP','MAX_5_PER_CONCEPTUAL_GAP_AND_3_PER_QUERY','retain only most direct official candidates','uncapped result accumulation','FAIL_CLOSED'],
  ];
  return specs.map((spec,index)=>({policy_id:spec[0],policy_type:spec[1],allowed_value:spec[2],required_condition:spec[3],forbidden_condition:spec[4],failure_disposition:spec[5]}));
}
 
function designSetRows() {
  const roles=['RUNTIME_GENERATOR','DESIGN_BUILDER','TARGET_AUTHORITY','CONCEPTUAL_GAP_AUTHORITY','QUERY_AUTHORITY','SOURCE_POLICY','RUNTIME_CONTRACT','OUTPUT_SCHEMA','EXECUTION_EXACT_SET','NEGATIVE_RESULTS','DESIGN_BASELINE','DESIGN_REVIEW_REQUEST','DESIGN_EXACT_SET','VALIDATION_LAST'];
  return DESIGN_PATHS.map((artifactPath,index)=>({artifact_id:`P0DISC-DESIGN-SET-${String(index+1).padStart(3,'0')}`,batch_id:DESIGN_BATCH,run_id:DESIGN_RUN,generation_order:String(index+1),artifact_path:artifactPath,artifact_role:roles[index],identity_policy:'EXACT_SHA256_BYTES_FILESYSTEM_MTIME_MS'}));
}
 
function predecessorErrors() {
  const errors=[];
  const entry=auditEntry(PREDECESSOR_AUDIT);
  if(!entry||entry.lines!==PREDECESSOR_ENTRY.lines||entry.bytes!==PREDECESSOR_ENTRY.bytes||entry.sha256!==PREDECESSOR_ENTRY.sha256)errors.push('PREDECESSOR_AUDIT_IDENTITY');
  const manifestBuffer=fs.readFileSync(abs(MANIFEST));
  if(manifestBuffer.length<MANIFEST_PREFIX.bytes||sha(manifestBuffer.subarray(0,MANIFEST_PREFIX.bytes))!==MANIFEST_PREFIX.sha256)errors.push('MANIFEST_PREFIX');
  const state=currentManifestState();
  if(state.errors.length)errors.push(...state.errors.map(code=>`MANIFEST:${code}`));
  const designRows=state.logicalRows.filter(row=>row.run_id===DESIGN_RUN).length;
  if(![0,14].includes(designRows)||state.physicalRecords!==MANIFEST_PREFIX.physicalRecords+designRows||state.logicalDataRows!==MANIFEST_PREFIX.logicalRows+designRows)errors.push(`MANIFEST_COUNTS:${state.physicalRecords}:${state.logicalDataRows}:${designRows}`);
  const summary=readCsv(TRIAGE_SUMMARY).rows;
  const p0=summary.find(row=>row.priority==='P0'&&row.workstream==='STRONG_FIELD_PRIMARY_EVIDENCE');
  if(!p0||`${p0.source_occurrences}|${p0.conceptual_gaps}|${p0.open_items}`!=='10|7|10')errors.push('TRIAGE_P0_SUMMARY');
  const targets=targetRows();
  if(targets.length!==10||new Set(targets.map(row=>row.source_occurrence_key)).size!==10||new Set(targets.map(row=>row.conceptual_gap_key)).size!==7)errors.push('TARGET_UNIVERSE');
  return [...new Set(errors)];
}
 
function protectedRows() {
  const inventory=readCsv(PROTECTED_INVENTORY).rows;
  if(inventory.length!==49)throw new Error(`PROTECTED_INVENTORY_COUNT:${inventory.length}`);
  return inventory.map(row=>{
    const identity=fileIdentity(row.artifact_path);
    return {path:row.artifact_path,...identity};
  });
}
 
function baselineRows() {
  const entry=auditEntry(PREDECESSOR_AUDIT);
  const rows=[
    {baseline_id:'P0DISC-DESIGN-BASE-001',identity_type:'NORMALIZED_PREDECESSOR_AUDIT_ENTRY',artifact_path:`${AUDIT_REPORT}#L${entry.start}-L${entry.end}`,rows:String(entry.lines),bytes:String(entry.bytes),sha256:entry.sha256,mtime:new Date(Math.trunc(fs.statSync(abs(AUDIT_REPORT)).mtimeMs)).toISOString(),required_state:'EXACT_TRIAGE_EXECUTION_PASS_ENTRY'},
    {baseline_id:'P0DISC-DESIGN-BASE-002',identity_type:'RAW_MANIFEST_PREFIX',artifact_path:`${MANIFEST}#FIRST${MANIFEST_PREFIX.bytes}BYTES`,rows:String(MANIFEST_PREFIX.logicalRows),bytes:String(MANIFEST_PREFIX.bytes),sha256:MANIFEST_PREFIX.sha256,mtime:new Date(Math.trunc(fs.statSync(abs(MANIFEST)).mtimeMs)).toISOString(),required_state:'APPEND_ONLY_PREFIX_EXACT_WITH_L1605_ENUMERATED'},
  ];
  for(const file of [TRIAGE_REGISTER,TRIAGE_SUMMARY,TRIAGE_APPLICATION,ANOMALY_AUTHORITY,PROTECTED_INVENTORY,SCRIPT,BUILDER,TARGET_AUTHORITY,GAP_AUTHORITY,QUERY_AUTHORITY,SOURCE_POLICY,CONTRACT,SCHEMA,EXEC_SET,NEG_RESULTS]){
    const identity=fileIdentity(file);
    rows.push({baseline_id:`P0DISC-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'PHYSICAL_FILE',artifact_path:file,rows:String(identity.rows),bytes:String(identity.bytes),sha256:identity.sha256,mtime:identity.mtime,required_state:'EXACT_FROZEN_DESIGN_INPUT'});
  }
  for(const item of protectedRows())rows.push({baseline_id:`P0DISC-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'PROTECTED_OUTPUT_CURRENT_IDENTITY',artifact_path:item.path,rows:String(item.lines),bytes:String(item.bytes),sha256:item.sha256,mtime:item.mtime,required_state:'NO_MUTATION'});
  return rows;
}
 
function requestText() {
  return `# P0 primary-source discovery detailed-design review request\n\ncase_id=${CASE_ID}\naction_id=NEXT-ROBOT-040-DESIGN-001\npredecessor_audit=${PREDECESSOR_AUDIT}\ndesign_batch=${DESIGN_BATCH}\ndesign_run=${DESIGN_RUN}\nrequested_release_audit=${RELEASE_AUDIT}\nrequested_execution_batch=${EXEC_BATCH}\nrequested_execution_run=${EXEC_RUN}\ntargets=10 P0 source occurrences\nconceptual_gaps=7\nqueries=14 exact bilingual query rows\nnetwork_execution_scope=PUBLIC_WEB_PRIMARY_SOURCE_DISCOVERY_ONLY\nsource_policy=OFFICIAL_PRIMARY_SOURCE_CLASSES_ONLY\nsecondary_policy=SEARCH_LEAD_ONLY_NOT_ACCEPTED_AS_CANDIDATE\nexecution_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\ncurrent_network_execution=NO\nproposed_execution_outputs=0\nproposed_execution_manifest_rows=0\n\nIf and only if this design independently passes, append the exact structured release lines required by the runtime and release only the named discovery batch/run. Execution must stop after candidate registration and independent execution/output review; no candidate may close a gap or upgrade a claim.\n`;
}
 
function exactFileRows(file,expected,columns,code) {
  if(!fs.existsSync(abs(file)))return[`${code}_MISSING`];
  const parsed=readCsv(file),errors=[];
  if(parsed.header.join('|')!==columns.join('|')||parsed.rows.length!==expected.length)errors.push(`${code}_SCHEMA_COUNT`);
  for(let index=0;index<expected.length;index++)if(!parsed.rows[index]||columns.some(column=>parsed.rows[index][column]!==String(expected[index][column]??''))){errors.push(`${code}_ROW:${index+1}`);break;}
  return errors;
}
 
function designManifestRows() {
  return currentManifestState().logicalRows.filter(row=>row.run_id===DESIGN_RUN);
}
 
function designManifestErrors({required=false}={}) {
  const rows=designManifestRows(),errors=[];
  if(required&&rows.length!==14)errors.push(`DESIGN_MANIFEST_ROWS:${rows.length}`);
  if(!required&&![0,14].includes(rows.length))errors.push(`DESIGN_MANIFEST_ROWS:${rows.length}`);
  if(rows.length&&rows.map(row=>row.artifact_path).join('|')!==DESIGN_PATHS.join('|'))errors.push('DESIGN_MANIFEST_PATH_ORDER');
  for(const row of rows){
    if(row.case_id!==CASE_ID||row.batch_id!==DESIGN_BATCH||!fs.existsSync(abs(row.artifact_path))){errors.push(`DESIGN_MANIFEST_SCOPE:${row.artifact_path}`);continue;}
    const identity=fileIdentity(row.artifact_path);
    if(row.sha256!==identity.sha256||row.bytes!==String(identity.bytes)||Date.parse(row.mtime)!==identity.mtimeMs)errors.push(`DESIGN_MANIFEST_IDENTITY:${row.artifact_path}`);
  }
  return errors;
}
 
function packageErrors({requireManifest=false}={}) {
  const errors=[...predecessorErrors()];
  errors.push(...exactFileRows(TARGET_AUTHORITY,targetRows(),TARGET_COLUMNS,'TARGETS'));
  errors.push(...exactFileRows(GAP_AUTHORITY,gapRows(),GAP_COLUMNS,'GAPS'));
  errors.push(...exactFileRows(QUERY_AUTHORITY,queryRows(),QUERY_COLUMNS,'QUERIES'));
  errors.push(...exactFileRows(SOURCE_POLICY,policyRows(),POLICY_COLUMNS,'POLICIES'));
  errors.push(...exactFileRows(CONTRACT,contractRows(),CONTRACT_COLUMNS,'CONTRACTS'));
  errors.push(...exactFileRows(SCHEMA,schemaRows(),SCHEMA_COLUMNS,'SCHEMAS'));
  errors.push(...exactFileRows(EXEC_SET,executionSetRows(),EXEC_SET_COLUMNS,'EXEC_SET'));
  errors.push(...exactFileRows(DESIGN_SET,designSetRows(),DESIGN_SET_COLUMNS,'DESIGN_SET'));
  errors.push(...designManifestErrors({required:requireManifest}));
  const neg=readCsv(NEG_RESULTS);
  if(neg.header.join('|')!==NEG_COLUMNS.join('|')||neg.rows.length!==20||neg.rows.some(row=>row.result!=='PASS'))errors.push('NEGATIVE_RESULTS');
  const protectedCurrent=protectedRows();
  if(protectedCurrent.length!==49)errors.push('PROTECTED49_COUNT');
  const outputs=[EXEC_BASELINE,QUERY_LEDGER,CANDIDATE_REGISTER,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
  if(outputs.some(file=>fs.existsSync(abs(file))))errors.push('PROPOSED_EXECUTION_OUTPUTS');
  if(currentManifestState().logicalRows.some(row=>row.run_id===EXEC_RUN))errors.push('PROPOSED_EXECUTION_MANIFEST_ROWS');
  for(const file of [SCRIPT,BUILDER])if(spawnSync(process.execPath,['--check',file],{cwd:ROOT}).status!==0)errors.push(`NODE_CHECK:${file}`);
  const preview=spawnSync(process.execPath,[SCRIPT,'--preview'],{cwd:ROOT,encoding:'utf8'});
  if(preview.status!==0||!preview.stdout.includes('"errors": []'))errors.push('RUNTIME_PREVIEW');
  const tests=spawnSync(process.execPath,[SCRIPT,'--self-test'],{cwd:ROOT,encoding:'utf8'});
  if(tests.status!==0)errors.push('RUNTIME_SELF_TEST');
  const runtimeInputs=prewriteErrors({requireRelease:false,requireStaging:false}).filter(code=>!code.startsWith('DESIGN_MANIFEST_ROWS:'));
  errors.push(...runtimeInputs.map(code=>`RUNTIME_INPUT:${code}`));
  return [...new Set(errors)];
}
 
function validationRows() {
  const state=currentManifestState(),entry=auditEntry(PREDECESSOR_AUDIT),negative=readCsv(NEG_RESULTS).rows;
  const checks=[
    ['PREDECESSOR_AUDIT',`${PREDECESSOR_ENTRY.lines}|${PREDECESSOR_ENTRY.bytes}|${PREDECESSOR_ENTRY.sha256}`,`${entry.lines}|${entry.bytes}|${entry.sha256}`],
    ['MANIFEST_PREFIX',`${MANIFEST_PREFIX.physicalRecords}|${MANIFEST_PREFIX.logicalRows}|${MANIFEST_PREFIX.bytes}|${MANIFEST_PREFIX.sha256}`,`${state.physicalRecords}|${state.logicalDataRows}|${MANIFEST_PREFIX.bytes}|${MANIFEST_PREFIX.sha256}`],
    ['P0_TARGETS','10',String(targetRows().length)],
    ['P0_CONCEPTUAL_GAPS','7',String(gapRows().length)],
    ['QUERY_AUTHORITY','14',String(queryRows().length)],
    ['SOURCE_POLICIES','12',String(policyRows().length)],
    ['RUNTIME_CONTRACTS','32',String(contractRows().length)],
    ['OUTPUT_SCHEMAS','8',String(schemaRows().length)],
    ['EXECUTION_EXACT_SET','16',String(executionSetRows().length)],
    ['NEGATIVE_TESTS','20|20_PASS',`${negative.length}|${negative.filter(row=>row.result==='PASS').length}_PASS`],
    ['PROTECTED_OUTPUTS','49',String(protectedRows().length)],
    ['DESIGN_EXACT_SET','14',String(designSetRows().length)],
    ['PROPOSED_EXECUTION_OUTPUTS','0',String([EXEC_BASELINE,QUERY_LEDGER,CANDIDATE_REGISTER,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION].filter(file=>fs.existsSync(abs(file))).length)],
    ['PROPOSED_EXECUTION_MANIFEST_ROWS','0',String(currentManifestState().logicalRows.filter(row=>row.run_id===EXEC_RUN).length)],
    ['CURRENT_NETWORK_EXECUTION','NO','NO'],
    ['GAP_EFFECT','DISCOVERY_ONLY_GAP_REMAINS_OPEN','DISCOVERY_ONLY_GAP_REMAINS_OPEN'],
    ['EVIDENCE_STRENGTH','NO_UPGRADE','NO_UPGRADE'],
  ];
  const rows=checks.map((item,index)=>({check_id:`P0DISC-DESIGN-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:'P0_PRIMARY_SOURCE_DISCOVERY_DESIGN'}));
  rows.push({check_id:'P0DISC-DESIGN-VAL-018',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identity checked after freeze'});
  return rows;
}
 
function build() {
  const base=predecessorErrors();
  if(base.length)throw new Error(`BASE:${base.join('|')}`);
  for(const file of DESIGN_PATHS.slice(2))if(fs.existsSync(abs(file)))throw new Error(`TARGET_EXISTS:${file}`);
  writeText(TARGET_AUTHORITY,serializeCsv(targetRows(),TARGET_COLUMNS));
  writeText(GAP_AUTHORITY,serializeCsv(gapRows(),GAP_COLUMNS));
  writeText(QUERY_AUTHORITY,serializeCsv(queryRows(),QUERY_COLUMNS));
  writeText(SOURCE_POLICY,serializeCsv(policyRows(),POLICY_COLUMNS));
  writeText(CONTRACT,serializeCsv(contractRows(),CONTRACT_COLUMNS));
  writeText(SCHEMA,serializeCsv(schemaRows(),SCHEMA_COLUMNS));
  writeText(EXEC_SET,serializeCsv(executionSetRows(),EXEC_SET_COLUMNS));
  writeText(NEG_RESULTS,serializeCsv(negativeRows(),NEG_COLUMNS));
  writeText(DESIGN_BASELINE,serializeCsv(baselineRows(),BASELINE_COLUMNS));
  writeText(DESIGN_REQUEST,requestText());
  writeText(DESIGN_SET,serializeCsv(designSetRows(),DESIGN_SET_COLUMNS));
  writeText(DESIGN_VALIDATION,serializeCsv(validationRows(),VALIDATION_COLUMNS));
  const errors=packageErrors();
  if(errors.length)throw new Error(`PACKAGE:${errors.join('|')}`);
  return {status:'P0_PRIMARY_SOURCE_DISCOVERY_DESIGN_BUILT_PENDING_INDEPENDENT_REVIEW',targets:10,gaps:7,queries:14,negative_tests:20,design_artifacts:14,execution_outputs:0,execution_manifest_rows:0};
}
 
function designManifestCandidateRows() {
  return DESIGN_PATHS.map(file=>{const identity=fileIdentity(file);return{case_id:CASE_ID,run_id:DESIGN_RUN,batch_id:DESIGN_BATCH,artifact_path:file,sha256:identity.sha256,bytes:String(identity.bytes),mtime:identity.mtime};});
}
 
function appendDesignManifest() {
  const errors=packageErrors();
  if(errors.length)throw new Error(`PACKAGE_PREAPPEND:${errors.join('|')}`);
  const before=fs.readFileSync(abs(MANIFEST));
  if(before.length!==MANIFEST_PREFIX.bytes||sha(before)!==MANIFEST_PREFIX.sha256)throw new Error('MANIFEST_PREAPPEND_IDENTITY');
  const rows=designManifestCandidateRows();
  const candidate=Buffer.concat([before,Buffer.from(serializeManifestDataRows(rows),'utf8')]);
  const state=validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:MANIFEST_PREFIX.bytes,sha256:MANIFEST_PREFIX.sha256},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:DESIGN_RUN,expectedPhysicalDelta:14});
  if(state.errors.length)throw new Error(`MANIFEST_CANDIDATE:${state.errors.join('|')}`);
  fs.writeFileSync(abs(MANIFEST),candidate);
  const post=packageErrors({requireManifest:true});
  if(post.length){fs.writeFileSync(abs(MANIFEST),before);throw new Error(`MANIFEST_POST:${post.join('|')}`);}
  return {status:'DESIGN_MANIFEST_APPENDED_DATA_ROWS_ONLY',rows:14,manifest_bytes:candidate.length,manifest_sha256:sha(candidate),physical_records:state.physicalRecords,logical_rows:state.logicalDataRows,header_shapes:state.headerShapeCount};
}
 
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
  const mode=process.argv[2]??'--validate-design';
  if(mode==='--build-design')console.log(JSON.stringify(build(),null,2));
  else if(mode==='--append-design-manifest')console.log(JSON.stringify(appendDesignManifest(),null,2));
  else if(mode==='--validate-design'){const errors=packageErrors();console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_DESIGN_PACKAGE',errors},null,2));if(errors.length)process.exitCode=1;}
  else if(mode==='--validate-package-manifest'){const errors=packageErrors({requireManifest:true});console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_DESIGN_PACKAGE_AND_MANIFEST',errors},null,2));if(errors.length)process.exitCode=1;}
  else throw new Error(`UNKNOWN_MODE:${mode}`);
}