MB-X Bilibili Pipeline
7 days ago edf769cf27fedc5088a2b992fe97a91e200bf81e
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
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {pathToFileURL} from 'node:url';
import * as prior from './detail_strengthening_p0_candidate_semantic_verification_runtime_repair004_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-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-001';
export const DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-001';
export const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-001';
export const EXEC_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-001';
export const EXEC_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-001';
export const SOURCE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-EXEC-OUTPUT-001';
export const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED7-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-REREVIEW-001';
export const EXEC_TOKEN='EXECUTE_DETAIL_STRENGTHENING_P0_QUALIFIED7_EVIDENCE_ACCEPTANCE_VERIFICATION_001';
export const SCRIPT='dev/ana-dev/detail_strengthening_p0_qualified7_evidence_acceptance_verification_runtime_20260730.mjs';
export const QUALIFICATION_INPUT=prior.QUALIFICATION,CANDIDATES=prior.CANDIDATES,PROVENANCE=prior.PROVENANCE,RAW_ARCHIVE=prior.RAW_ARCHIVE,GAP_INPUT=prior.GAP_SUMMARY,APPLICATION_INPUT=prior.APPLICATION,PROTECTED_INVENTORY=prior.PROTECTED_INVENTORY;
export const SOURCE_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_qualified7_source_audit_entry_authority_20260730.csv`;
export const CRITERIA=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_criteria_20260730.csv`;
export const DECISION_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_decision_authority_20260730.csv`;
export const CONTRACT=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_runtime_contract_20260730.csv`;
export const SCHEMA=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_schema_20260730.csv`;
export const FORMAL_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_formal_design_entry_authority_20260730.csv`;
export const EXEC_SET=`${BASE}/manifest/detail_strengthening_p0_qualified7_evidence_acceptance_execution_artifact_set_20260730.csv`;
export const EXEC_BASELINE=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_execution_baseline_20260730.csv`;
export const ACCEPTANCE_LEDGER=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_proposal_ledger_20260730.csv`;
export const GAP_SUMMARY=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_gap_readiness_summary_20260730.csv`;
export const APPLICATION=`${BASE}/evidence/detail_strengthening_p0_qualified7_evidence_acceptance_occurrence_application_20260730.csv`;
export const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_qualified7_evidence_acceptance_execution_20260730.md`;
export const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_qualified7_evidence_acceptance_execution_validation_20260730.csv`;
export const GENERATED=[EXEC_BASELINE,ACCEPTANCE_LEDGER,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
 
export const SOURCE_ENTRY_COLUMNS=prior.SOURCE_ENTRY_COLUMNS;
export const CRITERIA_COLUMNS=['criterion_id','conceptual_gap_key','required_subject_binding','required_claim_elements','allowed_evidence_use','held_rule','reject_rule','excluded_inferences','gap_effect','claim_strength_ceiling','formal_pool_effect','evidence_strength_effect'];
export const DECISION_COLUMNS=['acceptance_id','qualification_id','candidate_id','query_id','conceptual_gap_key','canonical_url','source_class','content_locator','snippet_text_sha256','criterion_id','proposed_evidence_class','claim_subject','claim_predicate','claim_object_or_metric','temporal_scope','geographic_scope','explicit_qualifiers','accepted_claim_text','excluded_inferences','proposal_outcome','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect','integration_effect','review_state'];
export const GAP_SUMMARY_COLUMNS=['summary_id','conceptual_gap_key','qualified_candidate_count','eligible_proposal_count','held_count','rejected_count','acceptance_readiness','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect','integration_effect'];
export const APPLICATION_COLUMNS=['application_id','target_id','source_occurrence_key','conceptual_gap_key','qualified_candidate_count','eligible_proposal_count','held_count','action','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect','output_mutation'];
export const CONTRACT_COLUMNS=['contract_id','scope','field_or_gate','required_value_or_rule','failure_state'];
export const SCHEMA_COLUMNS=['schema_id','artifact_role','column_order','primary_key','row_count_rule','serialization','derivation_rule'];
export const EXEC_SET_COLUMNS=prior.EXEC_SET_COLUMNS,BASELINE_COLUMNS=prior.BASELINE_COLUMNS,VALIDATION_COLUMNS=prior.VALIDATION_COLUMNS,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 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 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`);const 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:'P0ACC-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_allowed_literal:'Qualified7_evidence_acceptance_verification_detailed_design_preparation=ALLOWED'};}
function sourceTextErrors(text,row){const lines=text.split('\n').map(canonicalLine),errors=[];for(const marker of [row.required_pass_literal,row.required_allowed_literal])if(lines.filter(line=>line===marker).length!==1)errors.push(`SOURCE_MARKER_COUNT:${marker}`);if(lines.some(line=>/^(?:result|conclusion|review_result)=FAIL(?:_|$)/.test(line))||lines.some(line=>/^Qualified7_evidence_acceptance_verification_detailed_design_preparation=(?:NOT_ALLOWED|NOT_RELEASED)/.test(line)))errors.push('SOURCE_AUDIT_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')];if(parsed.rows.length!==1)return[...errors,`SOURCE_AUTHORITY_COUNT:${parsed.rows.length}`];const row=parsed.rows[0],entry=auditEntry(row.audit_id);if(!entry)return[...errors,'SOURCE_ENTRY_MISSING'];const expected=sourceAuthorityRow();for(const column of SOURCE_ENTRY_COLUMNS)if(String(row[column]??'')!==String(expected[column]??''))errors.push(`SOURCE_AUTHORITY_FIELD:${column}`);errors.push(...sourceTextErrors(entry.text,row));return[...new Set(errors)];}
 
export function criteriaRows(){const common={allowed_evidence_use:'ACCEPTANCE_PROPOSAL_ONLY_PENDING_INDEPENDENT_REVIEW',gap_effect:'OPEN_RETAINED_GAP',claim_strength_ceiling:'PENDING_VERIFICATION_MAX_NO_UPGRADE',formal_pool_effect:'NO_AUTOMATIC_FORMAL_POOL_CHANGE',evidence_strength_effect:'NO_UPGRADE'};return[
  {criterion_id:'P0ACC-CRIT-001',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-CHAIN-001',required_subject_binding:'filing issuer/product context must be explicit or claim remains document-scoped',required_claim_elements:'certification|supply stage|negative stage qualifiers',held_rule:'hold if named subject cannot be resolved for intended use',reject_rule:'reject inferred customer/order/volume beyond text',excluded_inferences:'exclusive supply|mass production|revenue|named customer unless explicit',...common},
  {criterion_id:'P0ACC-CRIT-002',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-CHAIN-002',required_subject_binding:'exact robot BOM or procurement subject',required_claim_elements:'component|price/share/order/revenue unit|period',held_rule:'hold missing robot-specific subject or unit',reject_rule:'reject generic procurement context',excluded_inferences:'complete BOM|ASP|supplier share|revenue attribution',...common},
  {criterion_id:'P0ACC-CRIT-003',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-COMPANY-001',required_subject_binding:'issuer identity and reporting period explicit',required_claim_elements:'robotics revenue source/share or margin|period|scope',held_rule:'hold if issuer identity or segment scope absent',reject_rule:'reject company-wide inference from segment text',excluded_inferences:'future growth|profitability|order certainty|valuation',...common},
  {criterion_id:'P0ACC-CRIT-004',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-MARKET-001',required_subject_binding:'named publisher and robot category',required_claim_elements:'period|geography|metric|unit|actual versus forecast',held_rule:'hold if category/period/unit ambiguous',reject_rule:'reject forecast as realized shipment',excluded_inferences:'investment conclusion|market share|realized future volume',...common},
  {criterion_id:'P0ACC-CRIT-005',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-MODEL-001',required_subject_binding:'official model/project identity',required_claim_elements:'capability|deployment or training basis|document scope',held_rule:'hold if model identity or capability not explicit',reject_rule:'reject project result as commercial adoption',excluded_inferences:'commercial revenue|general intelligence|mass deployment',...common},
  {criterion_id:'P0ACC-CRIT-006',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-PRODUCT-001',required_subject_binding:'specific robot product',required_claim_elements:'price|ASP|BOM|production|sales quantity with unit and period',held_rule:'hold missing product/unit/period',reject_rule:'reject platform quantity or tender budget as robot product metric',excluded_inferences:'ASP|BOM|sales|capacity without explicit product binding',...common},
  {criterion_id:'P0ACC-CRIT-007',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-SUPPLY-001',required_subject_binding:'customer/procurer and supplier/bidder identities',required_claim_elements:'product|contract/tender/award stage|period',held_rule:'hold one side or product absent',reject_rule:'reject open tender as awarded supply relationship',excluded_inferences:'appointment|order|exclusive supply|revenue without explicit award',...common}
];}
 
const claimMap={
  'P0DISCR1-CAND-001':{proposed_evidence_class:'REGULATORY_FILING_DOCUMENT_SCOPED_CHAIN_STAGE',claim_subject:'该发行审核问询回复所述机器人产品',claim_predicate:'部分已通过客户认证并进入小批量供货,部分仍在客户验证或样机测试且尚未取得批量订单',claim_object_or_metric:'认证/小批量供货/验证/样机/无批量订单的分层状态',temporal_scope:'文件披露时点2026-05-19',geographic_scope:'NOT_SPECIFIED_IN_FROZEN_SNIPPET',explicit_qualifiers:'部分产品;阶段分化;不得合并为全部量产',accepted_claim_text:'该问询回复披露:部分机器人产品已通过客户认证并进入小批量供货,另有部分仍处客户验证或样机测试且尚未取得批量订单。',excluded_inferences:'不得推断全部产品量产、独供、批量订单金额、收入或具体客户',proposal_outcome:'ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW'},
  'P0DISCR1-CAND-005':{proposed_evidence_class:'REGULATORY_FILING_METRIC_HELD_SUBJECT',claim_subject:'冻结摘要未显式标识的上交所披露发行人',claim_predicate:'披露机器人业务收入占比、系统集成占比及机器人业务毛利率',claim_object_or_metric:'58.81%|39.77%|18.77%',temporal_scope:'2024年半年度报告期',geographic_scope:'NOT_APPLICABLE',explicit_qualifiers:'必须先由全文/证券代码权威绑定发行人身份',accepted_claim_text:'HELD_NO_ACCEPTED_CLAIM_UNTIL_ISSUER_IDENTITY_BOUND',excluded_inferences:'不得在主体未绑定时写入任何公司经营事实;不得外推全年或未来利润',proposal_outcome:'HELD_BY_SUBJECT_IDENTITY_OR_SCOPE'},
  'P0DISCR1-CAND-006':{proposed_evidence_class:'ISSUER_ANNUAL_REPORT_SEGMENT_REVENUE_SOURCE',claim_subject:'Serve Robotics',claim_predicate:'其分部收入来源包括机器人车队服务、软件访问和机器人车队导航数据,且多数分部收入来自客户服务',claim_object_or_metric:'segment revenue sources; no amount accepted',temporal_scope:'2025 Form 10-K/2026-03-12 filing',geographic_scope:'issuer reporting scope',explicit_qualifiers:'收入来源描述而非金额、增速或盈利能力',accepted_claim_text:'Serve Robotics 年报称其分部收入来源包括机器人车队服务、软件访问及机器人车队导航数据,且多数分部收入来自客户服务。',excluded_inferences:'不得推断收入金额、增长、利润、订单或客户集中度',proposal_outcome:'ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW'},
  'P0DISCR1-CAND-007':{proposed_evidence_class:'INDUSTRY_BODY_MARKET_OBSERVATION',claim_subject:'International Federation of Robotics World Robotics 2025',claim_predicate:'报告2024年韩国工业机器人安装量和医疗机器人销量观察',claim_object_or_metric:'Korea industrial installations=30,600; medical robot sales≈16,700',temporal_scope:'2024 observations published 2025-09-25',geographic_scope:'Korea for industrial installations; report scope for medical robots',explicit_qualifiers:'工业机器人安装与医疗机器人销售是不同类别/口径',accepted_claim_text:'IFR World Robotics 2025 报告了2024年韩国约30,600台工业机器人安装量,并给出约16,700台医疗机器人销量观察。',excluded_inferences:'不得合并类别、推断全球总量、市场份额或投资结论',proposal_outcome:'ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW'},
  'P0DISCR1-CAND-008':{proposed_evidence_class:'REPORT_PUBLISHER_MARKET_FORECAST',claim_subject:'Omdia Robotics Hardware Market Forecast',claim_predicate:'预测全球人形机器人出货量',claim_object_or_metric:'>10,000 units in 2027; 38,000 units in 2030; implied 83% CAGR 2024-2030',temporal_scope:'forecast published 2024-07-25',geographic_scope:'global',explicit_qualifiers:'预测值,不是已实现出货量',accepted_claim_text:'Omdia 预测全球人形机器人出货量将在2027年超过10,000台、2030年达到38,000台,并给出2024—2030年约83%的复合增速含义。',excluded_inferences:'不得表述为已实现销量、公司收入、订单或投资结论',proposal_outcome:'ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW'},
  'P0DISCR1-CAND-009':{proposed_evidence_class:'OFFICIAL_MODEL_PRODUCT_CAPABILITY',claim_subject:'Xiaomi-Robotics-1',claim_predicate:'被官方描述为开箱即用的机器人基础模型,并以超过100,000小时真实操作轨迹训练',claim_object_or_metric:'foundation model capability and >100,000 training hours',temporal_scope:'page publication 2026-07-16',geographic_scope:'NOT_APPLICABLE',explicit_qualifiers:'官方产品/技术描述;训练小时不等于商业部署规模',accepted_claim_text:'Xiaomi Robotics 将 Xiaomi-Robotics-1 描述为开箱即用的机器人基础模型,并称其训练使用超过100,000小时的真实操作轨迹。',excluded_inferences:'不得推断通用智能、商业收入、量产部署或模型效果排名',proposal_outcome:'ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW'},
  'P0DISCR1-CAND-010':{proposed_evidence_class:'OFFICIAL_PROJECT_TECHNICAL_RESULT',claim_subject:'European Commission CORDIS HYPER project report',claim_predicate:'项目交付用于AI集成并控制工业机器人的API',claim_object_or_metric:'KUKA/ABB/Universal Robots; joint angles/trajectories/gripping force controls',temporal_scope:'project report published 2026-07-01',geographic_scope:'EU project reporting scope',explicit_qualifiers:'项目交付结果,不等于商业化规模部署',accepted_claim_text:'欧盟 CORDIS 项目报告称 HYPER 项目交付了用于 AI 集成并控制 KUKA、ABB、Universal Robots 等工业机器人的 API,可覆盖关节角、轨迹和夹持力。',excluded_inferences:'不得推断商业采购、收入、普遍部署、OEM正式采用或量产',proposal_outcome:'ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW'}
};
 
export function decisionRows(){const qualifications=readCsv(QUALIFICATION_INPUT).rows.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW'),candidates=new Map(readCsv(CANDIDATES).rows.map(row=>[row.candidate_id,row])),criteria=new Map(criteriaRows().map(row=>[row.conceptual_gap_key,row]));return qualifications.map((row,index)=>{const candidate=candidates.get(row.candidate_id),claim=claimMap[row.candidate_id],criterion=criteria.get(row.conceptual_gap_key);if(!candidate||!claim||!criterion)throw new Error(`DECISION_SOURCE_MISSING:${row.candidate_id}`);return{acceptance_id:`P0ACC-DEC-${String(index+1).padStart(3,'0')}`,qualification_id:row.qualification_id,candidate_id:row.candidate_id,query_id:row.query_id,conceptual_gap_key:row.conceptual_gap_key,canonical_url:row.canonical_url,source_class:row.source_class,content_locator:row.content_locator,snippet_text_sha256:row.snippet_text_sha256,criterion_id:criterion.criterion_id,...claim,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',integration_effect:'PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE',review_state:'PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW'};});}
 
export function deriveOutputs(decisions){const sourceGaps=readCsv(GAP_INPUT).rows,sourceApps=readCsv(APPLICATION_INPUT).rows,byGap=new Map();for(const row of decisions){if(!byGap.has(row.conceptual_gap_key))byGap.set(row.conceptual_gap_key,[]);byGap.get(row.conceptual_gap_key).push(row);}const summary=sourceGaps.map((row,index)=>{const group=byGap.get(row.conceptual_gap_key)??[],eligible=group.filter(item=>item.proposal_outcome==='ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW').length,held=group.filter(item=>item.proposal_outcome==='HELD_BY_SUBJECT_IDENTITY_OR_SCOPE').length,rejected=group.filter(item=>item.proposal_outcome==='REJECTED_FOR_ACCEPTANCE_CONTEXT_ONLY').length;return{summary_id:`P0ACC-SUM-${String(index+1).padStart(3,'0')}`,conceptual_gap_key:row.conceptual_gap_key,qualified_candidate_count:String(group.length),eligible_proposal_count:String(eligible),held_count:String(held),rejected_count:String(rejected),acceptance_readiness:eligible?'PROPOSAL_AVAILABLE_PENDING_INDEPENDENT_REVIEW':held?'HELD_PENDING_SCOPE_OR_IDENTITY':'NO_ELIGIBLE_PROPOSAL',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',integration_effect:'NO_FORMAL_EVIDENCE_WRITE'};});const summaryMap=new Map(summary.map(row=>[row.conceptual_gap_key,row]));const applications=sourceApps.map((row,index)=>{const item=summaryMap.get(row.conceptual_gap_key);return{application_id:`P0ACC-APP-${String(index+1).padStart(3,'0')}`,target_id:row.target_id,source_occurrence_key:row.source_occurrence_key,conceptual_gap_key:row.conceptual_gap_key,qualified_candidate_count:item.qualified_candidate_count,eligible_proposal_count:item.eligible_proposal_count,held_count:item.held_count,action:Number(item.eligible_proposal_count)>0?'RETAIN_OPEN_WITH_ACCEPTANCE_PROPOSAL_PENDING_REVIEW':Number(item.held_count)>0?'RETAIN_OPEN_HELD_SCOPE_OR_IDENTITY':'RETAIN_OPEN_NO_ELIGIBLE_PROPOSAL',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',output_mutation:'NONE'};});return{summary,applications};}
 
export function contractRows(){const rows=[
['SOURCE_AUDIT','exact append-stable PASS entry and detailed-design-preparation ALLOWED'],['NETWORK','FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK'],['QUALIFIED_UNIVERSE','exact7 from predecessor qualification; context7 excluded'],['CANDIDATE_PROVENANCE_RAW','exact candidate/provenance/raw identity inherited from predecessor PASS'],['CRITERIA','7 exact gap-specific acceptance criteria'],['DECISION','7 exact all-field acceptance proposals'],['OUTCOMES','ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW|HELD_BY_SUBJECT_IDENTITY_OR_SCOPE|REJECTED_FOR_ACCEPTANCE_CONTEXT_ONLY'],['ELIGIBLE_CEILING','proposal only, not accepted evidence'],['GAP_STATE','OPEN_RETAINED_GAP'],['CLAIM_STRENGTH','PENDING_VERIFICATION_MAX_NO_UPGRADE'],['FORMAL_POOL','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],['EVIDENCE_STRENGTH','NO_UPGRADE'],['INTEGRATION','PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE'],['OUTPUT_MUTATION','NONE'],['BASELINE','first generated artifact and exact release/manifest/input/protected binding'],['ACCEPTANCE_LEDGER','7 exact rows derived from decision authority'],['SUMMARY','7 exact per-gap rows'],['APPLICATION','10 exact per-occurrence rows'],['REQUEST','exact audit/batch/run/boundary provenance'],['VALIDATION','last generated artifact; any FAIL aborts'],['MANIFEST','18 data-only rows; seven-field exact identity and immutable prefix'],['ROLLBACK','restore manifest prefix and remove all six generated artifacts on any failure'],['REVIEW','independent execution and output-quality review required'],['RELEASE','structured PASS plus exact release/batch/run/network/ceiling markers'],['SOURCE_ENTRY_AUTHORITY','exact audit id, normalized entry lines/bytes/hash, append-stable prefix and unique exact literals'],['SUBJECT_SCOPE','held if frozen evidence cannot bind intended claim subject or scope'],['EXCLUDED_INFERENCES','every proposal carries explicit negative inference boundary'],['COUNT_BINDING','criteria7|decisions7|summary7|application10|exact_set18|manifest_delta18']
];return rows.map((item,index)=>({contract_id:`P0ACC-CON-${String(index+1).padStart(3,'0')}`,scope:index<14?'ACCEPTANCE_AUTHORITY':'EXECUTION_RUNTIME',field_or_gate:item[0],required_value_or_rule:item[1],failure_state:'FAIL_CLOSED_NO_OUTPUT_COMMIT'}));}
export function schemaRows(){return[
{schema_id:'P0ACC-SCHEMA-001',artifact_role:'ACCEPTANCE_CRITERIA',column_order:CRITERIA_COLUMNS.join('|'),primary_key:'criterion_id',row_count_rule:'7',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'exact criteriaRows'},
{schema_id:'P0ACC-SCHEMA-002',artifact_role:'ACCEPTANCE_DECISION_AUTHORITY',column_order:DECISION_COLUMNS.join('|'),primary_key:'acceptance_id|candidate_id',row_count_rule:'7',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'exact decisionRows from frozen qualified7'},
{schema_id:'P0ACC-SCHEMA-003',artifact_role:'EXECUTION_BASELINE',column_order:BASELINE_COLUMNS.join('|'),primary_key:'baseline_id',row_count_rule:'64',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'runtime identities before outputs'},
{schema_id:'P0ACC-SCHEMA-004',artifact_role:'ACCEPTANCE_PROPOSAL_LEDGER',column_order:DECISION_COLUMNS.join('|'),primary_key:'acceptance_id|candidate_id',row_count_rule:'7',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'byte-identical row semantics to decision authority'},
{schema_id:'P0ACC-SCHEMA-005',artifact_role:'GAP_READINESS_SUMMARY',column_order:GAP_SUMMARY_COLUMNS.join('|'),primary_key:'summary_id|conceptual_gap_key',row_count_rule:'7',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'deterministic grouping of proposal ledger'},
{schema_id:'P0ACC-SCHEMA-006',artifact_role:'OCCURRENCE_APPLICATION',column_order:APPLICATION_COLUMNS.join('|'),primary_key:'application_id|target_id',row_count_rule:'10',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'deterministic occurrence-to-gap mapping'},
{schema_id:'P0ACC-SCHEMA-007',artifact_role:'EXECUTION_REQUEST',column_order:'markdown_key_value_lines',primary_key:'none',row_count_rule:'1 file',serialization:'UTF8_NO_BOM_LF_TERMINAL_LF',derivation_rule:'exact release and retained-boundary request'},
{schema_id:'P0ACC-SCHEMA-008',artifact_role:'EXECUTION_VALIDATION',column_order:VALIDATION_COLUMNS.join('|'),primary_key:'check_id',row_count_rule:'20',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'19 PASS plus one INFO self-reference exclusion'},
{schema_id:'P0ACC-SCHEMA-009',artifact_role:'ARTIFACT_MANIFEST',column_order:'case_id|run_id|batch_id|artifact_path|sha256|bytes|mtime',primary_key:'run_id|artifact_path',row_count_rule:'18',serialization:'DATA_ROWS_ONLY_NO_HEADER',derivation_rule:'seven-field exact filesystem identity'}
];}
 
export function executionSetRows(){const paths=[SCRIPT,SOURCE_ENTRY_AUTHORITY,QUALIFICATION_INPUT,CANDIDATES,PROVENANCE,RAW_ARCHIVE,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,PROTECTED_INVENTORY,EXEC_BASELINE,ACCEPTANCE_LEDGER,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION],roles=['RUNTIME','SOURCE_AUDIT_ENTRY_AUTHORITY','QUALIFIED7_INPUT','CANDIDATE_INPUT','PROVENANCE_INPUT','RAW_ARCHIVE_INPUT','ACCEPTANCE_CRITERIA','DECISION_AUTHORITY','RUNTIME_CONTRACT','OUTPUT_SCHEMA','EXECUTION_EXACT_SET','PROTECTED49_AUTHORITY','EXECUTION_BASELINE_FIRST_GENERATED','ACCEPTANCE_PROPOSAL_LEDGER','GAP_READINESS_SUMMARY','OCCURRENCE_APPLICATION','EXECUTION_REQUEST','VALIDATION_LAST'];return paths.map((artifactPath,index)=>({artifact_id:`P0ACC-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 manifestState({expectedRows=[],expectedRunId='',frozenPrefix=null,expectedPhysicalDelta=null}={}){return validateAppendStableManifest(fs.readFileSync(abs(MANIFEST)),{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix,originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:expectedRows,expectedRunId,expectedPhysicalDelta,filesystemIdentity:{runIds:expectedRunId?[expectedRunId]:[],get:file=>fs.existsSync(abs(file))?identity(file):null}});}
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 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;}
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','evidence_acceptance_ceiling=PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE'],errors=[];for(const marker of required)if(lines.filter(line=>line===marker).length!==1)errors.push(`RELEASE_MARKER_COUNT:${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']:[];}
 
export function coreErrors({criteria=criteriaRows(),decisions=decisionRows(),summary=null,applications=null}={}){const errors=[],qualified=readCsv(QUALIFICATION_INPUT).rows.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW'),expectedDecisions=decisionRows(),derived=deriveOutputs(decisions);if(prior.validateExecution().length)errors.push(...prior.validateExecution().map(code=>`PREDECESSOR:${code}`));if(qualified.length!==7)errors.push(`QUALIFIED_COUNT:${qualified.length}:7`);errors.push(...compareRows(criteria,criteriaRows(),CRITERIA_COLUMNS,'CRITERIA'),...compareRows(decisions,expectedDecisions,DECISION_COLUMNS,'DECISION'));const ids=new Set(decisions.map(row=>row.candidate_id));if(ids.size!==7)errors.push(`DECISION_UNIQUE:${ids.size}:7`);for(const row of decisions){const input=qualified.find(item=>item.candidate_id===row.candidate_id);if(!input)errors.push(`QUALIFIED_MISSING:${row.candidate_id}`);if(row.gap_state_after!=='OPEN_RETAINED_GAP')errors.push(`GAP_CLOSED:${row.candidate_id}`);if(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.integration_effect!=='PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE')errors.push(`BOUNDARY:${row.candidate_id}`);if(!row.accepted_claim_text||!row.excluded_inferences)errors.push(`CLAIM_OR_EXCLUSION_EMPTY:${row.candidate_id}`);}if(decisions.filter(row=>row.proposal_outcome==='ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW').length!==6)errors.push('ELIGIBLE_COUNT');if(decisions.filter(row=>row.proposal_outcome==='HELD_BY_SUBJECT_IDENTITY_OR_SCOPE').length!==1)errors.push('HELD_COUNT');if(summary)errors.push(...compareRows(summary,derived.summary,GAP_SUMMARY_COLUMNS,'SUMMARY'));if(applications)errors.push(...compareRows(applications,derived.applications,APPLICATION_COLUMNS,'APPLICATION'));return[...new Set(errors)];}
 
export function designInputErrors({requireRelease=false,expectNoExecution=true}={}){const errors=[...sourceAuthorityErrors(),...formalEntryErrors(),...releaseErrors({required:requireRelease})];for(const file of [QUALIFICATION_INPUT,CANDIDATES,PROVENANCE,RAW_ARCHIVE,GAP_INPUT,APPLICATION_INPUT,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,PROTECTED_INVENTORY])if(!fs.existsSync(abs(file)))errors.push(`INPUT_MISSING:${file}`);if(errors.some(error=>error.startsWith('INPUT_MISSING')))return[...new Set(errors)];const criteria=readCsv(CRITERIA),decisions=readCsv(DECISION_AUTHORITY),contracts=readCsv(CONTRACT),schemas=readCsv(SCHEMA),execSet=readCsv(EXEC_SET);errors.push(...exactColumns(criteria,CRITERIA_COLUMNS,'CRITERIA'),...exactColumns(decisions,DECISION_COLUMNS,'DECISION'),...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(execSet,EXEC_SET_COLUMNS,'EXEC_SET'),...compareRows(execSet.rows,executionSetRows(),EXEC_SET_COLUMNS,'EXEC_SET'),...coreErrors({criteria:criteria.rows,decisions:decisions.rows}));if(expectNoExecution){if(GENERATED.some(file=>fs.existsSync(abs(file))))errors.push('EXECUTION_FILES_EXIST');if(manifestState().logicalRows.some(row=>row.run_id===EXEC_RUN))errors.push('EXECUTION_MANIFEST_ROWS');}return[...new Set(errors)];}
 
function baselineRows(){const source=auditEntry(SOURCE_AUDIT),release=auditEntry(RELEASE_AUDIT),manifest=fs.readFileSync(abs(MANIFEST));if(!source||!release)throw new Error('AUDIT_ENTRY_MISSING');const rows=[{baseline_id:'P0ACC-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_AUTHORITY_MATCH'},{baseline_id:'P0ACC-BASE-002',identity_type:'DESIGN_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_PASS_RELEASE_BATCH_RUN_NETWORK_AND_CEILING'},{baseline_id:'P0ACC-BASE-003',identity_type:'RAW_MANIFEST_BEFORE_EXECUTION',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'}];for(const file of executionSetRows().slice(0,12).map(row=>row.artifact_path)){const id=identity(file);rows.push({baseline_id:`P0ACC-BASE-${String(rows.length+1).padStart(3,'0')}`,identity_type:'FROZEN_EXECUTION_INPUT',artifact_path:file,rows:String(id.rows),bytes:String(id.bytes),sha256:id.sha256,mtime:id.mtime,required_state:'EXACT_NO_DRIFT'});}for(const item of protectedRows())rows.push({baseline_id:`P0ACC-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!==64)return[`BASELINE_COUNT:${rows.length}:64`];for(const [row,entry,code] of [[rows[0],auditEntry(SOURCE_AUDIT),'SOURCE'],[rows[1],auditEntry(RELEASE_AUDIT),'RELEASE']])if(!entry||row.rows!==String(entry.lines)||row.bytes!==String(entry.bytes)||row.sha256!==entry.sha256)errors.push(`BASELINE_${code}_AUDIT`);errors.push(...sourceAuthorityErrors());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)){if(!fs.existsSync(abs(row.artifact_path))){errors.push(`BASELINE_PATH_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(`BASELINE_IDENTITY:${row.artifact_path}`);}return errors;}
function requestText(){return`# Qualified7 evidence acceptance 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\nevidence_acceptance_ceiling=PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE\nproposal_rows=7\neligible=6\nheld=1\ngap_summary_rows=7\noccurrence_application_rows=10\ngap_effect=OPEN_RETAINED_GAP\nclaim_strength_ceiling=PENDING_VERIFICATION_MAX_NO_UPGRADE\nformal_pool_effect=NO_AUTOMATIC_FORMAL_POOL_CHANGE\nevidence_strength_effect=NO_UPGRADE\noutput_mutation=NONE\nrun_status=EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW\n`;}
function validationRows(state){const errors=coreErrors(state),checks=[['CORE_ERRORS','0',String(errors.length)],['SOURCE_AUTHORITY_ERRORS','0',String(sourceAuthorityErrors().length)],['QUALIFIED_INPUT','7',String(readCsv(QUALIFICATION_INPUT).rows.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW').length)],['CRITERIA','7',String(state.criteria.length)],['PROPOSALS','7',String(state.decisions.length)],['ELIGIBLE','6',String(state.decisions.filter(row=>row.proposal_outcome==='ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW').length)],['HELD','1',String(state.decisions.filter(row=>row.proposal_outcome==='HELD_BY_SUBJECT_IDENTITY_OR_SCOPE').length)],['SUMMARY','7',String(state.summary.length)],['APPLICATION','10',String(state.applications.length)],['OPEN_GAPS','7',String(state.summary.filter(row=>row.gap_state_after==='OPEN_RETAINED_GAP').length)],['OUTPUT_MUTATION','0',String(state.applications.filter(row=>row.output_mutation!=='NONE').length)],['CLAIM_CEILING','7',String(state.decisions.filter(row=>row.claim_strength_after==='PENDING_VERIFICATION_MAX_NO_UPGRADE').length)],['POOL_BOUNDARY','7',String(state.decisions.filter(row=>row.formal_pool_effect==='NO_AUTOMATIC_FORMAL_POOL_CHANGE').length)],['EVIDENCE_BOUNDARY','7',String(state.decisions.filter(row=>row.evidence_strength_effect==='NO_UPGRADE').length)],['INTEGRATION_WRITE','0',String(state.decisions.filter(row=>row.integration_effect!=='PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE').length)],['EXCLUDED_INFERENCE','7',String(state.decisions.filter(row=>row.excluded_inferences).length)],['EXACT_SET','18',String(executionSetRows().length)],['BASELINE','64','64'],['MANIFEST_DELTA','18','18']];const rows=checks.map((item,index)=>({check_id:`P0ACC-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:'QUALIFIED7_ACCEPTANCE_PROPOSAL_FAIL_CLOSED_ORACLE'}));rows.push({check_id:'P0ACC-EXEC-VAL-020',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identities postchecked'});return rows;}
function manifestRowsFor(paths){return paths.map(file=>{const id=identity(file);return{case_id:CASE_ID,run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:file,sha256:id.sha256,bytes:String(id.bytes),mtime:id.mtime};});}
 
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('|')}`);const manifestBefore=fs.readFileSync(abs(MANIFEST));try{write(EXEC_BASELINE,serializeCsv(baselineRows(),BASELINE_COLUMNS));const decisions=readCsv(DECISION_AUTHORITY).rows,derived=deriveOutputs(decisions),state={criteria:readCsv(CRITERIA).rows,decisions,summary:derived.summary,applications:derived.applications};write(ACCEPTANCE_LEDGER,serializeCsv(decisions,DECISION_COLUMNS));write(GAP_SUMMARY,serializeCsv(derived.summary,GAP_SUMMARY_COLUMNS));write(APPLICATION,serializeCsv(derived.applications,APPLICATION_COLUMNS));write(EXEC_REQUEST,requestText());const validation=validationRows(state);write(EXEC_VALIDATION,serializeCsv(validation,VALIDATION_COLUMNS));if(validation.some(row=>row.status==='FAIL'))throw new Error('VALIDATION_FAIL');const rows=manifestRowsFor(executionSetRows().map(row=>row.artifact_path)),candidate=Buffer.concat([manifestBefore,Buffer.from(serializeManifestDataRows(rows),'utf8')]),manifestCandidate=validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:manifestBefore.length,sha256:hash(manifestBefore)},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:EXEC_RUN,expectedPhysicalDelta:18});if(manifestCandidate.errors.length)throw new Error(`MANIFEST_CANDIDATE:${manifestCandidate.errors.join('|')}`);fs.writeFileSync(abs(MANIFEST),candidate);const post=validateExecution();if(post.length)throw new Error(`POSTWRITE:${post.join('|')}`);return{status:'EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW',proposal_rows:7,eligible:6,held:1,gap_summary_rows:7,application_rows:10,manifest_rows:18};}catch(error){const cleanup=[];try{fs.writeFileSync(abs(MANIFEST),manifestBefore);}catch(failure){cleanup.push(`MANIFEST:${failure.message}`);}for(const file of GENERATED)if(fs.existsSync(abs(file)))try{fs.rmSync(abs(file));}catch(failure){cleanup.push(`REMOVE:${file}:${failure.message}`);}if(cleanup.length)throw new Error(`ROLLBACK_INCOMPLETE_HELD:${cleanup.join('|')}:${error.message}`);throw error;}}
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(ACCEPTANCE_LEDGER),summary=readCsv(GAP_SUMMARY),applications=readCsv(APPLICATION),validation=readCsv(EXEC_VALIDATION),state={criteria:readCsv(CRITERIA).rows,decisions:decisions.rows,summary:summary.rows,applications:applications.rows};errors.push(...sourceAuthorityErrors(),...exactColumns(baseline,BASELINE_COLUMNS,'BASELINE'),...baselineErrors(baseline.rows),...exactColumns(decisions,DECISION_COLUMNS,'PROPOSALS'),...exactColumns(summary,GAP_SUMMARY_COLUMNS,'SUMMARY'),...exactColumns(applications,APPLICATION_COLUMNS,'APPLICATION'),...exactColumns(validation,VALIDATION_COLUMNS,'VALIDATION'),...coreErrors(state));if(normalize(fs.readFileSync(abs(EXEC_REQUEST)))!==requestText())errors.push('REQUEST_TEXT');if(validation.rows.length!==20||validation.rows.some(row=>row.status==='FAIL'))errors.push('VALIDATION_STATUS');const expected=manifestRowsFor(executionSetRows().map(row=>row.artifact_path)),prefix=baseline.rows[2],manifest=manifestState({expectedRows:expected,expectedRunId:EXEC_RUN,frozenPrefix:{bytes:Number(prefix.bytes),sha256:prefix.sha256},expectedPhysicalDelta:18});errors.push(...manifest.errors.map(code=>`MANIFEST:${code}`));return[...new Set(errors)];}
 
export function negativeRows(){const clean={criteria:criteriaRows(),decisions:decisionRows()},cases=[
['CLEAN',()=>clean,'ACCEPT','NONE'],
['DECISION_OUTCOME',()=>{const s=structuredClone(clean);s.decisions[0].proposal_outcome='ACCEPTED_EVIDENCE';return s;},'REJECT','DECISION_FIELD'],
['DECISION_CLAIM',()=>{const s=structuredClone(clean);s.decisions[0].accepted_claim_text='tamper';return s;},'REJECT','DECISION_FIELD'],
['DECISION_SUBJECT',()=>{const s=structuredClone(clean);s.decisions[0].claim_subject='tamper';return s;},'REJECT','DECISION_FIELD'],
['DECISION_REMOVE',()=>{const s=structuredClone(clean);s.decisions.pop();return s;},'REJECT','DECISION_COUNT'],
['DECISION_GAP_CLOSE',()=>{const s=structuredClone(clean);s.decisions[0].gap_state_after='CLOSED';return s;},'REJECT','DECISION_FIELD'],
['DECISION_STRENGTH',()=>{const s=structuredClone(clean);s.decisions[0].claim_strength_after='CONFIRMED';return s;},'REJECT','DECISION_FIELD'],
['DECISION_POOL',()=>{const s=structuredClone(clean);s.decisions[0].formal_pool_effect='FORMAL_POOL_CHANGE';return s;},'REJECT','DECISION_FIELD'],
['DECISION_EVIDENCE',()=>{const s=structuredClone(clean);s.decisions[0].evidence_strength_effect='UPGRADE';return s;},'REJECT','DECISION_FIELD'],
['DECISION_INTEGRATION',()=>{const s=structuredClone(clean);s.decisions[0].integration_effect='FORMAL_WRITE';return s;},'REJECT','DECISION_FIELD'],
['DECISION_EXCLUSION',()=>{const s=structuredClone(clean);s.decisions[0].excluded_inferences='';return s;},'REJECT','DECISION_FIELD'],
['CRITERIA_RULE',()=>{const s=structuredClone(clean);s.criteria[0].required_claim_elements='tamper';return s;},'REJECT','CRITERIA_FIELD'],
['CANDIDATE_SWAP',()=>{const s=structuredClone(clean);[s.decisions[0].candidate_id,s.decisions[1].candidate_id]=[s.decisions[1].candidate_id,s.decisions[0].candidate_id];return s;},'REJECT','DECISION_FIELD']
];const rows=cases.map((item,index)=>{const errors=coreErrors(item[1]()),actual=errors.length?'REJECT':'ACCEPT';return{test_id:`P0ACC-NEG-${String(index+1).padStart(3,'0')}-${item[0]}`,mutation_applied:index?'YES':'NO_CLEAN_CONTROL',oracle:'coreErrors',expected:item[2],expected_code:item[3],actual,actual_codes:errors.join('|')||'NONE',result:actual===item[2]&&(item[3]==='NONE'||errors.some(error=>error.startsWith(item[3])))?'PASS':'FAIL'};});const good=['result=PASS','execution_release=EXPLICITLY_RELEASED',`released_batch_id=${EXEC_BATCH}`,`released_run_id=${EXEC_RUN}`,'network_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK','evidence_acceptance_ceiling=PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE'].join('\n'),releaseCases=[['RELEASE_CLEAN',good,'ACCEPT','NONE'],['RELEASE_FAIL',`${good}\nresult=FAIL`,'REJECT','RELEASE_CONTRADICTION'],['RELEASE_DUPLICATE',`${good}\nresult=PASS`,'REJECT','RELEASE_MARKER_COUNT']];for(const item of releaseCases){const errors=releaseTextErrors(item[1]),actual=errors.length?'REJECT':'ACCEPT';rows.push({test_id:`P0ACC-NEG-${String(rows.length+1).padStart(3,'0')}-${item[0]}`,mutation_applied:item[0]==='RELEASE_CLEAN'?'NO_CLEAN_CONTROL':'YES',oracle:'releaseTextErrors',expected:item[2],expected_code:item[3],actual,actual_codes:errors.join('|')||'NONE',result:actual===item[2]&&(item[3]==='NONE'||errors.some(error=>error.startsWith(item[3])))?'PASS':'FAIL'});}return rows;}
 
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 decisions=decisionRows(),derived=deriveOutputs(decisions),errors=coreErrors({criteria:criteriaRows(),decisions,summary:derived.summary,applications:derived.applications});console.log(JSON.stringify({status:errors.length?'FAIL':'PREVIEW_PASS',qualified:7,eligible:6,held:1,summary:7,applications:10,contracts:contractRows().length,schemas:schemaRows().length,exact_set:executionSetRows().length,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 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}`);}