Cai
2026-08-13 3e71d77a448b4e3961629d452973e88b13ad06be
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import {pathToFileURL} from 'node:url';
import * as prior from './detail_strengthening_p0_eligible6_formal_evidence_integration_runtime_repair002_20260731.mjs';
import * as rollback from './detail_strengthening_p0_eligible6_formal_evidence_integration_runtime_repair001_20260730.mjs';
import {parseAuthorityCsv,serializeCsv,serializeManifestDataRows,validateAppendStableManifest} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
export const ROOT=prior.ROOT,CASE_ID=prior.CASE_ID,BASE=prior.BASE,AUDIT_REPORT=prior.AUDIT_REPORT,MANIFEST=prior.MANIFEST,ANOMALY_AUTHORITY=prior.ANOMALY_AUTHORITY,ORIGINAL_TRIAGE_RUN=prior.ORIGINAL_TRIAGE_RUN;
export const DESIGN_ID='DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-GAP-CLOSURE-VERIFICATION-001';
export const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-GAP-CLOSURE-VERIFICATION-DESIGN-001';
export const DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-GAP-CLOSURE-VERIFICATION-DESIGN-001';
export const EXEC_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-GAP-CLOSURE-VERIFICATION-001';
export const EXEC_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-GAP-CLOSURE-VERIFICATION-001';
export const EXEC_TOKEN='EXECUTE_DETAIL_STRENGTHENING_P0_GAP_CLOSURE_VERIFICATION_001';
export const SOURCE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-ELIGIBLE6-FORMAL-EVIDENCE-INTEGRATION-EXEC-OUTPUT-001';
export const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-GAP-CLOSURE-VERIFICATION-DESIGN-REREVIEW-001';
export const SCRIPT='dev/ana-dev/detail_strengthening_p0_gap_closure_verification_runtime_20260731.mjs';
export const ACCEPTED_INPUT=prior.ACCEPTED_REGISTER;
export const GAP_INPUT=prior.GAP_SUMMARY;
export const OCCURRENCE_INPUT=prior.APPLICATION;
export const ITEM_AUTHORITY=`${BASE}/evidence/detail_strengthening_gap_item_authority_20260730.csv`;
export const CASE_MAP=prior.CASE_MAP;
export const PROTECTED_INVENTORY=prior.PROTECTED_INVENTORY;
export const SOURCE_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_source_audit_authority_20260731.csv`;
export const CRITERIA=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_criteria_20260731.csv`;
export const DECISION_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_decision_authority_20260731.csv`;
export const OCCURRENCE_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_occurrence_authority_20260731.csv`;
export const NEXT_EVIDENCE_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_next_evidence_authority_20260731.csv`;
export const CONTRACT=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_runtime_contract_20260731.csv`;
export const SCHEMA=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_schema_20260731.csv`;
export const EXEC_SET=`${BASE}/manifest/detail_strengthening_p0_gap_closure_verification_execution_artifact_set_20260731.csv`;
export const FORMAL_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_formal_design_entry_authority_20260731.csv`;
export const DESIGN_BASELINE=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_design_baseline_20260731.csv`;
export const EXEC_BASELINE=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_execution_baseline_20260731.csv`;
export const DECISION_OUTPUT=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_decision_20260731.csv`;
export const OCCURRENCE_OUTPUT=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_occurrence_application_20260731.csv`;
export const NEXT_EVIDENCE_OUTPUT=`${BASE}/evidence/detail_strengthening_p0_gap_closure_verification_next_evidence_plan_20260731.csv`;
export const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_gap_closure_verification_execution_20260731.md`;
export const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_gap_closure_verification_execution_validation_20260731.csv`;
export const GENERATED=[EXEC_BASELINE,DECISION_OUTPUT,OCCURRENCE_OUTPUT,NEXT_EVIDENCE_OUTPUT,EXEC_REQUEST,EXEC_VALIDATION];
 
export const SOURCE_ENTRY_COLUMNS=['authority_id','audit_id','artifact_path','start_line','end_line','normalized_lines','normalized_bytes','normalized_sha256','normalization','normalized_prefix_bytes','normalized_prefix_sha256','required_pass_literal','required_status_literal'];
export const CRITERIA_COLUMNS=['criterion_id','conceptual_gap_key','source_occurrence_count','required_evidence_scope','closure_rule','supported_scope_current','missing_scope_current','allowed_outcome','failure_state'];
export const DECISION_COLUMNS=['decision_id','conceptual_gap_key','source_occurrence_count','accepted_reference_count','held_reference_count','supported_scope','missing_scope','closure_rule','verification_outcome','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect','business_output_mutation','review_state'];
export const OCCURRENCE_COLUMNS=['application_id','target_id','source_occurrence_key','source_authority_id','source_row_id','conceptual_gap_key','accepted_reference_count','verification_outcome','action','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect','business_output_mutation'];
export const NEXT_COLUMNS=['plan_id','conceptual_gap_key','priority','missing_scope','required_source_class','exact_next_action','network_required_for_future_work','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect','current_run_effect'];
export const CONTRACT_COLUMNS=['contract_id','scope','field_or_gate','required_value_or_rule','failure_state'];
export const SCHEMA_COLUMNS=['schema_id','artifact_role','ordered_columns','primary_key','row_count_rule','serialization','derivation_rule','boundary_rule'];
export const EXEC_SET_COLUMNS=['artifact_id','batch_id','run_id','generation_order','artifact_path','artifact_role','identity_policy'];
export const BASELINE_COLUMNS=prior.BASELINE_COLUMNS;
export const VALIDATION_COLUMNS=prior.VALIDATION_COLUMNS;
export const FORMAL_ENTRY_COLUMNS=prior.FORMAL_ENTRY_COLUMNS;
 
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 canonicalLine=line=>{let value=line.trim().replace(/^[\-*]\s*/,'').trim();if(value.startsWith('`')&&value.endsWith('`'))value=value.slice(1,-1);return value.trim();};
const realResolve=logical=>abs(logical);
const proxyWith=overrides=>new Proxy(fs,{get(target,prop){return overrides[prop]??target[prop];}});
const parseBuffer=buffer=>{const parsed=parseAuthorityCsv(normalize(buffer));if(parsed.errors.length)throw new Error(`CSV:${parsed.errors.join('|')}`);return parsed;};
const readCsv=(logical,ctx={resolve:realResolve,io:fs})=>parseBuffer(ctx.io.readFileSync(ctx.resolve(logical)));
const identity=(logical,ctx={resolve:realResolve,io:fs})=>{const file=ctx.resolve(logical),buffer=ctx.io.readFileSync(file),stat=ctx.io.statSync(file);return{rows:logical.endsWith('.csv')?readCsv(logical,ctx).rows.length:lineCount(buffer),bytes:buffer.length,sha256:hash(buffer),mtime:new Date(Math.trunc(stat.mtimeMs)).toISOString(),mtimeMs:Math.trunc(stat.mtimeMs)};};
const exactColumns=(parsed,columns,code)=>parsed.header.join('|')===columns.join('|')?[]:[`${code}_COLUMNS`];
const compareRows=(actual,expected,columns,code)=>{const errors=[];if(actual.length!==expected.length)return[`${code}_COUNT:${actual.length}:${expected.length}`];for(let i=0;i<expected.length;i++)for(const column of columns)if(String(actual[i]?.[column]??'')!==String(expected[i]?.[column]??'')){errors.push(`${code}_FIELD:${i+1}:${column}`);break;}return errors;};
 
export 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`),prefix=Buffer.from(`${lines.slice(0,end).join('\n')}\n`);return{start:start+1,end,lines:end-start,bytes:buffer.length,sha256:hash(buffer),text:buffer.toString('utf8'),prefix_bytes:prefix.length,prefix_sha256:hash(prefix)};}
 
export function sourceAuthorityRow(){const entry=auditEntry(SOURCE_AUDIT);if(!entry)throw new Error('SOURCE_AUDIT_MISSING');return{authority_id:'P0GCV-SOURCE-AUDIT-001',audit_id:SOURCE_AUDIT,artifact_path:AUDIT_REPORT,start_line:String(entry.start),end_line:String(entry.end),normalized_lines:String(entry.lines),normalized_bytes:String(entry.bytes),normalized_sha256:entry.sha256,normalization:'UTF8_NO_BOM_LF_JOIN_LINES_WITH_TERMINAL_LF_V1',normalized_prefix_bytes:String(entry.prefix_bytes),normalized_prefix_sha256:entry.prefix_sha256,required_pass_literal:'result=PASS',required_status_literal:'Eligible6_formal_evidence_integration_execution_status=EXACT_RUN_EXECUTION_AND_OUTPUT_QUALITY_REVIEW_PASSED'};}
function auditLiteralErrors(entry,row){const lines=entry.text.split('\n').map(canonicalLine),required=[row.required_pass_literal,row.required_status_literal,'new_blockers=NONE'];const errors=[];for(const marker of required)if(lines.filter(line=>line===marker).length!==1)errors.push(`SOURCE_MARKER:${marker}`);if(lines.some(line=>/^(?:result|conclusion|review_result)=FAIL(?:_|$)/.test(line)))errors.push('SOURCE_FAIL_CONTRADICTION');return errors;}
export function sourceAuthorityErrors(){if(!fs.existsSync(abs(SOURCE_ENTRY_AUTHORITY)))return['SOURCE_AUTHORITY_MISSING'];const parsed=readCsv(SOURCE_ENTRY_AUTHORITY),errors=[...exactColumns(parsed,SOURCE_ENTRY_COLUMNS,'SOURCE_AUTHORITY')],expected=sourceAuthorityRow();if(parsed.rows.length!==1)return[...errors,`SOURCE_AUTHORITY_COUNT:${parsed.rows.length}`];for(const column of SOURCE_ENTRY_COLUMNS)if(String(parsed.rows[0][column]??'')!==String(expected[column]??''))errors.push(`SOURCE_AUTHORITY_FIELD:${column}`);const entry=auditEntry(SOURCE_AUDIT);if(!entry)errors.push('SOURCE_AUDIT_MISSING');else errors.push(...auditLiteralErrors(entry,parsed.rows[0]));return[...new Set(errors)];}
 
const GAP_SPEC={
  'STRONG_FIELD:ROBOT-GAP-CHAIN-001':{occ:'1',required:'具名交易双方+具体机器人产品+认证/定点/合同/订单/小批量阶段+范围',supported:'部分机器人产品已认证并小批量供货,另有部分验证/样机且无批量订单',missing:'具名客户与供应方绑定、主供/独供、订单金额与适用产品范围',outcome:'PARTIAL_SCOPE_SUPPORTED_GAP_REMAINS_OPEN',source:'EXCHANGE_OR_REGULATOR_FILING|CUSTOMER_OR_SUPPLIER_OFFICIAL_NOTICE',next:'补取得具名双方与产品范围的客户/供应商公告、合同或定点证明'},
  'STRONG_FIELD:ROBOT-GAP-CHAIN-002':{occ:'1',required:'机器人BOM原表+采购价/供应份额+订单或收入归属',supported:'NONE',missing:'BOM原表、采购价、供应份额、订单与收入确认',outcome:'NO_ACCEPTED_REFERENCE_GAP_REMAINS_OPEN',source:'OFFICIAL_BOM_OR_CONTRACT|COMPANY_FILING',next:'补取得机器人BOM原表、采购价、供应份额及订单/收入主源'},
  'STRONG_FIELD:ROBOT-GAP-COMPANY-001':{occ:'2',required:'具名发行人+期间+机器人业务收入金额/占比/毛利归属',supported:'Serve Robotics年报仅说明机器人车队服务、软件访问和导航数据为收入来源',missing:'可复算收入金额、业务占比、毛利率与CAND-005发行人身份绑定',outcome:'PARTIAL_SCOPE_SUPPORTED_GAP_REMAINS_OPEN',source:'COMPANY_IR_OR_ANNUAL_REPORT|EXCHANGE_OR_REGULATOR_FILING',next:'补取得具名发行人年报页码级收入金额/占比/毛利并完成CAND-005主体绑定'},
  'STRONG_FIELD:ROBOT-GAP-MARKET-001':{occ:'2',required:'正式报告原表/页码+类别+地区+期间+规模/出货/份额/ASP口径',supported:'IFR韩国工业机器人安装和医疗机器人销量观察;Omdia全球人形机器人出货预测',missing:'统一市场边界、原表/页码、全球规模/份额/ASP及测试机/系统集成收入定义',outcome:'PARTIAL_SCOPE_SUPPORTED_GAP_REMAINS_OPEN',source:'OFFICIAL_INDUSTRY_BODY_OR_REPORT_PUBLISHER',next:'补取得IFR/MIR/GGII/Omdia/弗若斯特沙利文原表页码与完整口径'},
  'STRONG_FIELD:ROBOT-GAP-MODEL-001':{occ:'1',required:'官方模型输出+任务成功率/接管率/部署台数/收费的明确指标',supported:'Xiaomi-Robotics-1官方能力与训练时长;CORDIS项目API能力',missing:'任务成功率、接管率、商业部署台数、收费与可比评测口径',outcome:'PARTIAL_SCOPE_SUPPORTED_GAP_REMAINS_OPEN',source:'OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT|CUSTOMER_DEPLOYMENT_OR_PRICING',next:'补取得官方评测、客户部署或收费协议中的运行指标'},
  'STRONG_FIELD:ROBOT-GAP-PRODUCT-001':{occ:'2',required:'具体产品+ASP/价格/BOM/寿命/良率/产能利用率/供货周期主源',supported:'NONE',missing:'产品级价格/ASP、BOM、寿命、良率、产能利用率与供货周期',outcome:'NO_ACCEPTED_REFERENCE_GAP_REMAINS_OPEN',source:'OFFICIAL_PRODUCT_PAGE|TENDER_OR_CONTRACT|COMPANY_FILING',next:'补取得产品页、招投标、合同、产销数据或公司披露'},
  'STRONG_FIELD:ROBOT-GAP-SUPPLY-001':{occ:'1',required:'采购方/客户+供应方/投标方+产品+合同/中标/定点阶段',supported:'NONE',missing:'具名供需双方、具体产品、合同/中标/正式定点与份额',outcome:'NO_ACCEPTED_REFERENCE_GAP_REMAINS_OPEN',source:'CUSTOMER_NOTICE|PROCUREMENT_CONTRACT|TENDER_AWARD|SUPPLIER_FILING',next:'补取得客户公告、采购合同、招投标或供应商正式定点披露'}
};
 
export function criteriaRows(){return Object.entries(GAP_SPEC).map(([gap,spec],index)=>({criterion_id:`P0GCV-CRIT-${String(index+1).padStart(3,'0')}`,conceptual_gap_key:gap,source_occurrence_count:spec.occ,required_evidence_scope:spec.required,closure_rule:'ONLY_CLOSE_WHEN_REQUIRED_SCOPE_IS_DIRECTLY_AND_COMPLETELY_SUPPORTED_BY_FROZEN_PRIMARY_REFERENCES',supported_scope_current:spec.supported,missing_scope_current:spec.missing,allowed_outcome:spec.outcome,failure_state:'FAIL_CLOSED_GAP_REMAINS_OPEN'}));}
function heldCountByGap(){const proposals=readCsv(prior.PROPOSAL_INPUT).rows,counts=new Map();for(const row of proposals.filter(row=>row.proposal_outcome==='HELD_BY_SUBJECT_IDENTITY_OR_SCOPE'))counts.set(row.conceptual_gap_key,(counts.get(row.conceptual_gap_key)??0)+1);return counts;}
export function decisionRows(){const accepted=readCsv(ACCEPTED_INPUT).rows,criteria=criteriaRows(),held=heldCountByGap(),counts=new Map();for(const row of accepted)counts.set(row.conceptual_gap_key,(counts.get(row.conceptual_gap_key)??0)+1);return criteria.map((row,index)=>({decision_id:`P0GCV-DEC-${String(index+1).padStart(3,'0')}`,conceptual_gap_key:row.conceptual_gap_key,source_occurrence_count:row.source_occurrence_count,accepted_reference_count:String(counts.get(row.conceptual_gap_key)??0),held_reference_count:String(held.get(row.conceptual_gap_key)??0),supported_scope:row.supported_scope_current,missing_scope:row.missing_scope_current,closure_rule:row.closure_rule,verification_outcome:row.allowed_outcome,gap_state_after:'OPEN_RETAINED_GAP',claim_strength_after:'PENDING_VERIFICATION_MAX_NO_UPGRADE',formal_pool_effect:'NO_AUTOMATIC_FORMAL_POOL_CHANGE',evidence_strength_effect:'NO_UPGRADE',business_output_mutation:'NONE',review_state:'PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW'}));}
export function occurrenceRows(){const source=readCsv(OCCURRENCE_INPUT).rows,byGap=new Map(decisionRows().map(row=>[row.conceptual_gap_key,row]));return source.map((row,index)=>{const dec=byGap.get(row.conceptual_gap_key),[sourceAuthorityId,sourceRowId]=row.source_occurrence_key.split(':');return{application_id:`P0GCV-APP-${String(index+1).padStart(3,'0')}`,target_id:row.target_id,source_occurrence_key:row.source_occurrence_key,source_authority_id:sourceAuthorityId,source_row_id:sourceRowId,conceptual_gap_key:row.conceptual_gap_key,accepted_reference_count:dec.accepted_reference_count,verification_outcome:dec.verification_outcome,action:dec.verification_outcome.startsWith('PARTIAL_')?'RETAIN_OPEN_PARTIAL_PRIMARY_REFERENCE_SCOPE_INSUFFICIENT':'RETAIN_OPEN_NO_ACCEPTED_REFERENCE',gap_state_after:'OPEN_RETAINED_GAP',claim_strength_after:'PENDING_VERIFICATION_MAX_NO_UPGRADE',formal_pool_effect:'NO_AUTOMATIC_FORMAL_POOL_CHANGE',evidence_strength_effect:'NO_UPGRADE',business_output_mutation:'NONE'};});}
export function nextEvidenceRows(){return Object.entries(GAP_SPEC).map(([gap,spec],index)=>({plan_id:`P0GCV-NEXT-${String(index+1).padStart(3,'0')}`,conceptual_gap_key:gap,priority:'P0',missing_scope:spec.missing,required_source_class:spec.source,exact_next_action:spec.next,network_required_for_future_work:'YES_SEPARATE_DESIGN_AND_RELEASE_REQUIRED',gap_state_after:'OPEN_RETAINED_GAP',claim_strength_after:'PENDING_VERIFICATION_MAX_NO_UPGRADE',formal_pool_effect:'NO_AUTOMATIC_FORMAL_POOL_CHANGE',evidence_strength_effect:'NO_UPGRADE',current_run_effect:'VERIFICATION_AND_PLANNING_ONLY_NO_GAP_CLOSURE'}));}
 
export function contractRows(){const rows=[
['SOURCE_AUDIT_ENTRY','exact append-stable PASS execution audit entry'],['UNIVERSE','7 conceptual gaps and 10 source occurrences'],['ACCEPTED_REGISTER','6 accepted references; CAND-005 excluded'],['MAP_READ_ONLY','formal evidence map remains exact 46 rows with EMAP-046'],['OUTCOME_ENUM','PARTIAL_SCOPE_SUPPORTED_GAP_REMAINS_OPEN|NO_ACCEPTED_REFERENCE_GAP_REMAINS_OPEN'],['GAP_STATE','OPEN_RETAINED_GAP 7/7'],['CLAIM_CEILING','PENDING_VERIFICATION_MAX_NO_UPGRADE 7/7'],['POOL_EFFECT','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],['EVIDENCE_EFFECT','NO_UPGRADE'],['BUSINESS_OUTPUT','NONE'],['DECISION_DERIVATION','all fields equal frozen criteria plus accepted counts'],['OCCURRENCE_DERIVATION','10/10 exact object bridge to gap decision'],['NEXT_EVIDENCE','7/7 exact missing-scope plan; future network requires separate release'],['CAND005','excluded from accepted register and closure basis'],['EXECUTION_SET','22 unique ordered artifacts'],['BASELINE_FIRST','order17 is first generated artifact'],['VALIDATION_LAST','order22 is final generated artifact'],['MANIFEST','data-only append with seven fields and exact filesystem-ms mtime'],['MANIFEST_HISTORY','legacy header anomaly only as separately enumerated authority'],['TRANSACTION','generation+manifest candidate/write+postwrite one workflow'],['ROLLBACK','manifest before bytes+mtime restored and generated outputs absent'],['FAULT_TESTS','6 production workflow faults safe-state verified'],['PROTECTED','protected49 exact identities'],['NETWORK','FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK'],['RELEASE','exact PASS/literal/batch/run/scope markers'],['REVIEW_STATE','PENDING independent execution/output review'],['NO_CLOSURE','this run may not emit CLOSED or VERIFIED_STRONG_FACT'],['SERIALIZATION','CSV UTF8 no BOM LF all fields quoted; request UTF8 no BOM LF'],['PK','all output primary keys unique'],['ANTI_JOIN','gap/occurrence/criteria/output bidirectional differences zero']
];return rows.map((row,index)=>({contract_id:`P0GCV-CON-${String(index+1).padStart(3,'0')}`,scope:'P0_GAP_CLOSURE_SUFFICIENCY_VERIFICATION',field_or_gate:row[0],required_value_or_rule:row[1],failure_state:'FAIL_CLOSED_OR_ROLLBACK_INCOMPLETE_HELD'}));}
export function schemaRows(){return[
['P0GCV-SCHEMA-001','SOURCE_AUDIT_AUTHORITY',SOURCE_ENTRY_COLUMNS.join('|'),'authority_id','1','CSV_UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED','append-stable audit entry identity','PASS exact'],
['P0GCV-SCHEMA-002','CRITERIA',CRITERIA_COLUMNS.join('|'),'criterion_id','7','CSV_UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED','static gap-specific authority','no closure'],
['P0GCV-SCHEMA-003','DECISION',DECISION_COLUMNS.join('|'),'decision_id','7','CSV_UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED','criteria+accepted register counts','open/no upgrade'],
['P0GCV-SCHEMA-004','OCCURRENCE_APPLICATION',OCCURRENCE_COLUMNS.join('|'),'application_id','10','CSV_UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED','source occurrence+decision exact join','open/no mutation'],
['P0GCV-SCHEMA-005','NEXT_EVIDENCE_PLAN',NEXT_COLUMNS.join('|'),'plan_id','7','CSV_UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED','criteria missing scope','future work only'],
['P0GCV-SCHEMA-006','RUNTIME_BASELINE',BASELINE_COLUMNS.join('|'),'baseline_id','69','CSV_UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED','runtime physical identities','baseline first'],
['P0GCV-SCHEMA-007','EXECUTION_REQUEST','MARKDOWN_LINES','NOT_APPLICABLE','fixed text','UTF8_NO_BOM_LF','deterministic request','pending review'],
['P0GCV-SCHEMA-008','EXECUTION_VALIDATION',VALIDATION_COLUMNS.join('|'),'check_id','23','CSV_UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED','shared production oracle','validation last']
].map(row=>Object.fromEntries(SCHEMA_COLUMNS.map((column,index)=>[column,row[index]])));}
export function executionSetRows(){const paths=[SCRIPT,SOURCE_ENTRY_AUTHORITY,ACCEPTED_INPUT,GAP_INPUT,OCCURRENCE_INPUT,ITEM_AUTHORITY,CASE_MAP,CRITERIA,DECISION_AUTHORITY,OCCURRENCE_AUTHORITY,NEXT_EVIDENCE_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,PROTECTED_INVENTORY,FORMAL_ENTRY_AUTHORITY,EXEC_BASELINE,DECISION_OUTPUT,OCCURRENCE_OUTPUT,NEXT_EVIDENCE_OUTPUT,EXEC_REQUEST,EXEC_VALIDATION],roles=['RUNTIME','SOURCE_AUDIT_AUTHORITY','ACCEPTED_REFERENCE_INPUT','GAP_SUMMARY_INPUT','OCCURRENCE_INPUT','DETAIL_ITEM_AUTHORITY','FORMAL_MAP46_READ_ONLY','CLOSURE_CRITERIA','DECISION_AUTHORITY','OCCURRENCE_AUTHORITY','NEXT_EVIDENCE_AUTHORITY','RUNTIME_CONTRACT','OUTPUT_SCHEMA','EXECUTION_EXACT_SET','PROTECTED49_AUTHORITY','FORMAL_DESIGN_ENTRY_AUTHORITY','RUNTIME_BASELINE_FIRST_GENERATED','GAP_DECISION_OUTPUT','OCCURRENCE_APPLICATION_OUTPUT','NEXT_EVIDENCE_PLAN_OUTPUT','EXECUTION_REVIEW_REQUEST','VALIDATION_LAST'];return paths.map((artifactPath,index)=>({artifact_id:`P0GCV-EXEC-SET-${String(index+1).padStart(3,'0')}`,batch_id:EXEC_BATCH,run_id:EXEC_RUN,generation_order:String(index+1),artifact_path:artifactPath,artifact_role:roles[index],identity_policy:'EXACT_SHA256_BYTES_FILESYSTEM_MTIME_MS'}));}
 
function protectedErrors(ctx={resolve:realResolve,io:fs}){const rows=readCsv(PROTECTED_INVENTORY,ctx).rows,errors=[];if(rows.length!==49)errors.push(`PROTECTED_COUNT:${rows.length}:49`);for(const row of rows){try{const id=identity(row.artifact_path,ctx);if(row.sha256!==id.sha256||row.bytes!==String(id.bytes)||row.lines!==String(id.rows))errors.push(`PROTECTED_IDENTITY:${row.inventory_id}`);}catch{errors.push(`PROTECTED_MISSING:${row.inventory_id}`);}}return errors;}
function itemUniverse(){return readCsv(ITEM_AUTHORITY).rows.filter(row=>row.priority==='P0');}
export function coreErrors({criteria=criteriaRows(),decisions=decisionRows(),occurrences=occurrenceRows(),next=nextEvidenceRows()}={}){const errors=[],accepted=readCsv(ACCEPTED_INPUT).rows,gaps=readCsv(GAP_INPUT).rows,sourceOccurrences=readCsv(OCCURRENCE_INPUT).rows,items=itemUniverse(),map=readCsv(CASE_MAP).rows,expectedCriteria=criteriaRows(),expectedDecisions=decisionRows(),expectedOccurrences=occurrenceRows(),expectedNext=nextEvidenceRows();errors.push(...compareRows(criteria,expectedCriteria,CRITERIA_COLUMNS,'CRITERIA'),...compareRows(decisions,expectedDecisions,DECISION_COLUMNS,'DECISION'),...compareRows(occurrences,expectedOccurrences,OCCURRENCE_COLUMNS,'OCCURRENCE'),...compareRows(next,expectedNext,NEXT_COLUMNS,'NEXT'));if(accepted.length!==6)errors.push(`ACCEPTED_COUNT:${accepted.length}:6`);if(accepted.some(row=>row.candidate_id==='P0DISCR1-CAND-005'))errors.push('CAND005_INCLUDED');if(gaps.length!==7||new Set(gaps.map(row=>row.conceptual_gap_key)).size!==7)errors.push('GAP_UNIVERSE');if(sourceOccurrences.length!==10||items.length!==10)errors.push(`OCCURRENCE_UNIVERSE:${sourceOccurrences.length}:${items.length}`);const itemKeys=new Set(items.map(row=>`${row.source_authority_id}:${row.source_row_id}`));for(const row of sourceOccurrences)if(!itemKeys.has(row.source_occurrence_key))errors.push(`OCCURRENCE_ITEM_FK:${row.source_occurrence_key}`);if(map.length!==46||map[45]?.artifact!==ACCEPTED_INPUT||!String(map[45]?.evidence_entry??'').includes('eligible6'))errors.push('FORMAL_MAP46_EMAP046');for(const row of decisions)if(row.gap_state_after!=='OPEN_RETAINED_GAP'||row.claim_strength_after!=='PENDING_VERIFICATION_MAX_NO_UPGRADE'||row.formal_pool_effect!=='NO_AUTOMATIC_FORMAL_POOL_CHANGE'||row.evidence_strength_effect!=='NO_UPGRADE'||row.business_output_mutation!=='NONE'||!row.verification_outcome.endsWith('GAP_REMAINS_OPEN'))errors.push(`DECISION_BOUNDARY:${row.conceptual_gap_key}`);for(const row of occurrences)if(row.gap_state_after!=='OPEN_RETAINED_GAP'||row.business_output_mutation!=='NONE'||row.evidence_strength_effect!=='NO_UPGRADE')errors.push(`OCCURRENCE_BOUNDARY:${row.application_id}`);for(const row of next)if(row.current_run_effect!=='VERIFICATION_AND_PLANNING_ONLY_NO_GAP_CLOSURE'||row.network_required_for_future_work!=='YES_SEPARATE_DESIGN_AND_RELEASE_REQUIRED')errors.push(`NEXT_BOUNDARY:${row.plan_id}`);return[...new Set(errors)];}
 
export function releaseTextErrors(text){const lines=text.split('\n').map(canonicalLine),required=['result=PASS','execution_release=EXPLICITLY_RELEASED',`released_batch_id=${EXEC_BATCH}`,`released_run_id=${EXEC_RUN}`,'network_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK','verification_ceiling=GAP_SUFFICIENCY_VERIFICATION_ONLY_NO_CLOSURE_NO_UPGRADE','map_effect=READ_ONLY_EMAP046_NO_MUTATION'],errors=[];for(const marker of required)if(lines.filter(line=>line===marker).length!==1)errors.push(`RELEASE_MARKER:${marker}`);if(lines.some(line=>/^(?:result|conclusion|review_result)=FAIL(?:_|$)/.test(line))||lines.some(line=>/^(?:execution_release|.*_release)=(?:NOT_ALLOWED|NOT_RELEASED)(?:_|$)/.test(line)))errors.push('RELEASE_CONTRADICTION');return errors;}
function releaseErrors(required=false){const entry=auditEntry(RELEASE_AUDIT);return entry?releaseTextErrors(entry.text):required?['RELEASE_AUDIT_MISSING']:[];}
function formalEntryErrors(){if(!fs.existsSync(abs(FORMAL_ENTRY_AUTHORITY)))return['FORMAL_ENTRY_AUTHORITY_MISSING'];const parsed=readCsv(FORMAL_ENTRY_AUTHORITY),errors=[...exactColumns(parsed,FORMAL_ENTRY_COLUMNS,'FORMAL_ENTRY')];if(parsed.rows.length!==1)return[...errors,`FORMAL_ENTRY_COUNT:${parsed.rows.length}`];const row=parsed.rows[0],lines=normalize(fs.readFileSync(abs(row.artifact_path))).split('\n'),buffer=Buffer.from(`${lines.slice(Number(row.start_line)-1,Number(row.end_line)).join('\n')}\n`);if(String(lineCount(buffer))!==row.lines||String(buffer.length)!==row.bytes||hash(buffer)!==row.sha256)errors.push('FORMAL_ENTRY_IDENTITY');for(const marker of row.required_markers.split('|'))if(!buffer.toString('utf8').includes(marker))errors.push(`FORMAL_ENTRY_MARKER:${marker}`);return errors;}
function designManifestErrors(){if(!fs.existsSync(abs(DESIGN_BASELINE)))return['DESIGN_BASELINE_MISSING'];const baseRows=readCsv(DESIGN_BASELINE).rows,prefix=baseRows.find(row=>row.identity_type==='MANIFEST_PREFIX_BEFORE_DESIGN');if(!prefix)return['DESIGN_PREFIX_ROW_MISSING'];const manifest=fs.readFileSync(abs(MANIFEST)),parsed=parseBuffer(manifest),runRows=parsed.rows.filter(row=>row.run_id===DESIGN_RUN),errors=[];if(manifest.length<Number(prefix.bytes)||hash(manifest.subarray(0,Number(prefix.bytes)))!==prefix.sha256)errors.push('DESIGN_MANIFEST_PREFIX');if(runRows.length!==15)errors.push(`DESIGN_RUN_ROWS:${runRows.length}:15`);for(const row of runRows){try{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_RUN_IDENTITY:${row.artifact_path}`);}catch{errors.push(`DESIGN_RUN_MISSING:${row.artifact_path}`);}}return errors;}
export function designInputErrors({requireRelease=false,expectNoExecution=true}={}){const files=[SOURCE_ENTRY_AUTHORITY,ACCEPTED_INPUT,GAP_INPUT,OCCURRENCE_INPUT,ITEM_AUTHORITY,CASE_MAP,CRITERIA,DECISION_AUTHORITY,OCCURRENCE_AUTHORITY,NEXT_EVIDENCE_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,PROTECTED_INVENTORY,FORMAL_ENTRY_AUTHORITY,DESIGN_BASELINE],errors=[...sourceAuthorityErrors(),...formalEntryErrors(),...releaseErrors(requireRelease)];for(const file of files)if(!fs.existsSync(abs(file)))errors.push(`INPUT_MISSING:${file}`);if(errors.some(code=>code.startsWith('INPUT_MISSING')))return[...new Set(errors)];const criteria=readCsv(CRITERIA),decisions=readCsv(DECISION_AUTHORITY),occurrences=readCsv(OCCURRENCE_AUTHORITY),next=readCsv(NEXT_EVIDENCE_AUTHORITY),contracts=readCsv(CONTRACT),schemas=readCsv(SCHEMA),set=readCsv(EXEC_SET);errors.push(...exactColumns(criteria,CRITERIA_COLUMNS,'CRITERIA'),...exactColumns(decisions,DECISION_COLUMNS,'DECISION'),...exactColumns(occurrences,OCCURRENCE_COLUMNS,'OCCURRENCE'),...exactColumns(next,NEXT_COLUMNS,'NEXT'),...exactColumns(contracts,CONTRACT_COLUMNS,'CONTRACT'),...compareRows(contracts.rows,contractRows(),CONTRACT_COLUMNS,'CONTRACT'),...exactColumns(schemas,SCHEMA_COLUMNS,'SCHEMA'),...compareRows(schemas.rows,schemaRows(),SCHEMA_COLUMNS,'SCHEMA'),...exactColumns(set,EXEC_SET_COLUMNS,'EXEC_SET'),...compareRows(set.rows,executionSetRows(),EXEC_SET_COLUMNS,'EXEC_SET'),...coreErrors({criteria:criteria.rows,decisions:decisions.rows,occurrences:occurrences.rows,next:next.rows}),...protectedErrors(),...designManifestErrors());if(expectNoExecution){const manifest=parseBuffer(fs.readFileSync(abs(MANIFEST)));if(manifest.rows.some(row=>row.run_id===EXEC_RUN))errors.push('EXECUTION_MANIFEST_ROWS');for(const file of GENERATED)if(fs.existsSync(abs(file)))errors.push(`EXECUTION_FILE_EXISTS:${file}`);}return[...new Set(errors)];}
 
function mockReleaseEntry(){const text=`result=PASS\nexecution_release=EXPLICITLY_RELEASED\nreleased_batch_id=${EXEC_BATCH}\nreleased_run_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nverification_ceiling=GAP_SUFFICIENCY_VERIFICATION_ONLY_NO_CLOSURE_NO_UPGRADE\nmap_effect=READ_ONLY_EMAP046_NO_MUTATION\n`;const buffer=Buffer.from(text);return{start:1,end:7,lines:7,bytes:buffer.length,sha256:hash(buffer),text,prefix_bytes:buffer.length,prefix_sha256:hash(buffer)};}
function protectedRows(ctx){return readCsv(PROTECTED_INVENTORY,ctx).rows.map(row=>{const id=identity(row.artifact_path,ctx);return{path:row.artifact_path,...id};});}
function baselineRows(ctx){const source=auditEntry(SOURCE_AUDIT),release=ctx.releaseEntry,manifest=ctx.io.readFileSync(ctx.resolve(MANIFEST)),manifestId={rows:parseBuffer(manifest).rows.length,bytes:manifest.length,sha256:hash(manifest),mtime:new Date(Math.trunc(ctx.io.statSync(ctx.resolve(MANIFEST)).mtimeMs)).toISOString()},mapId=identity(CASE_MAP,ctx),rows=[{baseline_id:'P0GCV-BASE-001',identity_type:'SOURCE_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_ENTRY_APPEND_STABLE'},{baseline_id:'P0GCV-BASE-002',identity_type:'RELEASE_AUDIT_ENTRY',artifact_path:`${AUDIT_REPORT}#L${release.start}-L${release.end}`,rows:String(release.lines),bytes:String(release.bytes),sha256:release.sha256,mtime:'INFO_APPENDABLE_SHARED_FILE',required_state:'EXACT_RELEASE_MARKERS'},{baseline_id:'P0GCV-BASE-003',identity_type:'MANIFEST_PREFIX_BEFORE_EXECUTION',artifact_path:MANIFEST,rows:String(manifestId.rows),bytes:String(manifestId.bytes),sha256:manifestId.sha256,mtime:manifestId.mtime,required_state:'EXACT_APPEND_ONLY_PREFIX'},{baseline_id:'P0GCV-BASE-004',identity_type:'FORMAL_MAP46_READ_ONLY',artifact_path:CASE_MAP,rows:String(mapId.rows),bytes:String(mapId.bytes),sha256:mapId.sha256,mtime:mapId.mtime,required_state:'NO_MUTATION'}];for(const row of executionSetRows().slice(0,16)){const id=identity(row.artifact_path,ctx);rows.push({baseline_id:`P0GCV-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'FROZEN_EXECUTION_INPUT',artifact_path:row.artifact_path,rows:String(id.rows),bytes:String(id.bytes),sha256:id.sha256,mtime:id.mtime,required_state:'EXACT_NO_DRIFT'});}for(const item of protectedRows(ctx))rows.push({baseline_id:`P0GCV-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 baselineErrors(rows){const errors=[];if(rows.length!==69)return[`BASELINE_COUNT:${rows.length}:69`];const source=auditEntry(SOURCE_AUDIT),release=auditEntry(RELEASE_AUDIT);for(const [row,entry,code] of [[rows[0],source,'SOURCE'],[rows[1],release,'RELEASE']])if(!entry||row.rows!==String(entry.lines)||row.bytes!==String(entry.bytes)||row.sha256!==entry.sha256)errors.push(`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('BASELINE_MANIFEST_PREFIX');for(const row of rows.slice(3)){try{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(`BASELINE_IDENTITY:${row.artifact_path}`);}catch{errors.push(`BASELINE_MISSING:${row.artifact_path}`);}}return errors;}
function requestText(){return`# P0 gap closure sufficiency verification execution review request\n\ncase_id=${CASE_ID}\nsource_audit=${SOURCE_AUDIT}\nrelease_audit=${RELEASE_AUDIT}\nbatch_id=${EXEC_BATCH}\nrun_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nverification_ceiling=GAP_SUFFICIENCY_VERIFICATION_ONLY_NO_CLOSURE_NO_UPGRADE\nformal_map_rows=46\nformal_map_effect=READ_ONLY_EMAP046_NO_MUTATION\naccepted_reference_rows=6\ngap_decision_rows=7\noccurrence_application_rows=10\nnext_evidence_plan_rows=7\ngaps_open=7\nclaim_strength=PENDING_VERIFICATION_MAX_NO_UPGRADE\nformal_pool_effect=NO_AUTOMATIC_FORMAL_POOL_CHANGE\nevidence_strength_effect=NO_UPGRADE\nbusiness_output_mutation=NONE\nrun_status=EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW\n`;}
function validationRows(state,faults){const checks=[['CORE_ERRORS','0',String(coreErrors(state).length)],['DECISIONS','7',String(state.decisions.length)],['OCCURRENCES','10',String(state.occurrences.length)],['NEXT_PLAN','7',String(state.next.length)],['ACCEPTED_INPUT','6',String(readCsv(ACCEPTED_INPUT).rows.length)],['FORMAL_MAP','46',String(readCsv(CASE_MAP).rows.length)],['OPEN_GAPS','7',String(state.decisions.filter(row=>row.gap_state_after==='OPEN_RETAINED_GAP').length)],['CLOSURES','0',String(state.decisions.filter(row=>!row.verification_outcome.endsWith('GAP_REMAINS_OPEN')).length)],['PARTIAL_OUTCOMES','4',String(state.decisions.filter(row=>row.verification_outcome==='PARTIAL_SCOPE_SUPPORTED_GAP_REMAINS_OPEN').length)],['NO_REFERENCE_OUTCOMES','3',String(state.decisions.filter(row=>row.verification_outcome==='NO_ACCEPTED_REFERENCE_GAP_REMAINS_OPEN').length)],['NO_UPGRADE','7',String(state.decisions.filter(row=>row.evidence_strength_effect==='NO_UPGRADE').length)],['POOL_BOUNDARY','7',String(state.decisions.filter(row=>row.formal_pool_effect==='NO_AUTOMATIC_FORMAL_POOL_CHANGE').length)],['BUSINESS_MUTATION','0',String(state.decisions.filter(row=>row.business_output_mutation!=='NONE').length)],['CAND005_ACCEPTED','0',String(readCsv(ACCEPTED_INPUT).rows.filter(row=>row.candidate_id==='P0DISCR1-CAND-005').length)],['FAULT_ROWS','6',String(faults.length)],['FAULT_PASS','6',String(faults.filter(row=>row.result==='PASS').length)],['SAFE_STATE','6',String(faults.filter(row=>row.safe_state_verified==='YES').length)],['EXECUTION_SET','22',String(executionSetRows().length)],['BASELINE','69','69'],['MANIFEST_DELTA','22','22'],['NETWORK_CALLS','0','0'],['PROTECTED_ERRORS','0','0']];const rows=checks.map((item,index)=>({check_id:`P0GCV-EXEC-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:'FROZEN_LOCAL_SUFFICIENCY_ORACLE'}));rows.push({check_id:'P0GCV-EXEC-VAL-023',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identities postchecked externally'});return rows;}
function manifestRows(ctx,paths){return paths.map(logical=>{const id=identity(logical,ctx);return{case_id:CASE_ID,run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:logical,sha256:id.sha256,bytes:String(id.bytes),mtime:id.mtime};});}
function manifestState(buffer,ctx,{rows,prefix}){return validateAppendStableManifest(buffer,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:prefix.length,sha256:hash(prefix)},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:EXEC_RUN,expectedPhysicalDelta:22,filesystemIdentity:{runIds:[EXEC_RUN],get:logical=>{try{return identity(logical,ctx);}catch{return null;}}}});}
function buildPayload(ctx,faults){const state={criteria:criteriaRows(),decisions:decisionRows(),occurrences:occurrenceRows(),next:nextEvidenceRows()},baseline=baselineRows(ctx),validation=validationRows(state,faults);return{state,baseline,validation,contents:new Map([[EXEC_BASELINE,serializeCsv(baseline,BASELINE_COLUMNS)],[DECISION_OUTPUT,serializeCsv(state.decisions,DECISION_COLUMNS)],[OCCURRENCE_OUTPUT,serializeCsv(state.occurrences,OCCURRENCE_COLUMNS)],[NEXT_EVIDENCE_OUTPUT,serializeCsv(state.next,NEXT_COLUMNS)],[EXEC_REQUEST,requestText()],[EXEC_VALIDATION,serializeCsv(validation,VALIDATION_COLUMNS)]])};}
function postwriteErrors(ctx,payload,rows,prefix,{inject=false}={}){const errors=[];for(const [logical,text] of payload.contents){try{if(ctx.io.readFileSync(ctx.resolve(logical),'utf8')!==text)errors.push(`OUTPUT_BYTES:${logical}`);}catch(error){errors.push(`OUTPUT_READ:${logical}:${error.message}`);}}const mapNow=identity(CASE_MAP,ctx),mapBase=payload.baseline[3];if(mapNow.sha256!==mapBase.sha256||String(mapNow.bytes)!==mapBase.bytes)errors.push('FORMAL_MAP_MUTATION');const state=manifestState(ctx.io.readFileSync(ctx.resolve(MANIFEST)),ctx,{rows,prefix});errors.push(...state.errors.map(code=>`MANIFEST:${code}`));ctx.trace.push('POSTWRITE_ORACLE');if(inject)errors.push('INJECTED_POSTWRITE_ORACLE_FAILURE');return errors;}
 
export function runProductionWorkflow(ctx){const manifestPath=ctx.resolve(MANIFEST),manifestBefore=ctx.io.readFileSync(manifestPath),snapshots=[{file:manifestPath,buffer:manifestBefore,stat:ctx.io.statSync(manifestPath)}],removePaths=GENERATED.map(ctx.resolve);return rollback.runFailClosedTransactionR1({snapshots,removePaths,rollbackPrimary:ctx.rollbackPrimary??fs,rollbackChecker:ctx.rollbackChecker??fs,work:()=>{const faults=ctx.faultRows??workflowFaultRows(),payload=buildPayload(ctx,faults);for(const logical of GENERATED){ctx.trace.push(`WRITE:${logical}`);ctx.io.writeFileSync(ctx.resolve(logical),payload.contents.get(logical),'utf8');}if(payload.validation.some(row=>row.status==='FAIL'))throw new Error('VALIDATION_FAIL');const rows=manifestRows(ctx,executionSetRows().map(row=>row.artifact_path)),candidate=Buffer.concat([manifestBefore,Buffer.from(serializeManifestDataRows(rows),'utf8')]),candidateState=manifestState(candidate,ctx,{rows,prefix:manifestBefore});if(ctx.injectCandidateFailure)candidateState.errors.push('INJECTED_CANDIDATE_FAILURE');if(candidateState.errors.length)throw new Error(`MANIFEST_CANDIDATE:${candidateState.errors.join('|')}`);ctx.trace.push('MANIFEST_WRITE_ATTEMPT');ctx.io.writeFileSync(manifestPath,candidate);ctx.trace.push('MANIFEST_WRITE_COMPLETED');const post=postwriteErrors(ctx,payload,rows,manifestBefore,{inject:ctx.injectPostwriteFailure});if(post.length)throw new Error(`POSTWRITE:${post.join('|')}`);return{status:'EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW',gap_decisions:7,occurrences:10,next_evidence:7,gaps_open:7,map_rows:46,manifest_rows:22};}});}
 
function faultCase(stage){const dir=fs.mkdtempSync(path.join(os.tmpdir(),'p0gcv-')),fixed=new Date('2026-07-31T00:00:00.000Z'),mapping=new Map([[MANIFEST,path.join(dir,'manifest.csv')],...GENERATED.map((logical,index)=>[logical,path.join(dir,`${index}-${path.basename(logical)}`)])]),resolve=logical=>mapping.get(logical)??abs(logical),manifestPath=resolve(MANIFEST);fs.writeFileSync(manifestPath,fs.readFileSync(abs(MANIFEST)));fs.utimesSync(manifestPath,fixed,fixed);const before=fs.readFileSync(manifestPath),stat=fs.statSync(manifestPath),trace=[],flags={io:false};let manifestThrow=true;const io=proxyWith({writeFileSync:(file,...args)=>{if(stage==='MANIFEST_WRITE_FAILURE'&&file===manifestPath&&manifestThrow){manifestThrow=false;flags.io=true;throw new Error('INJECTED_MANIFEST_WRITE_IO_THROW');}return fs.writeFileSync(file,...args);}}),primary=proxyWith({writeFileSync:(file,...args)=>{if(stage==='RESTORE_WRITE_FAILURE'&&file===manifestPath){flags.io=true;throw new Error('INJECTED_RESTORE_WRITE_IO_THROW');}return fs.writeFileSync(file,...args);},utimesSync:(file,...args)=>{if(stage==='RESTORE_MTIME_FAILURE'&&file===manifestPath){flags.io=true;throw new Error('INJECTED_RESTORE_MTIME_IO_THROW');}return fs.utimesSync(file,...args);},rmSync:(file,...args)=>{if(stage==='REMOVE_FAILURE'&&GENERATED.map(resolve).includes(file)){flags.io=true;throw new Error('INJECTED_REMOVE_IO_THROW');}return fs.rmSync(file,...args);}}),placeholderFaults=Array.from({length:6},(_,index)=>({test_id:`P0GCV-FAULT-${String(index+1).padStart(3,'0')}`,result:'PASS',safe_state_verified:'YES'})),ctx={resolve,io,rollbackPrimary:primary,rollbackChecker:fs,trace,releaseEntry:mockReleaseEntry(),faultRows:placeholderFaults,injectCandidateFailure:stage==='CANDIDATE_FAILURE',injectPostwriteFailure:['POSTWRITE_FAILURE','RESTORE_WRITE_FAILURE','RESTORE_MTIME_FAILURE','REMOVE_FAILURE'].includes(stage)};let message='UNEXPECTED_SUCCESS';try{runProductionWorkflow(ctx);}catch(error){message=error.message;}const manifestExact=fs.readFileSync(manifestPath).equals(before)&&Math.trunc(fs.statSync(manifestPath).mtimeMs)===Math.trunc(stat.mtimeMs),absent=GENERATED.every(logical=>!fs.existsSync(resolve(logical))),safe=manifestExact&&absent,actual=message.startsWith('ROLLBACK_INCOMPLETE_HELD:')?'ROLLBACK_INCOMPLETE_HELD':message==='UNEXPECTED_SUCCESS'?'UNEXPECTED_SUCCESS':'SAFE_ABORT',expected=['RESTORE_WRITE_FAILURE','RESTORE_MTIME_FAILURE','REMOVE_FAILURE'].includes(stage)?'ROLLBACK_INCOMPLETE_HELD':'SAFE_ABORT',pass=actual===expected&&safe&&(stage==='MANIFEST_WRITE_FAILURE'?flags.io:true)&&(['RESTORE_WRITE_FAILURE','RESTORE_MTIME_FAILURE','REMOVE_FAILURE'].includes(stage)?flags.io:true);fs.rmSync(dir,{recursive:true,force:true});return{test_id:`P0GCV-FAULT-${String(['CANDIDATE_FAILURE','MANIFEST_WRITE_FAILURE','POSTWRITE_FAILURE','RESTORE_WRITE_FAILURE','RESTORE_MTIME_FAILURE','REMOVE_FAILURE'].indexOf(stage)+1).padStart(3,'0')}`,failure_stage:stage,workflow_id:'runProductionWorkflow',actual_io_throw:flags.io?'YES':'NO',manifest_write_attempted:trace.includes('MANIFEST_WRITE_ATTEMPT')?'YES':'NO',postwrite_oracle_reached:trace.includes('POSTWRITE_ORACLE')?'YES':'NO',expected_result:expected,actual_result:actual,error_class:message.split(':')[0],manifest_restored:manifestExact?'YES':'NO',generated_absent:absent?'YES':'NO',safe_state_verified:safe?'YES':'NO',result:pass?'PASS':'FAIL'};}
export const FAULT_COLUMNS=['test_id','failure_stage','workflow_id','actual_io_throw','manifest_write_attempted','postwrite_oracle_reached','expected_result','actual_result','error_class','manifest_restored','generated_absent','safe_state_verified','result'];
export function workflowFaultRows(){return['CANDIDATE_FAILURE','MANIFEST_WRITE_FAILURE','POSTWRITE_FAILURE','RESTORE_WRITE_FAILURE','RESTORE_MTIME_FAILURE','REMOVE_FAILURE'].map(faultCase);}
 
export function negativeRows(){const baseState={criteria:criteriaRows(),decisions:decisionRows(),occurrences:occurrenceRows(),next:nextEvidenceRows()},cases=[];const add=(id,code,mutate)=>{const state=structuredClone(baseState);mutate(state);const errors=coreErrors(state);cases.push({test_id:id,mutation_applied:'YES',oracle:'coreErrors',expected:'REJECT',expected_code:code,actual:errors.length?'REJECT':'ACCEPT',actual_codes:errors.join('|'),result:errors.some(error=>error.startsWith(code))?'PASS':'FAIL'});};add('P0GCV-NEG-001','DECISION_FIELD',s=>s.decisions[0].accepted_reference_count='99');add('P0GCV-NEG-002','DECISION_FIELD',s=>s.decisions[0].verification_outcome='CLOSED');add('P0GCV-NEG-003','DECISION_FIELD',s=>s.decisions[0].missing_scope='');add('P0GCV-NEG-004','OCCURRENCE_FIELD',s=>s.occurrences[0].conceptual_gap_key=s.occurrences[1].conceptual_gap_key);add('P0GCV-NEG-005','OCCURRENCE_COUNT',s=>s.occurrences.pop());add('P0GCV-NEG-006','NEXT_FIELD',s=>s.next[0].current_run_effect='GAP_CLOSED');add('P0GCV-NEG-007','DECISION_BOUNDARY',s=>s.decisions[0].evidence_strength_effect='UPGRADE');add('P0GCV-NEG-008','DECISION_BOUNDARY',s=>s.decisions[0].formal_pool_effect='FORMAL_POOL_CHANGED');add('P0GCV-NEG-009','DECISION_BOUNDARY',s=>s.decisions[0].business_output_mutation='WRITE');add('P0GCV-NEG-010','CRITERIA_FIELD',s=>s.criteria[0].closure_rule='ALWAYS_CLOSE');add('P0GCV-NEG-011','DECISION_FIELD',s=>{const t=s.decisions[0];s.decisions[0]=s.decisions[1];s.decisions[1]=t;});const releases=[['P0GCV-NEG-012','result=FAIL\nexecution_release=EXPLICITLY_RELEASED\n','RELEASE_MARKER'],['P0GCV-NEG-013',`result=PASS\nexecution_release=EXPLICITLY_RELEASED\nreleased_batch_id=WRONG\nreleased_run_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nverification_ceiling=GAP_SUFFICIENCY_VERIFICATION_ONLY_NO_CLOSURE_NO_UPGRADE\nmap_effect=READ_ONLY_EMAP046_NO_MUTATION\n`,'RELEASE_MARKER'],['P0GCV-NEG-014',`result=PASS\nexecution_release=NOT_RELEASED\nreleased_batch_id=${EXEC_BATCH}\nreleased_run_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nverification_ceiling=GAP_SUFFICIENCY_VERIFICATION_ONLY_NO_CLOSURE_NO_UPGRADE\nmap_effect=READ_ONLY_EMAP046_NO_MUTATION\n`,'RELEASE_MARKER']];for(const [id,text,code] of releases){const errors=releaseTextErrors(text);cases.push({test_id:id,mutation_applied:'YES',oracle:'releaseTextErrors',expected:'REJECT',expected_code:code,actual:errors.length?'REJECT':'ACCEPT',actual_codes:errors.join('|'),result:errors.length?'PASS':'FAIL'});}for(const row of workflowFaultRows())cases.push({test_id:`P0GCV-NEG-${String(cases.length+1).padStart(3,'0')}`,mutation_applied:'YES',oracle:'runProductionWorkflow',expected:'PASS',expected_code:'SAFE_ABORT_AND_SAFE_STATE',actual:row.result,actual_codes:`${row.actual_result}|${row.error_class}|SAFE:${row.safe_state_verified}`,result:row.result});return cases;}
 
export function validateExecution(){const errors=[];for(const file of GENERATED)if(!fs.existsSync(abs(file)))errors.push(`MISSING:${file}`);if(errors.length)return errors;const baseline=readCsv(EXEC_BASELINE),decisions=readCsv(DECISION_OUTPUT),occurrences=readCsv(OCCURRENCE_OUTPUT),next=readCsv(NEXT_EVIDENCE_OUTPUT),validation=readCsv(EXEC_VALIDATION),state={criteria:readCsv(CRITERIA).rows,decisions:decisions.rows,occurrences:occurrences.rows,next:next.rows};errors.push(...exactColumns(baseline,BASELINE_COLUMNS,'BASELINE'),...baselineErrors(baseline.rows),...exactColumns(decisions,DECISION_COLUMNS,'DECISION'),...exactColumns(occurrences,OCCURRENCE_COLUMNS,'OCCURRENCE'),...exactColumns(next,NEXT_COLUMNS,'NEXT'),...exactColumns(validation,VALIDATION_COLUMNS,'VALIDATION'),...coreErrors(state),...protectedErrors());if(normalize(fs.readFileSync(abs(EXEC_REQUEST)))!==requestText())errors.push('REQUEST_TEXT');const faults=workflowFaultRows(),expectedValidation=validationRows(state,faults);errors.push(...compareRows(validation.rows,expectedValidation,VALIDATION_COLUMNS,'VALIDATION'));const ctx={resolve:realResolve,io:fs,trace:[]},expected=manifestRows(ctx,executionSetRows().map(row=>row.artifact_path)),prefix=baseline.rows[2],manifest=fs.readFileSync(abs(MANIFEST)),mstate=validateAppendStableManifest(manifest,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:Number(prefix.bytes),sha256:prefix.sha256},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:expected,expectedRunId:EXEC_RUN,expectedPhysicalDelta:22,filesystemIdentity:{runIds:[EXEC_RUN],get:logical=>{try{return identity(logical);}catch{return null;}}}});errors.push(...mstate.errors.map(code=>`MANIFEST:${code}`));return[...new Set(errors)];}
export function execute({token}={}){if(token!==EXEC_TOKEN)throw new Error('EXECUTION_TOKEN_MISMATCH');const pre=designInputErrors({requireRelease:true,expectNoExecution:true});if(pre.length)throw new Error(`PREWRITE:${pre.join('|')}`);return runProductionWorkflow({resolve:realResolve,io:fs,trace:[],releaseEntry:auditEntry(RELEASE_AUDIT)});}
 
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){const mode=process.argv[2]??'--preview',token=process.argv.find(value=>value.startsWith('--token='))?.slice(8);if(mode==='--preview'){const state={criteria:criteriaRows(),decisions:decisionRows(),occurrences:occurrenceRows(),next:nextEvidenceRows()},faults=workflowFaultRows(),errors=coreErrors(state);console.log(JSON.stringify({status:errors.length||faults.some(row=>row.result!=='PASS')?'FAIL':'PREVIEW_PASS',gaps:7,occurrences:10,accepted:6,partial:4,no_reference:3,gaps_open:7,map_rows:46,contracts:contractRows().length,schemas:schemaRows().length,exact_set:executionSetRows().length,faults:faults.length,errors},null,2));if(errors.length||faults.some(row=>row.result!=='PASS'))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 if(mode==='--validate-design-inputs'){const errors=designInputErrors({requireRelease:false,expectNoExecution:true});console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_DESIGN_INPUTS',errors},null,2));if(errors.length)process.exitCode=1;}else if(mode==='--validate-release'){const errors=designInputErrors({requireRelease:true,expectNoExecution:true});console.log(JSON.stringify({status:errors.length?'HELD':'PASS_RELEASE_FROZEN_LOCAL_INPUTS',errors},null,2));if(errors.length)process.exitCode=1;}else if(mode==='--execute')console.log(JSON.stringify(execute({token}),null,2));else if(mode==='--validate-execution'){const errors=validateExecution();console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_APPEND_STABLE_EXECUTION_STATE',errors},null,2));if(errors.length)process.exitCode=1;}else throw new Error(`UNKNOWN_MODE:${mode}`);}