MB-X Bilibili Pipeline
7 days ago da3fb90457c961937a98000874dfc22c3f789ec6
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
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {pathToFileURL} from 'node:url';
import * as discovery from './detail_strengthening_p0_primary_source_discovery_runtime_repair002_20260730.mjs';
import {parseAuthorityCsv,serializeCsv,serializeManifestDataRows,validateAppendStableManifest} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
export const ROOT=process.cwd();
export const CASE_ID=discovery.CASE_ID;
export const BASE=discovery.BASE;
export const AUDIT_REPORT=discovery.AUDIT_REPORT;
export const MANIFEST=discovery.MANIFEST;
export const ANOMALY_AUTHORITY=discovery.ANOMALY_AUTHORITY;
export const ORIGINAL_TRIAGE_RUN=discovery.ORIGINAL_TRIAGE_RUN;
export const DESIGN_ID='DESIGN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-001';
export const DESIGN_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-001';
export const DESIGN_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-001';
export const EXEC_RUN='RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-001';
export const EXEC_BATCH='BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-001';
export const RELEASE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-CANDIDATE-SEMANTIC-VERIFICATION-DESIGN-REREVIEW-001';
export const SOURCE_AUDIT='AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-EXEC-OUTPUT-001';
export const EXEC_TOKEN='EXECUTE_DETAIL_STRENGTHENING_P0_CANDIDATE_SEMANTIC_VERIFICATION_001';
export const SCRIPT='dev/ana-dev/detail_strengthening_p0_candidate_semantic_verification_runtime_20260730.mjs';
export const CANDIDATES=discovery.CANDIDATE_REGISTER;
export const PROVENANCE=discovery.PROVENANCE_LEDGER;
export const RAW_ARCHIVE=discovery.RAW_ARCHIVE;
export const TARGET_AUTHORITY=discovery.TARGET_AUTHORITY;
export const GAP_AUTHORITY=discovery.GAP_AUTHORITY;
export const PROTECTED_INVENTORY=`${BASE}/evidence/final_gate_output_inventory_rebuild_repair001_20260728.csv`;
export const FORMAL_ENTRY_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_verification_formal_design_entry_authority_20260730.csv`;
export const CRITERIA=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_criteria_20260730.csv`;
export const DECISION_AUTHORITY=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_decision_authority_20260730.csv`;
export const CONTRACT=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_verification_contract_20260730.csv`;
export const SCHEMA=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_verification_schema_20260730.csv`;
export const EXEC_SET=`${BASE}/manifest/detail_strengthening_p0_candidate_semantic_verification_execution_artifact_set_20260730.csv`;
export const EXEC_BASELINE=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_verification_execution_baseline_20260730.csv`;
export const QUALIFICATION=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_qualification_ledger_20260730.csv`;
export const GAP_SUMMARY=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_gap_summary_20260730.csv`;
export const APPLICATION=`${BASE}/evidence/detail_strengthening_p0_candidate_semantic_occurrence_application_20260730.csv`;
export const EXEC_REQUEST=`${BASE}/manifest/review_request_detail_strengthening_p0_candidate_semantic_verification_execution_20260730.md`;
export const EXEC_VALIDATION=`${BASE}/manifest/detail_strengthening_p0_candidate_semantic_verification_execution_validation_20260730.csv`;
export const GENERATED=[EXEC_BASELINE,QUALIFICATION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
 
export const FORMAL_ENTRY_COLUMNS=['entry_id','design_id','artifact_path','start_line','end_line','lines','bytes','sha256','normalization','required_markers'];
export const CRITERIA_COLUMNS=['criterion_id','conceptual_gap_key','required_elements','qualified_rule','context_rule','reject_rule','held_rule','claim_strength_ceiling','gap_effect','formal_pool_effect','evidence_strength_effect'];
export const DECISION_COLUMNS=['qualification_id','candidate_id','query_id','conceptual_gap_key','canonical_url','source_class','content_locator','snippet_text_sha256','criterion_id','outcome','semantic_scope','reason_code','evidence_eligibility','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect','review_state'];
export const SUMMARY_COLUMNS=['summary_id','conceptual_gap_key','candidate_count','qualified_count','context_only_count','reject_count','held_count','result','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect'];
export const APPLICATION_COLUMNS=['application_id','target_id','source_occurrence_key','conceptual_gap_key','qualified_candidate_count','context_candidate_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','identity_type','artifact_path','rows','bytes','sha256','mtime','required_state'];
export const VALIDATION_COLUMNS=['check_id','check_description','expected','actual','status','evidence'];
 
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 clone=value=>JSON.parse(JSON.stringify(value));
const write=(file,text)=>{fs.mkdirSync(path.dirname(abs(file)),{recursive:true});fs.writeFileSync(abs(file),text,'utf8');};
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 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`);return{start:start+1,end,lines:end-start,bytes:buffer.length,sha256:hash(buffer),text:buffer.toString('utf8')};}
 
export function sourceAuditErrors(){const entry=auditEntry(SOURCE_AUDIT);if(!entry)return['SOURCE_AUDIT_MISSING'];const required=['result=PASS_P0_PRIMARY_SOURCE_DISCOVERY_EXECUTION_AND_OUTPUT_QUALITY_WITH_RETAINED_OPEN_GAPS','P0_primary_source_candidate_semantic_verification_detailed_design_preparation=ALLOWED'];return required.filter(marker=>!entry.text.includes(marker)).map(marker=>`SOURCE_AUDIT_MARKER:${marker}`);}
export function releaseTextErrors(text){const lines=text.split('\n').map(line=>line.trim().replace(/^[\-*]\s*/,'').replace(/`/g,''));const 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','candidate_outcome_ceiling=QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE'];const errors=[];for(const marker of required)if(!lines.includes(marker))errors.push(`RELEASE_MARKER:${marker}`);if(lines.some(line=>/^(?:result|conclusion)=FAIL(?:_|$)/.test(line))||lines.includes('execution_release=NOT_ALLOWED')||lines.includes('execution_release=NOT_RELEASED'))errors.push('RELEASE_CONTRADICTION');return errors;}
export function releaseErrors({required=false}={}){const entry=auditEntry(RELEASE_AUDIT);return entry?releaseTextErrors(entry.text):required?['RELEASE_AUDIT_MISSING']:[];}
 
export function criteriaRows(){return[
  ['P0SEM-CRIT-001','STRONG_FIELD:ROBOT-GAP-CHAIN-001','NAMED_PARTIES|CERTIFICATION_OR_NOMINATION_OR_CONTRACT_OR_ORDER_STAGE','Named parties and a documented certification, nomination, contract or order stage','Generic testing, certification-service or policy context without the target transaction','Officiality or topic mention alone','Locator, snippet hash or provenance mismatch'],
  ['P0SEM-CRIT-002','STRONG_FIELD:ROBOT-GAP-CHAIN-002','ROBOT_BOM_OR_PRICE_OR_SHARE_OR_ORDER_AMOUNT_OR_REVENUE_ATTRIBUTION','Robot-specific BOM, price, supplier share, order amount or revenue attribution','Generic BOM, procurement workflow or product award without cost or revenue attribution','Robot or BOM keyword alone','Locator, snippet hash or provenance mismatch'],
  ['P0SEM-CRIT-003','STRONG_FIELD:ROBOT-GAP-COMPANY-001','ISSUER|PERIOD|ROBOTICS_BUSINESS_OR_SEGMENT|REVENUE_OR_SHARE_OR_MARGIN','Issuer-period robotics business or segment revenue, share or margin is explicit','General company narrative without issuer-period financial attribution','Company or robotics keyword alone','Locator, snippet hash or provenance mismatch'],
  ['P0SEM-CRIT-004','STRONG_FIELD:ROBOT-GAP-MARKET-001','PUBLISHER|ROBOT_CATEGORY|PERIOD|GEOGRAPHY|SHIPMENT_OR_INSTALLATION_OR_SALES_METRIC','Publisher, category, period, geography and shipment, installation or sales metric are explicit','Market commentary lacking the complete metric scope','Forecast or shipment keyword alone','Locator, snippet hash or provenance mismatch'],
  ['P0SEM-CRIT-005','STRONG_FIELD:ROBOT-GAP-MODEL-001','OFFICIAL_ROBOT_FOUNDATION_MODEL|PRODUCT_OR_TECHNICAL_CAPABILITY|DEPLOYMENT_OR_PRICING','Official robot foundation-model product, capability, deployment or pricing information','Generic AI platform context without robot-model capability','AI or model keyword alone','Locator, snippet hash or provenance mismatch'],
  ['P0SEM-CRIT-006','STRONG_FIELD:ROBOT-GAP-PRODUCT-001','SPECIFIC_ROBOT_PRODUCT|PRICE_OR_ASP_OR_BOM_OR_PRODUCTION_OR_SALES_OR_TENDER_QUANTITY','Specific robot product tied to price, ASP, BOM, production, sales or tender quantity','Product or platform description without the target price, output or quantity fact','Product or procurement keyword alone','Locator, snippet hash or provenance mismatch'],
  ['P0SEM-CRIT-007','STRONG_FIELD:ROBOT-GAP-SUPPLY-001','BUYER_OR_CUSTOMER|SUPPLIER_OR_BIDDER|PRODUCT|CONTRACT_OR_AWARD_OR_NOMINATION_STAGE','Buyer/customer, supplier/bidder, product and confirmed contract, award or nomination stage','Open tender, bidder list or framework without confirmed supplier relationship','Tender or supplier keyword alone','Locator, snippet hash or provenance mismatch'],
].map(row=>({criterion_id:row[0],conceptual_gap_key:row[1],required_elements:row[2],qualified_rule:row[3],context_rule:row[4],reject_rule:row[5],held_rule:row[6],claim_strength_ceiling:'PENDING_VERIFICATION_MAX_NO_UPGRADE',gap_effect:'OPEN_RETAINED_GAP',formal_pool_effect:'NO_AUTOMATIC_FORMAL_POOL_CHANGE',evidence_strength_effect:'NO_UPGRADE'}));}
 
const DECISIONS={
  'P0DISCR1-CAND-001':['QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW','Named customer certification, small-batch supply and nomination/order-stage verification','NAMED_PARTIES_STAGE_DOCUMENTED'],
  'P0DISCR1-CAND-002':['CONTEXT_ONLY_NOT_GAP_CLOSING','Certification-service procurement scope without the target company transaction','CERTIFICATION_SERVICE_SCOPE_NO_TARGET_TRANSACTION'],
  'P0DISCR1-CAND-003':['CONTEXT_ONLY_NOT_GAP_CLOSING','Generic BOM and production-workflow requirement without robot cost or revenue attribution','GENERIC_BOM_WORKFLOW_NO_ROBOT_COST_ATTRIBUTION'],
  'P0DISCR1-CAND-004':['CONTEXT_ONLY_NOT_GAP_CLOSING','Product award notice without complete BOM, price, share or revenue attribution','PRODUCT_AWARD_NO_BOM_PRICE_OR_REVENUE_ATTRIBUTION'],
  'P0DISCR1-CAND-005':['QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW','Issuer-period robotics revenue share and gross margin are explicit','ISSUER_PERIOD_ROBOTICS_REVENUE_AND_MARGIN'],
  'P0DISCR1-CAND-006':['QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW','Issuer filing identifies robotics segment revenue sources','ISSUER_PERIOD_ROBOTICS_SEGMENT_REVENUE'],
  'P0DISCR1-CAND-007':['QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW','Official industry body gives category, period, geography and installation or sales metrics','PUBLISHER_CATEGORY_PERIOD_GEOGRAPHY_INSTALLATION_SALES'],
  'P0DISCR1-CAND-008':['QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW','Named report publisher gives category, period and global shipment forecast','PUBLISHER_CATEGORY_PERIOD_GLOBAL_SHIPMENT_FORECAST'],
  'P0DISCR1-CAND-009':['QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW','Official foundation-model product and capability are explicit','OFFICIAL_FOUNDATION_MODEL_PRODUCT_AND_CAPABILITY'],
  'P0DISCR1-CAND-010':['QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW','Official technical project report gives robot deployment and control capability','OFFICIAL_TECHNICAL_DEPLOYMENT_AND_CONTROL_CAPABILITY'],
  'P0DISCR1-CAND-011':['CONTEXT_ONLY_NOT_GAP_CLOSING','Platform resource description lacks robot product price, ASP, BOM, production or sales output','PLATFORM_RESOURCE_DESCRIPTION_NO_ROBOT_PRODUCT_PRICE_OUTPUT'],
  'P0DISCR1-CAND-012':['CONTEXT_ONLY_NOT_GAP_CLOSING','Product-specific award lacks disclosed price, ASP, BOM, production or sales fact','PRODUCT_SPECIFIC_AWARD_NO_PRICE_ASP_BOM_OR_PRODUCTION'],
  'P0DISCR1-CAND-013':['CONTEXT_ONLY_NOT_GAP_CLOSING','Tender bidder and quote information does not confirm the winning supplier relationship','TENDER_BIDDERS_QUOTE_AND_DELIVERY_NO_CONFIRMED_SUPPLIER_AWARD'],
  'P0DISCR1-CAND-014':['CONTEXT_ONLY_NOT_GAP_CLOSING','Open framework notice does not confirm an awarded supplier relationship','OPEN_FRAMEWORK_NOTICE_NO_CONFIRMED_SUPPLIER_AWARD'],
};
 
export function decisionRows(candidates=readCsv(CANDIDATES).rows){const criteria=new Map(criteriaRows().map(row=>[row.conceptual_gap_key,row.criterion_id]));return candidates.map((candidate,index)=>{const decision=DECISIONS[candidate.candidate_id];if(!decision)throw new Error(`DECISION_MISSING:${candidate.candidate_id}`);const qualified=decision[0]==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW';return{qualification_id:`P0SEM-QUAL-${String(index+1).padStart(3,'0')}`,candidate_id:candidate.candidate_id,query_id:candidate.query_id,conceptual_gap_key:candidate.conceptual_gap_key,canonical_url:candidate.canonical_url,source_class:candidate.source_class,content_locator:candidate.content_locator,snippet_text_sha256:candidate.snippet_text_sha256,criterion_id:criteria.get(candidate.conceptual_gap_key)??'',outcome:decision[0],semantic_scope:decision[1],reason_code:decision[2],evidence_eligibility:qualified?'ELIGIBLE_FOR_FUTURE_CONTROLLED_EVIDENCE_REVIEW':'NOT_ELIGIBLE_AS_DIRECT_EVIDENCE_CONTEXT_ONLY',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',review_state:'PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW'};});}
 
export function deriveOutputs(decisions=decisionRows(),targets=readCsv(TARGET_AUTHORITY).rows,gaps=readCsv(GAP_AUTHORITY).rows){const byGap=new Map();for(const row of decisions){const list=byGap.get(row.conceptual_gap_key)??[];list.push(row);byGap.set(row.conceptual_gap_key,list);}const summary=gaps.map((gap,index)=>{const rows=byGap.get(gap.conceptual_gap_key)??[],count=outcome=>rows.filter(row=>row.outcome===outcome).length,qualified=count('QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW'),context=count('CONTEXT_ONLY_NOT_GAP_CLOSING'),reject=count('REJECT_NOT_DIRECT'),held=count('HELD_LOCATOR_OR_IDENTITY');return{summary_id:`P0SEM-SUM-${String(index+1).padStart(3,'0')}`,conceptual_gap_key:gap.conceptual_gap_key,candidate_count:String(rows.length),qualified_count:String(qualified),context_only_count:String(context),reject_count:String(reject),held_count:String(held),result:held?'HELD_BY_CANDIDATE_IDENTITY':qualified?'QUALIFIED_CANDIDATE_EXISTS_PENDING_SEPARATE_EVIDENCE_REVIEW':'NO_DIRECT_QUALIFIED_CANDIDATE_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'};});const summaryMap=new Map(summary.map(row=>[row.conceptual_gap_key,row]));const applications=targets.map((target,index)=>{const item=summaryMap.get(target.conceptual_gap_key);return{application_id:`P0SEM-APP-${String(index+1).padStart(3,'0')}`,target_id:target.target_id,source_occurrence_key:target.source_occurrence_key,conceptual_gap_key:target.conceptual_gap_key,qualified_candidate_count:item.qualified_count,context_candidate_count:item.context_only_count,action:Number(item.qualified_count)>0?'REGISTER_QUALIFIED_CANDIDATE_PENDING_SEPARATE_EVIDENCE_APPLICATION_DESIGN':'RETAIN_GAP_NO_DIRECT_QUALIFIED_CANDIDATE',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 plus design preparation allowed'],['NETWORK','FROZEN_LOCAL_INPUTS_ONLY_NO_NETWORK'],['CANDIDATE_UNIVERSE','14 exact candidate IDs and all source projection fields'],['PROVENANCE','14 exact candidate/raw/query/url/locator/hash/source-class bindings'],['RAW_ARCHIVE','14 exact immutable JSONL identities inherited from discovery PASS'],['CRITERIA','7 exact gap-specific semantic criteria'],['DECISION','14 exact all-field candidate decisions'],['QUALIFIED_CEILING','qualification only, not evidence acceptance'],['OUTCOMES','QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW|CONTEXT_ONLY_NOT_GAP_CLOSING|REJECT_NOT_DIRECT|HELD_LOCATOR_OR_IDENTITY'],['GAP_STATE','OPEN_RETAINED_GAP'],['CLAIM_STRENGTH','PENDING_VERIFICATION_MAX_NO_UPGRADE'],['FORMAL_POOL','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],['EVIDENCE_STRENGTH','NO_UPGRADE'],['OUTPUT_MUTATION','NONE'],['BASELINE','first generated artifact and exact release/manifest/input/protected binding'],['QUALIFICATION','14 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','17 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'],
];return rows.map((row,index)=>({contract_id:`P0SEM-CON-${String(index+1).padStart(3,'0')}`,scope:index<14?'SEMANTIC_AUTHORITY':'EXECUTION_RUNTIME',field_or_gate:row[0],required_value_or_rule:row[1],failure_state:index===1?'HELD_BY_NETWORK_SCOPE_VIOLATION':'FAIL_CLOSED_NO_OUTPUT_COMMIT'}));}
export function schemaRows(){return[
  ['P0SEM-SCHEMA-001','SEMANTIC_CRITERIA',CRITERIA_COLUMNS,'criterion_id','7','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','exact criteriaRows'],
  ['P0SEM-SCHEMA-002','SEMANTIC_DECISION_AUTHORITY',DECISION_COLUMNS,'qualification_id|candidate_id','14','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','exact decisionRows from frozen candidates'],
  ['P0SEM-SCHEMA-003','EXECUTION_BASELINE',BASELINE_COLUMNS,'baseline_id','dynamic source/release/manifest/input/protected rows','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','runtime identities before outputs'],
  ['P0SEM-SCHEMA-004','QUALIFICATION_LEDGER',DECISION_COLUMNS,'qualification_id|candidate_id','14','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','byte-identical row semantics to decision authority'],
  ['P0SEM-SCHEMA-005','GAP_SUMMARY',SUMMARY_COLUMNS,'summary_id|conceptual_gap_key','7','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','deterministic grouping of qualification ledger'],
  ['P0SEM-SCHEMA-006','OCCURRENCE_APPLICATION',APPLICATION_COLUMNS,'application_id|target_id','10','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','deterministic target-to-gap mapping'],
  ['P0SEM-SCHEMA-007','EXECUTION_REQUEST',['markdown_key_value_lines'],'none','1 file','UTF8_NO_BOM_LF_TERMINAL_LF','exact release and retained-boundary request'],
  ['P0SEM-SCHEMA-008','EXECUTION_VALIDATION',VALIDATION_COLUMNS,'check_id','18','UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF','17 PASS plus one INFO self-reference exclusion'],
  ['P0SEM-SCHEMA-009','ARTIFACT_MANIFEST',['case_id','run_id','batch_id','artifact_path','sha256','bytes','mtime'],'run_id|artifact_path','17','DATA_ROWS_ONLY_NO_HEADER','seven-field exact filesystem identity'],
].map(row=>({schema_id:row[0],artifact_role:row[1],column_order:Array.isArray(row[2])?row[2].join('|'):row[2],primary_key:row[3],row_count_rule:row[4],serialization:row[5],derivation_rule:row[6]}));}
export function executionSetRows(){const paths=[SCRIPT,CANDIDATES,PROVENANCE,RAW_ARCHIVE,TARGET_AUTHORITY,GAP_AUTHORITY,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET,EXEC_BASELINE,QUALIFICATION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION],roles=['RUNTIME','CANDIDATES','PROVENANCE','RAW_ARCHIVE','TARGET_AUTHORITY','GAP_AUTHORITY','SEMANTIC_CRITERIA','DECISION_AUTHORITY','RUNTIME_CONTRACT','OUTPUT_SCHEMA','EXECUTION_EXACT_SET','EXECUTION_BASELINE_FIRST_GENERATED','QUALIFICATION_LEDGER','GAP_SUMMARY','OCCURRENCE_APPLICATION','EXECUTION_REQUEST','VALIDATION_LAST'];return paths.map((artifactPath,index)=>({artifact_id:`P0SEM-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 protectedRows(){const rows=readCsv(PROTECTED_INVENTORY).rows;if(rows.length!==49)throw new Error(`PROTECTED_COUNT:${rows.length}`);return rows.map(row=>({path:row.artifact_path,...identity(row.artifact_path)}));}
function manifestState({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 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 coreErrors(state){const expectedCandidates=readCsv(CANDIDATES),expectedProvenance=readCsv(PROVENANCE),expectedCriteria=criteriaRows(),expectedDecisions=decisionRows(expectedCandidates.rows),expectedDerived=deriveOutputs(expectedDecisions),errors=[];errors.push(...compareRows(state.candidates,expectedCandidates.rows,expectedCandidates.header,'CANDIDATE'),...compareRows(state.provenance,expectedProvenance.rows,expectedProvenance.header,'PROVENANCE'),...compareRows(state.criteria,expectedCriteria,CRITERIA_COLUMNS,'CRITERIA'),...compareRows(state.decisions,expectedDecisions,DECISION_COLUMNS,'DECISION'),...compareRows(state.summary,expectedDerived.summary,SUMMARY_COLUMNS,'SUMMARY'),...compareRows(state.applications,expectedDerived.applications,APPLICATION_COLUMNS,'APPLICATION'));
  const outcomes=new Set(['QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW','CONTEXT_ONLY_NOT_GAP_CLOSING','REJECT_NOT_DIRECT','HELD_LOCATOR_OR_IDENTITY']);
  for(const row of state.decisions){if(!outcomes.has(row.outcome))errors.push(`OUTCOME_ENUM:${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')errors.push(`CLAIM_UPGRADE:${row.candidate_id}`);if(row.formal_pool_effect!=='NO_AUTOMATIC_FORMAL_POOL_CHANGE')errors.push(`POOL_UPGRADE:${row.candidate_id}`);if(row.evidence_strength_effect!=='NO_UPGRADE')errors.push(`EVIDENCE_UPGRADE:${row.candidate_id}`);}for(const row of state.applications){if(row.output_mutation!=='NONE')errors.push(`OUTPUT_MUTATION:${row.target_id}`);if(row.gap_state_after!=='OPEN_RETAINED_GAP')errors.push(`APPLICATION_GAP_CLOSED:${row.target_id}`);}return[...new Set(errors)];}
function expectedState(){const candidates=clone(readCsv(CANDIDATES).rows),provenance=clone(readCsv(PROVENANCE).rows),criteria=clone(criteriaRows()),decisions=clone(decisionRows(candidates)),derived=deriveOutputs(decisions);return{candidates,provenance,criteria,decisions,summary:clone(derived.summary),applications:clone(derived.applications)};}
 
export function designInputErrors({requireRelease=false,expectNoExecution=true}={}){const errors=[...sourceAuditErrors(),...releaseErrors({required:requireRelease}),...formalEntryErrors(),...discovery.validateExecution()];for(const file of [CANDIDATES,PROVENANCE,RAW_ARCHIVE,TARGET_AUTHORITY,GAP_AUTHORITY,CRITERIA,DECISION_AUTHORITY,CONTRACT,SCHEMA,EXEC_SET])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'),...compareRows(criteria.rows,criteriaRows(),CRITERIA_COLUMNS,'CRITERIA'),...exactColumns(decisions,DECISION_COLUMNS,'DECISION'),...compareRows(decisions.rows,decisionRows(),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'));
  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:'P0SEM-BASE-001',identity_type:'SOURCE_EXECUTION_AUDIT_ENTRY',artifact_path:`${AUDIT_REPORT}#L${source.start}-L${source.end}`,rows:String(source.lines),bytes:String(source.bytes),sha256:source.sha256,mtime:'INFO_APPENDABLE_SHARED_FILE',required_state:'EXACT_SOURCE_PASS_AND_DESIGN_PREPARATION_ALLOWED'},{baseline_id:'P0SEM-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:'P0SEM-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,11).map(row=>row.artifact_path)){const id=identity(file);rows.push({baseline_id:`P0SEM-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:`P0SEM-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!==63)return[`BASELINE_COUNT:${rows.length}:63`];const source=auditEntry(SOURCE_AUDIT),release=auditEntry(RELEASE_AUDIT);for(const [row,entry,code] of [[rows[0],source,'SOURCE'],[rows[1],release,'RELEASE']])if(!entry||row.rows!==String(entry.lines)||row.bytes!==String(entry.bytes)||row.sha256!==entry.sha256)errors.push(`BASELINE_${code}_AUDIT`);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`# P0 一手来源候选语义资格审定执行复审请求\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\ncandidate_outcome_ceiling=QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE\nqualification_rows=14\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)],['CANDIDATES','14',String(state.candidates.length)],['PROVENANCE','14',String(state.provenance.length)],['CRITERIA','7',String(state.criteria.length)],['QUALIFICATION','14',String(state.decisions.length)],['QUALIFIED','7',String(state.decisions.filter(row=>row.outcome==='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW').length)],['CONTEXT_ONLY','7',String(state.decisions.filter(row=>row.outcome==='CONTEXT_ONLY_NOT_GAP_CLOSING').length)],['REJECT','0',String(state.decisions.filter(row=>row.outcome==='REJECT_NOT_DIRECT').length)],['HELD','0',String(state.decisions.filter(row=>row.outcome==='HELD_LOCATOR_OR_IDENTITY').length)],['SUMMARY','7',String(state.summary.length)],['APPLICATION','10',String(state.applications.length)],['OPEN_GAPS','14',String(state.decisions.filter(row=>row.gap_state_after==='OPEN_RETAINED_GAP').length)],['CLAIM_CEILING','14',String(state.decisions.filter(row=>row.claim_strength_after==='PENDING_VERIFICATION_MAX_NO_UPGRADE').length)],['POOL_BOUNDARY','14',String(state.decisions.filter(row=>row.formal_pool_effect==='NO_AUTOMATIC_FORMAL_POOL_CHANGE').length)],['EVIDENCE_BOUNDARY','14',String(state.decisions.filter(row=>row.evidence_strength_effect==='NO_UPGRADE').length)],['OUTPUT_MUTATION','0',String(state.applications.filter(row=>row.output_mutation!=='NONE').length)],['EXACT_SET','17',String(executionSetRows().length)]];const rows=checks.map((item,index)=>({check_id:`P0SEM-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:'SHARED_FAIL_CLOSED_SEMANTIC_ORACLE'}));rows.push({check_id:'P0SEM-EXEC-VAL-018',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 state=expectedState();write(QUALIFICATION,serializeCsv(state.decisions,DECISION_COLUMNS));write(GAP_SUMMARY,serializeCsv(state.summary,SUMMARY_COLUMNS));write(APPLICATION,serializeCsv(state.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')]),stateManifest=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:17});if(stateManifest.errors.length)throw new Error(`MANIFEST_CANDIDATE:${stateManifest.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',qualification_rows:14,qualified:7,context_only:7,gap_summary_rows:7,application_rows:10,manifest_rows:17};}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),qualification=readCsv(QUALIFICATION),summary=readCsv(GAP_SUMMARY),applications=readCsv(APPLICATION),validation=readCsv(EXEC_VALIDATION),state={candidates:readCsv(CANDIDATES).rows,provenance:readCsv(PROVENANCE).rows,criteria:readCsv(CRITERIA).rows,decisions:qualification.rows,summary:summary.rows,applications:applications.rows};errors.push(...exactColumns(baseline,BASELINE_COLUMNS,'BASELINE'),...baselineErrors(baseline.rows),...exactColumns(qualification,DECISION_COLUMNS,'QUALIFICATION'),...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');if(validation.rows.length!==18||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:17});errors.push(...manifest.errors.map(code=>`MANIFEST:${code}`));return[...new Set(errors)];}
 
export function negativeRows(){const base=expectedState(),tests=[];const add=(name,mutate,expectedCode)=>{const state=clone(base);mutate(state);const errors=coreErrors(state);tests.push({test_id:`P0SEM-NEG-${String(tests.length+1).padStart(3,'0')}-${name}`,mutation_applied:name==='CLEAN'?'NO_CLEAN_CONTROL':'YES',oracle:'coreErrors',expected:name==='CLEAN'?'ACCEPT':'REJECT',expected_code:expectedCode,actual:errors.length?'REJECT':'ACCEPT',actual_codes:errors.join('|')||'NONE',result:(name==='CLEAN'?!errors.length:errors.some(code=>code.startsWith(expectedCode)))?'PASS':'FAIL'});};
  add('CLEAN',()=>{},'NONE');
  add('CANDIDATE_SWAP',s=>{[s.candidates[0],s.candidates[1]]=[s.candidates[1],s.candidates[0]];},'CANDIDATE_FIELD');
  add('CANDIDATE_SNIPPET_HASH',s=>{s.candidates[0].snippet_text_sha256='0'.repeat(64);},'CANDIDATE_FIELD');
  add('CANDIDATE_LOCATOR',s=>{s.candidates[0].content_locator='WRONG';},'CANDIDATE_FIELD');
  add('CANDIDATE_SOURCE_CLASS',s=>{s.candidates[0].source_class='WRONG';},'CANDIDATE_FIELD');
  add('PROVENANCE_URL',s=>{s.provenance[0].canonical_url='https://invalid.example';},'PROVENANCE_FIELD');
  add('PROVENANCE_HASH',s=>{s.provenance[0].snippet_text_sha256='0'.repeat(64);},'PROVENANCE_FIELD');
  add('CRITERION_RULE',s=>{s.criteria[0].qualified_rule='OFFICIALITY_ONLY';},'CRITERIA_FIELD');
  add('DECISION_CRITERION',s=>{s.decisions[0].criterion_id='WRONG';},'DECISION_FIELD');
  add('CONTEXT_TO_QUALIFIED',s=>{s.decisions[1].outcome='QUALIFIED_PRIMARY_CANDIDATE_PENDING_EVIDENCE_REVIEW';},'DECISION_FIELD');
  add('QUALIFIED_TO_CONTEXT',s=>{s.decisions[0].outcome='CONTEXT_ONLY_NOT_GAP_CLOSING';},'DECISION_FIELD');
  add('GAP_CLOSE',s=>{s.decisions[0].gap_state_after='CLOSED';},'DECISION_FIELD');
  add('CLAIM_UPGRADE',s=>{s.decisions[0].claim_strength_after='CONFIRMED';},'DECISION_FIELD');
  add('POOL_UPGRADE',s=>{s.decisions[0].formal_pool_effect='FORMAL_POOL_CHANGE';},'DECISION_FIELD');
  add('EVIDENCE_UPGRADE',s=>{s.decisions[0].evidence_strength_effect='UPGRADE';},'DECISION_FIELD');
  add('DECISION_MISSING',s=>{s.decisions.pop();},'DECISION_COUNT');
  add('SUMMARY_OFFSET',s=>{s.summary[0].qualified_count=String(Number(s.summary[0].qualified_count)+1);s.summary[1].qualified_count=String(Math.max(0,Number(s.summary[1].qualified_count)-1));},'SUMMARY_FIELD');
  add('APPLICATION_CLOSE',s=>{s.applications[0].action='CLOSE_GAP';s.applications[0].gap_state_after='CLOSED';},'APPLICATION_FIELD');
  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','candidate_outcome_ceiling=QUALIFICATION_ONLY_NO_EVIDENCE_ACCEPTANCE'].join('\n');for(const [name,text,code] of [['RELEASE_FAIL_SUBSTRING',`result=FAIL\nnotes=${good.replace(/\n/g,' ')}`,'RELEASE_MARKER'],['RELEASE_WRONG_BATCH',good.replace(EXEC_BATCH,'WRONG-BATCH'),'RELEASE_MARKER']]){const errors=releaseTextErrors(text);tests.push({test_id:`P0SEM-NEG-${String(tests.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 tests;}
 
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){const mode=process.argv[2]??'--preview',token=process.argv.find(value=>value.startsWith('--token='))?.slice(8);if(mode==='--preview'){const state=expectedState(),errors=coreErrors(state);console.log(JSON.stringify({status:errors.length?'FAIL':'PREVIEW_PASS',candidates:state.candidates.length,criteria:state.criteria.length,qualified:state.decisions.filter(row=>row.outcome.startsWith('QUALIFIED_')).length,context_only:state.decisions.filter(row=>row.outcome.startsWith('CONTEXT_')).length,summary:state.summary.length,applications:state.applications.length,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}`);}