Cai
16 hours ago cd6bfbea57c2437c00f808317f896aacb2ad2440
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
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_repair001_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_repair001_20260731.mjs';
const FORMAL_DESIGN='ana-doc/机器人案例/案例分析设计.md';
const FAULT_RESULTS=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_transaction_fault_results_repair001_20260731.csv`;
const NEGATIVE=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_negative_results_repair001_20260731.csv`;
const DESIGN_BASELINE=`${BASE}/evidence/detail_strengthening_p0_open_gap_evidence_acquisition_design_baseline_repair001_20260731.csv`;
const DESIGN_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_open_gap_evidence_acquisition_design_repair001_20260731.md`;
const DESIGN_SET=`${BASE}/manifest/detail_strengthening_p0_open_gap_evidence_acquisition_design_artifact_set_repair001_20260731.csv`;
const DESIGN_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_open_gap_evidence_acquisition_design_validation_repair001_20260731.csv`;
const ORIGINAL_DESIGN_RUN=baseRun();
function baseRun(){return 'RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-EVIDENCE-ACQUISITION-DESIGN-001';}
const SOURCE_FAIL_EXPECTED={lines:68,bytes:10161,sha256:'b5c87dbb20430ae979c582f30824994f7251493f9c5a0dd8f4304542a0c61041'};
const DESIGN_PATHS=[SCRIPT,BUILDER,FORMAL_ENTRY_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,FAULT_RESULTS,NEGATIVE,DESIGN_BASELINE,DESIGN_REQUEST,DESIGN_SET,DESIGN_VALIDATION];
const DESIGN_SET_COLUMNS=['artifact_id','batch_id','run_id','generation_order','artifact_path','artifact_role','identity_policy'];
const FAULT_COLUMNS=['fault_id','fault_type','production_workflow','actual_io_or_oracle_failure','expected_status','actual_status','manifest_exact','staging_retained','generated_absent','retryable','safe_state','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 VALIDATION_COLUMNS=runtime.VALIDATION_COLUMNS;
const abs=value=>path.join(ROOT,...value.split('/')),sha=value=>crypto.createHash('sha256').update(value).digest('hex'),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 all=normalize(fs.readFileSync(abs(AUDIT_REPORT))).split('\n'),start=all.findIndex(line=>line.startsWith('### ')&&line.includes(auditId));if(start<0)return null;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{start:start+1,end,lines:end-start,bytes:buffer.length,sha256:sha(buffer),text:buffer.toString('utf8')};}
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:'P0ACQR1-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:'七个键各必须恰有一条|HELD_BY_REQUIRED_EXTERNAL_INFORMATION_METHOD_UNAVAILABLE|production transaction|ROLLBACK_INCOMPLETE_HELD|DISCOVERY_ONLY_GAP_REMAINS_OPEN|NO_UPGRADE|network和execution继续为0'};}
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 originalDesignRows(){return currentManifest().state.logicalRows.filter(row=>row.run_id===ORIGINAL_DESIGN_RUN);}
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:'P0ACQR1-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_THREE_BLOCKER_FAIL_ENTRY'});rows.push({baseline_id:'P0ACQR1-DESIGN-BASE-002',identity_type:'RAW_MANIFEST_PREFIX_BEFORE_REPAIR',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 row of originalDesignRows()){const id=identity(row.artifact_path);rows.push({baseline_id:`P0ACQR1-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'ORIGINAL_DESIGN_ARTIFACT15',artifact_path:row.artifact_path,rows:String(id.rows),bytes:String(id.bytes),sha256:id.sha256,mtime:id.mtime,required_state:'IMMUTABLE_FAILED_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:`P0ACQR1-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'FROZEN_REPAIR_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:`P0ACQR1-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_REPAIR001','DESIGN_BUILDER_REPAIR001','FORMAL_ENTRY_AUTHORITY_REPAIR001','CONTRACT_REPAIR001','SCHEMA_REPAIR001','EXECUTION_EXACT_SET_REPAIR001','TRANSACTION_FAULT_RESULTS','NEGATIVE_RESULTS','DESIGN_BASELINE','DESIGN_REVIEW_REQUEST','DESIGN_EXACT_SET','VALIDATION_LAST'];return DESIGN_PATHS.map((artifactPath,index)=>({artifact_id:`P0ACQR1-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 requestText(){return`# P0 开放缺口定向主来源证据采集 DESIGN-REPAIR-001 聚焦复审请求\n\ncase_id=${CASE_ID}\naction_id=NEXT-ROBOT-045-DESIGN-REPAIR-001\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\n原15项设计与manifest历史只读保留。本返修只关闭 release 七键唯一解析、执行时 capability unavailable 前门、begin/finalize production transaction 三项blocker。gap7/occurrence10/query14/policy15继续复用;execution exact-set26新增外部runtime capability evidence,baseline exact66;fault7/7、negative17/17由同一production oracle真实运行。审核PASS并精确release前 capability/network/staging/output/execution manifest均为0。\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(originalDesignRows().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','43',String(runtime.contractRows().length)],['SCHEMAS','13',String(runtime.schemaRows().length)],['EXEC_SET','26',String(runtime.executionSetRows().length)],['FAULT_PASS','7',String(fault.filter(row=>row.result==='PASS').length)],['FAULT_SAFE','7',String(fault.filter(row=>row.safe_state==='YES').length)],['NEGATIVE_PASS','17',String(negative.filter(row=>row.result==='PASS').length)],['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:`P0ACQR1-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:'REPAIR001_FAIL_CLOSED_DESIGN_ORACLE'}));rows.push({check_id:'P0ACQR1-DESIGN-VAL-022',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_REPAIR001_BUILT_PENDING_INDEPENDENT_FOCUSED_REREVIEW',original_design_rows:15,contracts:43,schemas:13,execution_exact_set:26,fault_pass:7,negative_pass:17,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_REPAIR'),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!==7||fault.some(row=>row.result!=='PASS'||row.safe_state!=='YES'))errors.push('FAULT');if(negative.length!==17||negative.some(row=>row.result!=='PASS'))errors.push('NEGATIVE');if(validation.length!==22||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_REPAIR001_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}`);}