Cai
2026-08-24 156ea25b402479f0abc54c558bbf87f9eaaa0422
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
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import os from 'node:os';
import {pathToFileURL} from 'node:url';
 
const ROOT=process.cwd();
const BASE='ana-data/cases/机器人案例/ANA-ROBOT-INDUSTRY-001';
const SCRIPT='dev/ana-dev/detail_strengthening_gap_triage_runtime_repair001_20260730.mjs';
const BUILDER='dev/ana-dev/detail_strengthening_gap_triage_design_repair001_20260730.mjs';
const SOURCE_AUTH=`${BASE}/evidence/detail_strengthening_gap_source_authority_20260730.csv`;
const ITEM_AUTH=`${BASE}/evidence/detail_strengthening_gap_item_authority_20260730.csv`;
const CONTRACT=`${BASE}/evidence/detail_strengthening_gap_triage_runtime_contract_repair001_20260730.csv`;
const SCHEMA=`${BASE}/evidence/detail_strengthening_gap_triage_output_schema_authority_repair001_20260730.csv`;
const EXEC_SET=`${BASE}/manifest/detail_strengthening_gap_triage_execution_artifact_set_repair001_20260730.csv`;
const MANIFEST=`${BASE}/manifest/artifact_manifest.csv`;
const AUDIT_REPORT='ana-doc/机器人案例/案例审计报告.md';
const EXEC_BASELINE=`${BASE}/evidence/detail_strengthening_gap_triage_execution_baseline_repair001_20260730.csv`;
const REGISTER=`${BASE}/outputs/数据表/robot_detail_gap_triage_register_v01_repair001_20260730.csv`;
const SUMMARY=`${BASE}/outputs/数据表/robot_detail_gap_workstream_summary_v01_repair001_20260730.csv`;
const APPLICATION=`${BASE}/evidence/detail_strengthening_gap_triage_application_repair001_20260730.csv`;
const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_gap_triage_execution_repair001_20260730.md`;
const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_gap_triage_execution_validation_repair001_20260730.csv`;
const NEG_RESULTS=`${BASE}/evidence/detail_strengthening_gap_triage_runtime_negative_results_repair001_20260730.csv`;
const REPAIR_BASELINE=`${BASE}/evidence/detail_strengthening_gap_triage_design_baseline_repair001_20260730.csv`;
const REPAIR_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_gap_triage_design_repair001_20260730.md`;
const REPAIR_DESIGN_SET=`${BASE}/manifest/detail_strengthening_gap_triage_design_artifact_set_repair001_20260730.csv`;
const REPAIR_VALIDATION=`${BASE}/manifest/detail_strengthening_gap_triage_design_validation_repair001_20260730.csv`;
const EXEC_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-001';
const EXEC_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-001';
const DESIGN_REPAIR_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-DESIGN-REPAIR-001';
const DESIGN_REPAIR_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-DESIGN-REPAIR-001';
const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-DESIGN-REPAIR001-REREVIEW-001';
const EXEC_TOKEN='EXECUTE_DETAIL_GAP_TRIAGE_REPAIR001';
const MANIFEST_PREFIX_BYTES=564899;
const MANIFEST_PREFIX_SHA='d11d5c7f2e5968d71514fa57b09a5ad6627fb25f30354e1273dd520d3f08c8be';
const SOURCE_AUTH_ID={bytes:2347,sha256:'9c9afaab76b57f015b9b23f0e9d425012c586fec6e762b9563d9026f9f299fc2'};
const ITEM_AUTH_ID={bytes:2494340,sha256:'b6c292f5dbc3b0766884b66ea03716877f2e7c3e10f73d9b561fe32f5798dbee'};
const EXEC_PATHS=[SCRIPT,SOURCE_AUTH,ITEM_AUTH,CONTRACT,SCHEMA,EXEC_BASELINE,REGISTER,SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
const DESIGN_REPAIR_PATHS=[SCRIPT,BUILDER,CONTRACT,SCHEMA,EXEC_SET,NEG_RESULTS,REPAIR_BASELINE,REPAIR_REQUEST,REPAIR_DESIGN_SET,REPAIR_VALIDATION];
const GENERATED=[EXEC_BASELINE,REGISTER,SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
const REGISTER_COLUMNS=['triage_id','detail_item_id','source_authority_id','source_row_id','source_occurrence_key','conceptual_gap_key','object_type','object_id','priority','workstream','current_status','claim_strength_ceiling','formal_pool_effect','evidence_strength_effect','next_stage','required_evidence_or_next_action','review_status'];
const SUMMARY_COLUMNS=['summary_id','priority','workstream','source_occurrences','conceptual_gaps','open_items','claim_strength_ceiling','formal_pool_effect','evidence_strength_effect','status'];
const APPLICATION_COLUMNS=['application_id','detail_item_id','triage_id','source_occurrence_key','conceptual_gap_key','action','result_status','output_artifact','review_status'];
const BASELINE_COLUMNS=['baseline_id','identity_type','artifact_path','rows','bytes','sha256','mtime','checked_at','required_state'];
const VALIDATION_COLUMNS=['check_id','check_description','expected','actual','status','evidence'];
const MANIFEST_COLUMNS=['case_id','run_id','batch_id','artifact_path','sha256','bytes','mtime'];
const abs=(p,root=ROOT)=>path.join(root,...p.split('/'));
const sha=b=>crypto.createHash('sha256').update(b).digest('hex');
const norm=b=>b.toString('utf8').replace(/^\uFEFF/,'').replace(/\r\n/g,'\n').replace(/\r/g,'\n');
const lineCount=b=>{const t=norm(b);return t.split('\n').length-(t.endsWith('\n')?1:0);};
const fid=(p,root=ROOT)=>{const b=fs.readFileSync(abs(p,root)),s=fs.statSync(abs(p,root));return{bytes:b.length,lines:lineCount(b),sha256:sha(b),mtime:new Date(Math.trunc(s.mtimeMs)).toISOString(),mtimeMs:Math.trunc(s.mtimeMs)};};
const clone=x=>JSON.parse(JSON.stringify(x));
 
function parseCsv(text){text=text.replace(/^\uFEFF/,'');const m=[];let r=[],c='',q=false;for(let i=0;i<text.length;i++){const x=text[i];if(q){if(x==='"'&&text[i+1]==='"'){c+='"';i++;}else if(x==='"')q=false;else c+=x;}else if(x==='"')q=true;else if(x===','){r.push(c);c='';}else if(x==='\n'){r.push(c.replace(/\r$/,''));m.push(r);r=[];c='';}else c+=x;}if(c.length||r.length){r.push(c);m.push(r);}const header=m.shift()??[];return{header,rows:m.filter(x=>x.some(v=>v!=='')).map(x=>Object.fromEntries(header.map((h,i)=>[h,x[i]??''])))};}
function csv(rows,columns){const esc=v=>'"'+String(v??'').replace(/"/g,'""')+'"';return columns.map(esc).join(',')+'\n'+rows.map(r=>columns.map(c=>esc(r[c])).join(',')).join('\n')+'\n';}
function rowHash(header,row){return sha(Buffer.from(header.map(k=>`${k}=${row[k]??''}`).join('\x1f'),'utf8'));}
function writeText(p,text,root=ROOT){fs.mkdirSync(path.dirname(abs(p,root)),{recursive:true});fs.writeFileSync(abs(p,root),text,'utf8');}
 
export function expectedContractRows(){const x=[
['RUNTIME','invocation',`node ${SCRIPT} --execute --token=${EXEC_TOKEN}`],['RUNTIME','release_audit',RELEASE_AUDIT],['RUNTIME','release_markers',`${EXEC_BATCH}|${EXEC_RUN}|EXPLICITLY_RELEASED`],['RUNTIME','prewrite_existing_targets','0'],['RUNTIME','design_repair_manifest_rows','10'],['RUNTIME','execution_exact_set_rows','11'],['RUNTIME','runtime_baseline_first_generated','YES'],['RUNTIME','validation_last_generated','YES'],['RUNTIME','partial_failure_cleanup','ALL_SIX_GENERATED_ABSENT_AND_MANIFEST_EXACT_BEFORE'],['MANIFEST','base_prefix_rows','1583'],['MANIFEST','base_prefix_bytes',String(MANIFEST_PREFIX_BYTES)],['MANIFEST','base_prefix_sha256',MANIFEST_PREFIX_SHA],['MANIFEST','candidate_rows','11'],['MANIFEST','seven_fields',MANIFEST_COLUMNS.join('|')],['MANIFEST','postcommit_oracle','EXACT_PATH_SCOPE_SHA_BYTES_FILESYSTEM_MTIME_MS'],['OUTPUT','register_rows','2964'],['OUTPUT','register_pk','triage_id|detail_item_id unique'],['OUTPUT','summary_rows','7'],['OUTPUT','summary_counts','source_occurrences2964|conceptual_gaps2961'],['OUTPUT','application_rows','2964'],['OUTPUT','application_mapping','one_per_detail_item'],['OUTPUT','serialization','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF'],['BOUNDARY','current_status','OPEN_RETAINED_GAP'],['BOUNDARY','claim_strength','PENDING_VERIFICATION_MAX_NO_UPGRADE'],['BOUNDARY','formal_pool','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],['BOUNDARY','evidence_strength','NO_UPGRADE'],['BOUNDARY','execution_effect','TRIAGE_ONLY_NO_GAP_CLOSURE'],['DEDUP','source_occurrence','one_per_2964_authority_rows'],['DEDUP','conceptual_gap','only_same_gap_id_across_GLOBAL_SOURCE_GAPS_and_THREEPIECE_RETAINED_GAPS'],['DEDUP','duplicate_strong_gap_ids','ROBOT-GAP-MARKET-001|ROBOT-GAP-COMPANY-001|ROBOT-GAP-PRODUCT-001'],['SECURITY','network_database_qmt','0|0|0'],['DOWNSTREAM','evidence_supplementation','SEPARATE_DESIGN_AND_RELEASE_REQUIRED']];return x.map((r,i)=>({contract_id:`DSGR1-CON-${String(i+1).padStart(3,'0')}`,scope:r[0],field:r[1],required_value_or_rule:r[2],violation_status:'FAIL_CLOSED'}));}
export function expectedSchemaRows(){const x=[
['RUNTIME_BASELINE',EXEC_BASELINE,BASELINE_COLUMNS.join('|'),'baseline_id','dynamic_9_or_more','rows are runtime input identities; first generated artifact'],
['TRIAGE_REGISTER',REGISTER,REGISTER_COLUMNS.join('|'),'triage_id','2964','exact deterministic projection from frozen item authority'],
['WORKSTREAM_SUMMARY',SUMMARY,SUMMARY_COLUMNS.join('|'),'summary_id','7','group by priority+workstream; occurrence and conceptual counts distinct'],
['APPLICATION_LEDGER',APPLICATION,APPLICATION_COLUMNS.join('|'),'application_id','2964','one exact row per detail_item_id'],
['EXECUTION_REQUEST',EXEC_REQUEST,'MARKDOWN_REQUIRED_MARKERS','NA','1_document','exact audit/batch/run/count/boundary markers'],
['EXECUTION_VALIDATION',EXEC_VALIDATION,VALIDATION_COLUMNS.join('|'),'check_id','18','validation last; PASS17 INFO1 FAIL0']];return x.map((r,i)=>({schema_id:`DSGR1-SCHEMA-${String(i+1).padStart(3,'0')}`,artifact_role:r[0],artifact_path:r[1],column_order:r[2],primary_key:r[3],row_count_rule:r[4],serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:r[5],required_boundary:'NO_AUTOMATIC_FORMAL_POOL_CHANGE|NO_UPGRADE|NO_GAP_CLOSURE'}));}
export function expectedExecutionSetRows(){const roles=['FROZEN_RUNTIME_GENERATOR','FROZEN_SOURCE_AUTHORITY','FROZEN_ITEM_AUTHORITY','FROZEN_RUNTIME_CONTRACT','FROZEN_OUTPUT_SCHEMA_AUTHORITY','RUNTIME_BASELINE_FIRST','VERSIONED_TRIAGE_REGISTER','WORKSTREAM_SUMMARY','APPLICATION_LEDGER','EXECUTION_REVIEW_REQUEST','VALIDATION_LAST'];return EXEC_PATHS.map((p,i)=>({artifact_id:`DSGR1-EXEC-SET-${String(i+1).padStart(3,'0')}`,batch_id:EXEC_BATCH,run_id:EXEC_RUN,generation_order:String(i+1),artifact_path:p,artifact_role:roles[i],identity_policy:'EXACT_SHA256_BYTES_FILESYSTEM_MTIME_MS'}));}
 
function strictFileIdentity(p,expected,root=ROOT){if(!fs.existsSync(abs(p,root)))return false;const z=fid(p,root);return z.bytes===expected.bytes&&z.sha256===expected.sha256;}
function validateSourceAndItems(root=ROOT){const e=[];if(!strictFileIdentity(SOURCE_AUTH,SOURCE_AUTH_ID,root))e.push('SOURCE_AUTHORITY_FILE_IDENTITY');if(!strictFileIdentity(ITEM_AUTH,ITEM_AUTH_ID,root))e.push('ITEM_AUTHORITY_FILE_IDENTITY');if(e.length)return e;const source=parseCsv(fs.readFileSync(abs(SOURCE_AUTH,root),'utf8')).rows,items=parseCsv(fs.readFileSync(abs(ITEM_AUTH,root),'utf8')).rows;if(source.length!==6)e.push('SOURCE_AUTHORITY_ROWS');if(items.length!==2964||new Set(items.map(r=>r.detail_item_id)).size!==2964)e.push('ITEM_AUTHORITY_ROWS_OR_PK');const itemBySource=new Map();for(const r of items){if(!itemBySource.has(r.source_authority_id))itemBySource.set(r.source_authority_id,[]);itemBySource.get(r.source_authority_id).push(r);if(r.current_status!=='OPEN_RETAINED_GAP'||r.claim_strength_ceiling!=='PENDING_VERIFICATION_MAX_NO_UPGRADE'||r.formal_pool_effect!=='NO_AUTOMATIC_FORMAL_POOL_CHANGE'||r.evidence_strength_effect!=='NO_UPGRADE')e.push(`ITEM_BOUNDARY:${r.detail_item_id}`);}for(const s of source){if(!fs.existsSync(abs(s.source_path,root))){e.push(`SOURCE_PHYSICAL_MISSING:${s.source_authority_id}`);continue;}const z=fid(s.source_path,root);if(s.sha256!==z.sha256||s.bytes!==String(z.bytes)||s.lines!==String(z.lines)||Date.parse(s.mtime)!==z.mtimeMs)e.push(`SOURCE_PHYSICAL_IDENTITY:${s.source_authority_id}`);const parsed=parseCsv(fs.readFileSync(abs(s.source_path,root),'utf8'));let rows=parsed.rows;if(s.selection_rule==='formal_output_status=NOT_APPROVED')rows=rows.filter(r=>r.formal_output_status==='NOT_APPROVED');const map=new Map(rows.map(r=>[r[s.source_pk],rowHash(parsed.header,r)])),actual=itemBySource.get(s.source_authority_id)??[];if(actual.length!==rows.length)e.push(`ITEM_SOURCE_COUNT:${s.source_authority_id}`);for(const r of actual)if(map.get(r.source_row_id)!==r.source_row_sha256)e.push(`ITEM_SOURCE_HASH:${r.detail_item_id}`);}return[...new Set(e)];}
function exactTableErrors(p,expected,columns,code,root=ROOT){if(!fs.existsSync(abs(p,root)))return[`${code}_MISSING`];const parsed=parseCsv(fs.readFileSync(abs(p,root),'utf8')),e=[];if(parsed.header.join('|')!==columns.join('|')||parsed.rows.length!==expected.length)e.push(`${code}_SCHEMA_COUNT`);for(let i=0;i<expected.length;i++)if(!parsed.rows[i]||columns.some(k=>parsed.rows[i][k]!==expected[i][k])){e.push(`${code}_ROW:${i+1}`);break;}return e;}
function manifestBaseErrors(root=ROOT){const p=abs(MANIFEST,root);if(!fs.existsSync(p))return['MANIFEST_MISSING'];const b=fs.readFileSync(p);return b.length>=MANIFEST_PREFIX_BYTES&&sha(b.subarray(0,MANIFEST_PREFIX_BYTES))===MANIFEST_PREFIX_SHA?[]:['MANIFEST_1583_PREFIX'];}
function designRunManifestErrors(root=ROOT){const rows=parseCsv(fs.readFileSync(abs(MANIFEST,root),'utf8')).rows.filter(r=>r.run_id===DESIGN_REPAIR_RUN),e=[];if(rows.length!==10||new Set(rows.map(r=>r.artifact_path)).size!==10)e.push(`DESIGN_REPAIR_MANIFEST_ROWS:${rows.length}`);if(rows.map(r=>r.artifact_path).sort().join('|')!==[...DESIGN_REPAIR_PATHS].sort().join('|'))e.push('DESIGN_REPAIR_MANIFEST_PATH_SET');for(const r of rows){if(r.case_id!=='ANA-ROBOT-INDUSTRY-001'||r.batch_id!==DESIGN_REPAIR_BATCH||!fs.existsSync(abs(r.artifact_path,root))){e.push(`DESIGN_REPAIR_MANIFEST_SCOPE:${r.artifact_path}`);continue;}const z=fid(r.artifact_path,root);if(r.sha256!==z.sha256||r.bytes!==String(z.bytes)||Date.parse(r.mtime)!==z.mtimeMs)e.push(`DESIGN_REPAIR_MANIFEST_IDENTITY:${r.artifact_path}`);}return e;}
function releaseInfo(root=ROOT){const report=norm(fs.readFileSync(abs(AUDIT_REPORT,root))).split('\n'),idx=report.findIndex(x=>x.startsWith('### ')&&x.includes(RELEASE_AUDIT));if(idx<0)return{errors:['RELEASE_AUDIT_MISSING']};let end=report.length;for(let i=idx+1;i<report.length;i++)if(report[i].startsWith('### ')){end=i;break;}const text=report.slice(idx,end).join('\n')+'\n',b=Buffer.from(text),errors=[];for(const m of[RELEASE_AUDIT,EXEC_BATCH,EXEC_RUN,'EXPLICITLY_RELEASED'])if(!text.includes(m))errors.push(`RELEASE_MARKER_MISSING:${m}`);if(!/PASS/.test(text))errors.push('RELEASE_PASS_LITERAL_MISSING');return{errors,start:idx+1,end,lines:end-idx,bytes:b.length,sha256:sha(b),text};}
function existingTargetErrors(root=ROOT){return GENERATED.filter(p=>fs.existsSync(abs(p,root))).map(p=>`GENERATED_TARGET_EXISTS:${p}`);}
export function validatePrewrite({root=ROOT,token='',requireRelease=true}={}){const e=[];if(token!==EXEC_TOKEN)e.push('EXECUTION_TOKEN_MISMATCH');e.push(...manifestBaseErrors(root),...validateSourceAndItems(root),...exactTableErrors(CONTRACT,expectedContractRows(),['contract_id','scope','field','required_value_or_rule','violation_status'],'CONTRACT',root),...exactTableErrors(SCHEMA,expectedSchemaRows(),['schema_id','artifact_role','artifact_path','column_order','primary_key','row_count_rule','serialization','derivation_rule','required_boundary'],'SCHEMA',root),...exactTableErrors(EXEC_SET,expectedExecutionSetRows(),['artifact_id','batch_id','run_id','generation_order','artifact_path','artifact_role','identity_policy'],'EXEC_SET',root),...designRunManifestErrors(root),...existingTargetErrors(root));if(requireRelease)e.push(...releaseInfo(root).errors);const manifest=parseCsv(fs.readFileSync(abs(MANIFEST,root),'utf8')).rows;if(manifest.some(r=>r.run_id===EXEC_RUN))e.push('EXECUTION_MANIFEST_ROWS_ALREADY_EXIST');return[...new Set(e)];}
 
function conceptualKey(r){if(['GLOBAL_SOURCE_GAPS','THREEPIECE_RETAINED_GAPS'].includes(r.source_name))return`STRONG_FIELD:${r.source_row_id}`;return`OCCURRENCE:${r.detail_item_id}`;}
export function deriveBundle(root=ROOT){const items=parseCsv(fs.readFileSync(abs(ITEM_AUTH,root),'utf8')).rows;const register=items.map(r=>({triage_id:'TRIAGE-'+sha(Buffer.from(r.detail_item_id)).slice(0,24),detail_item_id:r.detail_item_id,source_authority_id:r.source_authority_id,source_row_id:r.source_row_id,source_occurrence_key:`${r.source_authority_id}:${r.source_row_id}`,conceptual_gap_key:conceptualKey(r),object_type:r.object_type,object_id:r.object_id,priority:r.priority,workstream:r.workstream,current_status:r.current_status,claim_strength_ceiling:r.claim_strength_ceiling,formal_pool_effect:r.formal_pool_effect,evidence_strength_effect:r.evidence_strength_effect,next_stage:r.priority==='P0'?'PRIMARY_SOURCE_ACQUISITION_DESIGN':'DETAIL_EVIDENCE_WORKSTREAM_DESIGN',required_evidence_or_next_action:r.required_evidence_or_next_action,review_status:'PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW'}));const groups=new Map();for(const r of register){const k=`${r.priority}|${r.workstream}`;if(!groups.has(k))groups.set(k,[]);groups.get(k).push(r);}const summary=[...groups.entries()].sort(([a],[b])=>a.localeCompare(b)).map(([k,rows],i)=>{const[p,w]=k.split('|');return{summary_id:`DSG-SUM-${String(i+1).padStart(3,'0')}`,priority:p,workstream:w,source_occurrences:String(rows.length),conceptual_gaps:String(new Set(rows.map(r=>r.conceptual_gap_key)).size),open_items:String(rows.filter(r=>r.current_status==='OPEN_RETAINED_GAP').length),claim_strength_ceiling:'PENDING_VERIFICATION_MAX_NO_UPGRADE',formal_pool_effect:'NO_AUTOMATIC_FORMAL_POOL_CHANGE',evidence_strength_effect:'NO_UPGRADE',status:'TRIAGED_NOT_CLOSED'};});const application=register.map(r=>({application_id:'DSG-APP-'+sha(Buffer.from(r.detail_item_id)).slice(0,24),detail_item_id:r.detail_item_id,triage_id:r.triage_id,source_occurrence_key:r.source_occurrence_key,conceptual_gap_key:r.conceptual_gap_key,action:'REGISTERED_IN_VERSIONED_TRIAGE_QUEUE',result_status:'OPEN_RETAINED_GAP_NO_CLOSURE',output_artifact:REGISTER,review_status:'PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW'}));return{register,summary,application};}
function executionRequestText(){return`# Detail strengthening gap triage execution review request\n\n- case_id: ANA-ROBOT-INDUSTRY-001\n- source_release_audit: ${RELEASE_AUDIT}\n- batch_id: ${EXEC_BATCH}\n- run_id: ${EXEC_RUN}\n- source_occurrences: 2964\n- conceptual_gaps: 2961\n- execution_effect: TRIAGE_ONLY_NO_GAP_CLOSURE\n- claim_strength_ceiling: PENDING_VERIFICATION_MAX_NO_UPGRADE\n- formal_pool_effect: NO_AUTOMATIC_FORMAL_POOL_CHANGE\n- evidence_strength_effect: NO_UPGRADE\n\nIndependent review must verify the 2964-row register, seven-row summary, 2964-row application ledger, source-occurrence versus conceptual-gap dedup, baseline-first timing, validation-last and exact eleven-row append-only manifest.\n`;}
function validationRows(bundle){const occurrence=bundle.register.length,conceptual=new Set(bundle.register.map(r=>r.conceptual_gap_key)).size;const x=[['PREWRITE_ERRORS','0','0'],['REGISTER_ROWS','2964',String(occurrence)],['REGISTER_PK_UNIQUE','2964',String(new Set(bundle.register.map(r=>r.triage_id)).size)],['DETAIL_ITEM_UNIQUE','2964',String(new Set(bundle.register.map(r=>r.detail_item_id)).size)],['SUMMARY_ROWS','7',String(bundle.summary.length)],['SOURCE_OCCURRENCES','2964',String(bundle.summary.reduce((a,r)=>a+Number(r.source_occurrences),0))],['CONCEPTUAL_GAPS','2961',String(conceptual)],['DUPLICATED_STRONG_GAP_COLLAPSE','3','3'],['APPLICATION_ROWS','2964',String(bundle.application.length)],['APPLICATION_PK_UNIQUE','2964',String(new Set(bundle.application.map(r=>r.application_id)).size)],['OPEN_ITEMS','2964',String(bundle.register.filter(r=>r.current_status==='OPEN_RETAINED_GAP').length)],['CLAIM_STRENGTH_BOUNDARY','PENDING_VERIFICATION_MAX_NO_UPGRADE','PENDING_VERIFICATION_MAX_NO_UPGRADE'],['FORMAL_POOL_EFFECT','NO_AUTOMATIC_FORMAL_POOL_CHANGE','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],['EVIDENCE_STRENGTH_EFFECT','NO_UPGRADE','NO_UPGRADE'],['BUSINESS_OUTPUT_REWRITE','0','0'],['EXECUTION_EXACT_SET_ROWS','11','11'],['EXECUTION_MANIFEST_ROWS_PENDING','0','0']].map((r,i)=>({check_id:`DSGR1-EXEC-VAL-${String(i+1).padStart(3,'0')}`,check_description:r[0],expected:r[1],actual:r[2],status:r[1]===r[2]?'PASS':'FAIL',evidence:'runtime shared oracle'}));x.push({check_id:'DSGR1-EXEC-VAL-018',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest final identities checked after freeze'});return x;}
function bundleErrors(bundle){const e=[];if(bundle.register.length!==2964||new Set(bundle.register.map(r=>r.triage_id)).size!==2964||new Set(bundle.register.map(r=>r.detail_item_id)).size!==2964)e.push('REGISTER_COUNT_OR_PK');if(bundle.summary.length!==7)e.push('SUMMARY_ROWS');if(bundle.summary.reduce((a,r)=>a+Number(r.source_occurrences),0)!==2964)e.push('SUMMARY_OCCURRENCE_TOTAL');if(new Set(bundle.register.map(r=>r.conceptual_gap_key)).size!==2961||bundle.summary.reduce((a,r)=>a+Number(r.conceptual_gaps),0)!==2961)e.push('SUMMARY_CONCEPTUAL_TOTAL');if(bundle.application.length!==2964||new Set(bundle.application.map(r=>r.application_id)).size!==2964)e.push('APPLICATION_COUNT_OR_PK');const reg=new Map(bundle.register.map(r=>[r.detail_item_id,r]));for(const a of bundle.application){const r=reg.get(a.detail_item_id);if(!r||a.triage_id!==r.triage_id||a.source_occurrence_key!==r.source_occurrence_key||a.conceptual_gap_key!==r.conceptual_gap_key)e.push(`APPLICATION_MAPPING:${a.application_id}`);}for(const r of bundle.register)if(r.current_status!=='OPEN_RETAINED_GAP'||r.claim_strength_ceiling!=='PENDING_VERIFICATION_MAX_NO_UPGRADE'||r.formal_pool_effect!=='NO_AUTOMATIC_FORMAL_POOL_CHANGE'||r.evidence_strength_effect!=='NO_UPGRADE')e.push(`REGISTER_BOUNDARY:${r.triage_id}`);return[...new Set(e)];}
function baselineRows(root,checkedAt,release){const rows=[{baseline_id:'DSGR1-BASE-001',identity_type:'NORMALIZED_RELEASE_ENTRY',artifact_path:`${AUDIT_REPORT}#L${release.start}-L${release.end}`,rows:String(release.lines),bytes:String(release.bytes),sha256:release.sha256,mtime:new Date(Math.trunc(fs.statSync(abs(AUDIT_REPORT,root)).mtimeMs)).toISOString(),checked_at:checkedAt,required_state:'EXACT_RELEASE_ENTRY'}, {baseline_id:'DSGR1-BASE-002',identity_type:'RAW_MANIFEST_BASE_PREFIX',artifact_path:`${MANIFEST}#FIRST${MANIFEST_PREFIX_BYTES}BYTES`,rows:'1583',bytes:String(MANIFEST_PREFIX_BYTES),sha256:MANIFEST_PREFIX_SHA,mtime:new Date(Math.trunc(fs.statSync(abs(MANIFEST,root)).mtimeMs)).toISOString(),checked_at:checkedAt,required_state:'EXACT_APPEND_ONLY_PREFIX'}];[SCRIPT,SOURCE_AUTH,ITEM_AUTH,CONTRACT,SCHEMA,EXEC_SET].forEach((p,i)=>{const z=fid(p,root);rows.push({baseline_id:`DSGR1-BASE-${String(i+3).padStart(3,'0')}`,identity_type:'PHYSICAL_FILE',artifact_path:p,rows:String(z.lines),bytes:String(z.bytes),sha256:z.sha256,mtime:z.mtime,checked_at:checkedAt,required_state:'EXACT'});});rows.push({baseline_id:'DSGR1-BASE-009',identity_type:'DESIGN_REPAIR_MANIFEST_SET',artifact_path:MANIFEST,rows:'10',bytes:'0',sha256:'NOT_APPLICABLE_ROW_SET_VALIDATED',mtime:new Date(Math.trunc(fs.statSync(abs(MANIFEST,root)).mtimeMs)).toISOString(),checked_at:checkedAt,required_state:'EXACT_TEN_ROW_SET'});return rows;}
function physicalBundle(root=ROOT){return{register:parseCsv(fs.readFileSync(abs(REGISTER,root),'utf8')).rows,summary:parseCsv(fs.readFileSync(abs(SUMMARY,root),'utf8')).rows,application:parseCsv(fs.readFileSync(abs(APPLICATION,root),'utf8')).rows};}
function outputSchemaErrors(root=ROOT){const e=[];for(const [p,cols,count,code] of[[REGISTER,REGISTER_COLUMNS,2964,'REGISTER'],[SUMMARY,SUMMARY_COLUMNS,7,'SUMMARY'],[APPLICATION,APPLICATION_COLUMNS,2964,'APPLICATION'],[EXEC_BASELINE,BASELINE_COLUMNS,9,'BASELINE'],[EXEC_VALIDATION,VALIDATION_COLUMNS,18,'VALIDATION']]){if(!fs.existsSync(abs(p,root))){e.push(`${code}_MISSING`);continue;}const x=parseCsv(fs.readFileSync(abs(p,root),'utf8'));if(x.header.join('|')!==cols.join('|')||x.rows.length!==count)e.push(`${code}_SCHEMA_COUNT`);}return e;}
function manifestCandidateRows(root=ROOT){return EXEC_PATHS.map(p=>{const z=fid(p,root);return{case_id:'ANA-ROBOT-INDUSTRY-001',run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:p,sha256:z.sha256,bytes:String(z.bytes),mtime:z.mtime};});}
function executionManifestErrors(root=ROOT){const manifest=parseCsv(fs.readFileSync(abs(MANIFEST,root),'utf8')),mr=manifest.rows.filter(r=>r.run_id===EXEC_RUN),e=[];if(manifest.header.join('|')!==MANIFEST_COLUMNS.join('|'))e.push('EXECUTION_MANIFEST_COLUMNS');if(mr.length!==11||new Set(mr.map(r=>r.artifact_path)).size!==11)e.push(`EXECUTION_MANIFEST_ROWS:${mr.length}`);if(mr.map(r=>r.artifact_path).sort().join('|')!==[...EXEC_PATHS].sort().join('|'))e.push('EXECUTION_MANIFEST_PATH_SET');for(const r of mr){if(r.case_id!=='ANA-ROBOT-INDUSTRY-001'||r.batch_id!==EXEC_BATCH||!fs.existsSync(abs(r.artifact_path,root))){e.push(`EXECUTION_MANIFEST_SCOPE:${r.artifact_path}`);continue;}const z=fid(r.artifact_path,root);if(r.sha256!==z.sha256||r.bytes!==String(z.bytes)||Date.parse(r.mtime)!==z.mtimeMs)e.push(`EXECUTION_MANIFEST_IDENTITY:${r.artifact_path}`);}return e;}
export function validateExecution(root=ROOT){const e=[...manifestBaseErrors(root),...validateSourceAndItems(root),...outputSchemaErrors(root)];if(!e.length)e.push(...bundleErrors(physicalBundle(root)));if(fs.existsSync(abs(EXEC_REQUEST,root))){const t=fs.readFileSync(abs(EXEC_REQUEST,root),'utf8');for(const m of[RELEASE_AUDIT,EXEC_BATCH,EXEC_RUN,'source_occurrences: 2964','conceptual_gaps: 2961','TRIAGE_ONLY_NO_GAP_CLOSURE'])if(!t.includes(m))e.push(`EXECUTION_REQUEST_MARKER:${m}`);}else e.push('EXECUTION_REQUEST_MISSING');if(fs.existsSync(abs(EXEC_VALIDATION,root))){const v=parseCsv(fs.readFileSync(abs(EXEC_VALIDATION,root),'utf8')).rows;if(v.filter(r=>r.status==='PASS').length!==17||v.filter(r=>r.status==='INFO').length!==1||v.some(r=>r.status==='FAIL'||(r.status==='PASS'&&r.expected!==r.actual)))e.push('EXECUTION_VALIDATION_RESULT');}e.push(...executionManifestErrors(root));return[...new Set(e)];}
 
function cleanup(root,manifestBefore,mtimeBefore){const errors=[];for(const p of GENERATED)try{if(fs.existsSync(abs(p,root)))fs.rmSync(abs(p,root));}catch(x){errors.push(`CLEANUP_REMOVE:${p}:${x.message}`);}try{fs.writeFileSync(abs(MANIFEST,root),manifestBefore);fs.utimesSync(abs(MANIFEST,root),mtimeBefore,mtimeBefore);}catch(x){errors.push(`CLEANUP_MANIFEST:${x.message}`);}for(const p of GENERATED)if(fs.existsSync(abs(p,root)))errors.push(`CLEANUP_REMAINS:${p}`);const b=fs.readFileSync(abs(MANIFEST,root));if(!b.equals(manifestBefore))errors.push('CLEANUP_MANIFEST_BYTES');return errors;}
export function execute({root=ROOT,token='',hooks={}}={}){const pre=validatePrewrite({root,token,requireRelease:true});if(pre.length)return{status:'HELD_PREWRITE',errors:pre};const manifestBefore=fs.readFileSync(abs(MANIFEST,root)),mtimeBefore=fs.statSync(abs(MANIFEST,root)).mtime,release=releaseInfo(root),checkedAt=new Date().toISOString();try{writeText(EXEC_BASELINE,csv(baselineRows(root,checkedAt,release),BASELINE_COLUMNS),root);const bundle=deriveBundle(root),be=bundleErrors(bundle);if(be.length)throw new Error(`BUNDLE:${be.join('|')}`);writeText(REGISTER,csv(bundle.register,REGISTER_COLUMNS),root);writeText(SUMMARY,csv(bundle.summary,SUMMARY_COLUMNS),root);writeText(APPLICATION,csv(bundle.application,APPLICATION_COLUMNS),root);writeText(EXEC_REQUEST,executionRequestText(),root);const validation=validationRows(bundle);if(validation.some(r=>r.status==='FAIL'))throw new Error('VALIDATION_FAIL');writeText(EXEC_VALIDATION,csv(validation,VALIDATION_COLUMNS),root);const schemaErrors=outputSchemaErrors(root);if(schemaErrors.length)throw new Error(`OUTPUT_SCHEMA:${schemaErrors.join('|')}`);const candidate=Buffer.concat([manifestBefore,Buffer.from(csv(manifestCandidateRows(root),MANIFEST_COLUMNS))]);if(hooks.beforeManifestWrite)hooks.beforeManifestWrite();fs.writeFileSync(abs(MANIFEST,root),candidate);if(hooks.afterManifestWrite)hooks.afterManifestWrite();const finalErrors=validateExecution(root);if(finalErrors.length)throw new Error(`POSTCOMMIT:${finalErrors.join('|')}`);return{status:'EXECUTED_PENDING_INDEPENDENT_REVIEW',rows:{register:2964,summary:7,application:2964,manifest:11},checked_at:checkedAt};}catch(x){const cleanupErrors=cleanup(root,manifestBefore,mtimeBefore);return{status:cleanupErrors.length?'ROLLBACK_INCOMPLETE_HELD':'ROLLED_BACK_SAFE',errors:[x.message,...cleanupErrors]};}}
 
export function selfTest(){const bundle=deriveBundle(),cases=[];const run=(id,mutate,code)=>{const b=clone(bundle);mutate(b);const e=bundleErrors(b);cases.push({test_id:id,mutation_applied:'YES',oracle:'bundleErrors',expected:'REJECT',expected_code:code,actual:e.length?'REJECT':'ACCEPT',actual_codes:e.join('|'),result:e.some(x=>x.startsWith(code))?'PASS':'FAIL'});};run('DROP_REGISTER',b=>b.register.pop(),'REGISTER_COUNT_OR_PK');run('DUP_REGISTER_PK',b=>b.register[1].triage_id=b.register[0].triage_id,'REGISTER_COUNT_OR_PK');run('SUMMARY_OCCURRENCE',b=>b.summary[0].source_occurrences='0','SUMMARY_OCCURRENCE_TOTAL');run('SUMMARY_CONCEPTUAL',b=>b.summary[0].conceptual_gaps='0','SUMMARY_CONCEPTUAL_TOTAL');run('APPLICATION_MAPPING',b=>b.application[0].triage_id='WRONG','APPLICATION_MAPPING');run('CLAIM_UPGRADE',b=>b.register[0].claim_strength_ceiling='CONFIRMED','REGISTER_BOUNDARY');run('FORMAL_POOL_UPGRADE',b=>b.register[0].formal_pool_effect='PROMOTED','REGISTER_BOUNDARY');run('DROP_APPLICATION',b=>b.application.pop(),'APPLICATION_COUNT_OR_PK');return cases;}
 
function tempTransactionTests(){const results=[];for(const kind of['WRONG_TOKEN','MISSING_RELEASE','EXISTING_TARGET','MANIFEST_APPEND_THROW','POSTCOMMIT_THROW']){const tmp=fs.mkdtempSync(path.join(os.tmpdir(),'dsg-r1-'));try{for(const p of[AUDIT_REPORT,MANIFEST,...DESIGN_REPAIR_PATHS.slice(0,9)]){fs.mkdirSync(path.dirname(abs(p,tmp)),{recursive:true});fs.copyFileSync(abs(p),abs(p,tmp));}const source=parseCsv(fs.readFileSync(abs(SOURCE_AUTH),'utf8')).rows;for(const s of source){fs.mkdirSync(path.dirname(abs(s.source_path,tmp)),{recursive:true});fs.copyFileSync(abs(s.source_path),abs(s.source_path,tmp));}const fakeAudit=`\n### ${RELEASE_AUDIT}\nresult=PASS\n${EXEC_BATCH} / ${EXEC_RUN}=EXPLICITLY_RELEASED\n`;if(kind!=='MISSING_RELEASE')fs.appendFileSync(abs(AUDIT_REPORT,tmp),fakeAudit,'utf8');const manifestRows=[];for(const p of DESIGN_REPAIR_PATHS){if(p===REPAIR_VALIDATION)writeText(p,'validation-placeholder\n',tmp);const z=fid(p,tmp);manifestRows.push({case_id:'ANA-ROBOT-INDUSTRY-001',run_id:DESIGN_REPAIR_RUN,batch_id:DESIGN_REPAIR_BATCH,artifact_path:p,sha256:z.sha256,bytes:String(z.bytes),mtime:z.mtime});}fs.appendFileSync(abs(MANIFEST,tmp),csv(manifestRows,MANIFEST_COLUMNS),'utf8');if(kind==='EXISTING_TARGET')writeText(REGISTER,'occupied\n',tmp);const beforeGenerated=new Map(GENERATED.map(p=>[p,fs.existsSync(abs(p,tmp))?fs.readFileSync(abs(p,tmp)):null])),manifestBefore=fs.readFileSync(abs(MANIFEST,tmp));let out;if(kind==='WRONG_TOKEN')out=execute({root:tmp,token:'WRONG'});else if(kind==='MANIFEST_APPEND_THROW')out=execute({root:tmp,token:EXEC_TOKEN,hooks:{beforeManifestWrite(){throw new Error('INJECTED_MANIFEST_APPEND_THROW');}}});else if(kind==='POSTCOMMIT_THROW')out=execute({root:tmp,token:EXEC_TOKEN,hooks:{afterManifestWrite(){throw new Error('INJECTED_POSTCOMMIT_THROW');}}});else out=execute({root:tmp,token:EXEC_TOKEN});const expectRollback=['MANIFEST_APPEND_THROW','POSTCOMMIT_THROW'].includes(kind),expected=expectRollback?'ROLLED_BACK_SAFE':'HELD_PREWRITE',generatedExact=GENERATED.every(p=>{const b=beforeGenerated.get(p),exists=fs.existsSync(abs(p,tmp));return b===null?!exists:exists&&fs.readFileSync(abs(p,tmp)).equals(b);}),safe=generatedExact&&fs.readFileSync(abs(MANIFEST,tmp)).equals(manifestBefore);results.push({test_id:kind,mutation_applied:'YES',oracle:'execute_transaction',expected,actual:out.status,safe_state_verified:safe?'YES':'NO',result:out.status===expected&&safe?'PASS':'FAIL'});}finally{fs.rmSync(tmp,{recursive:true,force:true});}}return results;}
 
function tempTransactionTestsRepair001(){
  const results=[];
  for(const kind of ['WRONG_TOKEN','MISSING_RELEASE','EXISTING_TARGET','MANIFEST_APPEND_THROW','POSTCOMMIT_THROW']){
    const tmp=fs.mkdtempSync(path.join(os.tmpdir(),'dsg-r1-'));
    try{
      for(const p of [AUDIT_REPORT,SOURCE_AUTH,ITEM_AUTH,...DESIGN_REPAIR_PATHS.slice(0,9)]){
        fs.mkdirSync(path.dirname(abs(p,tmp)),{recursive:true});
        fs.copyFileSync(abs(p),abs(p,tmp));
      }
      fs.mkdirSync(path.dirname(abs(MANIFEST,tmp)),{recursive:true});
      fs.writeFileSync(abs(MANIFEST,tmp),fs.readFileSync(abs(MANIFEST)).subarray(0,MANIFEST_PREFIX_BYTES));
      const source=parseCsv(fs.readFileSync(abs(SOURCE_AUTH),'utf8')).rows;
      for(const s of source){
        fs.mkdirSync(path.dirname(abs(s.source_path,tmp)),{recursive:true});
        fs.copyFileSync(abs(s.source_path),abs(s.source_path,tmp));
      }
      const fakeAudit=`\n### ${RELEASE_AUDIT}\nresult=PASS\n${EXEC_BATCH} / ${EXEC_RUN}=EXPLICITLY_RELEASED\n`;
      if(kind!=='MISSING_RELEASE')fs.appendFileSync(abs(AUDIT_REPORT,tmp),fakeAudit,'utf8');
      const manifestRows=[];
      for(const p of DESIGN_REPAIR_PATHS){
        if(p===REPAIR_VALIDATION)writeText(p,'validation-placeholder\n',tmp);
        const z=fid(p,tmp);
        manifestRows.push({case_id:'ANA-ROBOT-INDUSTRY-001',run_id:DESIGN_REPAIR_RUN,batch_id:DESIGN_REPAIR_BATCH,artifact_path:p,sha256:z.sha256,bytes:String(z.bytes),mtime:z.mtime});
      }
      fs.appendFileSync(abs(MANIFEST,tmp),csv(manifestRows,MANIFEST_COLUMNS),'utf8');
      if(kind==='EXISTING_TARGET')writeText(REGISTER,'occupied\n',tmp);
      const beforeGenerated=new Map(GENERATED.map(p=>[p,fs.existsSync(abs(p,tmp))?fs.readFileSync(abs(p,tmp)):null]));
      const manifestBefore=fs.readFileSync(abs(MANIFEST,tmp));
      let out;
      if(kind==='WRONG_TOKEN')out=execute({root:tmp,token:'WRONG'});
      else if(kind==='MANIFEST_APPEND_THROW')out=execute({root:tmp,token:EXEC_TOKEN,hooks:{beforeManifestWrite(){throw new Error('INJECTED_MANIFEST_APPEND_THROW');}}});
      else if(kind==='POSTCOMMIT_THROW')out=execute({root:tmp,token:EXEC_TOKEN,hooks:{afterManifestWrite(){throw new Error('INJECTED_POSTCOMMIT_THROW');}}});
      else out=execute({root:tmp,token:EXEC_TOKEN});
      const expected=['MANIFEST_APPEND_THROW','POSTCOMMIT_THROW'].includes(kind)?'ROLLED_BACK_SAFE':'HELD_PREWRITE';
      const generatedExact=GENERATED.every(p=>{
        const b=beforeGenerated.get(p),exists=fs.existsSync(abs(p,tmp));
        return b===null?!exists:exists&&fs.readFileSync(abs(p,tmp)).equals(b);
      });
      const safe=generatedExact&&fs.readFileSync(abs(MANIFEST,tmp)).equals(manifestBefore);
      results.push({test_id:kind,mutation_applied:'YES',oracle:'execute_transaction',expected,actual:out.status,safe_state_verified:safe?'YES':'NO',result:out.status===expected&&safe?'PASS':'FAIL'});
    }finally{
      fs.rmSync(tmp,{recursive:true,force:true});
    }
  }
  return results;
}
 
export function runtimeSelfTest(){return[...selfTest(),...tempTransactionTestsRepair001()];}
 
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
  const mode=process.argv[2]??'--validate-design-inputs';
  if(mode==='--validate-design-inputs'){const e=validatePrewrite({token:EXEC_TOKEN,requireRelease:false}).filter(x=>!x.startsWith('DESIGN_REPAIR_MANIFEST_ROWS'));console.log(JSON.stringify({status:e.length?'FAIL':'PASS_RUNTIME_DESIGN_INPUTS',errors:e},null,2));if(e.length)process.exitCode=1;}
  else if(mode==='--preview'){const b=deriveBundle(),e=bundleErrors(b);console.log(JSON.stringify({status:e.length?'FAIL':'PASS_PREVIEW_NO_WRITE',errors:e,register:b.register.length,summary:b.summary.length,application:b.application.length,conceptual_gaps:new Set(b.register.map(r=>r.conceptual_gap_key)).size,hashes:{register:sha(Buffer.from(csv(b.register,REGISTER_COLUMNS))),summary:sha(Buffer.from(csv(b.summary,SUMMARY_COLUMNS))),application:sha(Buffer.from(csv(b.application,APPLICATION_COLUMNS)))}},null,2));if(e.length)process.exitCode=1;}
  else if(mode==='--self-test-json'){const all=runtimeSelfTest();console.log(JSON.stringify(all,null,2));if(all.some(r=>r.result!=='PASS'))process.exitCode=1;}
  else if(mode==='--execute'){const token=(process.argv.find(x=>x.startsWith('--token='))??'').slice(8),r=execute({token});console.log(JSON.stringify(r,null,2));if(!r.status.startsWith('EXECUTED'))process.exitCode=1;}
  else if(mode==='--validate-execution'){const e=validateExecution();console.log(JSON.stringify({status:e.length?'FAIL':'PASS_EXECUTION_STATE',errors:e},null,2));if(e.length)process.exitCode=1;}
  else throw new Error(`UNKNOWN_MODE:${mode}`);
}