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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import {pathToFileURL} from 'node:url';
import * as prior from './detail_strengthening_p0_open_gap_candidate_semantic_verification_runtime_repair001_20260731.mjs';
import {
  parseAuthorityCsv,
  serializeCsv,
  serializeManifestDataRows,
  validateAppendStableManifest,
} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
export const ROOT=prior.ROOT,CASE_ID=prior.CASE_ID,BASE=prior.BASE,AUDIT_REPORT=prior.AUDIT_REPORT,MANIFEST=prior.MANIFEST,ANOMALY_AUTHORITY=prior.ANOMALY_AUTHORITY,ORIGINAL_TRIAGE_RUN=prior.ORIGINAL_TRIAGE_RUN;
export const CANDIDATES=prior.CANDIDATES,PROVENANCE=prior.PROVENANCE,RAW_ARCHIVE=prior.RAW_ARCHIVE,TARGET_AUTHORITY=prior.TARGET_AUTHORITY,GAP_AUTHORITY=prior.GAP_AUTHORITY,PROTECTED_INVENTORY=prior.PROTECTED_INVENTORY;
export const CRITERIA=prior.CRITERIA,DECISION_AUTHORITY=prior.DECISION_AUTHORITY,SCHEMA=prior.SCHEMA;
export const FORMAL_ENTRY_COLUMNS=prior.FORMAL_ENTRY_COLUMNS,CRITERIA_COLUMNS=prior.CRITERIA_COLUMNS,DECISION_COLUMNS=prior.DECISION_COLUMNS,SUMMARY_COLUMNS=prior.SUMMARY_COLUMNS,APPLICATION_COLUMNS=prior.APPLICATION_COLUMNS,CONTRACT_COLUMNS=prior.CONTRACT_COLUMNS,SCHEMA_COLUMNS=prior.SCHEMA_COLUMNS,EXEC_SET_COLUMNS=prior.EXEC_SET_COLUMNS,BASELINE_COLUMNS=prior.BASELINE_COLUMNS,VALIDATION_COLUMNS=prior.VALIDATION_COLUMNS;
 
export const DESIGN_ID='DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-CANDIDATE-SEMANTIC-VERIFICATION-REPAIR-002';
export const DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REPAIR-002';
export const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REPAIR-002';
export const EXEC_RUN=prior.EXEC_RUN;
export const EXEC_BATCH=prior.EXEC_BATCH;
export const SOURCE_AUDIT=prior.SOURCE_AUDIT;
export const FAILED_REVIEW_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REPAIR001-REREVIEW-001';
export const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REPAIR002-REREVIEW-001';
export const EXEC_TOKEN='EXECUTE_DETAIL_STRENGTHENING_P0_OPEN_GAP_CANDIDATE_SEMANTIC_VERIFICATION_REPAIR002';
export const SCRIPT='dev/ana-dev/detail_strengthening_p0_open_gap_candidate_semantic_verification_runtime_repair002_20260731.mjs';
export const FORMAL_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_verification_formal_design_entry_authority_repair002_20260731.csv`;
export const CONTRACT=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_verification_contract_repair002_20260731.csv`;
export const EXEC_SET=`${BASE}/manifest/detail_strengthening_p0_open_gap_candidate_semantic_verification_execution_artifact_set_repair002_20260731.csv`;
export const FAULT_RESULTS=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_verification_transaction_fault_results_repair002_20260731.csv`;
export const EXEC_BASELINE=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_verification_execution_baseline_repair002_20260731.csv`;
export const QUALIFICATION=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_qualification_ledger_repair002_20260731.csv`;
export const GAP_SUMMARY=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_gap_summary_repair002_20260731.csv`;
export const APPLICATION=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_occurrence_application_repair002_20260731.csv`;
export const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_open_gap_candidate_semantic_verification_execution_repair002_20260731.md`;
export const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_open_gap_candidate_semantic_verification_execution_validation_repair002_20260731.csv`;
export const GENERATED=[EXEC_BASELINE,QUALIFICATION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
 
export const FAULT_COLUMNS=['fault_id','fault_name','expected_status','actual_status','actual_io_throw','stage_reached','manifest_bytes_exact','manifest_mtime_exact','generated_absent','transaction_safe','independent_safe','retryable','result'];
 
const abs=value=>path.join(ROOT,...value.split('/'));
const hash=value=>crypto.createHash('sha256').update(value).digest('hex');
const normalize=value=>value.toString('utf8').replace(/^\uFEFF/,'').replace(/\r\n/g,'\n').replace(/\r/g,'\n');
const lineCount=value=>{const text=normalize(value);return text.split('\n').length-(text.endsWith('\n')?1:0);};
const readCsv=file=>{const parsed=parseAuthorityCsv(normalize(fs.readFileSync(abs(file))));if(parsed.errors.length)throw new Error(`CSV:${file}:${parsed.errors.join('|')}`);return parsed;};
const identity=file=>{const buffer=fs.readFileSync(abs(file)),stat=fs.statSync(abs(file));return{rows:file.endsWith('.csv')?readCsv(file).rows.length:lineCount(buffer),bytes:buffer.length,sha256:hash(buffer),mtime:new Date(Math.trunc(stat.mtimeMs)).toISOString(),mtimeMs:Math.trunc(stat.mtimeMs)};};
const exactColumns=(parsed,columns,code)=>parsed.header.join('|')===columns.join('|')?[]:[`${code}_COLUMNS`];
const compareRows=(actual,expected,columns,code)=>{const errors=[];if(actual.length!==expected.length)return[`${code}_COUNT:${actual.length}:${expected.length}`];for(let index=0;index<expected.length;index++)for(const column of columns)if(String(actual[index]?.[column]??'')!==String(expected[index]?.[column]??'')){errors.push(`${code}_FIELD:${index+1}:${column}`);break;}return errors;};
const normalizedLines=text=>normalize(Buffer.from(text)).split('\n').map(line=>line.trim().replace(/^[\-*]\s*/, '').replace(/`/g,'').trim());
 
export const criteriaRows=prior.criteriaRows;
export const decisionRows=prior.decisionRows;
export const deriveOutputs=prior.deriveOutputs;
export const coreErrors=prior.coreErrors;
export const auditEntry=prior.auditEntry;
 
function exactKeyErrors(text,expected,scope){
  const lines=normalizedLines(text),errors=[];
  for(const [key,value] of Object.entries(expected)){
    const matches=lines.filter(line=>line.startsWith(`${key}=`));
    if(matches.length!==1)errors.push(`${scope}_KEY_COUNT:${key}:${matches.length}`);
    else if(matches[0]!==`${key}=${value}`)errors.push(`${scope}_KEY_VALUE:${key}:${matches[0].slice(key.length+1)}`);
  }
  return errors;
}
 
export function releaseTextErrors(text){
  const expected={
    reviewed_design_id:DESIGN_ID,
    result:'PASS',
    execution_release:'EXPLICITLY_RELEASED',
    released_batch_id:EXEC_BATCH,
    released_run_id:EXEC_RUN,
    network_scope:'FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK',
    candidate_outcome_ceiling:'QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE',
  };
  const lines=normalizedLines(text),errors=exactKeyErrors(text,expected,'RELEASE');
  if(lines.some(line=>/^(?:result|conclusion)=FAIL(?:_|$)/.test(line)))errors.push('RELEASE_CONTRADICTION:FAIL');
  if(lines.some(line=>/^execution_release=(?:NOT_ALLOWED|NOT_RELEASED)/.test(line)))errors.push('RELEASE_CONTRADICTION:NOT_RELEASED');
  return [...new Set(errors)];
}
 
export function releaseErrors({required=false}={}){
  const entry=auditEntry(RELEASE_AUDIT);
  return entry?releaseTextErrors(entry.text):required?['RELEASE_AUDIT_MISSING']:[];
}
 
export function formalScopeTextErrors(text){
  const expected={
    effective_network_scope:'FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK',
    superseded_conflicting_network_scope:'PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY',
    superseded_conflicting_scope_effect:'HISTORICAL_TEXT_NOT_EXECUTION_AUTHORITY',
    network_calls:'0',
    candidate_outcome_ceiling:'QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE',
  };
  const lines=normalizedLines(text),errors=exactKeyErrors(text,expected,'FORMAL_SCOPE');
  if(lines.some(line=>line==='network_scope=PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY'))errors.push('FORMAL_SCOPE_ACTIVE_NETWORK_CONTRADICTION');
  return [...new Set(errors)];
}
 
export function contractRows(){
  const rows=prior.contractRows().map((row,index)=>({...row,contract_id:`P0ACQSEMR2-CON-${String(index+1).padStart(3,'0')}`}));
  const additions=[
    ['FORMAL_SCOPE','NETWORK_SCOPE','effective scope exact local/no-network; conflicting prior acquisition text explicitly historical only'],
    ['RELEASE_GATE','SEVEN_KEYS_UNIQUE','reviewed_design_id/result/release/batch/run/network/ceiling each exactly one'],
    ['RELEASE_GATE','CONTRADICTION_REJECT','duplicate, wrong, FAIL, NOT_RELEASED, NOT_ALLOWED or mixed value rejects'],
    ['TRANSACTION','SINGLE_PRODUCTION_PATH','all six generated writes, manifest candidate/commit and postwrite use runProductionTransactionR2'],
    ['ROLLBACK','MANIFEST_BEFORE_IDENTITY','restore exact bytes and filesystem-ms mtime'],
    ['ROLLBACK','PRIMARY_FALLBACK','restore-write/mtime/remove primary failure invokes independent fallback and remains held'],
    ['ROLLBACK','POSTCHECK','exists/read/stat failure invokes independent verification and remains held'],
    ['FAULT_AUTHORITY','REAL_IO','ten production-path cases freeze actual throw, stage, safe state and retryability'],
    ['EXECUTION','NETWORK_CALLS','exactly zero; frozen local semantic verification only'],
  ];
  for(const [scope,field,rule] of additions)rows.push({contract_id:`P0ACQSEMR2-CON-${String(rows.length+1).padStart(3,'0')}`,scope,field_or_gate:field,required_value_or_rule:rule,failure_state:'FAIL_CLOSED_NO_OUTPUT_COMMIT'});
  return rows;
}
 
export const schemaRows=prior.schemaRows;
 
export function executionSetRows(){
  const paths=[SCRIPT,CANDIDATES,PROVENANCE,RAW_ARCHIVE,TARGET_AUTHORITY,GAP_AUTHORITY,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,FAULT_RESULTS,EXEC_BASELINE,QUALIFICATION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
  const roles=['RUNTIME_REPAIR002','CANDIDATES_REUSED','PROVENANCE_REUSED','RAW_ARCHIVE_REUSED','TARGET_AUTHORITY_REUSED','GAP_AUTHORITY_REUSED','SEMANTIC_CRITERIA_REUSED','DECISION_AUTHORITY_REUSED','RUNTIME_CONTRACT_REPAIR002','OUTPUT_SCHEMA_REUSED','EXECUTION_EXACT_SET_REPAIR002','TRANSACTION_FAULT_AUTHORITY_REPAIR002','EXECUTION_BASELINE_FIRST_GENERATED','QUALIFICATION_LEDGER','GAP_SUMMARY','OCCURRENCE_APPLICATION','EXECUTION_REQUEST','VALIDATION_LAST'];
  return paths.map((artifactPath,index)=>({artifact_id:`P0ACQSEMR2-EXEC-SET-${String(index+1).padStart(3,'0')}`,batch_id:EXEC_BATCH,run_id:EXEC_RUN,generation_order:String(index+1),artifact_path:artifactPath,artifact_role:roles[index],identity_policy:'EXACT_SHA256_BYTES_FILESYSTEM_MTIME_MS'}));
}
 
function manifestState({expectedRows=[],expectedRunId='',frozenPrefix=null,expectedPhysicalDelta=null}={}){
  return validateAppendStableManifest(fs.readFileSync(abs(MANIFEST)),{
    anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,
    frozenPrefix,
    originalRunId:ORIGINAL_TRIAGE_RUN,
    originalRunExpectedRows:11,
    expectedRunRows:expectedRows,
    expectedRunId,
    expectedPhysicalDelta,
    filesystemIdentity:{runIds:expectedRunId?[expectedRunId]:[],get:file=>fs.existsSync(abs(file))?identity(file):null},
  });
}
 
function protectedRows(){
  const rows=readCsv(PROTECTED_INVENTORY).rows;
  if(rows.length!==49)throw new Error(`PROTECTED_COUNT:${rows.length}`);
  return rows.map(row=>({path:row.artifact_path,...identity(row.artifact_path)}));
}
 
function formalEntryErrors(){
  if(!fs.existsSync(abs(FORMAL_ENTRY_AUTHORITY)))return['FORMAL_ENTRY_AUTHORITY_MISSING'];
  const parsed=readCsv(FORMAL_ENTRY_AUTHORITY),errors=[...exactColumns(parsed,FORMAL_ENTRY_COLUMNS,'FORMAL_ENTRY')];
  if(parsed.rows.length!==1)return[...errors,`FORMAL_ENTRY_COUNT:${parsed.rows.length}`];
  const row=parsed.rows[0],lines=normalize(fs.readFileSync(abs(row.artifact_path))).split('\n');
  const buffer=Buffer.from(`${lines.slice(Number(row.start_line)-1,Number(row.end_line)).join('\n')}\n`);
  if(String(lineCount(buffer))!==row.lines||String(buffer.length)!==row.bytes||hash(buffer)!==row.sha256)errors.push('FORMAL_ENTRY_IDENTITY');
  for(const marker of row.required_markers.split('|'))if(!buffer.toString('utf8').includes(marker))errors.push(`FORMAL_ENTRY_MARKER:${marker}`);
  errors.push(...formalScopeTextErrors(buffer.toString('utf8')));
  return errors;
}
 
function makeIo(overrides={}){
  return {
    existsSync:fs.existsSync,
    readFileSync:fs.readFileSync,
    writeFileSync:fs.writeFileSync,
    mkdirSync:fs.mkdirSync,
    rmSync:fs.rmSync,
    statSync:fs.statSync,
    utimesSync:fs.utimesSync,
    ...overrides,
  };
}
 
function verifySafeState({manifestPath,manifestBefore,manifestBeforeMtimeMs,generatedPaths,io}){
  const errors=[];
  let actualIoThrow=false;
  let manifestBytesExact=false,manifestMtimeExact=false,generatedAbsent=false;
  try{manifestBytesExact=io.existsSync(manifestPath)&&io.readFileSync(manifestPath).equals(manifestBefore);}catch(error){actualIoThrow ||= Boolean(error.actualIoThrow);errors.push(`POSTCHECK_READ:${error.message}`);}
  try{manifestMtimeExact=io.existsSync(manifestPath)&&Math.trunc(io.statSync(manifestPath).mtimeMs)===manifestBeforeMtimeMs;}catch(error){actualIoThrow ||= Boolean(error.actualIoThrow);errors.push(`POSTCHECK_STAT:${error.message}`);}
  try{generatedAbsent=generatedPaths.every(file=>!io.existsSync(file));}catch(error){actualIoThrow ||= Boolean(error.actualIoThrow);errors.push(`POSTCHECK_EXISTS:${error.message}`);}
  return{manifestBytesExact,manifestMtimeExact,generatedAbsent,safe:manifestBytesExact&&manifestMtimeExact&&generatedAbsent,actualIoThrow,errors};
}
 
export function runProductionTransactionR2({manifestPath,manifestBefore,manifestBeforeMtimeMs,payloads,buildManifestCandidate,postwriteOracle,io=makeIo(),fallbackIo=makeIo(),verifyIo=makeIo(),finalIo=makeIo()}={}){
  let stage='START',manifestCommitted=false,manifestRows=[];
  try{
    for(let index=0;index<payloads.length;index++){
      const payload=payloads[index];
      stage=`PAYLOAD_WRITE_${index+1}`;
      io.mkdirSync(path.dirname(payload.path),{recursive:true});
      io.writeFileSync(payload.path,payload.bytes);
    }
    stage='MANIFEST_CANDIDATE';
    const built=buildManifestCandidate();
    if(built.errors?.length)throw new Error(`MANIFEST_CANDIDATE:${built.errors.join('|')}`);
    manifestRows=built.rows??[];
    stage='MANIFEST_WRITE';
    io.writeFileSync(manifestPath,built.candidate);
    manifestCommitted=true;
    stage='POSTWRITE_ORACLE';
    const postErrors=postwriteOracle();
    if(postErrors.length)throw new Error(`POSTWRITE:${postErrors.join('|')}`);
    return{status:'COMMITTED',stage:'COMPLETED',manifestCommitted,manifestRows,safe:true,retryable:false,actualIoThrow:false,errors:[]};
  }catch(error){
    const cleanupErrors=[],generatedPaths=payloads.map(row=>row.path);
    let actualIoThrow=Boolean(error.actualIoThrow);
    const primary=(label,operation,fallback)=>{
      try{operation();}
      catch(failure){
        actualIoThrow ||= Boolean(failure.actualIoThrow);
        cleanupErrors.push(`${label}_PRIMARY:${failure.message}`);
        try{fallback();}catch(second){actualIoThrow ||= Boolean(second.actualIoThrow);cleanupErrors.push(`${label}_FALLBACK:${second.message}`);}
      }
    };
    primary('RESTORE_WRITE',()=>io.writeFileSync(manifestPath,manifestBefore),()=>fallbackIo.writeFileSync(manifestPath,manifestBefore));
    const beforeDate=new Date(manifestBeforeMtimeMs);
    primary('RESTORE_MTIME',()=>io.utimesSync(manifestPath,beforeDate,beforeDate),()=>fallbackIo.utimesSync(manifestPath,beforeDate,beforeDate));
    for(const file of generatedPaths){
      let exists=false;
      try{exists=io.existsSync(file);}catch(failure){cleanupErrors.push(`REMOVE_EXISTS_PRIMARY:${failure.message}`);try{exists=fallbackIo.existsSync(file);}catch(second){cleanupErrors.push(`REMOVE_EXISTS_FALLBACK:${second.message}`);}}
      if(exists)primary(`REMOVE:${path.basename(file)}`,()=>io.rmSync(file,{force:true}),()=>fallbackIo.rmSync(file,{force:true}));
    }
    const verified=verifySafeState({manifestPath,manifestBefore,manifestBeforeMtimeMs,generatedPaths,io:verifyIo});
    actualIoThrow ||= verified.actualIoThrow;
    cleanupErrors.push(...verified.errors.map(value=>`VERIFY_PRIMARY:${value}`));
    const final=verified.errors.length||!verified.safe?verifySafeState({manifestPath,manifestBefore,manifestBeforeMtimeMs,generatedPaths,io:finalIo}):verified;
    actualIoThrow ||= final.actualIoThrow;
    cleanupErrors.push(...final.errors.map(value=>`VERIFY_FALLBACK:${value}`));
    const safe=final.safe;
    const status=cleanupErrors.length||!safe?'ROLLBACK_INCOMPLETE_HELD':'SAFE_ABORT_RETRYABLE';
    return{status,stage,manifestCommitted,manifestRows,safe,retryable:status==='SAFE_ABORT_RETRYABLE',actualIoThrow,errors:[`CAUSE:${error.message}`,...cleanupErrors]};
  }
}
 
function injected(message){const error=new Error(message);error.actualIoThrow=true;return error;}
 
function runFaultCase(name){
  const dir=fs.mkdtempSync(path.join(os.tmpdir(),'p0-acq-sem-r2-'));
  const manifestPath=path.join(dir,'manifest.csv'),one=path.join(dir,'one.csv'),two=path.join(dir,'two.csv');
  const manifestBefore=Buffer.from('case_id,run_id,batch_id,artifact_path,sha256,bytes,mtime\n');
  fs.writeFileSync(manifestPath,manifestBefore);
  const beforeMtimeMs=Math.trunc(Date.now()-20000);
  const beforeDate=new Date(beforeMtimeMs);
  fs.utimesSync(manifestPath,beforeDate,beforeDate);
  const manifestCandidate=Buffer.concat([manifestBefore,Buffer.from('x,y,z,p,h,1,2026-07-31T00:00:00.000Z\n')]);
  const payloads=[{path:one,bytes:Buffer.from('one\n')},{path:two,bytes:Buffer.from('two\n')}];
  let writeCount=0,verifyThrow=false;
  const overrides={};
  let postwrite=()=>name==='SUCCESS_CONTROL'?[]:['INJECTED_POSTWRITE'];
  if(name==='PAYLOAD_WRITE_FAILURE')overrides.writeFileSync=(file,data)=>{if(file===two)throw injected('INJECTED_PAYLOAD_WRITE');return fs.writeFileSync(file,data);};
  if(name==='MANIFEST_WRITE_FAILURE')overrides.writeFileSync=(file,data)=>{if(file===manifestPath&&Buffer.from(data).equals(manifestCandidate))throw injected('INJECTED_MANIFEST_WRITE');return fs.writeFileSync(file,data);};
  if(name==='RESTORE_WRITE_FAILURE')overrides.writeFileSync=(file,data)=>{if(file===manifestPath&&++writeCount===2)throw injected('INJECTED_RESTORE_WRITE');return fs.writeFileSync(file,data);};
  if(name==='RESTORE_MTIME_FAILURE')overrides.utimesSync=(file,a,m)=>{if(file===manifestPath)throw injected('INJECTED_RESTORE_MTIME');return fs.utimesSync(file,a,m);};
  if(name==='REMOVE_FAILURE')overrides.rmSync=(file,options)=>{if(!verifyThrow){verifyThrow=true;throw injected('INJECTED_REMOVE');}return fs.rmSync(file,options);};
  const verifyOverrides={};
  if(name==='POSTCHECK_EXISTS_FAILURE')verifyOverrides.existsSync=file=>{if(!verifyThrow){verifyThrow=true;throw injected('INJECTED_POSTCHECK_EXISTS');}return fs.existsSync(file);};
  if(name==='POSTCHECK_READ_FAILURE')verifyOverrides.readFileSync=file=>{if(!verifyThrow){verifyThrow=true;throw injected('INJECTED_POSTCHECK_READ');}return fs.readFileSync(file);};
  if(name==='POSTCHECK_STAT_FAILURE')verifyOverrides.statSync=file=>{if(!verifyThrow){verifyThrow=true;throw injected('INJECTED_POSTCHECK_STAT');}return fs.statSync(file);};
  if(name==='POSTWRITE_FAILURE'||name==='CLEAN_ROLLBACK_CONTROL'||name.startsWith('RESTORE_')||name==='REMOVE_FAILURE'||name.startsWith('POSTCHECK_'))postwrite=()=>['INJECTED_POSTWRITE'];
  if(name==='SUCCESS_CONTROL')postwrite=()=>[];
  const result=runProductionTransactionR2({
    manifestPath,manifestBefore,manifestBeforeMtimeMs:beforeMtimeMs,payloads,
    buildManifestCandidate:()=>({candidate:manifestCandidate,rows:[{path:'x'}],errors:[]}),
    postwriteOracle:postwrite,
    io:makeIo(overrides),fallbackIo:makeIo(),verifyIo:makeIo(verifyOverrides),finalIo:makeIo(),
  });
  const independent=verifySafeState({manifestPath,manifestBefore,manifestBeforeMtimeMs:beforeMtimeMs,generatedPaths:[one,two],io:makeIo()});
  const heldNames=new Set(['RESTORE_WRITE_FAILURE','RESTORE_MTIME_FAILURE','REMOVE_FAILURE','POSTCHECK_EXISTS_FAILURE','POSTCHECK_READ_FAILURE','POSTCHECK_STAT_FAILURE']);
  const expectedStatus=name==='SUCCESS_CONTROL'?'COMMITTED':heldNames.has(name)?'ROLLBACK_INCOMPLETE_HELD':'SAFE_ABORT_RETRYABLE';
  const expectedIo=new Set(['PAYLOAD_WRITE_FAILURE','MANIFEST_WRITE_FAILURE','RESTORE_WRITE_FAILURE','RESTORE_MTIME_FAILURE','REMOVE_FAILURE','POSTCHECK_EXISTS_FAILURE','POSTCHECK_READ_FAILURE','POSTCHECK_STAT_FAILURE']).has(name)?'YES':'NO';
  const manifestBytesExact=name==='SUCCESS_CONTROL'?fs.readFileSync(manifestPath).equals(manifestCandidate):independent.manifestBytesExact;
  const manifestMtimeExact=name==='SUCCESS_CONTROL'?'N/A':independent.manifestMtimeExact?'YES':'NO';
  const generatedAbsent=name==='SUCCESS_CONTROL'?'N/A':independent.generatedAbsent?'YES':'NO';
  const independentSafe=name==='SUCCESS_CONTROL'?true:independent.safe;
  const pass=result.status===expectedStatus&&String(result.actualIoThrow?'YES':'NO')===expectedIo&&independentSafe&&(name==='SUCCESS_CONTROL'||result.safe===true);
  const row={fault_id:`P0ACQSEMR2-FAULT-${name}`,fault_name:name,expected_status:expectedStatus,actual_status:result.status,actual_io_throw:result.actualIoThrow?'YES':'NO',stage_reached:result.stage,manifest_bytes_exact:manifestBytesExact?'YES':'NO',manifest_mtime_exact:manifestMtimeExact,generated_absent:generatedAbsent,transaction_safe:result.safe?'YES':'NO',independent_safe:independentSafe?'YES':'NO',retryable:result.retryable?'YES':'NO',result:pass?'PASS':'FAIL'};
  fs.rmSync(dir,{recursive:true,force:true});
  return row;
}
 
export function transactionFaultRows(){
  return ['PAYLOAD_WRITE_FAILURE','MANIFEST_WRITE_FAILURE','POSTWRITE_FAILURE','RESTORE_WRITE_FAILURE','RESTORE_MTIME_FAILURE','REMOVE_FAILURE','POSTCHECK_EXISTS_FAILURE','POSTCHECK_READ_FAILURE','POSTCHECK_STAT_FAILURE','CLEAN_ROLLBACK_CONTROL'].map(runFaultCase);
}
 
export function transactionFaultErrors(rows=transactionFaultRows()){
  const errors=[];
  if(rows.length!==10)errors.push(`FAULT_COUNT:${rows.length}:10`);
  if(rows.some(row=>row.result!=='PASS'))errors.push(...rows.filter(row=>row.result!=='PASS').map(row=>`FAULT_FAIL:${row.fault_name}`));
  return errors;
}
 
export function designInputErrors({requireRelease=false,expectNoExecution=true}={}){
  const errors=[...prior.sourceAuditErrors(),...prior.sourcePackageLifecycleErrors(),...releaseErrors({required:requireRelease}),...formalEntryErrors()];
  for(const file of [CANDIDATES,PROVENANCE,RAW_ARCHIVE,TARGET_AUTHORITY,GAP_AUTHORITY,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,FAULT_RESULTS])if(!fs.existsSync(abs(file)))errors.push(`INPUT_MISSING:${file}`);
  if(errors.some(error=>error.startsWith('INPUT_MISSING')))return[...new Set(errors)];
  const criteria=readCsv(CRITERIA),decisions=readCsv(DECISION_AUTHORITY),contracts=readCsv(CONTRACT),schemas=readCsv(SCHEMA),execSet=readCsv(EXEC_SET),faults=readCsv(FAULT_RESULTS);
  errors.push(...exactColumns(criteria,CRITERIA_COLUMNS,'CRITERIA'),...compareRows(criteria.rows,criteriaRows(),CRITERIA_COLUMNS,'CRITERIA'));
  errors.push(...exactColumns(decisions,DECISION_COLUMNS,'DECISION'),...compareRows(decisions.rows,decisionRows(),DECISION_COLUMNS,'DECISION'));
  errors.push(...exactColumns(contracts,CONTRACT_COLUMNS,'CONTRACT'),...compareRows(contracts.rows,contractRows(),CONTRACT_COLUMNS,'CONTRACT'));
  errors.push(...exactColumns(schemas,SCHEMA_COLUMNS,'SCHEMA'),...compareRows(schemas.rows,schemaRows(),SCHEMA_COLUMNS,'SCHEMA'));
  errors.push(...exactColumns(execSet,EXEC_SET_COLUMNS,'EXEC_SET'),...compareRows(execSet.rows,executionSetRows(),EXEC_SET_COLUMNS,'EXEC_SET'));
  errors.push(...exactColumns(faults,FAULT_COLUMNS,'FAULT'),...compareRows(faults.rows,transactionFaultRows(),FAULT_COLUMNS,'FAULT'),...transactionFaultErrors(faults.rows));
  if(expectNoExecution){
    if(GENERATED.some(file=>fs.existsSync(abs(file))))errors.push('EXECUTION_FILES_EXIST');
    if(manifestState().logicalRows.some(row=>row.run_id===EXEC_RUN))errors.push('EXECUTION_MANIFEST_ROWS');
  }
  return[...new Set(errors)];
}
 
function baselineRows(){
  const source=auditEntry(SOURCE_AUDIT),release=auditEntry(RELEASE_AUDIT),manifest=fs.readFileSync(abs(MANIFEST));
  if(!source||!release)throw new Error('AUDIT_ENTRY_MISSING');
  const rows=[
    {baseline_id:'P0ACQSEMR2-BASE-001',identity_type:'SOURCE_EXECUTION_AUDIT_ENTRY',artifact_path:`${AUDIT_REPORT}#L${source.start}-L${source.end}`,rows:String(source.lines),bytes:String(source.bytes),sha256:source.sha256,mtime:'INFO_APPENDABLE_SHARED_FILE',required_state:'EXACT_SOURCE_PASS_AND_DESIGN_PREPARATION_ALLOWED'},
    {baseline_id:'P0ACQSEMR2-BASE-002',identity_type:'DESIGN_RELEASE_AUDIT_ENTRY',artifact_path:`${AUDIT_REPORT}#L${release.start}-L${release.end}`,rows:String(release.lines),bytes:String(release.bytes),sha256:release.sha256,mtime:'INFO_APPENDABLE_SHARED_FILE',required_state:'EXACT_UNIQUE_SEVEN_KEY_RELEASE'},
    {baseline_id:'P0ACQSEMR2-BASE-003',identity_type:'RAW_MANIFEST_BEFORE_EXECUTION',artifact_path:MANIFEST,rows:String(manifestState().logicalDataRows),bytes:String(manifest.length),sha256:hash(manifest),mtime:new Date(Math.trunc(fs.statSync(abs(MANIFEST)).mtimeMs)).toISOString(),required_state:'EXACT_APPEND_ONLY_PREFIX_BYTES_AND_MTIME'},
  ];
  for(const file of executionSetRows().slice(0,12).map(row=>row.artifact_path)){
    const id=identity(file);rows.push({baseline_id:`P0ACQSEMR2-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'FROZEN_EXECUTION_INPUT',artifact_path:file,rows:String(id.rows),bytes:String(id.bytes),sha256:id.sha256,mtime:id.mtime,required_state:'EXACT_NO_DRIFT'});
  }
  for(const item of protectedRows())rows.push({baseline_id:`P0ACQSEMR2-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'PROTECTED_OUTPUT_CURRENT_IDENTITY',artifact_path:item.path,rows:String(item.rows),bytes:String(item.bytes),sha256:item.sha256,mtime:item.mtime,required_state:'NO_MUTATION'});
  return rows;
}
 
function baselineErrors(rows){
  const errors=[];
  if(rows.length!==64)return[`BASELINE_COUNT:${rows.length}:64`];
  for(const [row,entry,code] of [[rows[0],auditEntry(SOURCE_AUDIT),'SOURCE'],[rows[1],auditEntry(RELEASE_AUDIT),'RELEASE']])if(!entry||row.rows!==String(entry.lines)||row.bytes!==String(entry.bytes)||row.sha256!==entry.sha256)errors.push(`BASELINE_${code}_AUDIT`);
  const manifest=fs.readFileSync(abs(MANIFEST)),prefix=rows[2];
  if(manifest.length<Number(prefix.bytes)||hash(manifest.subarray(0,Number(prefix.bytes)))!==prefix.sha256)errors.push('BASELINE_MANIFEST_PREFIX');
  for(const row of rows.slice(3)){
    if(!fs.existsSync(abs(row.artifact_path))){errors.push(`BASELINE_PATH_MISSING:${row.artifact_path}`);continue;}
    const id=identity(row.artifact_path);
    if(row.rows!==String(id.rows)||row.bytes!==String(id.bytes)||row.sha256!==id.sha256||Date.parse(row.mtime)!==id.mtimeMs)errors.push(`BASELINE_IDENTITY:${row.artifact_path}`);
  }
  return errors;
}
 
function expectedState(){
  const candidates=readCsv(CANDIDATES).rows,provenance=readCsv(PROVENANCE).rows,criteria=readCsv(CRITERIA).rows,decisions=readCsv(DECISION_AUTHORITY).rows,derived=deriveOutputs(decisions);
  return{candidates,provenance,criteria,decisions,summary:derived.summary,applications:derived.applications};
}
 
function requestText(){return`# P0 开放缺口新增候选语义核验执行复审请求(REPAIR-002)\n\ncase_id=${CASE_ID}\nsource_audit=${SOURCE_AUDIT}\nrelease_audit=${RELEASE_AUDIT}\ndesign_id=${DESIGN_ID}\nbatch_id=${EXEC_BATCH}\nrun_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nnetwork_calls=0\ncandidate_outcome_ceiling=QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE\nqualification_rows=14\nqualified_rows=4\ncontext_only_rows=10\ngap_summary_rows=7\noccurrence_application_rows=10\ngap_effect=OPEN_RETAINED_GAP\nclaim_strength_ceiling=PENDING_VERIFICATION_MAX_NO_UPGRADE\nformal_pool_effect=NO_AUTOMATIC_FORMAL_POOL_CHANGE\nevidence_strength_effect=NO_UPGRADE\noutput_mutation=NONE\nrun_status=EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW\n`;}
 
function validationRows(state){
  const errors=coreErrors(state),faults=readCsv(FAULT_RESULTS).rows;
  const checks=[
    ['CORE_ERRORS','0',String(errors.length)],['SOURCE_PACKAGE_ERRORS','0',String(prior.sourcePackageLifecycleErrors().length)],['FORMAL_SCOPE_ERRORS','0',String(formalEntryErrors().length)],['RELEASE_ERRORS','0',String(releaseErrors({required:true}).length)],
    ['CANDIDATES','14',String(state.candidates.length)],['PROVENANCE','14',String(state.provenance.length)],['CRITERIA','7',String(state.criteria.length)],['QUALIFICATION','14',String(state.decisions.length)],['QUALIFIED','4',String(state.decisions.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW').length)],['CONTEXT_ONLY','10',String(state.decisions.filter(row=>row.outcome==='CONTEXT_ONLY_NOT_GAP_CLOSING').length)],
    ['SUMMARY','7',String(state.summary.length)],['APPLICATION','10',String(state.applications.length)],['OPEN_GAPS','14',String(state.decisions.filter(row=>row.gap_state_after==='OPEN_RETAINED_GAP').length)],['CLAIM_CEILING','14',String(state.decisions.filter(row=>row.claim_strength_after==='PENDING_VERIFICATION_MAX_NO_UPGRADE').length)],['POOL_BOUNDARY','14',String(state.decisions.filter(row=>row.formal_pool_effect==='NO_AUTOMATIC_FORMAL_POOL_CHANGE').length)],['EVIDENCE_BOUNDARY','14',String(state.decisions.filter(row=>row.evidence_strength_effect==='NO_UPGRADE').length)],
    ['OUTPUT_MUTATION','0',String(state.applications.filter(row=>row.output_mutation!=='NONE').length)],['FAULT_PASS','10',String(faults.filter(row=>row.result==='PASS').length)],['EXACT_SET','18',String(executionSetRows().length)],['NETWORK_CALLS','0','0'],
  ];
  const rows=checks.map((item,index)=>({check_id:`P0ACQSEMR2-EXEC-VAL-${String(index+1).padStart(3,'0')}`,check_description:item[0],expected:item[1],actual:item[2],status:item[1]===item[2]?'PASS':'FAIL',evidence:'REPAIR002_SHARED_FAIL_CLOSED_ORACLE'}));
  rows.push({check_id:'P0ACQSEMR2-EXEC-VAL-021',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identities postchecked'});
  return rows;
}
 
function manifestRowsFor(paths){return paths.map(file=>{const id=identity(file);return{case_id:CASE_ID,run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:file,sha256:id.sha256,bytes:String(id.bytes),mtime:id.mtime};});}
 
export function execute({token}={}){
  if(token!==EXEC_TOKEN)throw new Error('EXECUTION_TOKEN_MISMATCH');
  const pre=designInputErrors({requireRelease:true,expectNoExecution:true});
  if(pre.length)throw new Error(`PREWRITE:${pre.join('|')}`);
  const manifestBefore=fs.readFileSync(abs(MANIFEST)),manifestBeforeMtimeMs=Math.trunc(fs.statSync(abs(MANIFEST)).mtimeMs),state=expectedState();
  const payloads=[
    {path:abs(EXEC_BASELINE),bytes:Buffer.from(serializeCsv(baselineRows(),BASELINE_COLUMNS))},
    {path:abs(QUALIFICATION),bytes:Buffer.from(serializeCsv(state.decisions,DECISION_COLUMNS))},
    {path:abs(GAP_SUMMARY),bytes:Buffer.from(serializeCsv(state.summary,SUMMARY_COLUMNS))},
    {path:abs(APPLICATION),bytes:Buffer.from(serializeCsv(state.applications,APPLICATION_COLUMNS))},
    {path:abs(EXEC_REQUEST),bytes:Buffer.from(requestText())},
    {path:abs(EXEC_VALIDATION),bytes:Buffer.from(serializeCsv(validationRows(state),VALIDATION_COLUMNS))},
  ];
  const result=runProductionTransactionR2({
    manifestPath:abs(MANIFEST),manifestBefore,manifestBeforeMtimeMs,payloads,
    buildManifestCandidate:()=>{
      const rows=manifestRowsFor(executionSetRows().map(row=>row.artifact_path));
      const candidate=Buffer.concat([manifestBefore,Buffer.from(serializeManifestDataRows(rows),'utf8')]);
      const checked=validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:manifestBefore.length,sha256:hash(manifestBefore)},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:EXEC_RUN,expectedPhysicalDelta:18});
      return{candidate,rows,errors:checked.errors};
    },
    postwriteOracle:()=>validateExecution(),
  });
  if(result.status!=='COMMITTED')throw new Error(`${result.status}:${result.errors.join('|')}`);
  return{status:'EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW',qualification_rows:14,qualified:4,context_only:10,gap_summary_rows:7,application_rows:10,manifest_rows:18};
}
 
export function validateExecution(){
  const errors=[];
  for(const file of GENERATED)if(!fs.existsSync(abs(file)))errors.push(`MISSING:${file}`);
  if(errors.length)return errors;
  const baseline=readCsv(EXEC_BASELINE),qualification=readCsv(QUALIFICATION),summary=readCsv(GAP_SUMMARY),applications=readCsv(APPLICATION),validation=readCsv(EXEC_VALIDATION),state={candidates:readCsv(CANDIDATES).rows,provenance:readCsv(PROVENANCE).rows,criteria:readCsv(CRITERIA).rows,decisions:qualification.rows,summary:summary.rows,applications:applications.rows};
  const expected=expectedState();
  errors.push(...prior.sourcePackageLifecycleErrors(),...formalEntryErrors(),...releaseErrors({required:true}));
  errors.push(...exactColumns(baseline,BASELINE_COLUMNS,'BASELINE'),...baselineErrors(baseline.rows));
  errors.push(...exactColumns(qualification,DECISION_COLUMNS,'QUALIFICATION'),...compareRows(qualification.rows,expected.decisions,DECISION_COLUMNS,'QUALIFICATION'));
  errors.push(...exactColumns(summary,SUMMARY_COLUMNS,'SUMMARY'),...compareRows(summary.rows,expected.summary,SUMMARY_COLUMNS,'SUMMARY'));
  errors.push(...exactColumns(applications,APPLICATION_COLUMNS,'APPLICATION'),...compareRows(applications.rows,expected.applications,APPLICATION_COLUMNS,'APPLICATION'));
  errors.push(...exactColumns(validation,VALIDATION_COLUMNS,'VALIDATION'),...coreErrors(state));
  if(normalize(fs.readFileSync(abs(EXEC_REQUEST)))!==requestText())errors.push('REQUEST_TEXT');
  if(validation.rows.length!==21||validation.rows.some(row=>row.status==='FAIL'))errors.push('VALIDATION_STATUS');
  const expectedManifest=manifestRowsFor(executionSetRows().map(row=>row.artifact_path)),prefix=baseline.rows[2],manifest=manifestState({expectedRows:expectedManifest,expectedRunId:EXEC_RUN,frozenPrefix:{bytes:Number(prefix.bytes),sha256:prefix.sha256},expectedPhysicalDelta:18});
  errors.push(...manifest.errors.map(code=>`MANIFEST:${code}`));
  return[...new Set(errors)];
}
 
export function negativeRows(){
  const rows=prior.negativeRows().map((row,index)=>({...row,test_id:`P0ACQSEMR2-BASE-${String(index+1).padStart(3,'0')}`}));
  const releaseGood=`reviewed_design_id=${DESIGN_ID}\nresult=PASS\nexecution_release=EXPLICITLY_RELEASED\nreleased_batch_id=${EXEC_BATCH}\nreleased_run_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\ncandidate_outcome_ceiling=QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE`;
  const scopeGood='effective_network_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nsuperseded_conflicting_network_scope=PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY\nsuperseded_conflicting_scope_effect=HISTORICAL_TEXT_NOT_EXECUTION_AUTHORITY\nnetwork_calls=0\ncandidate_outcome_ceiling=QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE';
  const cases=[
    ['RELEASE_CLEAN',releaseTextErrors(releaseGood),'ACCEPT','NONE'],
    ['RELEASE_DUP_RESULT',releaseTextErrors(`${releaseGood}\nresult=PASS`),'REJECT','RELEASE_KEY_COUNT:result'],
    ['RELEASE_WRONG_BATCH',releaseTextErrors(releaseGood.replace(`released_batch_id=${EXEC_BATCH}`,'released_batch_id=WRONG')),'REJECT','RELEASE_KEY_VALUE:released_batch_id'],
    ['RELEASE_CONFLICT_NETWORK',releaseTextErrors(`${releaseGood}\nnetwork_scope=PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY`),'REJECT','RELEASE_KEY_COUNT:network_scope'],
    ['RELEASE_CONFLICT_CEILING',releaseTextErrors(`${releaseGood}\ncandidate_outcome_ceiling=ACCEPTED`),'REJECT','RELEASE_KEY_COUNT:candidate_outcome_ceiling'],
    ['RELEASE_FAIL',releaseTextErrors(`${releaseGood}\nresult=FAIL`),'REJECT','RELEASE_KEY_COUNT:result'],
    ['RELEASE_NOT_RELEASED',releaseTextErrors(`${releaseGood}\nexecution_release=NOT_RELEASED`),'REJECT','RELEASE_KEY_COUNT:execution_release'],
    ['FORMAL_SCOPE_CLEAN',formalScopeTextErrors(scopeGood),'ACCEPT','NONE'],
    ['FORMAL_SCOPE_ACTIVE_NETWORK',formalScopeTextErrors(`${scopeGood}\nnetwork_scope=PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY`),'REJECT','FORMAL_SCOPE_ACTIVE_NETWORK_CONTRADICTION'],
    ['FORMAL_SCOPE_MISSING_SUPERSEDE',formalScopeTextErrors(scopeGood.replace('superseded_conflicting_scope_effect=HISTORICAL_TEXT_NOT_EXECUTION_AUTHORITY\n','')),'REJECT','FORMAL_SCOPE_KEY_COUNT:superseded_conflicting_scope_effect'],
    ['FAULT_AUTHORITY_CLEAN',transactionFaultErrors(),'ACCEPT','NONE'],
    ['FAULT_AUTHORITY_TAMPER',transactionFaultErrors(transactionFaultRows().map((row,index)=>index?row:{...row,result:'FAIL'})),'REJECT','FAULT_FAIL'],
  ];
  for(const [name,errors,expected,code] of cases){const actual=errors.length?'REJECT':'ACCEPT';rows.push({test_id:`P0ACQSEMR2-NEG-${String(rows.length+1).padStart(3,'0')}-${name}`,mutation_applied:name.endsWith('CLEAN')?'NO_CLEAN_CONTROL':'YES',oracle:name.startsWith('RELEASE')?'releaseTextErrors':name.startsWith('FORMAL')?'formalScopeTextErrors':'transactionFaultErrors',expected,expected_code:code,actual,actual_codes:errors.join('|')||'NONE',result:actual===expected&&(code==='NONE'||errors.some(error=>error.startsWith(code)))?'PASS':'FAIL'});}
  return rows;
}
 
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
  const mode=process.argv[2]??'--preview',token=process.argv.find(value=>value.startsWith('--token='))?.slice(8);
  if(mode==='--preview'){
    const state=expectedState(),errors=coreErrors(state),sourceErrors=prior.sourcePackageLifecycleErrors(),faultErrors=transactionFaultErrors();
    console.log(JSON.stringify({status:errors.length||sourceErrors.length||faultErrors.length?'FAIL':'PREVIEW_REPAIR002_PASS',candidates:14,criteria:7,qualified:4,context_only:10,summary:7,applications:10,contracts:contractRows().length,schemas:schemaRows().length,exact_set:executionSetRows().length,faults:transactionFaultRows().length,source_package_errors:sourceErrors,fault_errors:faultErrors,errors},null,2));
    if(errors.length||sourceErrors.length||faultErrors.length)process.exitCode=1;
  }else if(mode==='--self-test'){
    const rows=negativeRows();console.log(JSON.stringify({status:rows.every(row=>row.result==='PASS')?'SELF_TEST_PASS':'FAIL',tests:rows.length,rows},null,2));if(rows.some(row=>row.result!=='PASS'))process.exitCode=1;
  }else if(mode==='--validate-design-inputs'){
    const errors=designInputErrors({requireRelease:false,expectNoExecution:true});console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_DESIGN_REPAIR002_INPUTS',errors},null,2));if(errors.length)process.exitCode=1;
  }else if(mode==='--validate-release'){
    const errors=designInputErrors({requireRelease:true,expectNoExecution:true});console.log(JSON.stringify({status:errors.length?'HELD':'PASS_RELEASE_FROZEN_LOCAL_INPUTS',errors},null,2));if(errors.length)process.exitCode=1;
  }else if(mode==='--execute')console.log(JSON.stringify(execute({token}),null,2));
  else if(mode==='--validate-execution'){
    const errors=validateExecution();console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_APPEND_STABLE_EXECUTION_STATE',errors},null,2));if(errors.length)process.exitCode=1;
  }else throw new Error(`UNKNOWN_MODE:${mode}`);
}