Cai
12 hours ago 22384865fbdb92c4ce603c137b1cac52ab6450ba
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
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_primary_source_discovery_runtime_repair002_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,DESIGN_RUN,DESIGN_BATCH,EXEC_RUN,SCRIPT,FORMAL_DESIGN_ENTRY_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET}=runtime;
const BUILDER='dev/ana-dev/detail_strengthening_p0_primary_source_discovery_design_repair002_20260730.mjs';
const FORMAL_DESIGN='ana-doc/机器人案例/案例分析设计.md';
const PROTECTED_INVENTORY=`${BASE}/evidence/final_gate_output_inventory_rebuild_repair001_20260728.csv`;
const R1_DESIGN_SET=`${BASE}/manifest/detail_strengthening_p0_primary_source_discovery_design_artifact_set_repair001_20260730.csv`;
const R1_DESIGN_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_primary_source_discovery_design_validation_repair001_20260730.csv`;
const NEG_RESULTS=`${BASE}/evidence/detail_strengthening_p0_primary_source_discovery_negative_results_repair002_20260730.csv`;
const DESIGN_BASELINE=`${BASE}/evidence/detail_strengthening_p0_primary_source_discovery_design_baseline_repair002_20260730.csv`;
const DESIGN_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_primary_source_discovery_design_repair002_20260730.md`;
const DESIGN_SET=`${BASE}/manifest/detail_strengthening_p0_primary_source_discovery_design_artifact_set_repair002_20260730.csv`;
const DESIGN_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_primary_source_discovery_design_validation_repair002_20260730.csv`;
const PREDECESSOR_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-DESIGN-REREVIEW-001';
const PREDECESSOR_ENTRY={lines:50,bytes:8649,sha256:'343fb8d412724bed7180de96c1545db44ecac5208cacdaa17455f7ae97ba1260'};
const R1_DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-DESIGN-REPAIR-001';
const MANIFEST_PREFIX={bytes:598762,sha256:'ec9f2d9d2e20f0547564ed51d9aadf91a54d44bab305a57521ae023112d19c9a'};
const DESIGN_PATHS=[SCRIPT,BUILDER,FORMAL_DESIGN_ENTRY_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,NEG_RESULTS,DESIGN_BASELINE,DESIGN_REQUEST,DESIGN_SET,DESIGN_VALIDATION];
const FORMAL_ENTRY_COLUMNS=runtime.FORMAL_ENTRY_COLUMNS,CONTRACT_COLUMNS=runtime.CONTRACT_COLUMNS,SCHEMA_COLUMNS=runtime.SCHEMA_COLUMNS,EXEC_SET_COLUMNS=runtime.EXEC_SET_COLUMNS;
const NEG_COLUMNS=['test_id','mutation_applied','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('/')),hash=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 lines=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:lines(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 auditEntry(auditId){const content=normalize(fs.readFileSync(abs(AUDIT_REPORT))),all=content.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:hash(buffer)};}
function formalEntryRow(){const all=normalize(fs.readFileSync(abs(FORMAL_DESIGN))).split('\n'),heading='## DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-REPAIR-002(2026-07-30)',start=all.findIndex(line=>line===heading);if(start<0)throw new Error('FORMAL_REPAIR002_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:'P0DISCR2-FORMAL-DESIGN-001',design_id:'DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-REPAIR-002',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:'FORMAL_DESIGN_ENTRY_MARKER:NO_UPGRADE|CODEX_WEB_SEARCH_QUERY_AND_OPEN|HELD_BY_REQUIRED_EXTERNAL_INFORMATION_METHOD_UNAVAILABLE|NO_UPGRADE|21 条 data-only manifest'};}
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 manifestState(options={}){return validateAppendStableManifest(fs.readFileSync(abs(MANIFEST)),{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:MANIFEST_PREFIX,originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,...options});}
function r1ManifestRows(){return manifestState().logicalRows.filter(row=>row.run_id===R1_DESIGN_RUN);}
function designRows(){return manifestState().logicalRows.filter(row=>row.run_id===DESIGN_RUN);}
function baselineRows(){const predecessor=auditEntry(PREDECESSOR_AUDIT),manifest=fs.readFileSync(abs(MANIFEST));if(!predecessor)throw new Error('PREDECESSOR_MISSING');const rows=[{baseline_id:'P0DISCR2-DESIGN-BASE-001',identity_type:'PREDECESSOR_AUDIT_ENTRY',artifact_path:`${AUDIT_REPORT}#L${predecessor.start}-L${predecessor.end}`,rows:String(predecessor.lines),bytes:String(predecessor.bytes),sha256:predecessor.sha256,mtime:'INFO_APPENDABLE_SHARED_FILE',required_state:'EXACT_INITIAL_DESIGN_FAIL_ENTRY'},{baseline_id:'P0DISCR2-DESIGN-BASE-002',identity_type:'RAW_MANIFEST_PREFIX_AFTER_R1_SELF_DETECTED_FAIL',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_R1_14_ROWS_PRESERVED'}];for(const row of r1ManifestRows()){const id=identity(row.artifact_path);rows.push({baseline_id:`P0DISCR2-DESIGN-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'R1_DESIGN_ARTIFACT',artifact_path:row.artifact_path,rows:String(id.rows),bytes:String(id.bytes),sha256:id.sha256,mtime:id.mtime,required_state:'IMMUTABLE_FAILED_POSTWRITE_HISTORY'});}for(const item of protectedRows())rows.push({baseline_id:`P0DISCR2-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_DESIGN_ENTRY_AUTHORITY_REPAIR002','RUNTIME_CONTRACT_REPAIR002','SCHEMA_AUTHORITY_REPAIR002','EXECUTION_EXACT_SET_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:`P0DISCR2-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 一手来源发现详细设计 REPAIR-002 聚焦复审请求\n\ncase_id=${CASE_ID}\naction_id=NEXT-ROBOT-040-DESIGN-REPAIR-002\ndesign_id=DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-REPAIR-002\npredecessor_audit=${PREDECESSOR_AUDIT}\nrequested_release_audit=${runtime.RELEASE_AUDIT}\nrequested_batch=${runtime.EXEC_BATCH}\nrequested_run=${runtime.EXEC_RUN}\n\nREPAIR-001 的 14 条 manifest 作为 self-detected failed postwrite history 保留。本包以版本化 runtime/formal-entry/contract/schema/exact-set 修复精确 NO_UPGRADE marker,不回写任何前缀;查询、policy、method、10/7/14 集合和 protected49 均复用。执行器仍冻结 begin-discovery → 14 query raw/supplement/provenance → finalize 10/7/10 → validation-last → exact21 manifest。\n\n设计复审前 network=0、staging=0、candidate=0、proposed run manifest=0。\n`;}
function validationRows(){const predecessor=auditEntry(PREDECESSOR_AUDIT),negative=runtime.negativeRows(),preview=spawnSync(process.execPath,[abs(SCRIPT),'--preview'],{encoding:'utf8'}),checks=[['PREDECESSOR',`${PREDECESSOR_ENTRY.lines}/${PREDECESSOR_ENTRY.bytes}/${PREDECESSOR_ENTRY.sha256}`,predecessor?`${predecessor.lines}/${predecessor.bytes}/${predecessor.sha256}`:'MISSING'],['R1_HISTORY_ROWS','14',String(r1ManifestRows().length)],['FORMAL_ENTRY','1','1'],['TARGETS','10',String(runtime.authorityBundle().targets.length)],['GAPS','7',String(runtime.authorityBundle().gaps.length)],['QUERIES','14',String(runtime.authorityBundle().queries.length)],['QUERY_POLICY_ERRORS','0',String(r1QueryErrors())],['METHOD_ERRORS','0',String(r1MethodErrors())],['CONTRACTS','46',String(readCsv(CONTRACT).rows.length)],['SCHEMAS','12',String(readCsv(SCHEMA).rows.length)],['EXEC_SET','21',String(readCsv(EXEC_SET).rows.length)],['NEGATIVE_TESTS',String(negative.length),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)],['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)],['BOUNDARIES','NO_UPGRADE','NO_UPGRADE']];const rows=checks.map((item,index)=>({check_id:`P0DISCR2-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:'P0DISCR2-DESIGN-VAL-021',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identity postchecked'});return rows;}
function r1QueryErrors(){const imported=spawnSync(process.execPath,['-e',`import('./dev/ana-dev/detail_strengthening_p0_primary_source_discovery_runtime_repair001_20260730.mjs').then(m=>console.log(m.queryPolicyErrors().length))`],{cwd:ROOT,encoding:'utf8'});return Number(imported.stdout.trim()||-1);}
function r1MethodErrors(){const imported=spawnSync(process.execPath,['-e',`import('./dev/ana-dev/detail_strengthening_p0_primary_source_discovery_runtime_repair001_20260730.mjs').then(m=>console.log(m.methodAuthorityErrors(m.authorityBundle().methods).length))`],{cwd:ROOT,encoding:'utf8'});return Number(imported.stdout.trim()||-1);}
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('R2_TARGET_EXISTS');write(FORMAL_DESIGN_ENTRY_AUTHORITY,serializeCsv([formalEntryRow()],FORMAL_ENTRY_COLUMNS));write(CONTRACT,serializeCsv(runtime.contractRows(),CONTRACT_COLUMNS));write(SCHEMA,serializeCsv(runtime.schemaRows(),SCHEMA_COLUMNS));write(EXEC_SET,serializeCsv(runtime.executionSetRows(),EXEC_SET_COLUMNS));write(NEG_RESULTS,serializeCsv(runtime.negativeRows(),NEG_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 before=fs.readFileSync(abs(MANIFEST)),rows=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};}),candidate=Buffer.concat([before,Buffer.from(serializeManifestDataRows(rows),'utf8')]),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',r1_history_rows:14,design_rows:11,negative_tests:runtime.negativeRows().length,execution_outputs:0};}
function validate(){const errors=[];const predecessor=auditEntry(PREDECESSOR_AUDIT);if(!predecessor||predecessor.lines!==PREDECESSOR_ENTRY.lines||predecessor.bytes!==PREDECESSOR_ENTRY.bytes||predecessor.sha256!==PREDECESSOR_ENTRY.sha256)errors.push('PREDECESSOR');errors.push(...runtime.designInputErrors({requireRelease:false,expectNoExecution:true}));const neg=readCsv(NEG_RESULTS),validation=readCsv(DESIGN_VALIDATION);if(neg.rows.length!==runtime.negativeRows().length||neg.rows.some(row=>row.result!=='PASS'))errors.push('NEGATIVE');if(validation.rows.length!==21||validation.rows.some(row=>row.status==='FAIL'))errors.push('VALIDATION');if(r1ManifestRows().length!==14)errors.push('R1_HISTORY');if(protectedRows().length!==49)errors.push('PROTECTED');const rows=designRows();if(rows.length!==11||new Set(rows.map(row=>row.artifact_path)).size!==11)errors.push(`DESIGN_ROWS:${rows.length}`);for(const row of rows){const id=identity(row.artifact_path);if(row.sha256!==id.sha256||row.bytes!==String(id.bytes)||Date.parse(row.mtime)!==id.mtimeMs)errors.push(`IDENTITY:${row.artifact_path}`);}return[...new Set(errors)];}
function selfTest(){const errors=[];const row=formalEntryRow();if(!row.required_markers.includes('NO_UPGRADE'))errors.push('NO_UPGRADE_MARKER');const releaseFail=`result=FAIL\nnotes=result=PASS execution_release=EXPLICITLY_RELEASED released_batch_id=${runtime.EXEC_BATCH} released_run_id=${runtime.EXEC_RUN}`;if(!runtime.releaseTextErrors(releaseFail).length)errors.push('RELEASE_FALSE_POSITIVE');return 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==='--self-test'){const errors=selfTest();console.log(JSON.stringify({status:errors.length?'FAIL':'SELF_TEST_PASS',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 throw new Error(`UNKNOWN_MODE:${mode}`);}