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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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_qualified7_evidence_acceptance_verification_runtime_repair001_20260730.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,EXEC_RUN,EXEC_BATCH,SOURCE_AUDIT,PROTECTED_INVENTORY}=runtime;
const DESIGN_ID='DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-REPAIR-002';
const DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-REPAIR-002';
const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-REPAIR-002';
const INITIAL_DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-001';
const REPAIR1_DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-REPAIR-001';
const SOURCE_EXEC_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-001';
const BUILDER='dev/ana-dev/detail_strengthening_p0_qualified7_evidence_acceptance_verification_design_repair002_20260730.mjs';
const FORMAL_DESIGN='ana-doc/机器人案例/案例分析设计.md';
const FORMAL_AUTH=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_formal_design_entry_authority_repair002_20260730.csv`;
const REPAIR_CONTRACT=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_design_repair002_contract_20260730.csv`;
const NEG_RESULTS=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_design_repair002_negative_results_20260730.csv`;
const BASELINE=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_design_baseline_repair002_20260730.csv`;
const REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_qualified7_evidence_acceptance_design_repair002_20260730.md`;
const DESIGN_SET=`${BASE}/manifest/detail_strengthening_p0_qualified7_evidence_acceptance_design_artifact_set_repair002_20260730.csv`;
const VALIDATION=`${BASE}/manifest/detail_strengthening_p0_qualified7_evidence_acceptance_design_validation_repair002_20260730.csv`;
const MANIFEST_PREFIX={bytes:655657,sha256:'d96262d893446bc5aa69bcccdc9ec2679b32e4893d4fc79eb246418f6fb74a7b'};
const DESIGN_PATHS=[BUILDER,FORMAL_AUTH,REPAIR_CONTRACT,NEG_RESULTS,BASELINE,REQUEST,DESIGN_SET,VALIDATION];
const CONTRACT_COLUMNS=['contract_id','scope','field_or_gate','required_value_or_rule','failure_state'];
const NEG_COLUMNS=['test_id','mutation_applied','oracle','expected','expected_code','actual','actual_codes','result'];
const SET_COLUMNS=['artifact_id','batch_id','run_id','generation_order','artifact_path','artifact_role','identity_policy'];
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');};
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 runRows(runId){return manifestState().logicalRows.filter(row=>row.run_id===runId);}
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_ENTRY_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:'P0ACCR2-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:'REPAIR-002|DESIGN_REPAIR_MANIFEST_COUNT_BINDING=10|10|10|eligible6/held1|FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK|PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE|NO_UPGRADE'};}
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 countBindingErrors({exactSet=10,runRows=10,physicalDelta=10}={}){const errors=[];if(exactSet!==10)errors.push(`DESIGN_REPAIR_EXACT_SET_COUNT:${exactSet}:10`);if(runRows!==10)errors.push(`DESIGN_REPAIR_RUN_COUNT:${runRows}:10`);if(physicalDelta!==10)errors.push(`DESIGN_REPAIR_PHYSICAL_DELTA:${physicalDelta}:10`);if(new Set([exactSet,runRows,physicalDelta]).size!==1)errors.push(`DESIGN_REPAIR_COUNT_CROSSBIND:${exactSet}:${runRows}:${physicalDelta}`);return errors;}
function contractRows(){return[
  {contract_id:'P0ACCR2-CON-001',scope:'DESIGN_REPAIR',field_or_gate:'IMMUTABLE_MANIFEST_PREFIX',required_value_or_rule:`${MANIFEST_PREFIX.bytes}|${MANIFEST_PREFIX.sha256}`,failure_state:'FAIL_CLOSED_NO_APPEND'},
  {contract_id:'P0ACCR2-CON-002',scope:'DESIGN_REPAIR',field_or_gate:'FAILED_REPAIR001_HISTORY',required_value_or_rule:'10 exact paths and seven-field identities retained append-only',failure_state:'FAIL_CLOSED_NO_APPEND'},
  {contract_id:'P0ACCR2-CON-003',scope:'DESIGN_REPAIR',field_or_gate:'DESIGN_REPAIR_MANIFEST_COUNT_BINDING',required_value_or_rule:'exact_set=10|run_rows=10|physical_delta=10',failure_state:'FAIL_CLOSED_NO_APPEND'}
];}
function negativeRows(){const cases=[
  ['CLEAN_10',()=>countBindingErrors({exactSet:10,runRows:10,physicalDelta:10}),'ACCEPT','NONE'],
  ['STALE_14',()=>countBindingErrors({exactSet:10,runRows:10,physicalDelta:14}),'REJECT','DESIGN_REPAIR_PHYSICAL_DELTA:14:10'],
  ['RUN_9',()=>countBindingErrors({exactSet:10,runRows:9,physicalDelta:10}),'REJECT','DESIGN_REPAIR_RUN_COUNT:9:10']
];return cases.map((item,index)=>{const errors=item[1](),actual=errors.length?'REJECT':'ACCEPT';return{test_id:`P0ACCR2-NEG-${String(index+1).padStart(3,'0')}-${item[0]}`,mutation_applied:index?'YES':'NO_CLEAN_CONTROL',oracle:'countBindingErrors',expected:item[2],expected_code:item[3],actual,actual_codes:errors.join('|')||'NONE',result:actual===item[2]&&(item[3]==='NONE'||errors.includes(item[3]))?'PASS':'FAIL'};});}
function baselineRows(){const source=runtime.auditEntry(SOURCE_AUDIT),formal=formalEntryRow(),manifest=fs.readFileSync(abs(MANIFEST)),rows=[
  {baseline_id:'P0ACCR2-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_ALLOWED'},
  {baseline_id:'P0ACCR2-BASE-002',identity_type:'MANIFEST_PREFIX',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'},
  {baseline_id:'P0ACCR2-BASE-003',identity_type:'FORMAL_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_REPAIR002_MARKERS'}
];for(const [runId,type,count] of [[REPAIR1_DESIGN_RUN,'FAILED_REPAIR001_DESIGN_ARTIFACT',10],[INITIAL_DESIGN_RUN,'FAILED_INITIAL_DESIGN_ARTIFACT',14],[SOURCE_EXEC_RUN,'PREDECESSOR_EXECUTION_ARTIFACT',18]]){const prior=runRows(runId);if(prior.length!==count)throw new Error(`HISTORY_COUNT:${runId}:${prior.length}:${count}`);for(const row of prior){const id=identity(row.artifact_path);rows.push({baseline_id:`P0ACCR2-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:type,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:`P0ACCR2-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 setRows(){const roles=['DESIGN_REPAIR_BUILDER','FORMAL_ENTRY_AUTHORITY','COUNT_BINDING_CONTRACT','COUNT_BINDING_NEGATIVE_RESULTS','DESIGN_BASELINE','FOCUSED_REVIEW_REQUEST','DESIGN_EXACT_SET','VALIDATION_LAST'];return DESIGN_PATHS.map((artifact_path,index)=>({artifact_id:`P0ACCR2-SET-${String(index+1).padStart(3,'0')}`,batch_id:DESIGN_BATCH,run_id:DESIGN_RUN,generation_order:String(index+1),artifact_path,artifact_role:roles[index],identity_policy:'EXACT_SHA256_BYTES_FILESYSTEM_MTIME_MS'}));}
function requestText(){return`# Qualified7 evidence acceptance verification design REPAIR-002 focused review request\n\ncase_id=${CASE_ID}\naction_id=NEXT-ROBOT-042-DESIGN-REPAIR-002\ndesign_id=${DESIGN_ID}\nsource_audit=${SOURCE_AUDIT}\nrequested_release_audit=${runtime.RELEASE_AUDIT}\nrequested_batch=${EXEC_BATCH}\nrequested_run=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nevidence_acceptance_ceiling=PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE\n\nREPAIR-001 runtime preview and 19 negative tests pass. Its ten design rows are immutable failed design history; only stale postwrite expectedPhysicalDelta=14 is superseded by the exact 10|10|10 binding.\n\nIf the focused review passes, write exactly:\nresult=PASS\nexecution_release=EXPLICITLY_RELEASED\nreleased_batch_id=${EXEC_BATCH}\nreleased_run_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nevidence_acceptance_ceiling=PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE\n\nNo execution before exact release.\n`;}
function designRows(){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 validationRows(){const preview=spawnSync(process.execPath,[abs(runtime.SCRIPT),'--preview'],{cwd:ROOT}),self=spawnSync(process.execPath,[abs(runtime.SCRIPT),'--self-test'],{cwd:ROOT}),node=spawnSync(process.execPath,['--check',abs(BUILDER)],{cwd:ROOT}),neg=negativeRows(),checks=[
  ['RUNTIME_PREVIEW','0',String(preview.status??1)],['RUNTIME_SELF_TEST','0',String(self.status??1)],['BUILDER_NODE','0',String(node.status??1)],['REPAIR1_HISTORY','10',String(runRows(REPAIR1_DESIGN_RUN).length)],['INITIAL_HISTORY','14',String(runRows(INITIAL_DESIGN_RUN).length)],['SOURCE_EXEC_HISTORY','18',String(runRows(SOURCE_EXEC_RUN).length)],['COUNT_BINDING_ERRORS','0',String(countBindingErrors().length)],['NEGATIVE_RESULTS','3',String(neg.filter(row=>row.result==='PASS').length)],['CONTRACTS','3',String(contractRows().length)],['BASELINE','94',String(baselineRows().length)],['PROTECTED','49',String(protectedRows().length)],['EXECUTION_FILES','0',String(runtime.GENERATED.filter(file=>fs.existsSync(abs(file))).length)],['EXECUTION_MANIFEST','0',String(runRows(EXEC_RUN).length)],['MANIFEST_PREFIX',MANIFEST_PREFIX.sha256,hash(fs.readFileSync(abs(MANIFEST)).subarray(0,MANIFEST_PREFIX.bytes))],['DESIGN_EXACT_SET','8',String(setRows().length)]
];const rows=checks.map((item,index)=>({check_id:`P0ACCR2-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_COUNT_BINDING_FAIL_CLOSED_ORACLE'}));rows.push({check_id:'P0ACCR2-VAL-016',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identities postchecked'});return rows;}
function validate(){const errors=[],neg=readCsv(NEG_RESULTS),base=readCsv(BASELINE),set=readCsv(DESIGN_SET),val=readCsv(VALIDATION);errors.push(...runtime.designInputErrors({requireRelease:false,expectNoExecution:true}));if(neg.rows.length!==3||neg.rows.some(row=>row.result!=='PASS'))errors.push('NEGATIVE_RESULTS');if(base.rows.length!==94)errors.push(`BASELINE_COUNT:${base.rows.length}:94`);if(set.rows.length!==8)errors.push(`DESIGN_SET_COUNT:${set.rows.length}:8`);if(val.rows.length!==16||val.rows.some(row=>row.status==='FAIL'))errors.push('VALIDATION_STATUS');errors.push(...countBindingErrors({exactSet:runRows(REPAIR1_DESIGN_RUN).length,runRows:runRows(REPAIR1_DESIGN_RUN).length,physicalDelta:10}));const expected=designRows(),state=manifestState({expectedRunRows:expected,expectedRunId:DESIGN_RUN,expectedPhysicalDelta:8,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)];}
function build(){const before=fs.readFileSync(abs(MANIFEST));if(before.length!==MANIFEST_PREFIX.bytes||hash(before)!==MANIFEST_PREFIX.sha256)throw new Error('MANIFEST_PREFIX_DRIFT');if(DESIGN_PATHS.slice(1).some(file=>fs.existsSync(abs(file))))throw new Error('TARGET_EXISTS');const created=DESIGN_PATHS.slice(1);try{write(FORMAL_AUTH,serializeCsv([formalEntryRow()],runtime.FORMAL_ENTRY_COLUMNS));write(REPAIR_CONTRACT,serializeCsv(contractRows(),CONTRACT_COLUMNS));write(NEG_RESULTS,serializeCsv(negativeRows(),NEG_COLUMNS));write(BASELINE,serializeCsv(baselineRows(),runtime.BASELINE_COLUMNS));write(REQUEST,requestText());write(DESIGN_SET,serializeCsv(setRows(),SET_COLUMNS));const val=validationRows();write(VALIDATION,serializeCsv(val,runtime.VALIDATION_COLUMNS));if(val.some(row=>row.status==='FAIL'))throw new Error('VALIDATION_FAIL');const rows=designRows(),candidate=Buffer.concat([before,Buffer.from(serializeManifestDataRows(rows),'utf8')]),candidateState=validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:MANIFEST_PREFIX,originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:DESIGN_RUN,expectedPhysicalDelta:8});if(candidateState.errors.length)throw new Error(`MANIFEST_CANDIDATE:${candidateState.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',design_artifacts:8,repair1_history:10,negative_tests:3,execution_outputs:0};}catch(error){fs.writeFileSync(abs(MANIFEST),before);for(const file of created)if(fs.existsSync(abs(file)))fs.rmSync(abs(file));throw error;}}
 
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_QUALIFIED7_EVIDENCE_ACCEPTANCE_DESIGN_REPAIR002',errors},null,2));if(errors.length)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 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 throw new Error(`UNKNOWN_MODE:${mode}`);}