Cai
2026-08-16 2992aee3f9bb2eaa5dd4da28a598be3d67ea0ec0
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
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {spawnSync} from 'node:child_process';
import {pathToFileURL} from 'node:url';
import * as runtime from './detail_strengthening_p0_open_gap_evidence_acquisition_runtime_repair002_20260731.mjs';
import {parseAuthorityCsv,serializeCsv,serializeManifestDataRows,validateAppendStableManifest} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
const {ROOT,CASE_ID,BASE,AUDIT_REPORT,MANIFEST,ANOMALY_AUTHORITY,ORIGINAL_TRIAGE_RUN,DESIGN_ID,DESIGN_RUN,DESIGN_BATCH,EXEC_RUN,SCRIPT,FORMAL_ENTRY_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,PROTECTED_INVENTORY,CAPABILITY_EVIDENCE}=runtime;
const BUILDER='dev/ana-dev/detail_strengthening_p0_open_gap_evidence_acquisition_design_repair002_20260731.mjs';
const FORMAL_DESIGN='ana-doc/机器人案例/案例分析设计.md';
const SOURCE_FAIL_EXPECTED={lines:58,bytes:6774,sha256:'63d1a303fc4707025d094ca7fc9989759a376c8582f6271da38b69fb94311b5e'};
const R1_DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-DESIGN-REPAIR-001';
const ORIGINAL_DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-DESIGN-001';
const FAULT_RESULTS=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_transaction_fault_results_repair002_20260731.csv`;
const NEGATIVE=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_negative_results_repair002_20260731.csv`;
const DESIGN_BASELINE=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_design_baseline_repair002_20260731.csv`;
const DESIGN_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_open_gap_evidence_acquisition_design_repair002_20260731.md`;
const DESIGN_SET=`${BASE}/manifest/detail_strengthening_p0_open_gap_evidence_acquisition_design_artifact_set_repair002_20260731.csv`;
const DESIGN_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_open_gap_evidence_acquisition_design_validation_repair002_20260731.csv`;
const DESIGN_PATHS=[SCRIPT,BUILDER,FORMAL_ENTRY_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,FAULT_RESULTS,NEGATIVE,DESIGN_BASELINE,DESIGN_REQUEST,DESIGN_SET,DESIGN_VALIDATION];
 
const FAULT_COLUMNS=['fault_id','fault_type','production_workflow','actual_production_stage_reached','actual_io_or_oracle_failure','expected_status','actual_status','manifest_exact','staging_retained','generated_absent','transaction_reported_safe','independent_safe_state','retryable','result'];
const NEGATIVE_COLUMNS=['test_id','mutation','oracle','expected','expected_code','actual','actual_codes','result'];
const BASELINE_COLUMNS=['baseline_id','identity_type','artifact_path','rows','bytes','sha256','mtime','required_state'];
const DESIGN_SET_COLUMNS=['artifact_id','batch_id','run_id','generation_order','artifact_path','artifact_role','identity_policy'];
const VALIDATION_COLUMNS=['check_id','check_description','expected','actual','status','evidence'];
 
const abs=value=>path.join(ROOT,...value.split('/'));
const sha=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:sha(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');};
 
function auditEntry(auditId){const lines=normalize(fs.readFileSync(abs(AUDIT_REPORT))).split('\n'),start=lines.findIndex(line=>line.startsWith('### ')&&line.includes(auditId));if(start<0)return null;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 buffer=Buffer.from(`${lines.slice(start,end).join('\n')}\n`);return{start:start+1,end,lines:end-start,bytes:buffer.length,sha256:sha(buffer)};}
function formalEntryRow(){const all=normalize(fs.readFileSync(abs(FORMAL_DESIGN))).split('\n'),heading=`## ${DESIGN_ID}(2026-07-31)`,start=all.findIndex(line=>line===heading);if(start<0)throw new Error('FORMAL_HEADING_MISSING');let end=all.length;for(let i=start+1;i<all.length;i++)if(all[i].startsWith('## ')){end=i;break;}while(end>start&&all[end-1]==='')end--;const buffer=Buffer.from(`${all.slice(start,end).join('\n')}\n`);return{entry_id:'P0ACQR2-FORMAL-001',design_id:DESIGN_ID,artifact_path:FORMAL_DESIGN,start_line:String(start+1),end_line:String(end),lines:String(end-start),bytes:String(buffer.length),sha256:sha(buffer),normalization:'UTF8_NO_BOM_LF_JOIN_LINES_WITH_TERMINAL_LF_V1',required_markers:'runProductionFinalizeWorkflowR2|ROLLBACK_INCOMPLETE_HELD|SAFE_ABORT_RETRYABLE|PUBLIC_WEB_PRIMARY_SOURCE_EVIDENCE_ACQUISITION_ONLY|OPEN_RETAINED_GAP|NO_UPGRADE|network remain zero'};}
function currentManifest(){const buffer=fs.readFileSync(abs(MANIFEST)),state=validateAppendStableManifest(buffer,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11});if(state.errors.length)throw new Error(`MANIFEST:${state.errors.join('|')}`);return{buffer,state,bytes:buffer.length,sha256:sha(buffer),mtime:new Date(Math.trunc(fs.statSync(abs(MANIFEST)).mtimeMs)).toISOString()};}
function protectedRows(){return readCsv(PROTECTED_INVENTORY).rows.map(row=>({artifact_path:row.artifact_path,...identity(row.artifact_path)}));}
function manifestRunRows(runId){return currentManifest().state.logicalRows.filter(row=>row.run_id===runId);}
 
function baselineRows(){const source=auditEntry(runtime.SOURCE_FAIL_AUDIT),manifest=currentManifest(),rows=[];if(!source)throw new Error('SOURCE_FAIL_AUDIT_MISSING');rows.push({baseline_id:'P0ACQR2-DESIGN-BASE-001',identity_type:'SOURCE_FAIL_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_REPAIR001_FAIL_ENTRY'});rows.push({baseline_id:'P0ACQR2-DESIGN-BASE-002',identity_type:'RAW_MANIFEST_PREFIX_BEFORE_REPAIR002',artifact_path:MANIFEST,rows:String(manifest.state.logicalDataRows),bytes:String(manifest.bytes),sha256:manifest.sha256,mtime:manifest.mtime,required_state:'EXACT_APPEND_ONLY_PREFIX'});for(const runId of [ORIGINAL_DESIGN_RUN,R1_DESIGN_RUN])for(const row of manifestRunRows(runId)){const id=identity(row.artifact_path);rows.push({baseline_id:`P0ACQR2-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:runId===ORIGINAL_DESIGN_RUN?'ORIGINAL_DESIGN_ARTIFACT15':'REPAIR001_DESIGN_ARTIFACT12',artifact_path:row.artifact_path,rows:String(id.rows),bytes:String(id.bytes),sha256:id.sha256,mtime:id.mtime,required_state:'IMMUTABLE_DESIGN_HISTORY'});}for(const file of [runtime.TARGET_AUTHORITY,runtime.GAP_AUTHORITY,runtime.NEXT_PLAN,runtime.DECISION,runtime.MAP,runtime.QUERY_AUTHORITY,runtime.SOURCE_POLICY,runtime.METHOD_AUTHORITY,PROTECTED_INVENTORY,ANOMALY_AUTHORITY,SCRIPT,BUILDER,FORMAL_DESIGN]){const id=identity(file);rows.push({baseline_id:`P0ACQR2-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'FROZEN_REPAIR002_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:`P0ACQR2-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'PROTECTED49_CURRENT_IDENTITY',artifact_path:item.artifact_path,rows:String(item.rows),bytes:String(item.bytes),sha256:item.sha256,mtime:item.mtime,required_state:'NO_MUTATION'});return rows;}
function designSetRows(){const roles=['RUNTIME_REPAIR002','DESIGN_BUILDER_REPAIR002','FORMAL_ENTRY_AUTHORITY_REPAIR002','CONTRACT_REPAIR002','SCHEMA_REPAIR002','EXECUTION_EXACT_SET_REPAIR002','PRODUCTION_TRANSACTION_FAULT_RESULTS','NEGATIVE_RESULTS','DESIGN_BASELINE','DESIGN_REVIEW_REQUEST','DESIGN_EXACT_SET','VALIDATION_LAST'];return DESIGN_PATHS.map((artifactPath,index)=>({artifact_id:`P0ACQR2-DESIGN-SET-${String(index+1).padStart(3,'0')}`,batch_id:DESIGN_BATCH,run_id:DESIGN_RUN,generation_order:String(index+1),artifact_path:artifactPath,artifact_role:roles[index],identity_policy:'EXACT_SHA256_BYTES_FILESYSTEM_MTIME_MS'}));}
function sourceTransactionCheck(){const source=normalize(fs.readFileSync(abs(SCRIPT))),finalize=source.slice(source.indexOf('export function finalizeAcquisition'),source.indexOf('export function validateExecution'));return finalize.includes('runProductionFinalizeWorkflowR2({')&&!finalize.includes('fs.writeFileSync(')&&!finalize.includes('fs.rmSync(')?'PASS':'FAIL';}
function requestText(){return`# P0 open-gap evidence acquisition DESIGN-REPAIR-002 focused rereview request\n\ncase_id=${CASE_ID}\naction_id=NEXT-ROBOT-045-DESIGN-REPAIR-002\ndesign_id=${DESIGN_ID}\nsource_fail_audit=${runtime.SOURCE_FAIL_AUDIT}\nrequested_release_audit=${runtime.RELEASE_AUDIT}\nrequested_batch=${runtime.EXEC_BATCH}\nrequested_run=${runtime.EXEC_RUN}\n\nOnly BLOCK-045-DESIGN-TRANSACTION-ROLLBACK-EVIDENCE-001 is in scope. Original15 and REPAIR001 12 manifest rows are immutable. Production finalize performs no payload filesystem write outside runProductionFinalizeWorkflowR2. Fault authority invokes that same workflow for payload/manifest/postwrite/restore/remove/postcheck failures. Cleanup/postcheck exceptions stay ROLLBACK_INCOMPLETE_HELD even when fallback independently proves physical safety. Execution/network/capability/staging/output rows remain zero before independent PASS and exact release.\n`;}
function validationRows(){const source=auditEntry(runtime.SOURCE_FAIL_AUDIT),fault=runtime.faultRows(),negative=runtime.negativeRows(),preview=spawnSync(process.execPath,[abs(SCRIPT),'--preview'],{cwd:ROOT,encoding:'utf8'}),self=spawnSync(process.execPath,[abs(SCRIPT),'--self-test'],{cwd:ROOT,encoding:'utf8'}),manifest=currentManifest(),checks=[['SOURCE_FAIL_AUDIT',`${SOURCE_FAIL_EXPECTED.lines}/${SOURCE_FAIL_EXPECTED.bytes}/${SOURCE_FAIL_EXPECTED.sha256}`,source?`${source.lines}/${source.bytes}/${source.sha256}`:'MISSING'],['ORIGINAL_DESIGN_ROWS','15',String(manifestRunRows(ORIGINAL_DESIGN_RUN).length)],['REPAIR001_DESIGN_ROWS','12',String(manifestRunRows(R1_DESIGN_RUN).length)],['GAPS','7',String(readCsv(runtime.GAP_AUTHORITY).rows.length)],['OCCURRENCES','10',String(readCsv(runtime.TARGET_AUTHORITY).rows.length)],['QUERIES','14',String(readCsv(runtime.QUERY_AUTHORITY).rows.length)],['CONTRACTS','47',String(runtime.contractRows().length)],['SCHEMAS','13',String(runtime.schemaRows().length)],['EXEC_SET','26',String(runtime.executionSetRows().length)],['FAULT_PASS','11',String(fault.filter(row=>row.result==='PASS').length)],['FAULT_INDEPENDENT_SAFE','11',String(fault.filter(row=>row.independent_safe_state==='YES').length)],['NEGATIVE_PASS','19',String(negative.filter(row=>row.result==='PASS').length)],['PRODUCTION_NO_EXTERNAL_PAYLOAD_IO','PASS',sourceTransactionCheck()],['PROTECTED','49',String(protectedRows().length)],['RUNTIME_NODE','0',String(spawnSync(process.execPath,['--check',abs(SCRIPT)]).status??1)],['BUILDER_NODE','0',String(spawnSync(process.execPath,['--check',abs(BUILDER)]).status??1)],['PREVIEW','0',String(preview.status??1)],['SELF_TEST','0',String(self.status??1)],['MANIFEST_ERRORS','0',String(manifest.state.errors.length)],['CAPABILITY_PREMATURE','0',fs.existsSync(abs(CAPABILITY_EVIDENCE))?'1':'0'],['EXECUTION_FILES','0',String(runtime.GENERATED.filter(file=>fs.existsSync(abs(file))).length)],['EXECUTION_MANIFEST','0',String(manifest.state.logicalRows.filter(row=>row.run_id===EXEC_RUN).length)],['BOUNDARY','NO_UPGRADE','NO_UPGRADE']];const rows=checks.map((item,index)=>({check_id:`P0ACQR2-DESIGN-VAL-${String(index+1).padStart(3,'0')}`,check_description:item[0],expected:item[1],actual:item[2],status:item[1]===item[2]?'PASS':'FAIL',evidence:'REPAIR002_SINGLE_PRODUCTION_TRANSACTION_DESIGN_ORACLE'}));rows.push({check_id:`P0ACQR2-DESIGN-VAL-${String(rows.length+1).padStart(3,'0')}`,check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest postchecked'});return rows;}
function manifestRows(paths){return paths.map(file=>{const id=identity(file);return{case_id:CASE_ID,run_id:DESIGN_RUN,batch_id:DESIGN_BATCH,artifact_path:file,sha256:id.sha256,bytes:String(id.bytes),mtime:id.mtime};});}
 
function build(){const pre=currentManifest(),targets=DESIGN_PATHS.slice(2);if(targets.some(file=>fs.existsSync(abs(file))))throw new Error('REPAIR_TARGET_EXISTS');write(FORMAL_ENTRY_AUTHORITY,serializeCsv([formalEntryRow()],runtime.FORMAL_ENTRY_COLUMNS));write(CONTRACT,serializeCsv(runtime.contractRows(),runtime.CONTRACT_COLUMNS));write(SCHEMA,serializeCsv(runtime.schemaRows(),runtime.SCHEMA_COLUMNS));write(EXEC_SET,serializeCsv(runtime.executionSetRows(),runtime.EXEC_SET_COLUMNS));write(FAULT_RESULTS,serializeCsv(runtime.faultRows(),FAULT_COLUMNS));write(NEGATIVE,serializeCsv(runtime.negativeRows(),NEGATIVE_COLUMNS));write(DESIGN_BASELINE,serializeCsv(baselineRows(),BASELINE_COLUMNS));write(DESIGN_REQUEST,requestText());write(DESIGN_SET,serializeCsv(designSetRows(),DESIGN_SET_COLUMNS));const validation=validationRows();write(DESIGN_VALIDATION,serializeCsv(validation,VALIDATION_COLUMNS));if(validation.some(row=>row.status==='FAIL'))throw new Error(`VALIDATION_FAIL:${validation.filter(row=>row.status==='FAIL').map(row=>row.check_description).join('|')}`);const rows=manifestRows(DESIGN_PATHS),candidate=Buffer.concat([pre.buffer,Buffer.from(serializeManifestDataRows(rows),'utf8')]),state=validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:pre.bytes,sha256:pre.sha256},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:DESIGN_RUN,expectedPhysicalDelta:12,filesystemIdentity:{runIds:[DESIGN_RUN],get:file=>identity(file)}});if(state.errors.length)throw new Error(`MANIFEST_CANDIDATE:${state.errors.join('|')}`);fs.writeFileSync(abs(MANIFEST),candidate);const errors=validate();if(errors.length)throw new Error(`POSTWRITE:${errors.join('|')}`);return{status:'DESIGN_REPAIR002_BUILT_PENDING_INDEPENDENT_FOCUSED_REREVIEW',original_design_rows:15,repair001_design_rows:12,contracts:47,schemas:13,execution_exact_set:26,fault_pass:11,negative_pass:19,design_rows:12,execution_rows:0};}
function validate(){const errors=[],source=auditEntry(runtime.SOURCE_FAIL_AUDIT);if(!source||source.lines!==SOURCE_FAIL_EXPECTED.lines||source.bytes!==SOURCE_FAIL_EXPECTED.bytes||source.sha256!==SOURCE_FAIL_EXPECTED.sha256)errors.push('SOURCE_FAIL_AUDIT');errors.push(...runtime.designInputErrors({requireRelease:false,expectDesignManifest:true,allowCapability:false}));const baseline=readCsv(DESIGN_BASELINE).rows,prefix=baseline.find(row=>row.identity_type==='RAW_MANIFEST_PREFIX_BEFORE_REPAIR002'),current=fs.readFileSync(abs(MANIFEST));if(!prefix||current.length<Number(prefix.bytes)||sha(current.subarray(0,Number(prefix.bytes)))!==prefix.sha256)errors.push('MANIFEST_PREFIX');const rows=currentManifest().state.logicalRows.filter(row=>row.run_id===DESIGN_RUN);if(rows.length!==12||new Set(rows.map(row=>row.artifact_path)).size!==12)errors.push(`DESIGN_ROWS:${rows.length}`);for(const row of rows){const id=identity(row.artifact_path);if(row.case_id!==CASE_ID||row.batch_id!==DESIGN_BATCH||row.sha256!==id.sha256||row.bytes!==String(id.bytes)||Date.parse(row.mtime)!==id.mtimeMs)errors.push(`DESIGN_IDENTITY:${row.artifact_path}`);}const fault=readCsv(FAULT_RESULTS).rows,negative=readCsv(NEGATIVE).rows,validation=readCsv(DESIGN_VALIDATION).rows;if(fault.length!==11||fault.some(row=>row.result!=='PASS'||row.independent_safe_state!=='YES'))errors.push('FAULT');if(negative.length!==19||negative.some(row=>row.result!=='PASS'))errors.push('NEGATIVE');if(validation.some(row=>row.status==='FAIL'))errors.push('VALIDATION');return[...new Set(errors)];}
 
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){const mode=process.argv[2]??'--validate-design';if(mode==='--build-design')console.log(JSON.stringify(build(),null,2));else if(mode==='--validate-design'){const errors=validate();console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_DESIGN_REPAIR002_PACKAGE',errors},null,2));if(errors.length)process.exitCode=1;}else if(mode==='--validate-package-manifest'){const errors=currentManifest().state.errors;console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_APPEND_STABLE_MANIFEST',errors},null,2));if(errors.length)process.exitCode=1;}else throw new Error(`UNKNOWN_MODE:${mode}`);}