Cai
2026-08-26 cccd2a0ed738e460edd08a94f693fb667a3a8e08
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
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {pathToFileURL} from 'node:url';
import * as r2 from './detail_strengthening_p0_candidate_semantic_verification_runtime_repair002_20260730.mjs';
import {parseAuthorityCsv,serializeCsv,serializeManifestDataRows,validateAppendStableManifest} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
export const ROOT=r2.ROOT,CASE_ID=r2.CASE_ID,BASE=r2.BASE,AUDIT_REPORT=r2.AUDIT_REPORT,MANIFEST=r2.MANIFEST,ANOMALY_AUTHORITY=r2.ANOMALY_AUTHORITY,ORIGINAL_TRIAGE_RUN=r2.ORIGINAL_TRIAGE_RUN;
export const DESIGN_ID='DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-REPAIR-003';
export const DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REPAIR-003';
export const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REPAIR-003';
export const EXEC_RUN=r2.EXEC_RUN,EXEC_BATCH=r2.EXEC_BATCH;
export const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REPAIR003-REREVIEW-001';
export const SOURCE_AUDIT=r2.SOURCE_AUDIT,EXEC_TOKEN='EXECUTE_DETAIL_STRENGTHENING_P0_CANDIDATE_SEMANTIC_VERIFICATION_REPAIR003';
export const SCRIPT='dev/ana-dev/detail_strengthening_p0_candidate_semantic_verification_runtime_repair003_20260730.mjs';
export const CANDIDATES=r2.CANDIDATES,PROVENANCE=r2.PROVENANCE,RAW_ARCHIVE=r2.RAW_ARCHIVE,TARGET_AUTHORITY=r2.TARGET_AUTHORITY,GAP_AUTHORITY=r2.GAP_AUTHORITY,PROTECTED_INVENTORY=r2.PROTECTED_INVENTORY,CRITERIA=r2.CRITERIA,DECISION_AUTHORITY=r2.DECISION_AUTHORITY,SOURCE_ENTRY_AUTHORITY=r2.SOURCE_ENTRY_AUTHORITY,CONTRACT=r2.CONTRACT,SCHEMA=r2.SCHEMA;
export const FORMAL_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_verification_formal_design_entry_authority_repair003_20260730.csv`;
export const EXEC_SET=`${BASE}/manifest/detail_strengthening_p0_candidate_semantic_verification_execution_artifact_set_repair003_20260730.csv`;
export const EXEC_BASELINE=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_verification_execution_baseline_repair003_20260730.csv`;
export const QUALIFICATION=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_qualification_ledger_repair003_20260730.csv`;
export const GAP_SUMMARY=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_gap_summary_repair003_20260730.csv`;
export const APPLICATION=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_occurrence_application_repair003_20260730.csv`;
export const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_candidate_semantic_verification_execution_repair003_20260730.md`;
export const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_candidate_semantic_verification_execution_validation_repair003_20260730.csv`;
export const GENERATED=[EXEC_BASELINE,QUALIFICATION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
export const FORMAL_ENTRY_COLUMNS=r2.FORMAL_ENTRY_COLUMNS,SOURCE_ENTRY_COLUMNS=r2.SOURCE_ENTRY_COLUMNS,CRITERIA_COLUMNS=r2.CRITERIA_COLUMNS,DECISION_COLUMNS=r2.DECISION_COLUMNS,SUMMARY_COLUMNS=r2.SUMMARY_COLUMNS,APPLICATION_COLUMNS=r2.APPLICATION_COLUMNS,CONTRACT_COLUMNS=r2.CONTRACT_COLUMNS,SCHEMA_COLUMNS=r2.SCHEMA_COLUMNS,EXEC_SET_COLUMNS=r2.EXEC_SET_COLUMNS,BASELINE_COLUMNS=r2.BASELINE_COLUMNS,VALIDATION_COLUMNS=r2.VALIDATION_COLUMNS;
export const criteriaRows=r2.criteriaRows,decisionRows=r2.decisionRows,deriveOutputs=r2.deriveOutputs,coreErrors=r2.coreErrors,auditEntry=r2.auditEntry,sourceAuthorityErrors=r2.sourceAuthorityErrors,sourcePackageLifecycleErrors=r2.sourcePackageLifecycleErrors,contractRows=r2.contractRows,schemaRows=r2.schemaRows,sourceAuditTextErrors=r2.sourceAuditTextErrors;
 
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 write=(file,text)=>{fs.mkdirSync(path.dirname(abs(file)),{recursive:true});fs.writeFileSync(abs(file),text,'utf8');};
const exactColumns=(parsed,columns,code)=>parsed.header.join('|')===columns.join('|')?[]:[`${code}_COLUMNS`];
const compareRows=(actual,expected,columns,code)=>{const errors=[];if(actual.length!==expected.length)return[`${code}_COUNT:${actual.length}:${expected.length}`];for(let i=0;i<expected.length;i++)for(const column of columns)if(String(actual[i]?.[column]??'')!==String(expected[i]?.[column]??'')){errors.push(`${code}_FIELD:${i+1}:${column}`);break;}return errors;};
const canonicalLine=line=>{let value=line.trim().replace(/^[\-*]\s*/,'').trim();if(value.startsWith('`')&&value.endsWith('`')&&value.length>=2)value=value.slice(1,-1);return value.trim();};
export function releaseTextErrors(text){const lines=text.split('\n').map(canonicalLine),required=['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'],errors=[];for(const marker of required)if(lines.filter(line=>line===marker).length!==1)errors.push(`RELEASE_MARKER_COUNT:${marker}:${lines.filter(line=>line===marker).length}`);if(lines.some(line=>/^(?:result|conclusion|review_result)=FAIL(?:_|$)/.test(line))||lines.some(line=>/^(?:execution_release|.*_release)=(?:NOT_ALLOWED|NOT_RELEASED)(?:_|$)/.test(line)))errors.push('RELEASE_CONTRADICTION');return errors;}
export function releaseErrors({required=false}={}){const entry=auditEntry(RELEASE_AUDIT);return entry?releaseTextErrors(entry.text):required?['RELEASE_AUDIT_MISSING']:[];}
export function executionSetRows(){const paths=[SCRIPT,SOURCE_ENTRY_AUTHORITY,CANDIDATES,PROVENANCE,RAW_ARCHIVE,TARGET_AUTHORITY,GAP_AUTHORITY,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,EXEC_BASELINE,QUALIFICATION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION],roles=['RUNTIME_REPAIR003','SOURCE_AUDIT_ENTRY_AUTHORITY_REUSED','CANDIDATES_REUSED','PROVENANCE_REUSED','RAW_ARCHIVE_REUSED','TARGET_AUTHORITY_REUSED','GAP_AUTHORITY_REUSED','SEMANTIC_CRITERIA_REUSED','DECISION_AUTHORITY_REUSED','RUNTIME_CONTRACT_REPAIR002_REUSED','OUTPUT_SCHEMA_REPAIR002_REUSED','EXECUTION_EXACT_SET_REPAIR003','EXECUTION_BASELINE_FIRST_GENERATED','QUALIFICATION_LEDGER','GAP_SUMMARY','OCCURRENCE_APPLICATION','EXECUTION_REQUEST','VALIDATION_LAST'];return paths.map((artifactPath,index)=>({artifact_id:`P0SEMR3-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'),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}`);return errors;}
export function designInputErrors({requireRelease=false,expectNoExecution=true}={}){const errors=[...sourceAuthorityErrors(),...sourcePackageLifecycleErrors(),...releaseErrors({required:requireRelease}),...formalEntryErrors()];for(const file of [SOURCE_ENTRY_AUTHORITY,CANDIDATES,PROVENANCE,RAW_ARCHIVE,TARGET_AUTHORITY,GAP_AUTHORITY,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET])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);errors.push(...exactColumns(criteria,CRITERIA_COLUMNS,'CRITERIA'),...compareRows(criteria.rows,criteriaRows(),CRITERIA_COLUMNS,'CRITERIA'),...exactColumns(decisions,DECISION_COLUMNS,'DECISION'),...compareRows(decisions.rows,decisionRows(),DECISION_COLUMNS,'DECISION'),...exactColumns(contracts,CONTRACT_COLUMNS,'CONTRACT'),...compareRows(contracts.rows,contractRows(),CONTRACT_COLUMNS,'CONTRACT'),...exactColumns(schemas,SCHEMA_COLUMNS,'SCHEMA'),...compareRows(schemas.rows,schemaRows(),SCHEMA_COLUMNS,'SCHEMA'),...exactColumns(execSet,EXEC_SET_COLUMNS,'EXEC_SET'),...compareRows(execSet.rows,executionSetRows(),EXEC_SET_COLUMNS,'EXEC_SET'));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:'P0SEMR3-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_AUTHORITY_MATCH'},{baseline_id:'P0SEMR3-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_PASS_RELEASE_BATCH_RUN_NETWORK_AND_CEILING'},{baseline_id:'P0SEMR3-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'}];for(const file of executionSetRows().slice(0,12).map(row=>row.artifact_path)){const id=identity(file);rows.push({baseline_id:`P0SEMR3-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:`P0SEMR3-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`);errors.push(...sourceAuthorityErrors());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-003)\n\ncase_id=${CASE_ID}\nsource_audit=${SOURCE_AUDIT}\nrelease_audit=${RELEASE_AUDIT}\nbatch_id=${EXEC_BATCH}\nrun_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\ncandidate_outcome_ceiling=QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE\nqualification_rows=14\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),checks=[['CORE_ERRORS','0',String(errors.length)],['SOURCE_AUTHORITY_ERRORS','0',String(sourceAuthorityErrors().length)],['SOURCE_PACKAGE_ERRORS','0',String(sourcePackageLifecycleErrors().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','7',String(state.decisions.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW').length)],['CONTEXT_ONLY','7',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)],['EXACT_SET','18',String(executionSetRows().length)]];const rows=checks.map((item,index)=>({check_id:`P0SEMR3-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:'REPAIR003_SOURCE_ENTRY_FAIL_CLOSED_ORACLE'}));rows.push({check_id:'P0SEMR3-EXEC-VAL-018',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));try{write(EXEC_BASELINE,serializeCsv(baselineRows(),BASELINE_COLUMNS));const state=expectedState();write(QUALIFICATION,serializeCsv(state.decisions,DECISION_COLUMNS));write(GAP_SUMMARY,serializeCsv(state.summary,SUMMARY_COLUMNS));write(APPLICATION,serializeCsv(state.applications,APPLICATION_COLUMNS));write(EXEC_REQUEST,requestText());const validation=validationRows(state);write(EXEC_VALIDATION,serializeCsv(validation,VALIDATION_COLUMNS));if(validation.some(row=>row.status==='FAIL'))throw new Error('VALIDATION_FAIL');const rows=manifestRowsFor(executionSetRows().map(row=>row.artifact_path)),candidate=Buffer.concat([manifestBefore,Buffer.from(serializeManifestDataRows(rows),'utf8')]),manifestCandidate=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});if(manifestCandidate.errors.length)throw new Error(`MANIFEST_CANDIDATE:${manifestCandidate.errors.join('|')}`);fs.writeFileSync(abs(MANIFEST),candidate);const post=validateExecution();if(post.length)throw new Error(`POSTWRITE:${post.join('|')}`);return{status:'EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW',qualification_rows:14,qualified:7,context_only:7,gap_summary_rows:7,application_rows:10,manifest_rows:18};}catch(error){const cleanup=[];try{fs.writeFileSync(abs(MANIFEST),manifestBefore);}catch(failure){cleanup.push(`MANIFEST:${failure.message}`);}for(const file of GENERATED)if(fs.existsSync(abs(file)))try{fs.rmSync(abs(file));}catch(failure){cleanup.push(`REMOVE:${file}:${failure.message}`);}if(cleanup.length)throw new Error(`ROLLBACK_INCOMPLETE_HELD:${cleanup.join('|')}:${error.message}`);throw error;}}
export function validateExecution(){const errors=[];for(const file of GENERATED)if(!fs.existsSync(abs(file)))errors.push(`MISSING:${file}`);if(errors.length)return errors;const baseline=readCsv(EXEC_BASELINE),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};errors.push(...sourceAuthorityErrors(),...sourcePackageLifecycleErrors(),...exactColumns(baseline,BASELINE_COLUMNS,'BASELINE'),...baselineErrors(baseline.rows),...exactColumns(qualification,DECISION_COLUMNS,'QUALIFICATION'),...exactColumns(summary,SUMMARY_COLUMNS,'SUMMARY'),...exactColumns(applications,APPLICATION_COLUMNS,'APPLICATION'),...exactColumns(validation,VALIDATION_COLUMNS,'VALIDATION'),...coreErrors(state));if(normalize(fs.readFileSync(abs(EXEC_REQUEST)))!==requestText())errors.push('REQUEST_TEXT');if(validation.rows.length!==18||validation.rows.some(row=>row.status==='FAIL'))errors.push('VALIDATION_STATUS');const expected=manifestRowsFor(executionSetRows().map(row=>row.artifact_path)),prefix=baseline.rows[2],manifest=manifestState({expectedRows:expected,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=r2.negativeRows().map((row,index)=>({...row,test_id:`P0SEMR3-BASE-${String(index+1).padStart(3,'0')}`}));const good=['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'].join('\n'),cases=[['RELEASE_CLEAN',good,'ACCEPT','NONE'],['RELEASE_FAIL',`${good}\nresult=FAIL`,'REJECT','RELEASE_CONTRADICTION'],['RELEASE_DUPLICATE',`${good}\nresult=PASS`,'REJECT','RELEASE_MARKER_COUNT']];for(const [name,text,expected,code] of cases){const errors=releaseTextErrors(text),actual=errors.length?'REJECT':'ACCEPT';rows.push({test_id:`P0SEMR3-NEG-${String(rows.length+1).padStart(3,'0')}-${name}`,mutation_applied:name==='RELEASE_CLEAN'?'NO_CLEAN_CONTROL':'YES',oracle:'releaseTextErrors',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=sourcePackageLifecycleErrors(),authorityErrors=sourceAuthorityErrors();console.log(JSON.stringify({status:errors.length||sourceErrors.length||authorityErrors.length?'FAIL':'PREVIEW_REPAIR003_PASS',candidates:14,criteria:7,qualified:7,context_only:7,summary:7,applications:10,contracts:contractRows().length,schemas:schemaRows().length,exact_set:executionSetRows().length,source_authority_errors:authorityErrors,source_package_errors:sourceErrors,errors},null,2));if(errors.length||sourceErrors.length||authorityErrors.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_REPAIR003_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}`);}