Cai
2026-08-14 8ca003d034ab4142e718b4737ebbeef85052af40
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {pathToFileURL} from 'node:url';
import * as sem from './detail_strengthening_p0_open_gap_candidate_semantic_verification_runtime_repair002_20260731.mjs';
import {
  parseAuthorityCsv,
  serializeCsv,
  serializeManifestDataRows,
  validateAppendStableManifest,
} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
export const ROOT=process.cwd();
export const CASE_ID='ANA-ROBOT-INDUSTRY-001';
export const BASE='ana-data/cases/机器人案例/ANA-ROBOT-INDUSTRY-001';
export const AUDIT_REPORT='ana-doc/机器人案例/案例审计报告.md';
export const DESIGN_DOC='ana-doc/机器人案例/案例分析设计.md';
export const MANIFEST=`${BASE}/manifest/artifact_manifest.csv`;
export const ANOMALY_AUTHORITY=sem.ANOMALY_AUTHORITY;
export const ORIGINAL_TRIAGE_RUN=sem.ORIGINAL_TRIAGE_RUN;
export const PROTECTED_INVENTORY=sem.PROTECTED_INVENTORY;
export const AUTHORIZED_CUTOVER_RUN='RUN-ANA-ROBOT-COVERAGE-FIRST-STAGE3-CANONICAL-CUTOVER-001';
export const AUTHORIZED_CUTOVER_PATH=`${BASE}/outputs/核心文档/机器人报告索引.md`;
 
export const DESIGN_ID='DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED4-EVIDENCE-ACCEPTANCE-VERIFICATION-001';
export const DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED4-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-001';
export const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED4-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-001';
export const EXEC_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED4-EVIDENCE-ACCEPTANCE-VERIFICATION-001';
export const EXEC_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED4-EVIDENCE-ACCEPTANCE-VERIFICATION-001';
export const SOURCE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-OPEN-GAP-CANDIDATE-SEMANTIC-VERIFICATION-EXEC-OUTPUT-001';
export const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-QUALIFIED4-EVIDENCE-ACCEPTANCE-VERIFICATION-DESIGN-REREVIEW-001';
export const EXEC_TOKEN='EXECUTE_DETAIL_STRENGTHENING_P0_QUALIFIED4_EVIDENCE_ACCEPTANCE_VERIFICATION_001';
export const SCRIPT='dev/ana-dev/detail_strengthening_p0_qualified4_evidence_acceptance_verification_runtime_20260801.mjs';
 
export const QUALIFICATION_INPUT=sem.QUALIFICATION;
export const CANDIDATES=sem.CANDIDATES;
export const PROVENANCE=sem.PROVENANCE;
export const RAW_ARCHIVE=sem.RAW_ARCHIVE;
export const GAP_INPUT=sem.GAP_SUMMARY;
export const APPLICATION_INPUT=sem.APPLICATION;
export const SOURCE_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_source_audit_entry_authority_20260801.csv`;
export const FORMAL_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_formal_design_entry_authority_20260801.csv`;
export const CRITERIA=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_criteria_20260801.csv`;
export const DECISION_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_decision_authority_20260801.csv`;
export const CONTRACT=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_contract_20260801.csv`;
export const SCHEMA=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_schema_20260801.csv`;
export const EXEC_SET=`${BASE}/manifest/detail_strengthening_p0_qualified4_evidence_acceptance_execution_artifact_set_20260801.csv`;
export const FAULT_RESULTS=sem.FAULT_RESULTS;
export const EXEC_BASELINE=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_execution_baseline_20260801.csv`;
export const ACCEPTANCE_LEDGER=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_proposal_ledger_20260801.csv`;
export const GAP_SUMMARY=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_gap_readiness_summary_20260801.csv`;
export const APPLICATION=`${BASE}/evidence/detail_strengthening_p0_qualified4_evidence_acceptance_occurrence_application_20260801.csv`;
export const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_qualified4_evidence_acceptance_execution_20260801.md`;
export const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_qualified4_evidence_acceptance_execution_validation_20260801.csv`;
export const GENERATED=[EXEC_BASELINE,ACCEPTANCE_LEDGER,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
 
export const ENTRY_COLUMNS=['authority_id','audit_or_design_id','artifact_path','start_line','end_line','normalized_lines','normalized_bytes','normalized_sha256','required_marker_1','required_marker_2','required_marker_3'];
export const CRITERIA_COLUMNS=['criterion_id','candidate_id','conceptual_gap_key','required_subject_binding','required_claim_elements','allowed_evidence_use','held_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 SUMMARY_COLUMNS=['summary_id','conceptual_gap_key','qualified_input_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_input_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=['artifact_id','batch_id','run_id','generation_order','artifact_path','artifact_role','identity_policy'];
export const BASELINE_COLUMNS=['baseline_id','artifact_role','artifact_path','sha256','bytes','mtime','required_state'];
export const VALIDATION_COLUMNS=['check_id','check_description','expected','actual','status','evidence'];
 
const abs=file=>path.join(ROOT,...file.split('/'));
const normalize=value=>Buffer.isBuffer(value)?value.toString('utf8').replace(/^\uFEFF/,'').replace(/\r\n/g,'\n').replace(/\r/g,'\n'):String(value).replace(/^\uFEFF/,'').replace(/\r\n/g,'\n').replace(/\r/g,'\n');
const hash=value=>crypto.createHash('sha256').update(value).digest('hex');
const readCsv=file=>{const parsed=parseAuthorityCsv(normalize(fs.readFileSync(abs(file))));if(parsed.errors.length)throw new Error(`${file}:${parsed.errors.join('|')}`);return parsed;};
const fileIdentity=file=>{const buffer=fs.readFileSync(abs(file)),stat=fs.statSync(abs(file));return{sha256:hash(buffer),bytes:String(buffer.length),mtime:new Date(Math.trunc(stat.mtimeMs)).toISOString(),lines:String(normalize(buffer).split('\n').at(-1)===''?normalize(buffer).split('\n').length-1:normalize(buffer).split('\n').length)};};
const write=(file,bytes)=>{fs.mkdirSync(path.dirname(abs(file)),{recursive:true});fs.writeFileSync(abs(file),bytes);};
const exactColumns=(parsed,columns,label)=>parsed.header.join('|')===columns.join('|')?[]:[`${label}_COLUMNS`];
const compareRows=(actual,expected,columns,label)=>{const errors=[];if(actual.length!==expected.length)errors.push(`${label}_COUNT:${actual.length}:${expected.length}`);for(let i=0;i<Math.max(actual.length,expected.length);i++)for(const column of columns)if(String(actual[i]?.[column]??'')!==String(expected[i]?.[column]??''))errors.push(`${label}_FIELD:${i+1}:${column}`);return errors;};
 
export function entryById(file,id){
  const lines=normalize(fs.readFileSync(abs(file))).split('\n');
  const hits=[];
  for(let i=0;i<lines.length;i++)if(/^#{2,6}\s/.test(lines[i])&&lines[i].includes(id))hits.push(i);
  if(hits.length!==1)return null;
  const start=hits[0],level=(lines[start].match(/^#+/)?.[0].length??3),end=lines.findIndex((line,index)=>index>start&&new RegExp(`^#{2,${level}}\\s`).test(line));
  const stop=end===-1?lines.length-1:end;
  const selected=lines.slice(start,stop);
  while(selected.at(-1)==='')selected.pop();
  const text=`${selected.join('\n')}\n`,buffer=Buffer.from(text,'utf8');
  return{startLine:start+1,endLine:start+selected.length,lines:selected.length,bytes:buffer.length,sha256:hash(buffer),text};
}
 
function exactLineErrors(text,required){
  const lines=text.split('\n').map(line=>line.trim().replace(/^[\-*]\s*/,'').replace(/`/g,''));
  const errors=[];
  for(const [key,value] of Object.entries(required)){
    const matches=lines.filter(line=>line.startsWith(`${key}=`));
    if(matches.length!==1)errors.push(`KEY_COUNT:${key}:${matches.length}`);
    else if(matches[0]!==`${key}=${value}`)errors.push(`KEY_VALUE:${key}`);
  }
  return errors;
}
 
export function sourceAuditErrors(){
  const entry=entryById(AUDIT_REPORT,SOURCE_AUDIT);
  if(!entry)return['SOURCE_AUDIT_MISSING_OR_DUPLICATE'];
  return exactLineErrors(entry.text,{result:'PASS',next_allowed_action:'PREPARE_QUALIFIED4_EVIDENCE_ACCEPTANCE_VERIFICATION_DETAILED_DESIGN_ONLY',evidence_acceptance_release:'NOT_RELEASED',gap_closure_release:'NOT_RELEASED'}).map(code=>`SOURCE_AUDIT_${code}`);
}
 
export function releaseTextErrors(text){
  const errors=exactLineErrors(text,{reviewed_design_id:DESIGN_ID,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'});
  const lines=text.split('\n').map(line=>line.trim().replace(/^[\-*]\s*/,'').replace(/`/g,''));
  if(lines.some(line=>/^(?:result|conclusion)=FAIL(?:_|$)/.test(line)||line==='execution_release=NOT_ALLOWED'||line==='execution_release=NOT_RELEASED'))errors.push('RELEASE_CONTRADICTION');
  return errors;
}
 
export function releaseErrors({required=false}={}){const entry=entryById(AUDIT_REPORT,RELEASE_AUDIT);return entry?releaseTextErrors(entry.text):required?['RELEASE_AUDIT_MISSING']:[];}
 
export function criteriaRows(){return[
  {criterion_id:'P0Q4ACC-CRIT-001',candidate_id:'P0ACQR2-CAND-001',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-CHAIN-001',required_subject_binding:'named buyer and named supplier in one official award',required_claim_elements:'product|quantity|transaction_amount|award_date',allowed_evidence_use:'single procurement award fact only',held_rule:'hold if buyer supplier product quantity or amount is not explicit',excluded_inferences:'no long-term supply relationship;no exclusive supply;no mass production;no market share',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'},
  {criterion_id:'P0Q4ACC-CRIT-002',candidate_id:'P0ACQR2-CAND-005',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-COMPANY-001',required_subject_binding:'issuer and fiscal period explicit in annual report',required_claim_elements:'segment_revenue|segment_cost|gross_margin|period',allowed_evidence_use:'issuer-period service-robot segment fact only',held_rule:'hold if issuer period segment or metric unit is ambiguous',excluded_inferences:'no industry margin;no future earnings;no valuation or investment conclusion',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'},
  {criterion_id:'P0Q4ACC-CRIT-003',candidate_id:'P0ACQR2-CAND-008',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-MARKET-001',required_subject_binding:'publisher and forecast scope explicit',required_claim_elements:'category|geography|forecast_years|shipment_values|forecast_nature',allowed_evidence_use:'publisher forecast statement only',held_rule:'hold if forecast is presented as actual shipment or scope is missing',excluded_inferences:'no current actual shipments;no realized CAGR;no investment conclusion',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'},
  {criterion_id:'P0Q4ACC-CRIT-004',candidate_id:'P0ACQR2-CAND-013',conceptual_gap_key:'STRONG_FIELD:ROBOT-GAP-SUPPLY-001',required_subject_binding:'named buyer and named winning supplier in official result notice',required_claim_elements:'brand_model|quantity|unit_price|total_price|award_date',allowed_evidence_use:'single procurement result fact only',held_rule:'hold if winner product quantity or price is not explicit',excluded_inferences:'no recurring order;no exclusive supply;no production capacity;no supplier revenue attribution',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'},
];}
 
const claims={
  'P0ACQR2-CAND-001':{proposed_evidence_class:'OFFICIAL_PROCUREMENT_AWARD_FACT',claim_subject:'北京航空航天大学自动化科学与电气工程学院与深圳市枫湖智能科技有限公司之单一采购项目',claim_predicate:'成交',claim_object_or_metric:'具身智能轮式人形机器人1台;成交价446000元',temporal_scope:'结果公示日期2026-05-08',geographic_scope:'中国北京',explicit_qualifiers:'单一采购结果;仅限公示所列采购单位、供应商、产品、数量和金额',accepted_claim_text:'北航采购结果公示列明自动化科学与电气工程学院采购具身智能轮式人形机器人1台,成交供应商为深圳市枫湖智能科技有限公司,成交价446000元。',excluded_inferences:'不得外推长期供货、独家供应、批量量产、市场份额、供应商收入或投资结论'},
  'P0ACQR2-CAND-005':{proposed_evidence_class:'ISSUER_ANNUAL_REPORT_SEGMENT_FACT',claim_subject:'科沃斯机器人股份有限公司2024年度服务机器人业务分部',claim_predicate:'年度报告列示',claim_object_or_metric:'收入8,081,982,367.41元;营业成本4,447,531,334.45元;毛利率44.97%',temporal_scope:'2024年度',geographic_scope:'发行人披露口径',explicit_qualifiers:'仅限发行人年报分部口径与所列期间',accepted_claim_text:'科沃斯2024年年度报告列示服务机器人业务收入8,081,982,367.41元、营业成本4,447,531,334.45元及毛利率44.97%。',excluded_inferences:'不得外推行业利润率、未来盈利、订单、估值、正式池或投资结论'},
  'P0ACQR2-CAND-008':{proposed_evidence_class:'PUBLISHER_FORECAST_STATEMENT',claim_subject:'Omdia对全球人形机器人出货量的预测',claim_predicate:'预测',claim_object_or_metric:'2027年超过10000台;2030年达到38000台;2024至2030年预测CAGR 83%',temporal_scope:'发布于2024-07-25;预测期2024-2030',geographic_scope:'全球',explicit_qualifiers:'预测口径,不是已实现出货量',accepted_claim_text:'Omdia预测全球人形机器人出货量2027年超过10000台、2030年达到38000台,并给出2024至2030年83%的预测复合增速。',excluded_inferences:'不得表述为当前实际出货、已实现增速、确定市场规模或投资结论'},
  'P0ACQR2-CAND-013':{proposed_evidence_class:'OFFICIAL_PROCUREMENT_RESULT_FACT',claim_subject:'广州市工贸技师学院与广东众承人工智能研究有限公司之单一政府采购结果',claim_predicate:'中标',claim_object_or_metric:'乐聚Kuavo 4pro、Kuavo 5-W等机器人品牌型号、数量、单价和总价',temporal_scope:'结果公告日期2026-03-26',geographic_scope:'中国广州',explicit_qualifiers:'仅限公告所列采购人、中标供应商及逐项产品价格数量',accepted_claim_text:'中国政府采购网结果公告列明广州市工贸技师学院为采购人、广东众承人工智能研究有限公司为中标供应商,并披露乐聚Kuavo 4pro、Kuavo 5-W等机器人型号、数量、单价和总价。',excluded_inferences:'不得外推持续订单、独家供应、量产能力、收入贡献、正式池或投资结论'},
};
 
export function decisionRows(){
  const qualified=readCsv(QUALIFICATION_INPUT).rows.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW');
  const criteria=new Map(criteriaRows().map(row=>[row.candidate_id,row]));
  return qualified.map((row,index)=>{
    const criterion=criteria.get(row.candidate_id),claim=claims[row.candidate_id];
    if(!criterion||!claim)throw new Error(`QUALIFIED4_AUTHORITY_MISSING:${row.candidate_id}`);
    return{acceptance_id:`P0Q4ACC-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,proposal_outcome:'ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW',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=decisionRows()){
  const inputSummary=readCsv(GAP_INPUT).rows;
  const inputApplications=readCsv(APPLICATION_INPUT).rows;
  const countByGap=gap=>decisions.filter(row=>row.conceptual_gap_key===gap);
  const summary=inputSummary.map((row,index)=>{
    const rows=countByGap(row.conceptual_gap_key),eligible=rows.filter(item=>item.proposal_outcome==='ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW').length,held=rows.filter(item=>item.proposal_outcome.startsWith('HELD')).length,rejected=rows.filter(item=>item.proposal_outcome.startsWith('REJECTED')).length;
    return{summary_id:`P0Q4ACC-SUM-${String(index+1).padStart(3,'0')}`,conceptual_gap_key:row.conceptual_gap_key,qualified_input_count:String(rows.length),eligible_proposal_count:String(eligible),held_count:String(held),rejected_count:String(rejected),acceptance_readiness:eligible?'ELIGIBLE_PROPOSAL_EXISTS_PENDING_INDEPENDENT_REVIEW':'NO_QUALIFIED_INPUT_GAP_REMAINS_OPEN',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'};
  });
  const applications=inputApplications.map((row,index)=>{const rows=countByGap(row.conceptual_gap_key),eligible=rows.filter(item=>item.proposal_outcome==='ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW').length,held=rows.filter(item=>item.proposal_outcome.startsWith('HELD')).length;return{application_id:`P0Q4ACC-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_input_count:String(rows.length),eligible_proposal_count:String(eligible),held_count:String(held),action:eligible?'REGISTER_ACCEPTANCE_PROPOSAL_PENDING_INDEPENDENT_REVIEW':'NO_QUALIFIED_INPUT_GAP_RETAINED',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 rules=[
    ['SOURCE_AUDIT','exact append-stable PASS plus qualified4-design-only allowance'],['NETWORK','FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK'],['QUALIFIED_UNIVERSE','exact4 from predecessor PASS; context-only10 excluded'],['SOURCE_CHAIN','candidate provenance raw locator and hash exact'],['CRITERIA','4 candidate-specific subject and claim criteria'],['DECISION','4 exact all-field proposals'],['OUTCOME','proposal only pending independent review'],['GAP_STATE','OPEN_RETAINED_GAP'],['CLAIM_STRENGTH','PENDING_VERIFICATION_MAX_NO_UPGRADE'],['FORMAL_POOL','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],['EVIDENCE_STRENGTH','NO_UPGRADE'],['MAP','READ_ONLY_MAP46_NO_MUTATION'],['INTEGRATION','PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE'],['OUTPUT_MUTATION','NONE'],['BASELINE','first generated artifact'],['LEDGER','4 exact proposal rows'],['SUMMARY','7 exact gap rows'],['APPLICATION','10 exact occurrence rows'],['REQUEST','exact release and boundary provenance'],['VALIDATION','last generated artifact and no FAIL'],['MANIFEST','21 data-only seven-field rows'],['TRANSACTION','reuse audited runProductionTransactionR2'],['ROLLBACK','exact manifest bytes+mtime and generated absent'],['FAULT_AUTHORITY','reuse audited immutable fault10 authority'],['REVIEW','independent execution output review required'],['RELEASE','seven unique exact key lines'],['ACCEPTANCE_RELEASE','NOT_RELEASED_BY_PROPOSAL_EXECUTION'],['GAP_CLOSURE','NOT_RELEASED'],['SUBJECT_SCOPE','candidate-specific subject binding'],['EXCLUDED_INFERENCES','nonempty for every proposal'],['PROTECTED','48 frozen final-gate identities plus exact authorized Stage3 cutover identity'],['SERIALIZATION','UTF8 no BOM LF quoted CSV terminal LF'],['COUNT_BINDING','qualified4|criteria4|decisions4|summary7|application10|exact21'],['FROZEN_INPUTS','no refetch no network no source rewrite'],
  ];
  return rules.map((row,index)=>({contract_id:`P0Q4ACC-CON-${String(index+1).padStart(3,'0')}`,scope:'QUALIFIED4_EVIDENCE_ACCEPTANCE_PROPOSAL',field_or_gate:row[0],required_value_or_rule:row[1],failure_state:'FAIL_CLOSED_NO_OUTPUT_COMMIT'}));
}
 
export function schemaRows(){return[
  {schema_id:'P0Q4ACC-SCHEMA-001',artifact_role:'ACCEPTANCE_CRITERIA',column_order:CRITERIA_COLUMNS.join('|'),primary_key:'criterion_id|candidate_id',row_count_rule:'4',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'criteriaRows'},
  {schema_id:'P0Q4ACC-SCHEMA-002',artifact_role:'DECISION_AUTHORITY',column_order:DECISION_COLUMNS.join('|'),primary_key:'acceptance_id|candidate_id',row_count_rule:'4',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'decisionRows from qualified4'},
  {schema_id:'P0Q4ACC-SCHEMA-003',artifact_role:'EXECUTION_BASELINE',column_order:BASELINE_COLUMNS.join('|'),primary_key:'baseline_id',row_count_rule:'dynamic_exact_input_set',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'runtime prewrite physical identities'},
  {schema_id:'P0Q4ACC-SCHEMA-004',artifact_role:'ACCEPTANCE_PROPOSAL_LEDGER',column_order:DECISION_COLUMNS.join('|'),primary_key:'acceptance_id|candidate_id',row_count_rule:'4',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'byte-equivalent decision authority rows'},
  {schema_id:'P0Q4ACC-SCHEMA-005',artifact_role:'GAP_READINESS_SUMMARY',column_order: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:'deriveOutputs summary'},
  {schema_id:'P0Q4ACC-SCHEMA-006',artifact_role:'OCCURRENCE_APPLICATION',column_order:APPLICATION_COLUMNS.join('|'),primary_key:'application_id|source_occurrence_key',row_count_rule:'10',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'deriveOutputs applications'},
  {schema_id:'P0Q4ACC-SCHEMA-007',artifact_role:'EXECUTION_VALIDATION',column_order:VALIDATION_COLUMNS.join('|'),primary_key:'check_id',row_count_rule:'19',serialization:'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',derivation_rule:'validationRows validation-last'},
];}
 
export function executionSetRows(){
  const paths=[SCRIPT,SOURCE_ENTRY_AUTHORITY,QUALIFICATION_INPUT,CANDIDATES,PROVENANCE,RAW_ARCHIVE,GAP_INPUT,APPLICATION_INPUT,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,FAULT_RESULTS,PROTECTED_INVENTORY,EXEC_BASELINE,ACCEPTANCE_LEDGER,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
  const roles=['RUNTIME','SOURCE_AUDIT_ENTRY_AUTHORITY','QUALIFIED4_INPUT','CANDIDATE_INPUT','PROVENANCE_INPUT','RAW_ARCHIVE_INPUT','GAP7_INPUT','OCCURRENCE10_INPUT','ACCEPTANCE_CRITERIA','DECISION_AUTHORITY','RUNTIME_CONTRACT','OUTPUT_SCHEMA','EXECUTION_EXACT_SET','AUDITED_TRANSACTION_FAULT10','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:`P0Q4ACC-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 entryAuthorityErrors(file,id,label){
  if(!fs.existsSync(abs(file)))return[`${label}_AUTHORITY_MISSING`];
  const parsed=readCsv(file),errors=exactColumns(parsed,ENTRY_COLUMNS,label);
  if(parsed.rows.length!==1)return[...errors,`${label}_AUTHORITY_COUNT`];
  const row=parsed.rows[0],entry=entryById(row.artifact_path,id);
  if(!entry)return[...errors,`${label}_ENTRY_MISSING_OR_DUPLICATE`];
  for(const [field,value] of Object.entries({start_line:String(entry.startLine),end_line:String(entry.endLine),normalized_lines:String(entry.lines),normalized_bytes:String(entry.bytes),normalized_sha256:entry.sha256}))if(String(row[field])!==value)errors.push(`${label}_${field}`);
  for(const field of ['required_marker_1','required_marker_2','required_marker_3'])if(row[field]&&!entry.text.includes(row[field]))errors.push(`${label}_${field}`);
  return errors;
}
 
export function protectedErrors(){
  const errors=[],rows=readCsv(PROTECTED_INVENTORY).rows;
  if(rows.length!==49)errors.push(`PROTECTED_COUNT:${rows.length}:49`);
  const cutoverProtected=rows.filter(row=>row.artifact_path===AUTHORIZED_CUTOVER_PATH);
  if(cutoverProtected.length!==1)errors.push(`PROTECTED_CUTOVER_PATH_COUNT:${cutoverProtected.length}:1`);
  const manifestRows=readCsv(MANIFEST).rows.filter(row=>row.case_id===CASE_ID&&row.run_id===AUTHORIZED_CUTOVER_RUN&&row.artifact_path===AUTHORIZED_CUTOVER_PATH);
  if(manifestRows.length!==1)errors.push(`PROTECTED_CUTOVER_AUTHORITY_COUNT:${manifestRows.length}:1`);
  const cutoverAuthority=manifestRows[0];
  for(const row of rows){
    if(!fs.existsSync(abs(row.artifact_path))){errors.push(`PROTECTED_MISSING:${row.artifact_path}`);continue;}
    const id=fileIdentity(row.artifact_path),expected=row.artifact_path===AUTHORIZED_CUTOVER_PATH?cutoverAuthority:row;
    if(!expected){errors.push(`PROTECTED_AUTHORITY_MISSING:${row.artifact_path}`);continue;}
    if(id.sha256!==expected.sha256)errors.push(`PROTECTED_SHA:${row.artifact_path}`);
    if(id.bytes!==String(expected.bytes))errors.push(`PROTECTED_BYTES:${row.artifact_path}`);
    if(row.artifact_path===AUTHORIZED_CUTOVER_PATH&&Date.parse(id.mtime)!==Date.parse(expected.mtime))errors.push(`PROTECTED_MTIME:${row.artifact_path}`);
  }
  return errors;
}
 
function sourceChainErrors(){
  const errors=[],qualified=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])),provenance=new Map(readCsv(PROVENANCE).rows.map(row=>[row.candidate_id,row]));
  if(qualified.length!==4)errors.push(`QUALIFIED_COUNT:${qualified.length}:4`);
  for(const row of qualified){const candidate=candidates.get(row.candidate_id),prov=provenance.get(row.candidate_id);if(!candidate||!prov){errors.push(`SOURCE_CHAIN_MISSING:${row.candidate_id}`);continue;}for(const field of ['query_id','conceptual_gap_key','canonical_url','source_class','content_locator','snippet_text_sha256'])if(String(row[field])!==String(candidate[field]))errors.push(`QUALIFIED_CANDIDATE:${row.candidate_id}:${field}`);for(const field of ['query_id','conceptual_gap_key','canonical_url','content_locator','snippet_text_sha256'])if(String(candidate[field])!==String(prov[field]))errors.push(`CANDIDATE_PROVENANCE:${row.candidate_id}:${field}`);}
  return errors;
}
 
export function coreErrors({criteria=criteriaRows(),decisions=decisionRows(),summary=null,applications=null}={}){
  const errors=[...sourceChainErrors()],expectedCriteria=criteriaRows(),expectedDecisions=decisionRows(),derived=deriveOutputs(decisions);
  errors.push(...compareRows(criteria,expectedCriteria,CRITERIA_COLUMNS,'CRITERIA'),...compareRows(decisions,expectedDecisions,DECISION_COLUMNS,'DECISION'));
  if(new Set(decisions.map(row=>row.candidate_id)).size!==4)errors.push('DECISION_UNIQUE');
  for(const row of decisions){if(row.proposal_outcome!=='ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW')errors.push(`OUTCOME:${row.candidate_id}`);if(!row.accepted_claim_text||!row.excluded_inferences)errors.push(`CLAIM_BOUNDARY:${row.candidate_id}`);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.integration_effect!=='PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE')errors.push(`BOUNDARY:${row.candidate_id}`);}
  if(summary)errors.push(...compareRows(summary,derived.summary,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=[...sourceAuditErrors(),...releaseErrors({required:requireRelease}),...entryAuthorityErrors(SOURCE_ENTRY_AUTHORITY,SOURCE_AUDIT,'SOURCE_ENTRY'),...entryAuthorityErrors(FORMAL_ENTRY_AUTHORITY,DESIGN_ID,'FORMAL_ENTRY'),...protectedErrors()];
  for(const file of [QUALIFICATION_INPUT,CANDIDATES,PROVENANCE,RAW_ARCHIVE,GAP_INPUT,APPLICATION_INPUT,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,FAULT_RESULTS,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'),...exactColumns(schemas,SCHEMA_COLUMNS,'SCHEMA'),...exactColumns(execSet,EXEC_SET_COLUMNS,'EXEC_SET'),...compareRows(criteria.rows,criteriaRows(),CRITERIA_COLUMNS,'CRITERIA'),...compareRows(decisions.rows,decisionRows(),DECISION_COLUMNS,'DECISION'),...compareRows(contracts.rows,contractRows(),CONTRACT_COLUMNS,'CONTRACT'),...compareRows(schemas.rows,schemaRows(),SCHEMA_COLUMNS,'SCHEMA'),...compareRows(execSet.rows,executionSetRows(),EXEC_SET_COLUMNS,'EXEC_SET'),...coreErrors({criteria:criteria.rows,decisions:decisions.rows}));
  const faults=readCsv(FAULT_RESULTS).rows;if(faults.length!==10||faults.some(row=>row.result!=='PASS'))errors.push('FAULT10_AUTHORITY');
  if(expectNoExecution){for(const file of GENERATED)if(fs.existsSync(abs(file)))errors.push(`EXECUTION_FILE_EXISTS:${file}`);const manifest=parseAuthorityCsv(normalize(fs.readFileSync(abs(MANIFEST))));if(manifest.rows.some(row=>row.run_id===EXEC_RUN))errors.push('EXECUTION_MANIFEST_ROWS');}
  return[...new Set(errors)];
}
 
function manifestRowsFor(paths){return paths.map(file=>{const id=fileIdentity(file);return{case_id:CASE_ID,run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:file,sha256:id.sha256,bytes:id.bytes,mtime:id.mtime};});}
 
function baselineRows(){
  const files=[SCRIPT,SOURCE_ENTRY_AUTHORITY,QUALIFICATION_INPUT,CANDIDATES,PROVENANCE,RAW_ARCHIVE,GAP_INPUT,APPLICATION_INPUT,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,FAULT_RESULTS,PROTECTED_INVENTORY];
  const rows=files.map((file,index)=>{const id=fileIdentity(file);return{baseline_id:`P0Q4ACC-BASE-${String(index+1).padStart(3,'0')}`,artifact_role:'FROZEN_INPUT',artifact_path:file,sha256:id.sha256,bytes:id.bytes,mtime:id.mtime,required_state:'EXACT_BEFORE_EXECUTION'};});
  const manifest=fs.readFileSync(abs(MANIFEST)),stat=fs.statSync(abs(MANIFEST));
  rows.push({baseline_id:'P0Q4ACC-BASE-MANIFEST-PREFIX',artifact_role:'MANIFEST_PREFIX',artifact_path:MANIFEST,sha256:hash(manifest),bytes:String(manifest.length),mtime:new Date(Math.trunc(stat.mtimeMs)).toISOString(),required_state:'IMMUTABLE_PREFIX_BEFORE_EXACT21_APPEND'});
  const release=entryById(AUDIT_REPORT,RELEASE_AUDIT);if(!release)throw new Error('RELEASE_ENTRY_MISSING');
  rows.push({baseline_id:'P0Q4ACC-BASE-RELEASE',artifact_role:'RELEASE_AUDIT_ENTRY',artifact_path:AUDIT_REPORT,sha256:release.sha256,bytes:String(release.bytes),mtime:new Date(Math.trunc(fs.statSync(abs(AUDIT_REPORT)).mtimeMs)).toISOString(),required_state:`ENTRY_LINES_${release.startLine}_${release.endLine}`});
  return rows;
}
 
function baselineErrors(rows){
  const errors=[];
  for(const row of rows.filter(row=>row.artifact_role==='FROZEN_INPUT')){if(!fs.existsSync(abs(row.artifact_path))){errors.push(`BASELINE_MISSING:${row.artifact_path}`);continue;}const id=fileIdentity(row.artifact_path);if(id.sha256!==row.sha256||id.bytes!==String(row.bytes)||Date.parse(id.mtime)!==Date.parse(row.mtime))errors.push(`BASELINE_IDENTITY:${row.artifact_path}`);}
  const release=rows.find(row=>row.artifact_role==='RELEASE_AUDIT_ENTRY'),entry=entryById(AUDIT_REPORT,RELEASE_AUDIT);if(!release||!entry||release.sha256!==entry.sha256||String(release.bytes)!==String(entry.bytes))errors.push('BASELINE_RELEASE_ENTRY');
  return errors;
}
 
function requestText(){return `# Qualified4 证据接受/核验执行审核请求\n\n- case_id: ${CASE_ID}\n- batch_id: ${EXEC_BATCH}\n- run_id: ${EXEC_RUN}\n- design_id: ${DESIGN_ID}\n- release_audit: ${RELEASE_AUDIT}\n- source_audit: ${SOURCE_AUDIT}\n- scope: FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\n- qualified_inputs: 4\n- acceptance_proposals: 4\n- gap_state: OPEN_RETAINED_GAP\n- integration_effect: PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE\n- map_effect: READ_ONLY_MAP46_NO_MUTATION\n- formal_pool_effect: NO_AUTOMATIC_FORMAL_POOL_CHANGE\n- evidence_strength_effect: NO_UPGRADE\n- evidence_acceptance_release: NOT_RELEASED_PENDING_EXECUTION_REVIEW\n- gap_closure_release: NOT_RELEASED\n`;
}
 
function validationRows(state){
  const errors=coreErrors(state),checks=[
    ['CORE_ERRORS','0',String(errors.length)],['SOURCE_AUDIT_ERRORS','0',String(sourceAuditErrors().length)],['RELEASE_ERRORS','0',String(releaseErrors({required:true}).length)],['QUALIFIED_INPUTS','4',String(readCsv(QUALIFICATION_INPUT).rows.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW').length)],['CRITERIA','4',String(state.criteria.length)],['PROPOSALS','4',String(state.decisions.length)],['ELIGIBLE','4',String(state.decisions.filter(row=>row.proposal_outcome==='ACCEPTANCE_PROPOSAL_ELIGIBLE_PENDING_INDEPENDENT_REVIEW').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)],['INTEGRATION_WRITE','0',String(state.decisions.filter(row=>row.integration_effect!=='PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE').length)],['POOL_CHANGE','0',String(state.decisions.filter(row=>row.formal_pool_effect!=='NO_AUTOMATIC_FORMAL_POOL_CHANGE').length)],['EVIDENCE_UPGRADE','0',String(state.decisions.filter(row=>row.evidence_strength_effect!=='NO_UPGRADE').length)],['PROTECTED_ERRORS','0',String(protectedErrors().length)],['FAULT_PASS','10',String(readCsv(FAULT_RESULTS).rows.filter(row=>row.result==='PASS').length)],['EXACT_SET','21',String(executionSetRows().length)],['MANIFEST_DELTA','21','21']
  ];
  const rows=checks.map((item,index)=>({check_id:`P0Q4ACC-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:'QUALIFIED4_ACCEPTANCE_PROPOSAL_FAIL_CLOSED_ORACLE'}));
  rows.push({check_id:'P0Q4ACC-EXEC-VAL-019',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identities postchecked'});
  return rows;
}
 
function validateManifestForRun(prefixRow){
  const expected=manifestRowsFor(executionSetRows().map(row=>row.artifact_path));
  return validateAppendStableManifest(fs.readFileSync(abs(MANIFEST)),{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:Number(prefixRow.bytes),sha256:prefixRow.sha256},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:expected,expectedRunId:EXEC_RUN,expectedPhysicalDelta:21}).errors;
}
 
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(...sourceAuditErrors(),...releaseErrors({required:true}),...protectedErrors(),...exactColumns(baseline,BASELINE_COLUMNS,'BASELINE'),...baselineErrors(baseline.rows),...exactColumns(decisions,DECISION_COLUMNS,'LEDGER'),...exactColumns(summary,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');
  const expectedValidation=validationRows(state);errors.push(...compareRows(validation.rows,expectedValidation,VALIDATION_COLUMNS,'VALIDATION'));if(validation.rows.some(row=>row.status==='FAIL'))errors.push('VALIDATION_FAIL');
  const prefix=baseline.rows.find(row=>row.artifact_role==='MANIFEST_PREFIX');if(!prefix)errors.push('MANIFEST_PREFIX_BASELINE_MISSING');else errors.push(...validateManifestForRun(prefix).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('|')}`);
  const manifestBefore=fs.readFileSync(abs(MANIFEST)),manifestBeforeMtimeMs=Math.trunc(fs.statSync(abs(MANIFEST)).mtimeMs),decisions=readCsv(DECISION_AUTHORITY).rows,derived=deriveOutputs(decisions),state={criteria:readCsv(CRITERIA).rows,decisions,summary:derived.summary,applications:derived.applications};
  const baseline=baselineRows(),validation=validationRows(state);
  const payloads=[
    {path:abs(EXEC_BASELINE),bytes:Buffer.from(serializeCsv(baseline,BASELINE_COLUMNS))},
    {path:abs(ACCEPTANCE_LEDGER),bytes:Buffer.from(serializeCsv(decisions,DECISION_COLUMNS))},
    {path:abs(GAP_SUMMARY),bytes:Buffer.from(serializeCsv(derived.summary,SUMMARY_COLUMNS))},
    {path:abs(APPLICATION),bytes:Buffer.from(serializeCsv(derived.applications,APPLICATION_COLUMNS))},
    {path:abs(EXEC_REQUEST),bytes:Buffer.from(requestText())},
    {path:abs(EXEC_VALIDATION),bytes:Buffer.from(serializeCsv(validation,VALIDATION_COLUMNS))},
  ];
  if(validation.some(row=>row.status==='FAIL'))throw new Error('VALIDATION_FAIL');
  const result=sem.runProductionTransactionR2({manifestPath:abs(MANIFEST),manifestBefore,manifestBeforeMtimeMs,payloads,buildManifestCandidate:()=>{const rows=manifestRowsFor(executionSetRows().map(row=>row.artifact_path)),candidate=Buffer.concat([manifestBefore,Buffer.from(serializeManifestDataRows(rows),'utf8')]),checked=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:21});return{candidate,rows,errors:checked.errors};},postwriteOracle:()=>validateExecution()});
  if(result.status!=='COMMITTED')throw new Error(`${result.status}:${result.stage}:${result.errors.join('|')}`);
  return{status:'EXECUTED_PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW',proposal_rows:4,eligible:4,summary_rows:7,application_rows:10,manifest_rows:21};
}
 
export function negativeRows(){
  const clean={criteria:criteriaRows(),decisions:decisionRows(),...deriveOutputs(decisionRows())},cases=[
    ['DECISION_OUTCOME',s=>{s.decisions[0].proposal_outcome='ACCEPTED_EVIDENCE';},'OUTCOME'],['DECISION_CLAIM',s=>{s.decisions[0].accepted_claim_text='tamper';},'DECISION_FIELD'],['DECISION_SUBJECT',s=>{s.decisions[0].claim_subject='tamper';},'DECISION_FIELD'],['DECISION_REMOVE',s=>{s.decisions.pop();},'DECISION_COUNT'],['GAP_CLOSE',s=>{s.decisions[0].gap_state_after='CLOSED';},'DECISION_FIELD'],['STRENGTH_UPGRADE',s=>{s.decisions[0].evidence_strength_effect='UPGRADE';},'DECISION_FIELD'],['FORMAL_POOL',s=>{s.decisions[0].formal_pool_effect='FORMAL_POOL_CHANGE';},'DECISION_FIELD'],['INTEGRATION_WRITE',s=>{s.decisions[0].integration_effect='FORMAL_WRITE';},'DECISION_FIELD'],['EXCLUSION_EMPTY',s=>{s.decisions[0].excluded_inferences='';},'CLAIM_BOUNDARY'],['CRITERIA_TAMPER',s=>{s.criteria[0].allowed_evidence_use='unbounded';},'CRITERIA_FIELD'],['SUMMARY_OFFSET',s=>{s.summary[0].eligible_proposal_count='0';s.summary[1].eligible_proposal_count='1';},'SUMMARY_FIELD'],['APPLICATION_MUTATION',s=>{s.applications[0].output_mutation='WRITE';},'APPLICATION_FIELD'],
  ];
  const rows=cases.map((item,index)=>{const state=structuredClone(clean);item[1](state);const errors=coreErrors({criteria:state.criteria,decisions:state.decisions,summary:state.summary,applications:state.applications});return{test_id:`P0Q4ACC-NEG-${String(index+1).padStart(3,'0')}-${item[0]}`,mutation_applied:'YES',oracle:'coreErrors',expected:'REJECT',expected_code:item[2],actual:errors.length?'REJECT':'ACCEPT',actual_codes:errors.join('|')||'NONE',result:errors.length&&errors.some(code=>code.startsWith(item[2]))?'PASS':'FAIL'};});
  const releaseGood=`reviewed_design_id=${DESIGN_ID}\nresult=PASS\nexecution_release=EXPLICITLY_RELEASED\nreleased_batch_id=${EXEC_BATCH}\nreleased_run_id=${EXEC_RUN}\nnetwork_scope=FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK\nevidence_acceptance_ceiling=PROPOSAL_ONLY_NO_FORMAL_EVIDENCE_WRITE`;
  for(const [name,text,code] of [['RELEASE_DUP_RESULT',`${releaseGood}\nresult=PASS`,'KEY_COUNT:result'],['RELEASE_WRONG_RUN',releaseGood.replace(EXEC_RUN,'WRONG'),'KEY_VALUE:released_run_id'],['RELEASE_NETWORK',releaseGood.replace('FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK','PUBLIC_WEB'),'KEY_VALUE:network_scope'],['RELEASE_FAIL',`${releaseGood}\nresult=FAIL`,'KEY_COUNT:result']]){const errors=releaseTextErrors(text);rows.push({test_id:`P0Q4ACC-NEG-${String(rows.length+1).padStart(3,'0')}-${name}`,mutation_applied:'YES',oracle:'releaseTextErrors',expected:'REJECT',expected_code:code,actual:errors.length?'REJECT':'ACCEPT',actual_codes:errors.join('|')||'NONE',result:errors.some(error=>error.startsWith(code))?'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:4,eligible:4,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}`);
}