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_candidate_semantic_verification_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,EXEC_BATCH,SOURCE_AUDIT,FAILED_REVIEW_AUDIT,RELEASE_AUDIT,SCRIPT,FORMAL_ENTRY_AUTHORITY,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,FAULT_RESULTS,PROTECTED_INVENTORY}=runtime;
|
const FORMAL_DESIGN='ana-doc/机器人案例/案例分析设计.md';
|
const BUILDER='dev/ana-dev/detail_strengthening_p0_open_gap_candidate_semantic_verification_design_repair002_20260731.mjs';
|
const NEG_RESULTS=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_verification_negative_results_repair002_20260731.csv`;
|
const DESIGN_BASELINE=`${BASE}/evidence/detail_strengthening_p0_open_gap_candidate_semantic_verification_design_baseline_repair002_20260731.csv`;
|
const DESIGN_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_open_gap_candidate_semantic_verification_design_repair002_20260731.md`;
|
const DESIGN_SET=`${BASE}/manifest/detail_strengthening_p0_open_gap_candidate_semantic_verification_design_artifact_set_repair002_20260731.csv`;
|
const DESIGN_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_open_gap_candidate_semantic_verification_design_validation_repair002_20260731.csv`;
|
const MANIFEST_PREFIX={bytes:775534,sha256:'cefccff58fadeaff555c8c334adfaae907a4fef776625fdd7e916c6e93208f65'};
|
const INITIAL_DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-001';
|
const REPAIR001_DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REPAIR-001';
|
const DESIGN_PATHS=[SCRIPT,BUILDER,FORMAL_ENTRY_AUTHORITY,CONTRACT,EXEC_SET,FAULT_RESULTS,NEG_RESULTS,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 NEG_COLUMNS=['test_id','mutation_applied','oracle','expected','expected_code','actual','actual_codes','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 write=(file,text)=>{fs.mkdirSync(path.dirname(abs(file)),{recursive:true});fs.writeFileSync(abs(file),text,'utf8');};
|
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;};
|
|
function manifestState(options={}){
|
return validateAppendStableManifest(fs.readFileSync(abs(MANIFEST)),{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:MANIFEST_PREFIX,originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,...options});
|
}
|
|
function auditRow(auditId,baselineId,state){
|
const entry=runtime.auditEntry(auditId);
|
if(!entry)throw new Error(`AUDIT_MISSING:${auditId}`);
|
return{baseline_id:baselineId,identity_type:'APPEND_STABLE_AUDIT_ENTRY',artifact_path:`${AUDIT_REPORT}#L${entry.start}-L${entry.end}`,rows:String(entry.lines),bytes:String(entry.bytes),sha256:entry.sha256,mtime:'INFO_APPENDABLE_SHARED_FILE',required_state:state};
|
}
|
|
function formalEntryRow(){
|
const all=normalize(fs.readFileSync(abs(FORMAL_DESIGN))).split('\n'),start=all.findIndex(line=>line.startsWith('## ')&&line.includes(DESIGN_ID));
|
if(start<0)throw new Error('FORMAL_REPAIR002_ENTRY_MISSING');
|
let end=all.length;for(let index=start+1;index<all.length;index++)if(all[index].startsWith('## ')){end=index;break;}while(end>start&&all[end-1]==='')end--;
|
const buffer=Buffer.from(`${all.slice(start,end).join('\n')}\n`);
|
return{entry_id:'P0ACQSEMR2-FORMAL-DESIGN-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:hash(buffer),normalization:'UTF8_NO_BOM_LF_JOIN_LINES_WITH_TERMINAL_LF_V1',required_markers:'effective_network_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK|superseded_conflicting_scope_effect=HISTORICAL_TEXT_NOT_EXECUTION_AUTHORITY|network_calls=0|candidate_outcome_ceiling=QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE|runProductionTransactionR2|exact18'};
|
}
|
|
function historyRows(){
|
const rows=manifestState().logicalRows;
|
return rows.filter(row=>row.run_id===INITIAL_DESIGN_RUN||row.run_id===REPAIR001_DESIGN_RUN);
|
}
|
|
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 baselineRows(){
|
const manifest=fs.readFileSync(abs(MANIFEST)),formal=formalEntryRow();
|
const rows=[
|
auditRow(SOURCE_AUDIT,'P0ACQSEMR2-DESIGN-BASE-001','SOURCE_EXECUTION_PASS'),
|
auditRow(FAILED_REVIEW_AUDIT,'P0ACQSEMR2-DESIGN-BASE-002','REPAIR001_FAIL_AND_EXACT_THREE_BLOCKERS'),
|
{baseline_id:'P0ACQSEMR2-DESIGN-BASE-003',identity_type:'RAW_MANIFEST_PREFIX_AFTER_REPAIR001',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:'APPEND_ONLY_13_PLUS_10_HISTORY_PRESERVED'},
|
{baseline_id:'P0ACQSEMR2-DESIGN-BASE-004',identity_type:'FORMAL_REPAIR002_DESIGN_ENTRY',artifact_path:`${formal.artifact_path}#L${formal.start_line}-L${formal.end_line}`,rows:formal.lines,bytes:formal.bytes,sha256:formal.sha256,mtime:'INFO_APPENDABLE_SHARED_FILE',required_state:'EXACT_EFFECTIVE_SCOPE'},
|
];
|
for(const row of historyRows()){
|
const id=identity(row.artifact_path);rows.push({baseline_id:`P0ACQSEMR2-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'PRIOR_DESIGN_ARTIFACT_HISTORY',artifact_path:row.artifact_path,rows:String(id.rows),bytes:String(id.bytes),sha256:id.sha256,mtime:id.mtime,required_state:'IMMUTABLE_APPEND_ONLY_HISTORY'});
|
}
|
for(const item of protectedRows())rows.push({baseline_id:`P0ACQSEMR2-DESIGN-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 designSetRows(){
|
const roles=['RUNTIME_REPAIR002','DESIGN_BUILDER_REPAIR002','FORMAL_REPAIR002_ENTRY_AUTHORITY','RUNTIME_CONTRACT_REPAIR002','EXECUTION_EXACT_SET_REPAIR002','TRANSACTION_FAULT_RESULTS_REPAIR002','NEGATIVE_RESULTS_REPAIR002','DESIGN_BASELINE_REPAIR002','DESIGN_REVIEW_REQUEST_REPAIR002','DESIGN_EXACT_SET_REPAIR002','VALIDATION_LAST'];
|
return DESIGN_PATHS.map((artifactPath,index)=>({artifact_id:`P0ACQSEMR2-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 开放缺口新增14候选语义核验详细设计 REPAIR-002 聚焦复审请求\n\ncase_id=${CASE_ID}\naction_id=NEXT-ROBOT-046-DESIGN-REPAIR-002\ndesign_id=${DESIGN_ID}\nsource_execution_audit=${SOURCE_AUDIT}\nfailed_review_audit=${FAILED_REVIEW_AUDIT}\nrequested_release_audit=${RELEASE_AUDIT}\nrequested_batch=${EXEC_BATCH}\nrequested_run=${EXEC_RUN}\n\n本轮只修 formal scope、release 七键唯一解析与 production rollback。初版13条及REPAIR-001 10条设计manifest历史保持不变;candidate14、qualified4/context-only10、criteria7、protected49、map46只读及7个开放gap均不重开。\n\n如且仅如聚焦复审通过,请逐行且每键恰一登记:\nreviewed_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\n\nREPAIR-002冻结execution exact18、baseline-first、validation-last、单一runProductionTransactionR2、manifest bytes+mtime rollback、独立fallback/postcheck和10项真实production fault。审计PASS前execution outputs=0、execution manifest rows=0;不得联网、接受候选、关闭gap或升级证据/正式池。\n`;}
|
|
function validationRows(){
|
const source=runtime.auditEntry(SOURCE_AUDIT),failed=runtime.auditEntry(FAILED_REVIEW_AUDIT),negative=runtime.negativeRows(),faults=runtime.transactionFaultRows();
|
const preview=spawnSync(process.execPath,[abs(SCRIPT),'--preview'],{cwd:ROOT,encoding:'utf8'}),runtimeCheck=spawnSync(process.execPath,['--check',abs(SCRIPT)],{cwd:ROOT}),builderCheck=spawnSync(process.execPath,['--check',abs(BUILDER)],{cwd:ROOT});
|
const history=historyRows();
|
const checks=[
|
['SOURCE_AUDIT','PRESENT',source?'PRESENT':'MISSING'],['FAILED_REVIEW_AUDIT','PRESENT',failed?'PRESENT':'MISSING'],['INITIAL_HISTORY','13',String(history.filter(row=>row.run_id===INITIAL_DESIGN_RUN).length)],['REPAIR001_HISTORY','10',String(history.filter(row=>row.run_id===REPAIR001_DESIGN_RUN).length)],
|
['FORMAL_SCOPE_ERRORS','0',String(runtime.formalScopeTextErrors(fs.readFileSync(abs(FORMAL_DESIGN),'utf8').split(`## ${DESIGN_ID}`)[1]??'').length)],['CRITERIA','7',String(readCsv(CRITERIA).rows.length)],['DECISIONS','14',String(readCsv(DECISION_AUTHORITY).rows.length)],['QUALIFIED','4',String(readCsv(DECISION_AUTHORITY).rows.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW').length)],['CONTEXT_ONLY','10',String(readCsv(DECISION_AUTHORITY).rows.filter(row=>row.outcome==='CONTEXT_ONLY_NOT_GAP_CLOSING').length)],
|
['CONTRACTS','34',String(readCsv(CONTRACT).rows.length)],['SCHEMAS','9',String(readCsv(SCHEMA).rows.length)],['EXEC_SET','18',String(readCsv(EXEC_SET).rows.length)],['FAULT_PASS','10',String(faults.filter(row=>row.result==='PASS').length)],['NEGATIVE_PASS',String(negative.length),String(negative.filter(row=>row.result==='PASS').length)],['RUNTIME_NODE','0',String(runtimeCheck.status??1)],['BUILDER_NODE','0',String(builderCheck.status??1)],['PREVIEW','0',String(preview.status??1)],['PROTECTED','49',String(protectedRows().length)],['MANIFEST_PREFIX',MANIFEST_PREFIX.sha256,hash(fs.readFileSync(abs(MANIFEST)).subarray(0,MANIFEST_PREFIX.bytes))],['EXECUTION_FILES','0',String(runtime.GENERATED.filter(file=>fs.existsSync(abs(file))).length)],['EXECUTION_MANIFEST_ROWS','0',String(manifestState().logicalRows.filter(row=>row.run_id===EXEC_RUN).length)],
|
];
|
const rows=checks.map((item,index)=>({check_id:`P0ACQSEMR2-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_FAIL_CLOSED_DESIGN_ORACLE'}));
|
rows.push({check_id:'P0ACQSEMR2-DESIGN-VAL-022',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identities postchecked'});
|
return rows;
|
}
|
|
function manifestRowsForDesign(){return DESIGN_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 baselineErrors(rows){
|
const errors=[];
|
if(rows.length!==76)return[`DESIGN_BASELINE_COUNT:${rows.length}:76`];
|
for(const [row,auditId,code] of [[rows[0],SOURCE_AUDIT,'SOURCE'],[rows[1],FAILED_REVIEW_AUDIT,'FAILED_REVIEW']]){const entry=runtime.auditEntry(auditId);if(!entry||row.rows!==String(entry.lines)||row.bytes!==String(entry.bytes)||row.sha256!==entry.sha256)errors.push(`DESIGN_BASELINE_${code}`);}
|
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('DESIGN_BASELINE_MANIFEST_PREFIX');
|
for(const row of rows.slice(4)){if(!fs.existsSync(abs(row.artifact_path))){errors.push(`DESIGN_BASELINE_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(`DESIGN_BASELINE_IDENTITY:${row.artifact_path}`);}
|
return errors;
|
}
|
|
function build(){
|
const manifest=fs.readFileSync(abs(MANIFEST));
|
if(manifest.length!==MANIFEST_PREFIX.bytes||hash(manifest)!==MANIFEST_PREFIX.sha256)throw new Error('MANIFEST_PREFIX_DRIFT');
|
if(DESIGN_PATHS.slice(2).some(file=>fs.existsSync(abs(file))))throw new Error('REPAIR002_TARGET_EXISTS');
|
if(runtime.GENERATED.some(file=>fs.existsSync(abs(file))))throw new Error('EXECUTION_TARGET_EXISTS');
|
write(FORMAL_ENTRY_AUTHORITY,serializeCsv([formalEntryRow()],runtime.FORMAL_ENTRY_COLUMNS));
|
write(CONTRACT,serializeCsv(runtime.contractRows(),runtime.CONTRACT_COLUMNS));
|
write(EXEC_SET,serializeCsv(runtime.executionSetRows(),runtime.EXEC_SET_COLUMNS));
|
write(FAULT_RESULTS,serializeCsv(runtime.transactionFaultRows(),runtime.FAULT_COLUMNS));
|
write(NEG_RESULTS,serializeCsv(runtime.negativeRows(),NEG_COLUMNS));
|
write(DESIGN_BASELINE,serializeCsv(baselineRows(),runtime.BASELINE_COLUMNS));
|
write(DESIGN_REQUEST,requestText());
|
write(DESIGN_SET,serializeCsv(designSetRows(),DESIGN_SET_COLUMNS));
|
const validation=validationRows();write(DESIGN_VALIDATION,serializeCsv(validation,runtime.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 before=fs.readFileSync(abs(MANIFEST)),rows=manifestRowsForDesign(),candidate=Buffer.concat([before,Buffer.from(serializeManifestDataRows(rows),'utf8')]);
|
const state=validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:MANIFEST_PREFIX,originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:DESIGN_RUN,expectedPhysicalDelta:11});
|
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_REREVIEW',prior_history_rows:23,repair_artifacts:11,faults:10,negative_tests:runtime.negativeRows().length,execution_outputs:0};
|
}
|
|
function validate(){
|
const errors=[...runtime.designInputErrors({requireRelease:false,expectNoExecution:true})];
|
const negative=readCsv(NEG_RESULTS),faults=readCsv(FAULT_RESULTS),baseline=readCsv(DESIGN_BASELINE),designSet=readCsv(DESIGN_SET),validation=readCsv(DESIGN_VALIDATION);
|
errors.push(...compareRows(negative.rows,runtime.negativeRows(),NEG_COLUMNS,'NEGATIVE'));
|
errors.push(...compareRows(faults.rows,runtime.transactionFaultRows(),runtime.FAULT_COLUMNS,'FAULT'));
|
errors.push(...baselineErrors(baseline.rows));
|
if(designSet.rows.length!==11)errors.push(`DESIGN_SET_COUNT:${designSet.rows.length}:11`);
|
if(validation.rows.length!==22||validation.rows.some(row=>row.status==='FAIL'))errors.push('DESIGN_VALIDATION');
|
const history=historyRows();if(history.filter(row=>row.run_id===INITIAL_DESIGN_RUN).length!==13||history.filter(row=>row.run_id===REPAIR001_DESIGN_RUN).length!==10)errors.push('PRIOR_HISTORY');
|
const expected=manifestRowsForDesign(),state=manifestState({expectedRunRows:expected,expectedRunId:DESIGN_RUN,expectedPhysicalDelta:11,filesystemIdentity:{runIds:[DESIGN_RUN],get:file=>fs.existsSync(abs(file))?identity(file):null}});errors.push(...state.errors.map(code=>`MANIFEST:${code}`));
|
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_CANDIDATE_SEMANTIC_VERIFICATION_DESIGN_REPAIR002',errors},null,2));if(errors.length)process.exitCode=1;}
|
else if(mode==='--self-test'){const rows=runtime.negativeRows();console.log(JSON.stringify({status:rows.every(row=>row.result==='PASS')?'SELF_TEST_PASS':'FAIL',tests:rows.length},null,2));if(rows.some(row=>row.result!=='PASS'))process.exitCode=1;}
|
else if(mode==='--validate-package-manifest'){const errors=manifestState().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}`);
|
}
|