Cai
2026-08-09 9d2e633b4345c7e2e4764fb3d7a88e5277e64943
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {pathToFileURL} from 'node:url';
import {
  MANIFEST_COLUMNS,
  hashBuffer,
  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 MANIFEST = `${BASE}/manifest/artifact_manifest.csv`;
export const ANOMALY_AUTHORITY = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_anomaly_authority_repair001_20260730.csv`;
export const ORIGINAL_TRIAGE_RUN = 'RUN-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-001';
export const DESIGN_RUN = 'RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-DESIGN-001';
export const DESIGN_BATCH = 'BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-DESIGN-001';
export const EXEC_RUN = 'RUN-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-001';
export const EXEC_BATCH = 'BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-001';
export const RELEASE_AUDIT = 'AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-P0-PRIMARY-SOURCE-DISCOVERY-DESIGN-REREVIEW-001';
export const EXEC_TOKEN = 'EXECUTE_DETAIL_STRENGTHENING_P0_PRIMARY_SOURCE_DISCOVERY001';
 
export const SCRIPT = 'dev/ana-dev/detail_strengthening_p0_primary_source_discovery_runtime_20260730.mjs';
export const TARGET_AUTHORITY = `${BASE}/evidence/detail_strengthening_p0_primary_source_target_authority_20260730.csv`;
export const GAP_AUTHORITY = `${BASE}/evidence/detail_strengthening_p0_conceptual_gap_authority_20260730.csv`;
export const QUERY_AUTHORITY = `${BASE}/evidence/detail_strengthening_p0_primary_source_query_authority_20260730.csv`;
export const SOURCE_POLICY = `${BASE}/evidence/detail_strengthening_p0_primary_source_policy_20260730.csv`;
export const CONTRACT = `${BASE}/evidence/detail_strengthening_p0_primary_source_discovery_runtime_contract_20260730.csv`;
export const SCHEMA = `${BASE}/evidence/detail_strengthening_p0_primary_source_discovery_schema_authority_20260730.csv`;
export const EXEC_SET = `${BASE}/manifest/detail_strengthening_p0_primary_source_discovery_execution_artifact_set_20260730.csv`;
export const EXEC_BASELINE = `${BASE}/evidence/detail_strengthening_p0_primary_source_discovery_execution_baseline_20260730.csv`;
export const QUERY_LEDGER = `${BASE}/evidence/detail_strengthening_p0_primary_source_query_execution_ledger_20260730.csv`;
export const CANDIDATE_REGISTER = `${BASE}/evidence/detail_strengthening_p0_primary_source_candidate_register_20260730.csv`;
export const OCCURRENCE_DISPOSITION = `${BASE}/evidence/detail_strengthening_p0_primary_source_occurrence_disposition_20260730.csv`;
export const GAP_SUMMARY = `${BASE}/outputs/数据表/robot_detail_p0_primary_source_discovery_summary_v01_20260730.csv`;
export const APPLICATION = `${BASE}/evidence/detail_strengthening_p0_primary_source_discovery_application_20260730.csv`;
export const EXEC_REQUEST = `${BASE}/manifest/review_request_detail_strengthening_p0_primary_source_discovery_execution_20260730.md`;
export const EXEC_VALIDATION = `${BASE}/manifest/detail_strengthening_p0_primary_source_discovery_execution_validation_20260730.csv`;
 
export const TARGET_COLUMNS = ['target_id','triage_id','detail_item_id','source_authority_id','source_row_id','source_occurrence_key','conceptual_gap_key','object_type','object_id','priority','workstream','current_status','required_evidence_or_next_action','claim_strength_ceiling','formal_pool_effect','evidence_strength_effect','discovery_effect'];
export const GAP_COLUMNS = ['gap_id','conceptual_gap_key','occurrence_count','source_occurrence_keys','object_ids','source_classes_required','query_ids','candidate_cap','gap_state_before','gap_state_after_discovery','claim_strength_ceiling','formal_pool_effect','evidence_strength_effect'];
export const QUERY_COLUMNS = ['query_id','conceptual_gap_key','query_language','query_text','required_source_class','domain_policy_id','result_inspection_cap','candidate_capture_cap','secondary_source_policy','execution_order'];
export const POLICY_COLUMNS = ['policy_id','policy_type','allowed_value','required_condition','forbidden_condition','failure_disposition'];
export const CONTRACT_COLUMNS = ['contract_id','scope','field','required_value_or_rule','violation_status'];
export const SCHEMA_COLUMNS = ['schema_id','artifact_role','artifact_path','column_order','primary_key','row_count_rule','serialization','derivation_rule','required_boundary'];
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 QUERY_LEDGER_COLUMNS = ['query_execution_id','query_id','conceptual_gap_key','query_text_sha256','searched_at','result_count_inspected','candidate_count_captured','execution_status','tool_boundary','gap_effect'];
export const CANDIDATE_COLUMNS = ['candidate_id','query_id','conceptual_gap_key','canonical_url','source_domain','source_class','publisher','title','publication_date','access_status','primary_source_status','relevance_status','content_locator','snippet_text','snippet_text_sha256','discovered_at','candidate_disposition','gap_effect','claim_strength_after','formal_pool_effect','evidence_strength_effect','review_state'];
export const DISPOSITION_COLUMNS = ['disposition_id','target_id','source_occurrence_key','conceptual_gap_key','candidate_count','primary_confirmed_count','primary_pending_count','result','gap_state_after','claim_strength_after','formal_pool_effect','evidence_strength_effect','required_next_action'];
export const SUMMARY_COLUMNS = ['summary_id','conceptual_gap_key','source_occurrences','queries_executed','candidates_captured','primary_confirmed','primary_pending','result','gap_state_after','claim_strength_ceiling','formal_pool_effect','evidence_strength_effect'];
export const APPLICATION_COLUMNS = ['application_id','target_id','conceptual_gap_key','source_occurrence_key','candidate_ids','application_action','application_result','gap_effect','claim_strength_effect','formal_pool_effect','evidence_strength_effect','review_status'];
export const VALIDATION_COLUMNS = ['check_id','check_description','expected','actual','status','evidence'];
 
export const abs = value => path.join(ROOT, ...value.split('/'));
export const sha = value => crypto.createHash('sha256').update(value).digest('hex');
export const normalizeText = value => value.toString('utf8').replace(/^\uFEFF/, '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
export const lineCount = value => {
  const text = normalizeText(value);
  return text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
};
export function readCsv(file) {
  const parsed = parseAuthorityCsv(normalizeText(fs.readFileSync(abs(file))));
  if (parsed.errors.length) throw new Error(`CSV_PARSE:${file}:${parsed.errors.join('|')}`);
  return parsed;
}
export function fileIdentity(file) {
  const buffer = fs.readFileSync(abs(file));
  const stat = fs.statSync(abs(file));
  return {
    rows: file.endsWith('.csv') ? readCsv(file).rows.length : lineCount(buffer),
    lines: lineCount(buffer),
    bytes: buffer.length,
    sha256: sha(buffer),
    mtime: new Date(Math.trunc(stat.mtimeMs)).toISOString(),
    mtimeMs: Math.trunc(stat.mtimeMs),
  };
}
 
export function auditEntry(auditId) {
  const lines = normalizeText(fs.readFileSync(abs(AUDIT_REPORT))).split('\n');
  const start = lines.findIndex(line => line.startsWith('### ') && line.includes(auditId));
  if (start < 0) return null;
  let end = lines.length;
  for (let index = start + 1; index < lines.length; index++) {
    if (lines[index].startsWith('### ')) { end = index; break; }
  }
  while (end > start && lines[end - 1] === '') end--;
  const buffer = Buffer.from(`${lines.slice(start, end).join('\n')}\n`, 'utf8');
  return { start: start + 1, end, lines: end - start, bytes: buffer.length, sha256: sha(buffer), text: buffer.toString('utf8') };
}
 
export function releaseErrors({ requireRelease = true } = {}) {
  const entry = auditEntry(RELEASE_AUDIT);
  if (!entry) return requireRelease ? ['RELEASE_AUDIT_MISSING'] : [];
  const required = [
    'result=PASS',
    'execution_release=EXPLICITLY_RELEASED',
    `released_batch_id=${EXEC_BATCH}`,
    `released_run_id=${EXEC_RUN}`,
    'network_execution_scope=PUBLIC_WEB_PRIMARY_SOURCE_DISCOVERY_ONLY',
  ];
  const errors = [];
  for (const marker of required) if (!entry.text.split('\n').some(line => line.trim().replace(/^[\-*]\s*/, '').replace(/`/g, '') === marker)) errors.push(`RELEASE_MARKER:${marker}`);
  if (/(?:result|conclusion)=FAIL|execution_release=NOT_ALLOWED|NOT_RELEASED/.test(entry.text)) errors.push('RELEASE_CONTRADICTION');
  return errors;
}
 
export function authorityBundle() {
  return {
    targets: readCsv(TARGET_AUTHORITY).rows,
    gaps: readCsv(GAP_AUTHORITY).rows,
    queries: readCsv(QUERY_AUTHORITY).rows,
    policies: readCsv(SOURCE_POLICY).rows,
    contracts: readCsv(CONTRACT).rows,
    schemas: readCsv(SCHEMA).rows,
    executionSet: readCsv(EXEC_SET).rows,
  };
}
 
function exactColumns(parsed, expected, code) {
  return parsed.header.join('|') === expected.join('|') ? [] : [`${code}_COLUMNS`];
}
const integer = value => /^(0|[1-9][0-9]*)$/.test(String(value));
const iso = value => /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(String(value)) && Number.isFinite(Date.parse(value));
const canonicalUrl = value => {
  try {
    const url = new URL(value);
    url.hash = '';
    for (const key of [...url.searchParams.keys()]) if (/^(utm_|spm$|source$|from$)/i.test(key)) url.searchParams.delete(key);
    url.hostname = url.hostname.toLowerCase();
    if (url.pathname.length > 1) url.pathname = url.pathname.replace(/\/+$/, '');
    return url.toString();
  } catch { return ''; }
};
 
export function validateStaging(queryLedger, candidates, bundle = authorityBundle()) {
  const errors = [];
  const queryById = new Map(bundle.queries.map(row => [row.query_id, row]));
  const gapByKey = new Map(bundle.gaps.map(row => [row.conceptual_gap_key, row]));
  if (bundle.targets.length !== 10 || new Set(bundle.targets.map(row => row.target_id)).size !== 10) errors.push('TARGET_AUTHORITY_COUNT');
  if (bundle.gaps.length !== 7 || new Set(bundle.gaps.map(row => row.conceptual_gap_key)).size !== 7) errors.push('GAP_AUTHORITY_COUNT');
  if (bundle.queries.length !== 14 || new Set(bundle.queries.map(row => row.query_id)).size !== 14) errors.push('QUERY_AUTHORITY_COUNT');
  if (queryLedger.length !== 14 || new Set(queryLedger.map(row => row.query_id)).size !== 14) errors.push(`QUERY_LEDGER_SET:${queryLedger.length}:${new Set(queryLedger.map(row => row.query_id)).size}`);
  const ledgerByQuery = new Map(queryLedger.map(row => [row.query_id, row]));
  for (const query of bundle.queries) {
    const row = ledgerByQuery.get(query.query_id);
    if (!row) { errors.push(`QUERY_LEDGER_MISSING:${query.query_id}`); continue; }
    if (row.conceptual_gap_key !== query.conceptual_gap_key) errors.push(`QUERY_LEDGER_GAP:${query.query_id}`);
    if (row.query_text_sha256 !== sha(Buffer.from(query.query_text, 'utf8'))) errors.push(`QUERY_LEDGER_TEXT_HASH:${query.query_id}`);
    if (!iso(row.searched_at)) errors.push(`QUERY_LEDGER_TIME:${query.query_id}`);
    if (!integer(row.result_count_inspected) || Number(row.result_count_inspected) > Number(query.result_inspection_cap)) errors.push(`QUERY_LEDGER_RESULT_COUNT:${query.query_id}`);
    if (!integer(row.candidate_count_captured)) errors.push(`QUERY_LEDGER_CANDIDATE_COUNT:${query.query_id}`);
    if (!['COMPLETED_WITH_CANDIDATES','COMPLETED_NO_PRIMARY_CANDIDATE','ACCESS_BLOCKED'].includes(row.execution_status)) errors.push(`QUERY_LEDGER_STATUS:${query.query_id}`);
    if (row.tool_boundary !== 'PUBLIC_WEB_READ_ONLY_NO_LOGIN_NO_PAYWALL_BYPASS') errors.push(`QUERY_LEDGER_TOOL_BOUNDARY:${query.query_id}`);
    if (row.gap_effect !== 'DISCOVERY_ONLY_GAP_REMAINS_OPEN') errors.push(`QUERY_LEDGER_GAP_EFFECT:${query.query_id}`);
  }
  const candidateIds = new Set();
  const gapCounts = new Map();
  const queryCounts = new Map();
  const urlGapKeys = new Set();
  const allowedClasses = new Set(['OFFICIAL_INDUSTRY_BODY_OR_REPORT_PUBLISHER','EXCHANGE_OR_REGULATOR_FILING','COMPANY_IR_OR_ANNUAL_REPORT','OFFICIAL_PRODUCT_OR_TECHNICAL_DOCUMENT','OFFICIAL_CONTRACT_TENDER_OR_CUSTOMER_NOTICE','OFFICIAL_DATASET_OR_STATISTICAL_RELEASE']);
  for (const row of candidates) {
    if (!row.candidate_id || candidateIds.has(row.candidate_id)) errors.push(`CANDIDATE_ID:${row.candidate_id}`);
    candidateIds.add(row.candidate_id);
    const query = queryById.get(row.query_id);
    if (!query) { errors.push(`CANDIDATE_QUERY:${row.candidate_id}`); continue; }
    if (row.conceptual_gap_key !== query.conceptual_gap_key) errors.push(`CANDIDATE_GAP:${row.candidate_id}`);
    const normalized = canonicalUrl(row.canonical_url);
    if (!normalized || normalized !== row.canonical_url) errors.push(`CANDIDATE_CANONICAL_URL:${row.candidate_id}`);
    let domain = '';
    try { domain = new URL(row.canonical_url).hostname.toLowerCase(); } catch {}
    if (domain !== row.source_domain.toLowerCase()) errors.push(`CANDIDATE_DOMAIN:${row.candidate_id}`);
    if (!allowedClasses.has(row.source_class)) errors.push(`CANDIDATE_SOURCE_CLASS:${row.candidate_id}`);
    if (!['AVAILABLE','PARTIAL_PREVIEW','ACCESS_BLOCKED'].includes(row.access_status)) errors.push(`CANDIDATE_ACCESS:${row.candidate_id}`);
    if (!['PRIMARY_CONFIRMED','PRIMARY_CANDIDATE_NEEDS_REVIEW'].includes(row.primary_source_status)) errors.push(`CANDIDATE_PRIMARY_STATUS:${row.candidate_id}`);
    if (!['DIRECT','POTENTIALLY_DIRECT'].includes(row.relevance_status)) errors.push(`CANDIDATE_RELEVANCE:${row.candidate_id}`);
    if (!row.publisher || !row.title || !row.content_locator) errors.push(`CANDIDATE_REQUIRED_TEXT:${row.candidate_id}`);
    if (Buffer.byteLength(row.snippet_text, 'utf8') > 800) errors.push(`CANDIDATE_SNIPPET_LIMIT:${row.candidate_id}`);
    if (row.snippet_text_sha256 !== sha(Buffer.from(row.snippet_text, 'utf8'))) errors.push(`CANDIDATE_SNIPPET_HASH:${row.candidate_id}`);
    if (!iso(row.discovered_at)) errors.push(`CANDIDATE_TIME:${row.candidate_id}`);
    if (row.candidate_disposition !== 'CANDIDATE_CAPTURED_PENDING_INDEPENDENT_SEMANTIC_REVIEW') errors.push(`CANDIDATE_DISPOSITION:${row.candidate_id}`);
    if (row.gap_effect !== 'DISCOVERY_ONLY_GAP_REMAINS_OPEN') errors.push(`CANDIDATE_GAP_EFFECT:${row.candidate_id}`);
    if (row.claim_strength_after !== 'PENDING_VERIFICATION_MAX_NO_UPGRADE') errors.push(`CANDIDATE_STRENGTH:${row.candidate_id}`);
    if (row.formal_pool_effect !== 'NO_AUTOMATIC_FORMAL_POOL_CHANGE') errors.push(`CANDIDATE_POOL:${row.candidate_id}`);
    if (row.evidence_strength_effect !== 'NO_UPGRADE') errors.push(`CANDIDATE_EVIDENCE_EFFECT:${row.candidate_id}`);
    if (row.review_state !== 'PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW') errors.push(`CANDIDATE_REVIEW_STATE:${row.candidate_id}`);
    const urlGap = `${row.conceptual_gap_key}|${row.canonical_url}`;
    if (urlGapKeys.has(urlGap)) errors.push(`CANDIDATE_DUPLICATE_URL_GAP:${row.candidate_id}`);
    urlGapKeys.add(urlGap);
    gapCounts.set(row.conceptual_gap_key, (gapCounts.get(row.conceptual_gap_key) ?? 0) + 1);
    queryCounts.set(row.query_id, (queryCounts.get(row.query_id) ?? 0) + 1);
  }
  for (const [gapKey, count] of gapCounts) {
    const cap = Number(gapByKey.get(gapKey)?.candidate_cap ?? -1);
    if (count > cap) errors.push(`GAP_CANDIDATE_CAP:${gapKey}:${count}:${cap}`);
  }
  for (const query of bundle.queries) {
    const actual = queryCounts.get(query.query_id) ?? 0;
    const ledger = ledgerByQuery.get(query.query_id);
    if (ledger && Number(ledger.candidate_count_captured) !== actual) errors.push(`QUERY_CANDIDATE_COUNT_MISMATCH:${query.query_id}:${ledger.candidate_count_captured}:${actual}`);
    if (actual > Number(query.candidate_capture_cap)) errors.push(`QUERY_CANDIDATE_CAP:${query.query_id}:${actual}`);
    if (ledger?.execution_status === 'COMPLETED_WITH_CANDIDATES' && actual === 0) errors.push(`QUERY_STATUS_WITHOUT_CANDIDATE:${query.query_id}`);
    if (ledger && ledger.execution_status !== 'COMPLETED_WITH_CANDIDATES' && actual !== 0) errors.push(`QUERY_CANDIDATE_WITH_NONCANDIDATE_STATUS:${query.query_id}`);
  }
  return [...new Set(errors)];
}
 
export function deriveOutputs(queryLedger, candidates, bundle = authorityBundle()) {
  const candidateByGap = new Map();
  for (const row of candidates) {
    if (!candidateByGap.has(row.conceptual_gap_key)) candidateByGap.set(row.conceptual_gap_key, []);
    candidateByGap.get(row.conceptual_gap_key).push(row);
  }
  const dispositions = bundle.targets.map((target, index) => {
    const rows = candidateByGap.get(target.conceptual_gap_key) ?? [];
    const confirmed = rows.filter(row => row.primary_source_status === 'PRIMARY_CONFIRMED').length;
    const pending = rows.filter(row => row.primary_source_status === 'PRIMARY_CANDIDATE_NEEDS_REVIEW').length;
    return {
      disposition_id: `P0DISC-DISP-${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,
      candidate_count: String(rows.length),
      primary_confirmed_count: String(confirmed),
      primary_pending_count: String(pending),
      result: rows.length ? 'CANDIDATES_FOUND_PENDING_SEMANTIC_REVIEW' : 'NO_PRIMARY_CANDIDATE_FOUND_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',
      required_next_action: rows.length ? 'INDEPENDENT_SOURCE_AND_SEMANTIC_REVIEW_BEFORE_ANY_GAP_EFFECT' : target.required_evidence_or_next_action,
    };
  });
  const summary = bundle.gaps.map((gap, index) => {
    const targets = bundle.targets.filter(row => row.conceptual_gap_key === gap.conceptual_gap_key);
    const queries = queryLedger.filter(row => row.conceptual_gap_key === gap.conceptual_gap_key);
    const rows = candidateByGap.get(gap.conceptual_gap_key) ?? [];
    return {
      summary_id: `P0DISC-SUM-${String(index + 1).padStart(3, '0')}`,
      conceptual_gap_key: gap.conceptual_gap_key,
      source_occurrences: String(targets.length),
      queries_executed: String(queries.length),
      candidates_captured: String(rows.length),
      primary_confirmed: String(rows.filter(row => row.primary_source_status === 'PRIMARY_CONFIRMED').length),
      primary_pending: String(rows.filter(row => row.primary_source_status === 'PRIMARY_CANDIDATE_NEEDS_REVIEW').length),
      result: rows.length ? 'CANDIDATE_SET_READY_FOR_INDEPENDENT_REVIEW' : 'NO_CANDIDATE_RETAINED_GAP',
      gap_state_after: '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 applications = dispositions.map((row, index) => {
    const ids = (candidateByGap.get(row.conceptual_gap_key) ?? []).map(item => item.candidate_id).sort();
    return {
      application_id: `P0DISC-APP-${String(index + 1).padStart(3, '0')}`,
      target_id: row.target_id,
      conceptual_gap_key: row.conceptual_gap_key,
      source_occurrence_key: row.source_occurrence_key,
      candidate_ids: ids.join('|'),
      application_action: ids.length ? 'REGISTER_CANDIDATES_FOR_REVIEW_ONLY' : 'REGISTER_NO_CANDIDATE_RETAIN_GAP',
      application_result: 'NO_GAP_CLOSURE_NO_OUTPUT_MUTATION',
      gap_effect: 'OPEN_RETAINED_GAP',
      claim_strength_effect: 'PENDING_VERIFICATION_MAX_NO_UPGRADE',
      formal_pool_effect: 'NO_AUTOMATIC_FORMAL_POOL_CHANGE',
      evidence_strength_effect: 'NO_UPGRADE',
      review_status: 'PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW',
    };
  });
  return { dispositions, summary, applications };
}
 
export function bundleErrors({ queryLedger, candidates, dispositions, summary, applications }, bundle = authorityBundle()) {
  const errors = [...validateStaging(queryLedger, candidates, bundle)];
  const expected = deriveOutputs(queryLedger, candidates, bundle);
  const compare = (actual, wanted, columns, code) => {
    if (actual.length !== wanted.length) { errors.push(`${code}_COUNT:${actual.length}:${wanted.length}`); return; }
    for (let index = 0; index < wanted.length; index++) {
      if (columns.some(column => String(actual[index]?.[column] ?? '') !== String(wanted[index]?.[column] ?? ''))) {
        errors.push(`${code}_ROW:${index + 1}`);
        break;
      }
    }
  };
  compare(dispositions, expected.dispositions, DISPOSITION_COLUMNS, 'DISPOSITION');
  compare(summary, expected.summary, SUMMARY_COLUMNS, 'SUMMARY');
  compare(applications, expected.applications, APPLICATION_COLUMNS, 'APPLICATION');
  return [...new Set(errors)];
}
 
export function contractRows() {
  const rows = [
    ['RELEASE','AUDIT','exact PASS + exact execution_release/batch/run/network scope'],
    ['SCOPE','TARGETS','10 exact P0 source occurrences'],
    ['SCOPE','CONCEPTUAL_GAPS','7 exact conceptual gaps'],
    ['SCOPE','QUERIES','14 exact query rows; two per conceptual gap'],
    ['NETWORK','BOUNDARY','PUBLIC_WEB_READ_ONLY_NO_LOGIN_NO_PAYWALL_BYPASS'],
    ['NETWORK','DISCOVERY_ONLY','no content purchase; no credential; no form submission'],
    ['SOURCE','PRIMARY_CLASSES','six enumerated official primary-source classes only'],
    ['SOURCE','SECONDARY','search lead only; never captured as accepted candidate'],
    ['QUERY_LEDGER','PK','query_execution_id unique and query_id bijective with authority'],
    ['QUERY_LEDGER','COUNTS','result and candidate counts exact; caps enforced'],
    ['CANDIDATE','PK','candidate_id unique'],
    ['CANDIDATE','URL','canonical HTTPS/HTTP URL; domain exact; per-gap URL unique'],
    ['CANDIDATE','TEXT','publisher/title/locator required; snippet <=800 UTF-8 bytes; exact hash'],
    ['CANDIDATE','STATE','PRIMARY_CONFIRMED or PRIMARY_CANDIDATE_NEEDS_REVIEW only'],
    ['CANDIDATE','CAP','maximum five candidates per conceptual gap'],
    ['DERIVATION','OCCURRENCE','exact 10 rows from target authority and candidate-by-gap counts'],
    ['DERIVATION','SUMMARY','exact 7 rows from gap authority/query ledger/candidate register'],
    ['DERIVATION','APPLICATION','exact 10 rows from occurrence and candidate IDs'],
    ['GAP','EFFECT','OPEN_RETAINED_GAP for every target and gap'],
    ['CLAIM','CEILING','PENDING_VERIFICATION_MAX_NO_UPGRADE'],
    ['POOL','EFFECT','NO_AUTOMATIC_FORMAL_POOL_CHANGE'],
    ['EVIDENCE','EFFECT','NO_UPGRADE'],
    ['OUTPUT','MUTATION','NO_BUSINESS_OUTPUT_MUTATION'],
    ['EXECUTION','BASELINE','baseline first generated output after release and staging validation'],
    ['EXECUTION','VALIDATION','validation last generated output'],
    ['EXECUTION','EXACT_SET','16 unique paths in order1..16'],
    ['MANIFEST','ANOMALY','L1605 sole enumerated non-data header retained'],
    ['MANIFEST','APPEND','data rows only; no header; exact sixteen-row delta'],
    ['MANIFEST','SEVEN_FIELDS','case/run/batch/path/hash/bytes/filesystem-ms-mtime exact'],
    ['MANIFEST','TRANSACTION','candidate validate; append; postvalidate; rollback on failure'],
    ['REVIEW','STATE','PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW'],
    ['REVIEW','NEXT_GATE','candidate source and semantic review required before any gap effect'],
  ];
  return rows.map((row, index) => ({ contract_id: `P0DISC-CON-${String(index + 1).padStart(3, '0')}`, scope: row[0], field: row[1], required_value_or_rule: row[2], violation_status: 'FAIL_CLOSED_OR_HELD' }));
}
 
export function schemaRows() {
  const rows = [
    ['EXECUTION_BASELINE', EXEC_BASELINE, BASELINE_COLUMNS, 'baseline_id', 'dynamic_12_or_more', 'frozen identities and release/prewrite state', 'BASELINE_FIRST'],
    ['QUERY_EXECUTION_LEDGER', QUERY_LEDGER, QUERY_LEDGER_COLUMNS, 'query_execution_id', 'exact14', 'exact query authority execution records', 'DISCOVERY_ONLY_GAP_REMAINS_OPEN'],
    ['CANDIDATE_REGISTER', CANDIDATE_REGISTER, CANDIDATE_COLUMNS, 'candidate_id', '0_to_35', 'validated public-web primary-source candidates', 'DISCOVERY_ONLY_GAP_REMAINS_OPEN'],
    ['OCCURRENCE_DISPOSITION', OCCURRENCE_DISPOSITION, DISPOSITION_COLUMNS, 'disposition_id', 'exact10', 'deterministic from target+candidate-by-gap', 'OPEN_RETAINED_GAP'],
    ['GAP_SUMMARY', GAP_SUMMARY, SUMMARY_COLUMNS, 'summary_id', 'exact7', 'deterministic from gap+query+candidate', 'OPEN_RETAINED_GAP'],
    ['APPLICATION', APPLICATION, APPLICATION_COLUMNS, 'application_id', 'exact10', 'deterministic review-only application', 'NO_GAP_CLOSURE_NO_OUTPUT_MUTATION'],
    ['EXECUTION_REQUEST', EXEC_REQUEST, ['MARKDOWN_UTF8_NO_BOM_LF'], 'NOT_APPLICABLE', 'exact_one_file', 'frozen request text', 'NO_UPGRADE'],
    ['EXECUTION_VALIDATION', EXEC_VALIDATION, VALIDATION_COLUMNS, 'check_id', 'exact18', 'fail-closed execution oracle', 'VALIDATION_LAST'],
  ];
  return rows.map((row, index) => ({ schema_id: `P0DISC-SCHEMA-${String(index + 1).padStart(3, '0')}`, artifact_role: row[0], artifact_path: row[1], column_order: row[2].join('|'), primary_key: row[3], row_count_rule: row[4], serialization: row[0] === 'EXECUTION_REQUEST' ? 'UTF8_NO_BOM_LF_MARKDOWN' : 'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_CSV', derivation_rule: row[5], required_boundary: row[6] }));
}
 
export function executionSetRows() {
  const paths = [SCRIPT,TARGET_AUTHORITY,GAP_AUTHORITY,QUERY_AUTHORITY,SOURCE_POLICY,CONTRACT,SCHEMA,EXEC_SET,EXEC_BASELINE,QUERY_LEDGER,CANDIDATE_REGISTER,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
  const roles = ['RUNTIME_GENERATOR','TARGET_AUTHORITY','GAP_AUTHORITY','QUERY_AUTHORITY','SOURCE_POLICY','RUNTIME_CONTRACT','OUTPUT_SCHEMA','EXECUTION_EXACT_SET','EXECUTION_BASELINE_FIRST','QUERY_EXECUTION_LEDGER','CANDIDATE_REGISTER','OCCURRENCE_DISPOSITION','GAP_SUMMARY','APPLICATION_LEDGER','EXECUTION_REVIEW_REQUEST','VALIDATION_LAST'];
  return paths.map((artifactPath, index) => ({ artifact_id: `P0DISC-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' }));
}
 
export function syntheticCleanBundle() {
  const bundle = authorityBundle();
  const searchedAt = '2026-07-30T04:00:00.000Z';
  const queryLedger = bundle.queries.map((query, index) => ({
    query_execution_id: `P0DISC-QEXEC-${String(index + 1).padStart(3, '0')}`,
    query_id: query.query_id,
    conceptual_gap_key: query.conceptual_gap_key,
    query_text_sha256: sha(Buffer.from(query.query_text, 'utf8')),
    searched_at: searchedAt,
    result_count_inspected: index === 0 ? '1' : '0',
    candidate_count_captured: index === 0 ? '1' : '0',
    execution_status: index === 0 ? 'COMPLETED_WITH_CANDIDATES' : 'COMPLETED_NO_PRIMARY_CANDIDATE',
    tool_boundary: 'PUBLIC_WEB_READ_ONLY_NO_LOGIN_NO_PAYWALL_BYPASS',
    gap_effect: 'DISCOVERY_ONLY_GAP_REMAINS_OPEN',
  }));
  const first = bundle.queries[0];
  const snippet = 'Synthetic primary-source candidate used only by the runtime self-test.';
  const candidates = [{
    candidate_id: 'P0DISC-CAND-SYNTHETIC-001',
    query_id: first.query_id,
    conceptual_gap_key: first.conceptual_gap_key,
    canonical_url: 'https://www.sec.gov/Archives/example',
    source_domain: 'www.sec.gov',
    source_class: 'EXCHANGE_OR_REGULATOR_FILING',
    publisher: 'Synthetic regulator fixture',
    title: 'Synthetic official filing candidate',
    publication_date: '2026-07-30',
    access_status: 'AVAILABLE',
    primary_source_status: 'PRIMARY_CONFIRMED',
    relevance_status: 'DIRECT',
    content_locator: 'synthetic-self-test-fixture',
    snippet_text: snippet,
    snippet_text_sha256: sha(Buffer.from(snippet, 'utf8')),
    discovered_at: searchedAt,
    candidate_disposition: 'CANDIDATE_CAPTURED_PENDING_INDEPENDENT_SEMANTIC_REVIEW',
    gap_effect: 'DISCOVERY_ONLY_GAP_REMAINS_OPEN',
    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',
  }];
  return { queryLedger, candidates, ...deriveOutputs(queryLedger, candidates, bundle) };
}
 
export function negativeRows() {
  const clean = syntheticCleanBundle();
  const cases = [
    ['CLEAN_ACCEPT', value => value, 'ACCEPT', 'NONE'],
    ['QUERY_MISSING', value => ({...value, queryLedger:value.queryLedger.slice(1)}), 'REJECT', 'QUERY_LEDGER_SET'],
    ['QUERY_TEXT_HASH', value => ({...value, queryLedger:value.queryLedger.map((row,index)=>index?row:{...row,query_text_sha256:'0'.repeat(64)})}), 'REJECT', 'QUERY_LEDGER_TEXT_HASH'],
    ['QUERY_GAP', value => ({...value, queryLedger:value.queryLedger.map((row,index)=>index?row:{...row,conceptual_gap_key:'WRONG'})}), 'REJECT', 'QUERY_LEDGER_GAP'],
    ['QUERY_TOOL_BOUNDARY', value => ({...value, queryLedger:value.queryLedger.map((row,index)=>index?row:{...row,tool_boundary:'LOGIN'})}), 'REJECT', 'QUERY_LEDGER_TOOL_BOUNDARY'],
    ['QUERY_GAP_EFFECT', value => ({...value, queryLedger:value.queryLedger.map((row,index)=>index?row:{...row,gap_effect:'CLOSED'})}), 'REJECT', 'QUERY_LEDGER_GAP_EFFECT'],
    ['DISPOSITION_CLOSE', value => ({...value, dispositions:value.dispositions.map((row,index)=>index?row:{...row,gap_state_after:'CLOSED'})}), 'REJECT', 'DISPOSITION_ROW'],
    ['SUMMARY_CLOSE', value => ({...value, summary:value.summary.map((row,index)=>index?row:{...row,gap_state_after:'CLOSED'})}), 'REJECT', 'SUMMARY_ROW'],
    ['APPLICATION_CLOSE', value => ({...value, applications:value.applications.map((row,index)=>index?row:{...row,application_result:'CLOSED_WITHOUT_REVIEW'})}), 'REJECT', 'APPLICATION_ROW'],
    ['CLAIM_UPGRADE', value => ({...value, dispositions:value.dispositions.map((row,index)=>index?row:{...row,claim_strength_after:'CONFIRMED'})}), 'REJECT', 'DISPOSITION_ROW'],
    ['POOL_CHANGE', value => ({...value, applications:value.applications.map((row,index)=>index?row:{...row,formal_pool_effect:'FORMAL_POOL_CHANGED'})}), 'REJECT', 'APPLICATION_ROW'],
    ['EVIDENCE_UPGRADE', value => ({...value, summary:value.summary.map((row,index)=>index?row:{...row,evidence_strength_effect:'UPGRADE'})}), 'REJECT', 'SUMMARY_ROW'],
    ['CANDIDATE_SOURCE_CLASS', value => ({...value, candidates:value.candidates.map(row=>({...row,source_class:'SECONDARY_MEDIA'}))}), 'REJECT', 'CANDIDATE_SOURCE_CLASS'],
    ['CANDIDATE_PRIMARY_STATUS', value => ({...value, candidates:value.candidates.map(row=>({...row,primary_source_status:'SECONDARY'}))}), 'REJECT', 'CANDIDATE_PRIMARY_STATUS'],
    ['CANDIDATE_CANONICAL_URL', value => ({...value, candidates:value.candidates.map(row=>({...row,canonical_url:`${row.canonical_url}?utm_source=test`}))}), 'REJECT', 'CANDIDATE_CANONICAL_URL'],
    ['CANDIDATE_SNIPPET_HASH', value => ({...value, candidates:value.candidates.map(row=>({...row,snippet_text_sha256:'0'.repeat(64)}))}), 'REJECT', 'CANDIDATE_SNIPPET_HASH'],
    ['CANDIDATE_GAP_EFFECT', value => ({...value, candidates:value.candidates.map(row=>({...row,gap_effect:'GAP_CLOSED'}))}), 'REJECT', 'CANDIDATE_GAP_EFFECT'],
    ['CANDIDATE_CLAIM_UPGRADE', value => ({...value, candidates:value.candidates.map(row=>({...row,claim_strength_after:'CONFIRMED'}))}), 'REJECT', 'CANDIDATE_STRENGTH'],
    ['QUERY_CANDIDATE_COUNT_MISMATCH', value => ({...value, queryLedger:value.queryLedger.map((row,index)=>index?row:{...row,candidate_count_captured:'2'})}), 'REJECT', 'QUERY_CANDIDATE_COUNT_MISMATCH'],
    ['CANDIDATE_UNKNOWN_QUERY', value => ({...value, candidates:value.candidates.map(row=>({...row,query_id:'UNKNOWN'}))}), 'REJECT', 'CANDIDATE_QUERY'],
  ];
  return cases.map((item, index) => {
    const mutated = item[1](structuredClone(clean));
    const errors = bundleErrors(mutated);
    const actual = errors.length ? 'REJECT' : 'ACCEPT';
    return { test_id: `P0DISC-NEG-${String(index + 1).padStart(3, '0')}-${item[0]}`, mutation_applied: index ? 'YES' : 'NO_CLEAN_CONTROL', oracle: 'bundleErrors', expected: item[2], expected_code: item[3], actual, actual_codes: errors.join('|') || 'NONE', result: actual === item[2] && (item[3] === 'NONE' || errors.some(code => code.startsWith(item[3]))) ? 'PASS' : 'FAIL' };
  });
}
 
function executionRequestText() {
  return `# P0 primary-source discovery execution review request\n\ncase_id=${CASE_ID}\nrelease_audit=${RELEASE_AUDIT}\nbatch_id=${EXEC_BATCH}\nrun_id=${EXEC_RUN}\nscope=10 P0 source occurrences / 7 conceptual gaps / 14 frozen searches\nnetwork_scope=PUBLIC_WEB_PRIMARY_SOURCE_DISCOVERY_ONLY\nsource_scope=OFFICIAL_PRIMARY_SOURCE_CLASSES_ONLY\ngap_effect=DISCOVERY_ONLY_GAP_REMAINS_OPEN\nclaim_strength_ceiling=PENDING_VERIFICATION_MAX_NO_UPGRADE\nformal_pool_effect=NO_AUTOMATIC_FORMAL_POOL_CHANGE\nevidence_strength_effect=NO_UPGRADE\noutput_mutation=NO_BUSINESS_OUTPUT_MUTATION\n\nIndependent review must verify query execution, candidate primary-source provenance, deterministic 10/7/10 derivations, exact manifest transaction and all persistent boundaries.\n`;
}
 
function manifestState({ expectedRunRows = [], expectedRunId = '', frozenPrefix = null, expectedPhysicalDelta = null } = {}) {
  const anomalyRows = readCsv(ANOMALY_AUTHORITY).rows;
  const buffer = fs.readFileSync(abs(MANIFEST));
  return validateAppendStableManifest(buffer, {
    anomalyRows,
    frozenPrefix,
    originalRunId: ORIGINAL_TRIAGE_RUN,
    originalRunExpectedRows: 11,
    expectedRunRows,
    expectedRunId,
    expectedPhysicalDelta,
    filesystemIdentity: {
      runIds: expectedRunId ? [expectedRunId] : [],
      get: artifactPath => fs.existsSync(abs(artifactPath)) ? fileIdentity(artifactPath) : null,
    },
  });
}
 
function currentDesignManifestRows() {
  const state = manifestState();
  return state.logicalRows.filter(row => row.run_id === DESIGN_RUN);
}
 
export function prewriteErrors({ requireRelease = true, requireStaging = true } = {}) {
  const errors = [...releaseErrors({requireRelease})];
  const bundle = authorityBundle();
  if (bundle.targets.length !== 10) errors.push('TARGET_AUTHORITY_COUNT');
  if (bundle.gaps.length !== 7) errors.push('GAP_AUTHORITY_COUNT');
  if (bundle.queries.length !== 14) errors.push('QUERY_AUTHORITY_COUNT');
  if (bundle.contracts.length !== 32) errors.push('CONTRACT_COUNT');
  if (bundle.schemas.length !== 8) errors.push('SCHEMA_COUNT');
  if (bundle.executionSet.length !== 16) errors.push('EXECUTION_SET_COUNT');
  const designRows = currentDesignManifestRows();
  if (designRows.length !== 14 || new Set(designRows.map(row => row.artifact_path)).size !== 14) errors.push(`DESIGN_MANIFEST_ROWS:${designRows.length}`);
  for (const row of designRows) {
    if (!fs.existsSync(abs(row.artifact_path))) { errors.push(`DESIGN_PATH_MISSING:${row.artifact_path}`); continue; }
    const identity = fileIdentity(row.artifact_path);
    if (row.case_id !== CASE_ID || row.batch_id !== DESIGN_BATCH || row.sha256 !== identity.sha256 || row.bytes !== String(identity.bytes) || Date.parse(row.mtime) !== identity.mtimeMs) errors.push(`DESIGN_MANIFEST_IDENTITY:${row.artifact_path}`);
  }
  const outputs = [EXEC_BASELINE,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
  if (outputs.some(file => fs.existsSync(abs(file)))) errors.push('EXECUTION_OUTPUT_EXISTS');
  const state = manifestState();
  errors.push(...state.errors.map(code => `MANIFEST:${code}`));
  if (state.logicalRows.some(row => row.run_id === EXEC_RUN)) errors.push('EXECUTION_MANIFEST_ROWS_EXIST');
  if (requireStaging) {
    if (!fs.existsSync(abs(QUERY_LEDGER)) || !fs.existsSync(abs(CANDIDATE_REGISTER))) errors.push('STAGING_FILES_REQUIRED');
    else {
      const query = readCsv(QUERY_LEDGER), candidates = readCsv(CANDIDATE_REGISTER);
      errors.push(...exactColumns(query, QUERY_LEDGER_COLUMNS, 'QUERY_LEDGER'));
      errors.push(...exactColumns(candidates, CANDIDATE_COLUMNS, 'CANDIDATE_REGISTER'));
      errors.push(...validateStaging(query.rows, candidates.rows, bundle));
    }
  } else if (fs.existsSync(abs(QUERY_LEDGER)) || fs.existsSync(abs(CANDIDATE_REGISTER))) errors.push('STAGING_MUST_BE_ABSENT_BEFORE_DISCOVERY');
  return [...new Set(errors)];
}
 
function baselineRows() {
  const release = auditEntry(RELEASE_AUDIT);
  const manifestBuffer = fs.readFileSync(abs(MANIFEST));
  const rows = [
    { baseline_id:'P0DISC-EXEC-BASE-001',identity_type:'NORMALIZED_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:new Date(Math.trunc(fs.statSync(abs(AUDIT_REPORT)).mtimeMs)).toISOString(),required_state:'EXACT_PASS_AND_RELEASE_ENTRY' },
    { baseline_id:'P0DISC-EXEC-BASE-002',identity_type:'RAW_MANIFEST_BEFORE_EXECUTION',artifact_path:MANIFEST,rows:String(manifestState().logicalDataRows),bytes:String(manifestBuffer.length),sha256:sha(manifestBuffer),mtime:new Date(Math.trunc(fs.statSync(abs(MANIFEST)).mtimeMs)).toISOString(),required_state:'EXACT_APPEND_ONLY_PREFIX' },
  ];
  for (const file of [SCRIPT,TARGET_AUTHORITY,GAP_AUTHORITY,QUERY_AUTHORITY,SOURCE_POLICY,CONTRACT,SCHEMA,EXEC_SET,ANOMALY_AUTHORITY,QUERY_LEDGER,CANDIDATE_REGISTER]) {
    const identity = fileIdentity(file);
    rows.push({ baseline_id:`P0DISC-EXEC-BASE-${String(rows.length + 1).padStart(3,'0')}`,identity_type:'PHYSICAL_FILE',artifact_path:file,rows:String(identity.rows),bytes:String(identity.bytes),sha256:identity.sha256,mtime:identity.mtime,required_state:'EXACT_FROZEN_EXECUTION_INPUT' });
  }
  return rows;
}
 
function validationRows(queryLedger, candidates, derived) {
  const errors = bundleErrors({queryLedger,candidates,dispositions:derived.dispositions,summary:derived.summary,applications:derived.applications});
  const state = manifestState();
  const checks = [
    ['RUNTIME_ERRORS','0',String(errors.length)],
    ['TARGETS','10','10'],
    ['CONCEPTUAL_GAPS','7','7'],
    ['QUERY_LEDGER','14',String(queryLedger.length)],
    ['CANDIDATES','0_to_35',String(candidates.length)],
    ['OCCURRENCE_DISPOSITIONS','10',String(derived.dispositions.length)],
    ['GAP_SUMMARY','7',String(derived.summary.length)],
    ['APPLICATION','10',String(derived.applications.length)],
    ['GAP_STATE','OPEN_RETAINED_GAP',derived.dispositions.every(row=>row.gap_state_after==='OPEN_RETAINED_GAP')?'OPEN_RETAINED_GAP':'MISMATCH'],
    ['CLAIM_CEILING','PENDING_VERIFICATION_MAX_NO_UPGRADE',derived.dispositions.every(row=>row.claim_strength_after==='PENDING_VERIFICATION_MAX_NO_UPGRADE')?'PENDING_VERIFICATION_MAX_NO_UPGRADE':'MISMATCH'],
    ['FORMAL_POOL','NO_AUTOMATIC_FORMAL_POOL_CHANGE',derived.applications.every(row=>row.formal_pool_effect==='NO_AUTOMATIC_FORMAL_POOL_CHANGE')?'NO_AUTOMATIC_FORMAL_POOL_CHANGE':'MISMATCH'],
    ['EVIDENCE_STRENGTH','NO_UPGRADE',derived.applications.every(row=>row.evidence_strength_effect==='NO_UPGRADE')?'NO_UPGRADE':'MISMATCH'],
    ['BUSINESS_OUTPUT_MUTATION','NO','NO'],
    ['MANIFEST_PREWRITE_ERRORS','0',String(state.errors.length)],
    ['EXECUTION_EXACT_SET','16','16'],
    ['REVIEW_STATE','PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW','PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW'],
    ['DISCOVERY_EFFECT','DISCOVERY_ONLY_GAP_REMAINS_OPEN','DISCOVERY_ONLY_GAP_REMAINS_OPEN'],
  ];
  const rows = checks.map((item,index)=>({check_id:`P0DISC-EXEC-VAL-${String(index+1).padStart(3,'0')}`,check_description:item[0],expected:item[1],actual:item[2],status:(item[1]===item[2]||(item[1]==='0_to_35'&&Number(item[2])<=35))?'PASS':'FAIL',evidence:'P0_PRIMARY_SOURCE_DISCOVERY_RUNTIME'}));
  rows.push({check_id:'P0DISC-EXEC-VAL-018',check_description:'SELF_REFERENCE_EXCLUDED',expected:'SELF_REFERENCE_EXCLUDED',actual:'SELF_REFERENCE_EXCLUDED',status:'INFO',evidence:'validation and manifest identities checked after freeze'});
  return rows;
}
 
function manifestRowsForExecution(paths) {
  return paths.map(file => {
    const identity = fileIdentity(file);
    return { case_id:CASE_ID,run_id:EXEC_RUN,batch_id:EXEC_BATCH,artifact_path:file,sha256:identity.sha256,bytes:String(identity.bytes),mtime:identity.mtime };
  });
}
 
function writeFile(file, content) {
  fs.mkdirSync(path.dirname(abs(file)), {recursive:true});
  fs.writeFileSync(abs(file), content, 'utf8');
}
 
export function execute({ token } = {}) {
  if (token !== EXEC_TOKEN) throw new Error('EXECUTION_TOKEN_MISMATCH');
  const errors = prewriteErrors({requireRelease:true,requireStaging:true});
  if (errors.length) throw new Error(`PREWRITE:${errors.join('|')}`);
  const manifestBefore = fs.readFileSync(abs(MANIFEST));
  const generated = [EXEC_BASELINE,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION];
  try {
    const queryLedger = readCsv(QUERY_LEDGER).rows;
    const candidates = readCsv(CANDIDATE_REGISTER).rows;
    const derived = deriveOutputs(queryLedger,candidates);
    writeFile(EXEC_BASELINE,serializeCsv(baselineRows(),BASELINE_COLUMNS));
    writeFile(OCCURRENCE_DISPOSITION,serializeCsv(derived.dispositions,DISPOSITION_COLUMNS));
    writeFile(GAP_SUMMARY,serializeCsv(derived.summary,SUMMARY_COLUMNS));
    writeFile(APPLICATION,serializeCsv(derived.applications,APPLICATION_COLUMNS));
    writeFile(EXEC_REQUEST,executionRequestText());
    const validation = validationRows(queryLedger,candidates,derived);
    writeFile(EXEC_VALIDATION,serializeCsv(validation,VALIDATION_COLUMNS));
    if (validation.some(row=>row.status==='FAIL')) throw new Error('EXECUTION_VALIDATION_FAIL');
    const paths = executionSetRows().map(row=>row.artifact_path);
    const rows = manifestRowsForExecution(paths);
    const candidate = Buffer.concat([manifestBefore,Buffer.from(serializeManifestDataRows(rows),'utf8')]);
    const candidateState = validateAppendStableManifest(candidate,{anomalyRows:readCsv(ANOMALY_AUTHORITY).rows,frozenPrefix:{bytes:manifestBefore.length,sha256:sha(manifestBefore)},originalRunId:ORIGINAL_TRIAGE_RUN,originalRunExpectedRows:11,expectedRunRows:rows,expectedRunId:EXEC_RUN,expectedPhysicalDelta:16});
    if (candidateState.errors.length) throw new Error(`MANIFEST_CANDIDATE:${candidateState.errors.join('|')}`);
    fs.writeFileSync(abs(MANIFEST),candidate);
    const post = validateExecution();
    if (post.length) throw new Error(`POSTWRITE:${post.join('|')}`);
    return {status:'EXECUTED_PENDING_INDEPENDENT_REVIEW',queries:queryLedger.length,candidates:candidates.length,occurrences:derived.dispositions.length,gaps:derived.summary.length,manifest_rows:rows.length};
  } catch (error) {
    const cleanup = [];
    try { fs.writeFileSync(abs(MANIFEST),manifestBefore); } catch (failure) { cleanup.push(`MANIFEST_RESTORE:${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 [QUERY_LEDGER,CANDIDATE_REGISTER,EXEC_BASELINE,OCCURRENCE_DISPOSITION,GAP_SUMMARY,APPLICATION,EXEC_REQUEST,EXEC_VALIDATION]) if (!fs.existsSync(abs(file))) errors.push(`OUTPUT_MISSING:${file}`);
  if (errors.length) return errors;
  const query = readCsv(QUERY_LEDGER), candidates = readCsv(CANDIDATE_REGISTER), dispositions = readCsv(OCCURRENCE_DISPOSITION), summary = readCsv(GAP_SUMMARY), applications = readCsv(APPLICATION), validation = readCsv(EXEC_VALIDATION);
  errors.push(...exactColumns(query,QUERY_LEDGER_COLUMNS,'QUERY_LEDGER'),...exactColumns(candidates,CANDIDATE_COLUMNS,'CANDIDATE_REGISTER'),...exactColumns(dispositions,DISPOSITION_COLUMNS,'DISPOSITION'),...exactColumns(summary,SUMMARY_COLUMNS,'SUMMARY'),...exactColumns(applications,APPLICATION_COLUMNS,'APPLICATION'),...exactColumns(validation,VALIDATION_COLUMNS,'VALIDATION'));
  errors.push(...bundleErrors({queryLedger:query.rows,candidates:candidates.rows,dispositions:dispositions.rows,summary:summary.rows,applications:applications.rows}));
  if (validation.rows.length!==18||validation.rows.some(row=>row.status==='FAIL')) errors.push('VALIDATION_STATUS');
  const expectedRows = manifestRowsForExecution(executionSetRows().map(row=>row.artifact_path));
  const state = manifestState({expectedRunRows:expectedRows,expectedRunId:EXEC_RUN});
  errors.push(...state.errors.map(code=>`MANIFEST:${code}`));
  if (state.logicalRows.filter(row=>row.run_id===EXEC_RUN).length!==16) errors.push('EXECUTION_MANIFEST_COUNT');
  return [...new Set(errors)];
}
 
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const mode = process.argv[2] ?? '--preview';
  if (mode === '--preview') {
    const clean = syntheticCleanBundle();
    console.log(JSON.stringify({status:'PREVIEW',targets:authorityBundle().targets.length,gaps:authorityBundle().gaps.length,queries:clean.queryLedger.length,candidates:clean.candidates.length,dispositions:clean.dispositions.length,summary:clean.summary.length,applications:clean.applications.length,errors:bundleErrors(clean)},null,2));
  } else if (mode === '--self-test') {
    const rows = negativeRows();
    console.log(JSON.stringify(rows,null,2));
    if (rows.some(row=>row.result!=='PASS')) process.exitCode=1;
  } else if (mode === '--validate-release') {
    const errors = prewriteErrors({requireRelease:true,requireStaging:false});
    console.log(JSON.stringify({status:errors.length?'HELD':'PASS_RELEASE_PRE_DISCOVERY',errors},null,2));
    if (errors.length) process.exitCode=1;
  } else if (mode === '--validate-design-inputs') {
    const errors = prewriteErrors({requireRelease:false,requireStaging:false}).filter(code=>!code.startsWith('DESIGN_MANIFEST_ROWS:'));
    console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_DESIGN_INPUTS',errors},null,2));
    if (errors.length) process.exitCode=1;
  } else if (mode === '--validate-staging') {
    const errors = prewriteErrors({requireRelease:true,requireStaging:true});
    console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_STAGING_PREWRITE',errors},null,2));
    if (errors.length) process.exitCode=1;
  } else if (mode === '--execute') {
    const tokenArg = process.argv.find(value=>value.startsWith('--token='));
    console.log(JSON.stringify(execute({token:tokenArg?.slice(8)}),null,2));
  } else if (mode === '--validate-execution') {
    const errors = validateExecution();
    console.log(JSON.stringify({status:errors.length?'FAIL':'PASS_EXECUTION_STATE',errors},null,2));
    if (errors.length) process.exitCode=1;
  } else throw new Error(`UNKNOWN_MODE:${mode}`);
}