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
| 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';
| import {deriveBundle as deriveFrozenBundle} from './detail_strengthening_gap_triage_runtime_repair001_20260730.mjs';
|
| const ROOT=process.cwd();
| const CASE_ID='ANA-ROBOT-INDUSTRY-001';
| const BASE='ana-data/cases/机器人案例/ANA-ROBOT-INDUSTRY-001';
| const SCRIPT='dev/ana-dev/detail_strengthening_gap_triage_runtime_repair002_20260730.mjs';
| const BUILDER='dev/ana-dev/detail_strengthening_gap_triage_design_repair002_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_repair002_20260730.csv`;
| const SCHEMA=`${BASE}/evidence/detail_strengthening_gap_triage_output_schema_authority_repair002_20260730.csv`;
| const EXEC_SET=`${BASE}/manifest/detail_strengthening_gap_triage_execution_artifact_set_repair002_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_repair002_20260730.csv`;
| const REGISTER=`${BASE}/outputs/数据表/robot_detail_gap_triage_register_v01_repair002_20260730.csv`;
| const SUMMARY=`${BASE}/outputs/数据表/robot_detail_gap_workstream_summary_v01_repair002_20260730.csv`;
| const APPLICATION=`${BASE}/evidence/detail_strengthening_gap_triage_application_repair002_20260730.csv`;
| const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_gap_triage_execution_repair002_20260730.md`;
| const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_gap_triage_execution_validation_repair002_20260730.csv`;
| const NEG_RESULTS=`${BASE}/evidence/detail_strengthening_gap_triage_runtime_negative_results_repair002_20260730.csv`;
| const DESIGN_BASELINE=`${BASE}/evidence/detail_strengthening_gap_triage_design_baseline_repair002_20260730.csv`;
| const DESIGN_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_gap_triage_design_repair002_20260730.md`;
| const DESIGN_SET=`${BASE}/manifest/detail_strengthening_gap_triage_design_artifact_set_repair002_20260730.csv`;
| const DESIGN_VALIDATION=`${BASE}/manifest/detail_strengthening_gap_triage_design_validation_repair002_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_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-DESIGN-REPAIR-002';
| const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-DESIGN-REPAIR-002';
| const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-DESIGN-REPAIR002-REREVIEW-001';
| const EXEC_TOKEN='EXECUTE_DETAIL_GAP_TRIAGE_REPAIR002';
| const MANIFEST_PREFIX={rows:1593,bytes:568778,sha256:'ed132bad8778e6773aa0021b887262d86a0d592ec4de4684b495c39775a12380'};
| const SOURCE_AUTH_ID={bytes:2347,sha256:'9c9afaab76b57f015b9b23f0e9d425012c586fec6e762b9563d9026f9f299fc2'};
| const ITEM_AUTH_ID={bytes:2494340,sha256:'b6c292f5dbc3b0766884b66ea03716877f2e7c3e10f73d9b561fe32f5798dbee'};
| const DESIGN_PATHS=[SCRIPT,BUILDER,CONTRACT,SCHEMA,EXEC_SET,NEG_RESULTS,DESIGN_BASELINE,DESIGN_REQUEST,DESIGN_SET,DESIGN_VALIDATION];
| const EXEC_PATHS=[SCRIPT,SOURCE_AUTH,ITEM_AUTH,CONTRACT,SCHEMA,EXEC_BASELINE,REGISTER,SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_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 clone=x=>JSON.parse(JSON.stringify(x));
| 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)};};
| 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 writeText(p,text,root=ROOT){fs.mkdirSync(path.dirname(abs(p,root)),{recursive:true});fs.writeFileSync(abs(p,root),text,'utf8');}
| function rowExactErrors(actual,expected,columns,code){const e=[];if(actual.length!==expected.length)e.push(`${code}_ROW_COUNT:${actual.length}:${expected.length}`);for(let i=0;i<Math.min(actual.length,expected.length);i++)for(const k of columns)if(actual[i][k]!==String(expected[i][k]??'')){e.push(`${code}_FIELD:${i+1}:${k}`);break;}return e;}
|
| export function contractRows(){const x=[
| ['RELEASE','heading',RELEASE_AUDIT],['RELEASE','result_line','result=PASS'],['RELEASE','release_line','execution_release=EXPLICITLY_RELEASED'],['RELEASE','batch_line',`released_batch_id=${EXEC_BATCH}`],['RELEASE','run_line',`released_run_id=${EXEC_RUN}`],['RELEASE','substring_mentions','DO_NOT_COUNT'],
| ['RUNTIME','invocation',`node ${SCRIPT} --execute --token=${EXEC_TOKEN}`],['RUNTIME','existing_targets','0'],['RUNTIME','baseline_first','YES'],['RUNTIME','validation_last','YES'],['RUNTIME','cleanup','SIX_ABSENT_AND_MANIFEST_EXACT_BEFORE'],
| ['OUTPUT','register_rows','2964'],['OUTPUT','register_exact_projection','ALL_17_FIELDS_EQUAL_FROZEN_REDERIVATION'],['OUTPUT','summary_rows','7'],['OUTPUT','summary_exact_groups','ALL_10_FIELDS_EQUAL_FROZEN_REDERIVATION'],['OUTPUT','application_rows','2964'],['OUTPUT','application_exact_projection','ALL_9_FIELDS_EQUAL_FROZEN_REDERIVATION'],
| ['OUTPUT','request_serialization','UTF8_NO_BOM_LF_MARKDOWN_TERMINAL_LF'],['OUTPUT','baseline_rows','EXACT_9'],['OUTPUT','csv_serialization','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF'],
| ['MANIFEST','prefix_rows',String(MANIFEST_PREFIX.rows)],['MANIFEST','prefix_bytes',String(MANIFEST_PREFIX.bytes)],['MANIFEST','prefix_sha256',MANIFEST_PREFIX.sha256],['MANIFEST','design_rows','10'],['MANIFEST','execution_rows','11'],['MANIFEST','seven_fields',MANIFEST_COLUMNS.join('|')],['MANIFEST','all_fields_exact','CASE_RUN_BATCH_PATH_SHA_BYTES_FILESYSTEM_MTIME_MS'],
| ['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_occurrences','2964'],['DEDUP','conceptual_gaps','2961'],['DOWNSTREAM','supplementation','SEPARATE_DESIGN_AND_RELEASE_REQUIRED']
| ];return x.map((r,i)=>({contract_id:`DSGR2-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 schemaRows(){const x=[
| ['RUNTIME_BASELINE',EXEC_BASELINE,BASELINE_COLUMNS.join('|'),'baseline_id','EXACT_9','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','append-stable release entry + manifest prefix + six frozen physical inputs + design manifest set'],
| ['TRIAGE_REGISTER',REGISTER,REGISTER_COLUMNS.join('|'),'triage_id','EXACT_2964','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','all fields exact from frozen item authority'],
| ['WORKSTREAM_SUMMARY',SUMMARY,SUMMARY_COLUMNS.join('|'),'summary_id','EXACT_7','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','all groups and fields exact from register'],
| ['APPLICATION_LEDGER',APPLICATION,APPLICATION_COLUMNS.join('|'),'application_id','EXACT_2964','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','all fields exact from register; closure forbidden'],
| ['EXECUTION_REQUEST',EXEC_REQUEST,'MARKDOWN_REQUIRED_EXACT_TEXT','NA','EXACT_1_DOCUMENT','UTF8_NO_BOM_LF_MARKDOWN_TERMINAL_LF','exact structured release/batch/run/count/boundary markers'],
| ['EXECUTION_VALIDATION',EXEC_VALIDATION,VALIDATION_COLUMNS.join('|'),'check_id','EXACT_20','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','PASS19 INFO1 FAIL0; validation last']
| ];return x.map((r,i)=>({schema_id:`DSGR2-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:r[5],derivation_rule:r[6],required_boundary:'NO_AUTOMATIC_FORMAL_POOL_CHANGE|NO_UPGRADE|NO_GAP_CLOSURE'}));}
| export function executionSetRows(){const roles=['FROZEN_RUNTIME_GENERATOR_R2','FROZEN_SOURCE_AUTHORITY','FROZEN_ITEM_AUTHORITY','FROZEN_RUNTIME_CONTRACT_R2','FROZEN_OUTPUT_SCHEMA_R2','RUNTIME_BASELINE_FIRST','VERSIONED_TRIAGE_REGISTER_R2','WORKSTREAM_SUMMARY_R2','APPLICATION_LEDGER_R2','EXECUTION_REVIEW_REQUEST_R2','VALIDATION_LAST'];return EXEC_PATHS.map((p,i)=>({artifact_id:`DSGR2-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 manifestPrefixErrors(root=ROOT){if(!fs.existsSync(abs(MANIFEST,root)))return['MANIFEST_MISSING'];const b=fs.readFileSync(abs(MANIFEST,root));return b.length>=MANIFEST_PREFIX.bytes&&sha(b.subarray(0,MANIFEST_PREFIX.bytes))===MANIFEST_PREFIX.sha256?[]:['MANIFEST_1593_PREFIX'];}
| function designManifestErrors(root=ROOT){const rows=parseCsv(fs.readFileSync(abs(MANIFEST,root),'utf8')).rows.filter(r=>r.run_id===DESIGN_RUN),e=[];if(rows.length!==10||new Set(rows.map(r=>r.artifact_path)).size!==10)e.push(`DESIGN_MANIFEST_ROWS:${rows.length}`);if(rows.length&&rows.map(r=>r.artifact_path).sort().join('|')!==[...DESIGN_PATHS].sort().join('|'))e.push('DESIGN_MANIFEST_PATH_SET');for(const r of rows){if(r.case_id!==CASE_ID||r.batch_id!==DESIGN_BATCH||!fs.existsSync(abs(r.artifact_path,root))){e.push(`DESIGN_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_MANIFEST_IDENTITY:${r.artifact_path}`);}return e;}
| function frozenAuthorityErrors(root=ROOT){const e=[];for(const [p,id,code] of [[SOURCE_AUTH,SOURCE_AUTH_ID,'SOURCE_AUTH'],[ITEM_AUTH,ITEM_AUTH_ID,'ITEM_AUTH']]){if(!fs.existsSync(abs(p,root))){e.push(`${code}_MISSING`);continue;}const z=fid(p,root);if(z.bytes!==id.bytes||z.sha256!==id.sha256)e.push(`${code}_IDENTITY`);}return e;}
| function exactAuthorityErrors(p,expected,columns,code,root=ROOT){if(!fs.existsSync(abs(p,root)))return[`${code}_MISSING`];const x=parseCsv(fs.readFileSync(abs(p,root),'utf8')),e=[];if(x.header.join('|')!==columns.join('|'))e.push(`${code}_COLUMNS`);e.push(...rowExactErrors(x.rows,expected,columns,code));return e;}
|
| function structuredReleaseErrors(section){const trimmed=section.map(x=>x.trim()),required=[`result=PASS`,`execution_release=EXPLICITLY_RELEASED`,`released_batch_id=${EXEC_BATCH}`,`released_run_id=${EXEC_RUN}`],errors=[];for(const r of required)if(trimmed.filter(x=>x===r).length!==1)errors.push(`RELEASE_EXACT_LINE:${r}`);return errors;}
| function auditSection(root=ROOT){const lines=norm(fs.readFileSync(abs(AUDIT_REPORT,root))).split('\n'),start=lines.findIndex(x=>x.startsWith('### ')&&x.includes(RELEASE_AUDIT));if(start<0)return{errors:['RELEASE_AUDIT_MISSING']};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 section=lines.slice(start,end),errors=structuredReleaseErrors(section),b=Buffer.from(section.join('\n')+'\n');return{errors,start:start+1,end,lines:section.length,bytes:b.length,sha256:sha(b)};}
|
| export function expectedBundle(){const b=deriveFrozenBundle();for(const r of b.application)r.output_artifact=REGISTER;return b;}
| export function bundleErrors(actual){const expected=expectedBundle(),e=[];e.push(...rowExactErrors(actual.register,expected.register,REGISTER_COLUMNS,'REGISTER_EXACT'));e.push(...rowExactErrors(actual.summary,expected.summary,SUMMARY_COLUMNS,'SUMMARY_EXACT'));e.push(...rowExactErrors(actual.application,expected.application,APPLICATION_COLUMNS,'APPLICATION_EXACT'));return e;}
| function requestText(){return`# Detail strengthening gap triage execution REPAIR-002 review request\n\nresult_state=EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW\nsource_release_audit=${RELEASE_AUDIT}\nbatch_id=${EXEC_BATCH}\nrun_id=${EXEC_RUN}\nsource_occurrences=2964\nconceptual_gaps=2961\nexecution_effect=TRIAGE_ONLY_NO_GAP_CLOSURE\nclaim_strength_ceiling=PENDING_VERIFICATION_MAX_NO_UPGRADE\nformal_pool_effect=NO_AUTOMATIC_FORMAL_POOL_CHANGE\nevidence_strength_effect=NO_UPGRADE\n\nIndependent review must recompute every register, summary and application field from frozen authority and verify exact eleven-row append-only manifest.\n`;}
| function validationRows(bundle){const x=[
| ['PREWRITE_ERRORS','0','0'],['REGISTER_ROWS','2964',String(bundle.register.length)],['REGISTER_EXACT_FIELDS','0','0'],['SUMMARY_ROWS','7',String(bundle.summary.length)],['SUMMARY_EXACT_GROUPS','0','0'],['APPLICATION_ROWS','2964',String(bundle.application.length)],['APPLICATION_EXACT_FIELDS','0','0'],['SOURCE_OCCURRENCES','2964',String(bundle.summary.reduce((a,r)=>a+Number(r.source_occurrences),0))],['CONCEPTUAL_GAPS','2961',String(bundle.summary.reduce((a,r)=>a+Number(r.conceptual_gaps),0))],['OPEN_ITEMS','2964',String(bundle.summary.reduce((a,r)=>a+Number(r.open_items),0))],['CLAIM_STRENGTH','PENDING_VERIFICATION_MAX_NO_UPGRADE','PENDING_VERIFICATION_MAX_NO_UPGRADE'],['FORMAL_POOL','NO_AUTOMATIC_FORMAL_POOL_CHANGE','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],['EVIDENCE_STRENGTH','NO_UPGRADE','NO_UPGRADE'],['EXECUTION_EFFECT','TRIAGE_ONLY_NO_GAP_CLOSURE','TRIAGE_ONLY_NO_GAP_CLOSURE'],['BASELINE_ROWS','9','9'],['REQUEST_FORMAT','MARKDOWN','MARKDOWN'],['EXECUTION_EXACT_SET','11','11'],['EXECUTION_MANIFEST_PENDING','0','0'],['BUSINESS_OUTPUT_REWRITE','0','0']
| ].map((r,i)=>({check_id:`DSGR2-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:'repair002 strict runtime oracle'}));x.push({check_id:'DSGR2-EXEC-VAL-020',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 baselineRows(root,checkedAt,release){const rows=[
| {baseline_id:'DSGR2-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:'INFO_APPENDABLE_SHARED_FILE',checked_at:checkedAt,required_state:'EXACT_STRUCTURED_RELEASE_ENTRY'},
| {baseline_id:'DSGR2-BASE-002',identity_type:'RAW_MANIFEST_PREFIX',artifact_path:`${MANIFEST}#FIRST${MANIFEST_PREFIX.bytes}BYTES`,rows:String(MANIFEST_PREFIX.rows),bytes:String(MANIFEST_PREFIX.bytes),sha256:MANIFEST_PREFIX.sha256,mtime:'INFO_APPENDABLE_MANIFEST',checked_at:checkedAt,required_state:'EXACT_APPEND_ONLY_PREFIX'}
| ];for(const p of [SCRIPT,SOURCE_AUTH,ITEM_AUTH,CONTRACT,SCHEMA,EXEC_SET]){const z=fid(p,root);rows.push({baseline_id:`DSGR2-BASE-${String(rows.length+1).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:'DSGR2-BASE-009',identity_type:'DESIGN_REPAIR_MANIFEST_SET',artifact_path:MANIFEST,rows:'10',bytes:'NOT_APPLICABLE_ROW_SET',sha256:'NOT_APPLICABLE_ROW_SET',mtime:'INFO_APPENDABLE_MANIFEST',checked_at:checkedAt,required_state:'EXACT_TEN_ROW_SET'});return rows;}
|
| function existingTargetErrors(root=ROOT){return GENERATED.filter(p=>fs.existsSync(abs(p,root))).map(p=>`GENERATED_TARGET_EXISTS:${p}`);}
| export function prewriteErrors({root=ROOT,token='',requireRelease=true}={}){const e=[];if(token!==EXEC_TOKEN)e.push('EXECUTION_TOKEN_MISMATCH');e.push(...manifestPrefixErrors(root),...frozenAuthorityErrors(root),...exactAuthorityErrors(CONTRACT,contractRows(),['contract_id','scope','field','required_value_or_rule','violation_status'],'CONTRACT',root),...exactAuthorityErrors(SCHEMA,schemaRows(),['schema_id','artifact_role','artifact_path','column_order','primary_key','row_count_rule','serialization','derivation_rule','required_boundary'],'SCHEMA',root),...exactAuthorityErrors(EXEC_SET,executionSetRows(),['artifact_id','batch_id','run_id','generation_order','artifact_path','artifact_role','identity_policy'],'EXEC_SET',root),...designManifestErrors(root),...existingTargetErrors(root));if(requireRelease)e.push(...auditSection(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 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 requiredArtifactErrors(exists){const e=[];if(!exists(EXEC_REQUEST))e.push('REQUEST_MISSING');if(!exists(EXEC_VALIDATION))e.push('VALIDATION_MISSING');return e;}
| function outputErrors(root=ROOT){const e=[...requiredArtifactErrors(p=>fs.existsSync(abs(p,root)))];for(const [p,cols,count,code] of [[EXEC_BASELINE,BASELINE_COLUMNS,9,'BASELINE'],[REGISTER,REGISTER_COLUMNS,2964,'REGISTER'],[SUMMARY,SUMMARY_COLUMNS,7,'SUMMARY'],[APPLICATION,APPLICATION_COLUMNS,2964,'APPLICATION'],[EXEC_VALIDATION,VALIDATION_COLUMNS,20,'VALIDATION']]){if(!fs.existsSync(abs(p,root))){if(!e.includes(`${code}_MISSING`))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`);}if(fs.existsSync(abs(EXEC_REQUEST,root))&&fs.readFileSync(abs(EXEC_REQUEST,root),'utf8')!==requestText())e.push('REQUEST_EXACT_TEXT');if(!e.some(x=>x.startsWith('REGISTER_')||x.startsWith('SUMMARY_')||x.startsWith('APPLICATION_')))e.push(...bundleErrors(physicalBundle(root)));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!==19||v.filter(r=>r.status==='INFO').length!==1||v.some(r=>r.status==='FAIL'||(r.status==='PASS'&&r.expected!==r.actual)))e.push('VALIDATION_RESULT');}return e;}
| function manifestCandidateRows(root=ROOT){return EXEC_PATHS.map(p=>{const z=fid(p,root);return{case_id:CASE_ID,run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:p,sha256:z.sha256,bytes:String(z.bytes),mtime:z.mtime};});}
| function manifestFieldErrors(rows,expected){return rowExactErrors(rows,expected,MANIFEST_COLUMNS,'MANIFEST_EXACT');}
| export function strictManifestErrors(rows,root=ROOT){const expected=manifestCandidateRows(root),e=[];if(rows.length!==11||new Set(rows.map(r=>r.artifact_path)).size!==11)e.push(`MANIFEST_ROWS:${rows.length}`);e.push(...manifestFieldErrors(rows,expected));for(const r of rows){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(r.mtime)||Date.parse(r.mtime)!==fid(r.artifact_path,root).mtimeMs)e.push(`MANIFEST_MTIME:${r.artifact_path}`);}return e;}
| export function executionErrors(root=ROOT){const e=[...manifestPrefixErrors(root),...frozenAuthorityErrors(root),...outputErrors(root)];const manifest=parseCsv(fs.readFileSync(abs(MANIFEST,root),'utf8')),rows=manifest.rows.filter(r=>r.run_id===EXEC_RUN);e.push(...strictManifestErrors(rows,root));return[...new Set(e)];}
|
| function cleanup(root,before,mtime){const e=[];for(const p of GENERATED)try{if(fs.existsSync(abs(p,root)))fs.rmSync(abs(p,root));}catch(x){e.push(`CLEANUP_REMOVE:${p}:${x.message}`);}try{fs.writeFileSync(abs(MANIFEST,root),before);fs.utimesSync(abs(MANIFEST,root),mtime,mtime);}catch(x){e.push(`CLEANUP_MANIFEST:${x.message}`);}for(const p of GENERATED)if(fs.existsSync(abs(p,root)))e.push(`CLEANUP_REMAINS:${p}`);if(!fs.readFileSync(abs(MANIFEST,root)).equals(before))e.push('CLEANUP_MANIFEST_BYTES');return e;}
| export function execute({root=ROOT,token='',hooks={}}={}){const pre=prewriteErrors({root,token,requireRelease:true});if(pre.length)return{status:'HELD_PREWRITE',errors:pre};const before=fs.readFileSync(abs(MANIFEST,root)),mtime=fs.statSync(abs(MANIFEST,root)).mtime,release=auditSection(root),checkedAt=new Date().toISOString();try{writeText(EXEC_BASELINE,csv(baselineRows(root,checkedAt,release),BASELINE_COLUMNS),root);const bundle=expectedBundle();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,requestText(),root);const v=validationRows(bundle);writeText(EXEC_VALIDATION,csv(v,VALIDATION_COLUMNS),root);const oe=outputErrors(root);if(oe.length)throw new Error(`OUTPUT:${oe.join('|')}`);const candidate=Buffer.concat([before,Buffer.from(csv(manifestCandidateRows(root),MANIFEST_COLUMNS))]);if(hooks.beforeManifestWrite)hooks.beforeManifestWrite();fs.writeFileSync(abs(MANIFEST,root),candidate);if(hooks.afterManifestWrite)hooks.afterManifestWrite();const final=executionErrors(root);if(final.length)throw new Error(`POSTCOMMIT:${final.join('|')}`);return{status:'EXECUTED_PENDING_INDEPENDENT_REVIEW',register:2964,summary:7,application:2964,manifest_rows:11,checked_at:checkedAt};}catch(x){const ce=cleanup(root,before,mtime);return{status:ce.length?'ROLLBACK_INCOMPLETE_HELD':'ROLLED_BACK_SAFE',errors:[x.message,...ce]};}}
|
| function releaseNegative(){const lines=[`### ${RELEASE_AUDIT}`,'result=FAIL','PASS is explicitly not granted','execution_release=NOT_RELEASED','requested EXPLICITLY_RELEASED but NOT_RELEASED',`released_batch_id=${EXEC_BATCH}`,`released_run_id=${EXEC_RUN}`],errors=structuredReleaseErrors(lines);return{test_id:'FAIL_RELEASE_WITH_PASS_MENTIONS',mutation_applied:'YES',oracle:'structuredReleaseErrors',expected:'REJECT',expected_code:'RELEASE_EXACT_LINE:result=PASS',actual:errors.length?'REJECT':'ACCEPT',actual_codes:errors.join('|'),result:errors.includes('RELEASE_EXACT_LINE:result=PASS')?'PASS':'FAIL'};}
| function bundleNegativeRows(){const base=expectedBundle(),cases=[];const run=(id,mutate,code)=>{const b=clone(base);mutate(b);const e=bundleErrors(b);cases.push({test_id:id,mutation_applied:'YES',oracle:'bundleErrorsR2',expected:'REJECT',expected_code:code,actual:e.length?'REJECT':'ACCEPT',actual_codes:e.join('|'),result:e.some(x=>x.startsWith(code))?'PASS':'FAIL'});};run('REGISTER_SOURCE_PROJECTION',b=>b.register[0].object_id='WRONG_OBJECT','REGISTER_EXACT_FIELD');run('SUMMARY_OFFSETTING_GROUPS',b=>{b.summary[0].source_occurrences=String(Number(b.summary[0].source_occurrences)+1);b.summary[1].source_occurrences=String(Number(b.summary[1].source_occurrences)-1);b.summary[0].conceptual_gaps=String(Number(b.summary[0].conceptual_gaps)+1);b.summary[1].conceptual_gaps=String(Number(b.summary[1].conceptual_gaps)-1);},'SUMMARY_EXACT_FIELD');run('APPLICATION_CLOSED',b=>{b.application[0].action='CLOSED_WITHOUT_EVIDENCE';b.application[0].result_status='CLOSED';b.application[0].output_artifact='WRONG_OUTPUT';},'APPLICATION_EXACT_FIELD');return cases;}
| function missingArtifactRows(){return[EXEC_REQUEST,EXEC_VALIDATION].map((missing,i)=>{const e=requiredArtifactErrors(p=>p!==missing),code=i===0?'REQUEST_MISSING':'VALIDATION_MISSING';return{test_id:code,mutation_applied:'YES',oracle:'requiredArtifactErrors',expected:'REJECT',expected_code:code,actual:e.length?'REJECT':'ACCEPT',actual_codes:e.join('|'),result:e.includes(code)?'PASS':'FAIL'};});}
| function manifestNegativeRows(){const base=EXEC_PATHS.map((p,i)=>({case_id:CASE_ID,run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:p,sha256:`sha-${i}`,bytes:String(100+i),mtime:'2026-07-30T00:00:00.000Z'})),fields=['case_id','run_id','batch_id','artifact_path','sha256','bytes','mtime'];return fields.map(field=>{const actual=clone(base);actual[0][field]=field==='mtime'?'NOT-A-TIMESTAMP':`WRONG-${field}`;const e=manifestFieldErrors(actual,base);return{test_id:`MANIFEST_${field.toUpperCase()}`,mutation_applied:'YES',oracle:'manifestFieldErrors',expected:'REJECT',expected_code:'MANIFEST_EXACT_FIELD',actual:e.length?'REJECT':'ACCEPT',actual_codes:e.join('|'),result:e.some(x=>x.startsWith('MANIFEST_EXACT_FIELD'))?'PASS':'FAIL'};});}
| function transactionNegativeRows(){
| const rows=[];
| for(const kind of ['WRONG_TOKEN','FAIL_RELEASE_WITH_PASS_MENTIONS','EXISTING_TARGET','MANIFEST_APPEND_THROW','POSTCOMMIT_THROW']){
| const tmp=fs.mkdtempSync(path.join(os.tmpdir(),'dsg-r2-'));
| try{
| for(const p of [AUDIT_REPORT,SOURCE_AUTH,ITEM_AUTH,...DESIGN_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 sources=parseCsv(fs.readFileSync(abs(SOURCE_AUTH),'utf8')).rows;
| for(const s of sources){fs.mkdirSync(path.dirname(abs(s.source_path,tmp)),{recursive:true});fs.copyFileSync(abs(s.source_path),abs(s.source_path,tmp));}
| const release=kind==='FAIL_RELEASE_WITH_PASS_MENTIONS'
| ?`\n### ${RELEASE_AUDIT}\nresult=FAIL\nPASS is explicitly not granted\nexecution_release=NOT_RELEASED\nrequested EXPLICITLY_RELEASED but NOT_RELEASED\nreleased_batch_id=${EXEC_BATCH}\nreleased_run_id=${EXEC_RUN}\n`
| :`\n### ${RELEASE_AUDIT}\nresult=PASS\nexecution_release=EXPLICITLY_RELEASED\nreleased_batch_id=${EXEC_BATCH}\nreleased_run_id=${EXEC_RUN}\n`;
| fs.appendFileSync(abs(AUDIT_REPORT,tmp),release,'utf8');
| const designRows=[];
| for(const p of DESIGN_PATHS){if(p===DESIGN_VALIDATION)writeText(p,'validation-placeholder\n',tmp);const z=fid(p,tmp);designRows.push({case_id:CASE_ID,run_id:DESIGN_RUN,batch_id:DESIGN_BATCH,artifact_path:p,sha256:z.sha256,bytes:String(z.bytes),mtime:z.mtime});}
| fs.appendFileSync(abs(MANIFEST,tmp),csv(designRows,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])),beforeManifest=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(beforeManifest);
| rows.push({test_id:`TRANSACTION_${kind}`,mutation_applied:'YES',oracle:'executeR2',expected,expected_code:kind==='FAIL_RELEASE_WITH_PASS_MENTIONS'?'RELEASE_EXACT_LINE:result=PASS':'SAFE_STATE',actual:out.status,actual_codes:(out.errors??[]).join('|'),safe_state_verified:safe?'YES':'NO',result:out.status===expected&&safe?'PASS':'FAIL'});
| }finally{fs.rmSync(tmp,{recursive:true,force:true});}
| }
| return rows;
| }
| export function negativeRows(){return[releaseNegative(),...bundleNegativeRows(),...missingArtifactRows(),...manifestNegativeRows(),...transactionNegativeRows()];}
|
| if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){const mode=process.argv[2]??'--preview';if(mode==='--preview'){const b=expectedBundle(),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==='--validate-design-inputs'){const e=prewriteErrors({token:EXEC_TOKEN,requireRelease:false}).filter(x=>x.startsWith('DESIGN_MANIFEST_ROWS:')||x==='DESIGN_MANIFEST_PATH_SET'?false:true);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==='--self-test-json'){const r=negativeRows();console.log(JSON.stringify(r,null,2));if(r.some(x=>x.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=executionErrors();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}`);}
|
|