Cai
16 hours ago cd6bfbea57c2437c00f808317f896aacb2ad2440
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
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import crypto from 'node:crypto';
import { pathToFileURL } from 'node:url';
import {
  MANIFEST_COLUMNS,
  PRIMARY_HEADER_TEXT,
  hashBuffer,
  parseAuthorityCsv,
  serializeCsv,
  serializeManifestDataRows,
  validateAppendStableManifest,
} from './artifact_manifest_append_stable_parser_repair001_20260730.mjs';
 
const ROOT = process.cwd();
export const CASE_ID = 'ANA-ROBOT-INDUSTRY-001';
const BASE = 'ana-data/cases/机器人案例/ANA-ROBOT-INDUSTRY-001';
const MANIFEST = `${BASE}/manifest/artifact_manifest.csv`;
const AUDIT_REPORT = 'ana-doc/机器人案例/案例审计报告.md';
const SOURCE_AUDIT = 'AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-EXEC-OUTPUT-001';
const RELEASE_AUDIT = 'AUDIT-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-MANIFEST-INTEGRITY-DESIGN-REPAIR001-REREVIEW-001';
const ORIGINAL_RUN = 'RUN-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-001';
const ORIGINAL_EXEC_SET = `${BASE}/manifest/detail_strengthening_gap_triage_execution_artifact_set_repair002_20260730.csv`;
export const DESIGN_BATCH = 'BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-MANIFEST-INTEGRITY-DESIGN-REPAIR-001';
export const DESIGN_RUN = 'RUN-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-MANIFEST-INTEGRITY-DESIGN-REPAIR-001';
export const EXEC_BATCH = 'BATCH-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-EXECUTION-MANIFEST-INTEGRITY-REPAIR-001';
export const EXEC_RUN = 'RUN-ANA-ROBOT-DETAIL-STRENGTHENING-GAP-TRIAGE-EXECUTION-MANIFEST-INTEGRITY-REPAIR-001';
export const EXEC_TOKEN = 'EXECUTE_DETAIL_GAP_TRIAGE_MANIFEST_INTEGRITY_REPAIR001';
 
export const FROZEN_ANOMALOUS_MANIFEST = {
  bytes: 576712,
  sha256: '86f78b608a9be91cf404944ef3d01c6f8d88cfda542cdcba5fb890123386a10e',
  logicalDataRows: 1614,
  physicalRecords: 1616,
};
export const IMMUTABLE_PRE_EXECUTION_PREFIX = {
  bytes: 572657,
  sha256: '0b67e4b20f9bd5a55db1a943e544d21b30109a693f4dd3887583db9ded5b264e',
  dataRows: 1603,
};
 
export const PARSER = 'dev/ana-dev/artifact_manifest_append_stable_parser_repair001_20260730.mjs';
export const RUNTIME = 'dev/ana-dev/detail_strengthening_gap_triage_manifest_integrity_runtime_repair001_20260730.mjs';
export const BUILDER = 'dev/ana-dev/detail_strengthening_gap_triage_manifest_integrity_design_repair001_20260730.mjs';
export const ANOMALY_AUTHORITY = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_anomaly_authority_repair001_20260730.csv`;
export const CONTRACT = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_integrity_contract_repair001_20260730.csv`;
export const SCHEMA = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_integrity_schema_authority_repair001_20260730.csv`;
export const EXEC_SET = `${BASE}/manifest/detail_strengthening_gap_triage_manifest_integrity_execution_artifact_set_repair001_20260730.csv`;
export const NEGATIVE_RESULTS = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_integrity_negative_results_repair001_20260730.csv`;
export const DESIGN_BASELINE = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_integrity_design_baseline_repair001_20260730.csv`;
export const DESIGN_REQUEST = `${BASE}/manifest/review_request_detail_strengthening_gap_triage_manifest_integrity_design_repair001_20260730.md`;
export const DESIGN_SET = `${BASE}/manifest/detail_strengthening_gap_triage_manifest_integrity_design_artifact_set_repair001_20260730.csv`;
export const DESIGN_VALIDATION = `${BASE}/manifest/detail_strengthening_gap_triage_manifest_integrity_design_validation_repair001_20260730.csv`;
 
export const EXEC_BASELINE = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_integrity_execution_baseline_repair001_20260730.csv`;
export const ANOMALY_REGISTRY = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_legacy_anomaly_registry_repair001_20260730.csv`;
export const APPLICATION = `${BASE}/evidence/detail_strengthening_gap_triage_manifest_integrity_application_repair001_20260730.csv`;
export const EXEC_REQUEST = `${BASE}/manifest/review_request_detail_strengthening_gap_triage_manifest_integrity_execution_repair001_20260730.md`;
export const EXEC_VALIDATION = `${BASE}/manifest/detail_strengthening_gap_triage_manifest_integrity_execution_validation_repair001_20260730.csv`;
 
export const DESIGN_PATHS = [PARSER, RUNTIME, BUILDER, ANOMALY_AUTHORITY, CONTRACT, SCHEMA, EXEC_SET, NEGATIVE_RESULTS, DESIGN_BASELINE, DESIGN_REQUEST, DESIGN_SET, DESIGN_VALIDATION];
export const EXEC_PATHS = [PARSER, RUNTIME, ANOMALY_AUTHORITY, CONTRACT, SCHEMA, EXEC_SET, EXEC_BASELINE, ANOMALY_REGISTRY, APPLICATION, EXEC_REQUEST, EXEC_VALIDATION];
const GENERATED = [EXEC_BASELINE, ANOMALY_REGISTRY, APPLICATION, EXEC_REQUEST, EXEC_VALIDATION];
 
export const ANOMALY_COLUMNS = ['anomaly_id', 'manifest_path', 'physical_line', 'record_index', 'disposition', 'raw_record_sha256', 'raw_record_bytes', 'raw_record_terminator', 'primary_header_line', 'authority_manifest_bytes', 'authority_manifest_sha256', 'immutable_prefix_bytes', 'immutable_prefix_sha256', 'original_run_id', 'original_run_rows'];
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 SET_COLUMNS = ['artifact_id', 'batch_id', 'run_id', 'generation_order', 'artifact_path', 'artifact_role', 'identity_policy'];
export const NEGATIVE_COLUMNS = ['test_id', 'mutation_applied', 'oracle', 'expected', 'expected_code', 'actual', 'actual_codes', 'result'];
export const BASELINE_COLUMNS = ['baseline_id', 'artifact_role', 'artifact_path', 'rows', 'bytes', 'sha256', 'mtime', 'required_state', 'checked_at'];
export const REGISTRY_COLUMNS = ['anomaly_id', 'manifest_path', 'physical_line', 'disposition', 'raw_record_sha256', 'raw_record_bytes', 'observed_header_shape_count', 'logical_data_rows_before_repair_append', 'original_run_rows', 'repair_effect', 'status'];
export const APPLICATION_COLUMNS = ['application_id', 'anomaly_id', 'action', 'result_status', 'manifest_rewrite', 'business_output_rewrite', 'original_run_rows', 'formal_pool_effect', 'evidence_strength_effect'];
export const VALIDATION_COLUMNS = ['check_id', 'check_description', 'expected', 'actual', 'status', 'evidence'];
 
const abs = (relative, root = ROOT) => path.join(root, ...relative.split('/'));
const sha = buffer => crypto.createHash('sha256').update(buffer).digest('hex');
const normalized = text => text.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const lineCount = buffer => {
  const text = normalized(buffer.toString('utf8'));
  return text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
};
 
export function fileIdentity(relative, root = ROOT) {
  const buffer = fs.readFileSync(abs(relative, root));
  const stat = fs.statSync(abs(relative, root));
  return {
    rows: relative.endsWith('.csv') ? parseAuthorityCsv(buffer.toString('utf8')).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),
  };
}
 
function readCsv(relative, root = ROOT) {
  const parsed = parseAuthorityCsv(fs.readFileSync(abs(relative, root), 'utf8'));
  if (parsed.errors.length) throw new Error(`CSV_PARSE:${relative}:${parsed.errors.join('|')}`);
  return parsed;
}
 
function writeText(relative, text, root = ROOT) {
  fs.mkdirSync(path.dirname(abs(relative, root)), { recursive: true });
  fs.writeFileSync(abs(relative, root), text, 'utf8');
}
 
export function anomalyAuthorityRows() {
  return [{
    anomaly_id: 'MANIFEST-ANOMALY-001',
    manifest_path: MANIFEST,
    physical_line: '1605',
    record_index: '1605',
    disposition: 'LEGACY_DUPLICATE_HEADER_NON_DATA_ROW',
    raw_record_sha256: '29f15c31901f3466d74aa8b421bdb023949c5f764c58a0d30444ed4b2d4ba5d4',
    raw_record_bytes: '71',
    raw_record_terminator: 'LF',
    primary_header_line: '1',
    authority_manifest_bytes: String(FROZEN_ANOMALOUS_MANIFEST.bytes),
    authority_manifest_sha256: FROZEN_ANOMALOUS_MANIFEST.sha256,
    immutable_prefix_bytes: String(IMMUTABLE_PRE_EXECUTION_PREFIX.bytes),
    immutable_prefix_sha256: IMMUTABLE_PRE_EXECUTION_PREFIX.sha256,
    original_run_id: ORIGINAL_RUN,
    original_run_rows: '11',
  }];
}
 
export function contractRows() {
  const entries = [
    ['MANIFEST', 'primary_header', 'L1_EXACT_PRIMARY_HEADER'],
    ['MANIFEST', 'authorized_anomaly', 'EXACT_L1605_ONLY'],
    ['MANIFEST', 'anomaly_disposition', 'LEGACY_DUPLICATE_HEADER_NON_DATA_ROW'],
    ['MANIFEST', 'anomaly_count', 'EXACT_1'],
    ['MANIFEST', 'header_shape_count', 'EXACT_2_INCLUDING_PRIMARY'],
    ['MANIFEST', 'logical_rows', 'PHYSICAL_RECORDS_MINUS_PRIMARY_HEADER_MINUS_EXACT_ANOMALY'],
    ['MANIFEST', 'all_other_records', 'EXACT_SEVEN_VALID_FIELDS'],
    ['MANIFEST', 'immutable_prefix', `${IMMUTABLE_PRE_EXECUTION_PREFIX.bytes}|${IMMUTABLE_PRE_EXECUTION_PREFIX.sha256}`],
    ['MANIFEST', 'frozen_anomalous_file', `${FROZEN_ANOMALOUS_MANIFEST.bytes}|${FROZEN_ANOMALOUS_MANIFEST.sha256}`],
    ['ORIGINAL_RUN', 'row_count', 'EXACT_11_UNIQUE_PATHS'],
    ['ORIGINAL_RUN', 'identity', 'EXACT_SEVEN_FIELDS_AND_FILESYSTEM_MS_MTIME'],
    ['DESIGN_APPEND', 'writer', 'DATA_ROWS_ONLY_NO_HEADER'],
    ['DESIGN_APPEND', 'physical_delta', `EXACT_${DESIGN_PATHS.length}_RECORDS`],
    ['EXECUTION_APPEND', 'writer', 'DATA_ROWS_ONLY_NO_HEADER'],
    ['EXECUTION_APPEND', 'physical_delta', `EXACT_${EXEC_PATHS.length}_RECORDS`],
    ['EXECUTION', 'invocation', `node ${RUNTIME} --execute --token=${EXEC_TOKEN}`],
    ['EXECUTION', 'release_audit', RELEASE_AUDIT],
    ['EXECUTION', 'release_lines', 'result=PASS|execution_release=EXPLICITLY_RELEASED|exact batch|exact run'],
    ['EXECUTION', 'baseline_first', 'YES'],
    ['EXECUTION', 'validation_last', 'YES'],
    ['EXECUTION', 'existing_targets', 'ZERO'],
    ['EXECUTION', 'manifest_transaction', 'APPEND_DATA_ROWS_THEN_POSTVALIDATE_OR_EXACT_ROLLBACK'],
    ['EXECUTION', 'business_output_rewrite', 'NO'],
    ['EXECUTION', 'original_generator_rerun', 'NO'],
    ['NEGATIVE', 'extra_header', 'REJECT'],
    ['NEGATIVE', 'altered_header', 'REJECT'],
    ['NEGATIVE', 'moved_header', 'REJECT'],
    ['NEGATIVE', 'missing_anomaly_authority', 'REJECT'],
    ['NEGATIVE', 'duplicate_original_run', 'REJECT'],
    ['NEGATIVE', 'wrong_seven_fields', 'REJECT_ALL_7'],
    ['NEGATIVE', 'prefix_drift', 'REJECT'],
    ['NEGATIVE', 'future_writer_with_header', 'REJECT'],
    ['BOUNDARY', 'execution_effect', 'TRIAGE_ONLY_NO_GAP_CLOSURE'],
    ['BOUNDARY', 'formal_pool_effect', 'NO_AUTOMATIC_FORMAL_POOL_CHANGE'],
    ['BOUNDARY', 'evidence_strength_effect', 'NO_UPGRADE'],
    ['BOUNDARY', 'claim_strength_ceiling', 'PENDING_VERIFICATION_MAX_NO_UPGRADE'],
  ];
  return entries.map((entry, index) => ({
    contract_id: `DGTMIR-CON-${String(index + 1).padStart(3, '0')}`,
    scope: entry[0],
    field: entry[1],
    required_value_or_rule: entry[2],
    violation_status: 'FAIL_CLOSED',
  }));
}
 
export function schemaRows() {
  const definitions = [
    ['RUNTIME_BASELINE', EXEC_BASELINE, BASELINE_COLUMNS.join('|'), 'baseline_id', 'AT_LEAST_10', 'append-stable release entry + frozen manifest + original outputs + design authority'],
    ['ANOMALY_REGISTRY', ANOMALY_REGISTRY, REGISTRY_COLUMNS.join('|'), 'anomaly_id', 'EXACT_1', 'exact anomaly authority plus observed manifest state'],
    ['APPLICATION', APPLICATION, APPLICATION_COLUMNS.join('|'), 'application_id', 'EXACT_1', 'manifest compatibility registration only; no business rewrite'],
    ['EXECUTION_REQUEST', EXEC_REQUEST, 'MARKDOWN_EXACT_TEXT', 'NOT_APPLICABLE', 'EXACT_1_DOCUMENT', 'deterministic request text'],
    ['EXECUTION_VALIDATION', EXEC_VALIDATION, VALIDATION_COLUMNS.join('|'), 'check_id', 'PASS_ONLY_PLUS_SELF_REFERENCE_INFO', 'validation-last fail-closed checks'],
  ];
  return definitions.map((definition, index) => ({
    schema_id: `DGTMIR-SCHEMA-${String(index + 1).padStart(3, '0')}`,
    artifact_role: definition[0],
    artifact_path: definition[1],
    column_order: definition[2],
    primary_key: definition[3],
    row_count_rule: definition[4],
    serialization: definition[0] === 'EXECUTION_REQUEST' ? 'UTF8_NO_BOM_LF_MARKDOWN_TERMINAL_LF' : 'UTF8_NO_BOM_LF_ALL_FIELDS_QUOTED_TERMINAL_LF',
    derivation_rule: definition[5],
    required_boundary: 'NO_BUSINESS_OUTPUT_REWRITE|NO_AUTOMATIC_FORMAL_POOL_CHANGE|NO_UPGRADE',
  }));
}
 
export function executionSetRows() {
  const roles = ['SHARED_APPEND_STABLE_PARSER', 'FROZEN_REPAIR_RUNTIME', 'FROZEN_ANOMALY_AUTHORITY', 'FROZEN_RUNTIME_CONTRACT', 'FROZEN_OUTPUT_SCHEMA', 'FROZEN_EXECUTION_EXACT_SET', 'RUNTIME_BASELINE_FIRST', 'LEGACY_ANOMALY_REGISTRY', 'REPAIR_APPLICATION', 'EXECUTION_REVIEW_REQUEST', 'VALIDATION_LAST'];
  return EXEC_PATHS.map((artifactPath, index) => ({
    artifact_id: `DGTMIR-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 designSetRows() {
  const roles = ['SHARED_APPEND_STABLE_PARSER', 'REPAIR_RUNTIME_GENERATOR', 'DESIGN_REPAIR_BUILDER', 'ANOMALY_AUTHORITY', 'RUNTIME_CONTRACT', 'OUTPUT_SCHEMA', 'EXECUTION_EXACT_SET', 'RUNTIME_NEGATIVE_RESULTS', 'DESIGN_BASELINE', 'DESIGN_REVIEW_REQUEST', 'DESIGN_EXACT_SET', 'VALIDATION_LAST'];
  return DESIGN_PATHS.map((artifactPath, index) => ({
    artifact_id: `DGTMIR-DESIGN-SET-${String(index + 1).padStart(3, '0')}`,
    batch_id: DESIGN_BATCH,
    run_id: DESIGN_RUN,
    generation_order: String(index + 1),
    artifact_path: artifactPath,
    artifact_role: roles[index],
    identity_policy: 'EXACT_SHA256_BYTES_FILESYSTEM_MTIME_MS',
  }));
}
 
function expectedManifestRows(paths, runId, batchId, root = ROOT) {
  return paths.map(artifactPath => {
    const identity = fileIdentity(artifactPath, root);
    return {
      case_id: CASE_ID,
      run_id: runId,
      batch_id: batchId,
      artifact_path: artifactPath,
      sha256: identity.sha256,
      bytes: String(identity.bytes),
      mtime: identity.mtime,
    };
  });
}
 
function anomalyRowsFromFile(root = ROOT) {
  return readCsv(ANOMALY_AUTHORITY, root).rows;
}
 
function originalExecutionPaths(root = ROOT) {
  const parsed = readCsv(ORIGINAL_EXEC_SET, root);
  return parsed.rows.sort((a, b) => Number(a.generation_order) - Number(b.generation_order)).map(row => row.artifact_path);
}
 
function filesystemOracle(root, runIds) {
  return {
    runIds,
    get(relative) {
      if (!fs.existsSync(abs(relative, root))) return null;
      return fileIdentity(relative, root);
    },
  };
}
 
function validateManifestState(buffer, { root = ROOT, includeDesign = true, includeExecution = false } = {}) {
  const anomalyRows = anomalyRowsFromFile(root);
  const baseOptions = {
    anomalyRows,
    frozenPrefix: FROZEN_ANOMALOUS_MANIFEST,
    originalRunId: ORIGINAL_RUN,
    originalRunExpectedRows: 11,
    filesystemIdentity: filesystemOracle(root, [ORIGINAL_RUN, DESIGN_RUN, EXEC_RUN]),
  };
  const errors = [];
  const base = validateAppendStableManifest(buffer, baseOptions);
  errors.push(...base.errors);
  if (base.logicalDataRows < FROZEN_ANOMALOUS_MANIFEST.logicalDataRows) errors.push('LOGICAL_DATA_ROWS_TRUNCATED');
  if (includeDesign) {
    const expected = expectedManifestRows(DESIGN_PATHS, DESIGN_RUN, DESIGN_BATCH, root);
    const validation = validateAppendStableManifest(buffer, { ...baseOptions, expectedRunId: DESIGN_RUN, expectedRunRows: expected });
    errors.push(...validation.errors);
  }
  if (includeExecution) {
    const expected = expectedManifestRows(EXEC_PATHS, EXEC_RUN, EXEC_BATCH, root);
    const validation = validateAppendStableManifest(buffer, { ...baseOptions, expectedRunId: EXEC_RUN, expectedRunRows: expected });
    errors.push(...validation.errors);
  }
  const expectedDelta = (includeDesign ? DESIGN_PATHS.length : 0) + (includeExecution ? EXEC_PATHS.length : 0);
  const prefixRecords = validateAppendStableManifest(buffer.subarray(0, FROZEN_ANOMALOUS_MANIFEST.bytes), baseOptions).physicalRecords;
  const currentRecords = base.physicalRecords;
  if (currentRecords - prefixRecords !== expectedDelta) errors.push(`PHYSICAL_APPEND_DELTA:${currentRecords - prefixRecords}:${expectedDelta}`);
  const expectedLogical = FROZEN_ANOMALOUS_MANIFEST.logicalDataRows + expectedDelta;
  if (base.logicalDataRows !== expectedLogical) errors.push(`LOGICAL_DATA_ROWS:${base.logicalDataRows}:${expectedLogical}`);
  return { ...base, errors: [...new Set(errors)] };
}
 
function auditEntry(auditId, root = ROOT) {
  const lines = normalized(fs.readFileSync(abs(AUDIT_REPORT, root), 'utf8')).split('\n');
  const start = lines.findIndex(line => line.startsWith('### ') && line.includes(auditId));
  if (start < 0) return { errors: ['AUDIT_ENTRY_MISSING'] };
  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`);
  return { errors: [], start: start + 1, end, rows: end - start, bytes: buffer.length, sha256: sha(buffer) };
}
 
function releaseErrors(root = ROOT) {
  const entry = auditEntry(RELEASE_AUDIT, root);
  if (entry.errors.length) return entry.errors;
  const lines = normalized(fs.readFileSync(abs(AUDIT_REPORT, root), 'utf8')).split('\n').slice(entry.start - 1, entry.end).map(line => line.trim());
  const required = [`result=PASS`, `execution_release=EXPLICITLY_RELEASED`, `released_batch_id=${EXEC_BATCH}`, `released_run_id=${EXEC_RUN}`];
  const errors = [];
  for (const line of required) if (lines.filter(value => value === line).length !== 1) errors.push(`RELEASE_EXACT_LINE:${line}`);
  return errors;
}
 
function originalOutputIdentityErrors(root = ROOT) {
  const buffer = fs.readFileSync(abs(MANIFEST, root));
  const state = validateAppendStableManifest(buffer, {
    anomalyRows: anomalyRowsFromFile(root),
    frozenPrefix: FROZEN_ANOMALOUS_MANIFEST,
    originalRunId: ORIGINAL_RUN,
    originalRunExpectedRows: 11,
    filesystemIdentity: filesystemOracle(root, [ORIGINAL_RUN]),
  });
  const errors = [...state.errors];
  const expectedPaths = originalExecutionPaths(root);
  const actualPaths = state.logicalRows.filter(row => row.run_id === ORIGINAL_RUN).map(row => row.artifact_path);
  if (expectedPaths.join('|') !== actualPaths.join('|')) errors.push('ORIGINAL_RUN_PATH_ORDER');
  return [...new Set(errors)];
}
 
export function designInputErrors({ root = ROOT, requireDesignManifest = false } = {}) {
  const errors = [];
  for (const relative of [PARSER, RUNTIME, BUILDER, ORIGINAL_EXEC_SET, MANIFEST]) if (!fs.existsSync(abs(relative, root))) errors.push(`INPUT_MISSING:${relative}`);
  if (errors.length) return errors;
  const buffer = fs.readFileSync(abs(MANIFEST, root));
  if (buffer.length < FROZEN_ANOMALOUS_MANIFEST.bytes || hashBuffer(buffer.subarray(0, FROZEN_ANOMALOUS_MANIFEST.bytes)) !== FROZEN_ANOMALOUS_MANIFEST.sha256) errors.push('FROZEN_ANOMALOUS_MANIFEST_PREFIX');
  if (fs.existsSync(abs(ANOMALY_AUTHORITY, root))) {
    const state = requireDesignManifest ? validateManifestState(buffer, { root, includeDesign: true, includeExecution: false }) : validateManifestState(buffer, { root, includeDesign: false, includeExecution: false });
    errors.push(...state.errors);
    errors.push(...originalOutputIdentityErrors(root));
  } else if (requireDesignManifest) errors.push('ANOMALY_AUTHORITY_MISSING');
  return [...new Set(errors)];
}
 
export function prewriteErrors({ root = ROOT, token = '', requireRelease = true } = {}) {
  const errors = [...designInputErrors({ root, requireDesignManifest: true })];
  if (token !== EXEC_TOKEN) errors.push('EXECUTION_TOKEN_MISMATCH');
  for (const relative of GENERATED) if (fs.existsSync(abs(relative, root))) errors.push(`GENERATED_TARGET_EXISTS:${relative}`);
  if (requireRelease) errors.push(...releaseErrors(root));
  const state = validateManifestState(fs.readFileSync(abs(MANIFEST, root)), { root, includeDesign: true, includeExecution: false });
  if (state.logicalRows.some(row => row.run_id === EXEC_RUN)) errors.push('EXECUTION_MANIFEST_ROWS_ALREADY_EXIST');
  return [...new Set(errors)];
}
 
function baselineRows(root, checkedAt) {
  const release = auditEntry(RELEASE_AUDIT, root);
  const manifestIdentity = fileIdentity(MANIFEST, root);
  const rows = [{
    baseline_id: 'DGTMIR-EXEC-BASE-001', artifact_role: 'APPEND_STABLE_RELEASE_ENTRY', artifact_path: `${AUDIT_REPORT}#L${release.start}-L${release.end}`,
    rows: String(release.rows), bytes: String(release.bytes), sha256: release.sha256, mtime: '', required_state: 'EXACT_ENTRY_IDENTITY', checked_at: checkedAt,
  }, {
    baseline_id: 'DGTMIR-EXEC-BASE-002', artifact_role: 'PREWRITE_MANIFEST', artifact_path: MANIFEST,
    rows: String(manifestIdentity.rows), bytes: String(manifestIdentity.bytes), sha256: manifestIdentity.sha256, mtime: manifestIdentity.mtime, required_state: 'EXACT_PREWRITE_APPEND_STABLE_STATE', checked_at: checkedAt,
  }];
  for (const relative of [PARSER, RUNTIME, ANOMALY_AUTHORITY, CONTRACT, SCHEMA, EXEC_SET, ORIGINAL_EXEC_SET, ...originalExecutionPaths(root)]) {
    const identity = fileIdentity(relative, root);
    rows.push({
      baseline_id: `DGTMIR-EXEC-BASE-${String(rows.length + 1).padStart(3, '0')}`,
      artifact_role: originalExecutionPaths(root).includes(relative) ? 'ORIGINAL_EXECUTION_ARTIFACT_UNCHANGED' : 'FROZEN_REPAIR_INPUT',
      artifact_path: relative,
      rows: String(identity.rows), bytes: String(identity.bytes), sha256: identity.sha256, mtime: identity.mtime,
      required_state: 'EXACT_UNCHANGED', checked_at: checkedAt,
    });
  }
  return rows;
}
 
function registryRows(state) {
  const authority = anomalyRowsFromFile()[0];
  return [{
    anomaly_id: authority.anomaly_id,
    manifest_path: MANIFEST,
    physical_line: authority.physical_line,
    disposition: authority.disposition,
    raw_record_sha256: authority.raw_record_sha256,
    raw_record_bytes: authority.raw_record_bytes,
    observed_header_shape_count: String(state.headerShapeCount),
    logical_data_rows_before_repair_append: String(state.logicalDataRows),
    original_run_rows: '11',
    repair_effect: 'COMPATIBILITY_PARSER_AND_DATA_ONLY_WRITER_NO_MANIFEST_REWRITE',
    status: 'ENUMERATED_LEGACY_ANOMALY_RETAINED_NON_DATA',
  }];
}
 
function applicationRows() {
  return [{
    application_id: 'DGTMIR-APPLICATION-001', anomaly_id: 'MANIFEST-ANOMALY-001',
    action: 'REGISTER_APPEND_STABLE_MANIFEST_COMPATIBILITY', result_status: 'PENDING_INDEPENDENT_EXECUTION_AND_OUTPUT_QUALITY_REVIEW',
    manifest_rewrite: 'NO', business_output_rewrite: 'NO', original_run_rows: '11',
    formal_pool_effect: 'NO_AUTOMATIC_FORMAL_POOL_CHANGE', evidence_strength_effect: 'NO_UPGRADE',
  }];
}
 
function requestText() {
  return `# Detail strengthening gap triage manifest-integrity repair execution review request\n\nsource_audit=${SOURCE_AUDIT}\nsource_execution_run=${ORIGINAL_RUN}\nrepair_release_audit=${RELEASE_AUDIT}\nrepair_batch_id=${EXEC_BATCH}\nrepair_run_id=${EXEC_RUN}\nrepair_scope=append-stable manifest compatibility only\nlegacy_anomaly=physical_line_1605|LEGACY_DUPLICATE_HEADER_NON_DATA_ROW\noriginal_execution_rows=11\nmanifest_rewrite=NO\nbusiness_output_rewrite=NO\nexecution_effect=TRIAGE_ONLY_NO_GAP_CLOSURE\nformal_pool_effect=NO_AUTOMATIC_FORMAL_POOL_CHANGE\nevidence_strength_effect=NO_UPGRADE\n\nIndependent review must verify the exact anomaly authority, data-only repair append, global logical-row parsing, original eleven-row identity, and all repair artifact identities.\n`;
}
 
function validationRows(preState, postState = null) {
  const checks = [
    ['PRIMARY_HEADER', '1', String(preState.primaryHeaderCount)],
    ['HEADER_SHAPE_COUNT', '2', String(preState.headerShapeCount)],
    ['AUTHORIZED_ANOMALY', '1', String(preState.anomalies.length)],
    ['ANOMALY_LINE', '1605', preState.anomalies[0]?.physical_line ?? 'MISSING'],
    ['ANOMALY_DISPOSITION', 'LEGACY_DUPLICATE_HEADER_NON_DATA_ROW', preState.anomalies[0]?.disposition ?? 'MISSING'],
    ['ORIGINAL_RUN_ROWS', '11', String(preState.logicalRows.filter(row => row.run_id === ORIGINAL_RUN).length)],
    ['ORIGINAL_RUN_UNIQUE_PATHS', '11', String(new Set(preState.logicalRows.filter(row => row.run_id === ORIGINAL_RUN).map(row => row.artifact_path)).size)],
    ['PREWRITE_GLOBAL_ERRORS', '0', String(preState.errors.length)],
    ['MANIFEST_REWRITE', 'NO', 'NO'],
    ['BUSINESS_OUTPUT_REWRITE', 'NO', 'NO'],
    ['FORMAL_POOL_EFFECT', 'NO_AUTOMATIC_FORMAL_POOL_CHANGE', 'NO_AUTOMATIC_FORMAL_POOL_CHANGE'],
    ['EVIDENCE_STRENGTH_EFFECT', 'NO_UPGRADE', 'NO_UPGRADE'],
    ['REPAIR_APPEND_SERIALIZATION', 'DATA_ROWS_ONLY_NO_HEADER', 'DATA_ROWS_ONLY_NO_HEADER'],
    ['REPAIR_EXACT_SET', String(EXEC_PATHS.length), String(EXEC_PATHS.length)],
    ['POSTWRITE_GLOBAL_ERRORS', postState ? '0' : 'DEFERRED_POSTWRITE', postState ? String(postState.errors.length) : 'DEFERRED_POSTWRITE'],
  ];
  const rows = checks.map((check, index) => ({
    check_id: `DGTMIR-EXEC-VAL-${String(index + 1).padStart(3, '0')}`,
    check_description: check[0], expected: check[1], actual: check[2], status: check[1] === check[2] ? 'PASS' : 'FAIL', evidence: 'append-stable manifest runtime oracle',
  }));
  rows.push({ check_id: 'DGTMIR-EXEC-VAL-016', 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 outputErrors(root = ROOT) {
  const errors = [];
  const definitions = [
    [EXEC_BASELINE, BASELINE_COLUMNS, null, 'BASELINE'],
    [ANOMALY_REGISTRY, REGISTRY_COLUMNS, 1, 'REGISTRY'],
    [APPLICATION, APPLICATION_COLUMNS, 1, 'APPLICATION'],
    [EXEC_VALIDATION, VALIDATION_COLUMNS, 16, 'VALIDATION'],
  ];
  for (const [relative, columns, count, code] of definitions) {
    if (!fs.existsSync(abs(relative, root))) { errors.push(`${code}_MISSING`); continue; }
    const parsed = readCsv(relative, root);
    if (parsed.header.join('|') !== columns.join('|')) errors.push(`${code}_COLUMNS`);
    if (count !== null && parsed.rows.length !== count) errors.push(`${code}_ROWS:${parsed.rows.length}:${count}`);
  }
  if (!fs.existsSync(abs(EXEC_REQUEST, root)) || fs.readFileSync(abs(EXEC_REQUEST, root), 'utf8') !== requestText()) errors.push('REQUEST_EXACT_TEXT');
  if (fs.existsSync(abs(ANOMALY_REGISTRY, root))) {
    const row = readCsv(ANOMALY_REGISTRY, root).rows[0];
    if (row?.physical_line !== '1605' || row?.disposition !== 'LEGACY_DUPLICATE_HEADER_NON_DATA_ROW' || row?.manifest_rewrite !== undefined) errors.push('REGISTRY_EXACT');
  }
  if (fs.existsSync(abs(APPLICATION, root))) {
    const row = readCsv(APPLICATION, root).rows[0];
    if (row?.manifest_rewrite !== 'NO' || row?.business_output_rewrite !== 'NO' || row?.formal_pool_effect !== 'NO_AUTOMATIC_FORMAL_POOL_CHANGE' || row?.evidence_strength_effect !== 'NO_UPGRADE') errors.push('APPLICATION_BOUNDARY');
  }
  if (fs.existsSync(abs(EXEC_VALIDATION, root))) {
    const rows = readCsv(EXEC_VALIDATION, root).rows;
    if (rows.some(row => row.status === 'FAIL' || (row.status === 'PASS' && row.expected !== row.actual)) || rows.filter(row => row.status === 'INFO').length !== 1) errors.push('VALIDATION_RESULT');
  }
  return errors;
}
 
export function executionErrors(root = ROOT) {
  const errors = [...outputErrors(root), ...originalOutputIdentityErrors(root)];
  if (!errors.some(error => error.endsWith('_MISSING'))) {
    const state = validateManifestState(fs.readFileSync(abs(MANIFEST, root)), { root, includeDesign: true, includeExecution: true });
    errors.push(...state.errors);
  }
  return [...new Set(errors)];
}
 
function cleanup(root, before, beforeMtime) {
  const errors = [];
  for (const relative of GENERATED) {
    try { if (fs.existsSync(abs(relative, root))) fs.rmSync(abs(relative, root)); }
    catch (error) { errors.push(`CLEANUP_REMOVE:${relative}:${error.message}`); }
  }
  try {
    fs.writeFileSync(abs(MANIFEST, root), before);
    fs.utimesSync(abs(MANIFEST, root), beforeMtime, beforeMtime);
  } catch (error) { errors.push(`CLEANUP_MANIFEST:${error.message}`); }
  if (!fs.readFileSync(abs(MANIFEST, root)).equals(before)) errors.push('CLEANUP_MANIFEST_BYTES');
  for (const relative of GENERATED) if (fs.existsSync(abs(relative, root))) errors.push(`CLEANUP_REMAINS:${relative}`);
  return errors;
}
 
export function execute({ root = ROOT, token = '', hooks = {} } = {}) {
  const prewrite = prewriteErrors({ root, token, requireRelease: true });
  if (prewrite.length) return { status: 'HELD_PREWRITE', errors: prewrite };
  const before = fs.readFileSync(abs(MANIFEST, root));
  const beforeMtime = fs.statSync(abs(MANIFEST, root)).mtime;
  const checkedAt = new Date().toISOString();
  try {
    const preState = validateManifestState(before, { root, includeDesign: true, includeExecution: false });
    writeText(EXEC_BASELINE, serializeCsv(baselineRows(root, checkedAt), BASELINE_COLUMNS), root);
    writeText(ANOMALY_REGISTRY, serializeCsv(registryRows(preState), REGISTRY_COLUMNS), root);
    writeText(APPLICATION, serializeCsv(applicationRows(), APPLICATION_COLUMNS), root);
    writeText(EXEC_REQUEST, requestText(), root);
    writeText(EXEC_VALIDATION, serializeCsv(validationRows(preState), VALIDATION_COLUMNS), root);
    const outputValidation = outputErrors(root);
    if (outputValidation.length) throw new Error(`OUTPUT:${outputValidation.join('|')}`);
    const manifestRows = expectedManifestRows(EXEC_PATHS, EXEC_RUN, EXEC_BATCH, root);
    const append = Buffer.from(serializeManifestDataRows(manifestRows), 'utf8');
    if (append.toString('utf8').includes(`${PRIMARY_HEADER_TEXT}\n`)) throw new Error('REPAIR_APPEND_CONTAINS_HEADER');
    const candidate = Buffer.concat([before, append]);
    const candidateState = validateManifestState(candidate, { root, includeDesign: true, includeExecution: true });
    if (candidateState.errors.length) throw new Error(`MANIFEST_CANDIDATE:${candidateState.errors.join('|')}`);
    if (hooks.beforeManifestWrite) hooks.beforeManifestWrite();
    fs.writeFileSync(abs(MANIFEST, root), candidate);
    if (hooks.afterManifestWrite) hooks.afterManifestWrite();
    const finalErrors = executionErrors(root);
    if (finalErrors.length) throw new Error(`POSTCOMMIT:${finalErrors.join('|')}`);
    return { status: 'EXECUTED_PENDING_INDEPENDENT_REVIEW', anomaly_count: 1, original_run_rows: 11, repair_manifest_rows: EXEC_PATHS.length, checked_at: checkedAt };
  } catch (error) {
    const cleanupErrors = cleanup(root, before, beforeMtime);
    return { status: cleanupErrors.length ? 'ROLLBACK_INCOMPLETE_HELD' : 'ROLLED_BACK_SAFE', errors: [error.message, ...cleanupErrors] };
  }
}
 
function mutateRecord(buffer, line, mutate) {
  const text = buffer.toString('utf8');
  const records = text.match(/.*?(?:\r\n|\n|$)/g).filter(Boolean);
  records[line - 1] = mutate(records[line - 1]);
  return Buffer.from(records.join(''), 'utf8');
}
 
function validatePrivate(buffer, authority = anomalyAuthorityRows(), options = {}) {
  return validateAppendStableManifest(buffer, {
    anomalyRows: authority,
    frozenPrefix: options.skipPrefix ? undefined : FROZEN_ANOMALOUS_MANIFEST,
    originalRunId: ORIGINAL_RUN,
    originalRunExpectedRows: 11,
    expectedRunId: options.expectedRunId,
    expectedRunRows: options.expectedRunRows ?? [],
    expectedPhysicalDelta: options.expectedPhysicalDelta,
  }).errors;
}
 
export function negativeRows(root = ROOT) {
  const base = fs.readFileSync(abs(MANIFEST, root)).subarray(0, FROZEN_ANOMALOUS_MANIFEST.bytes);
  const authority = anomalyAuthorityRows();
  const original = validateAppendStableManifest(base, { anomalyRows: authority, frozenPrefix: FROZEN_ANOMALOUS_MANIFEST, originalRunId: ORIGINAL_RUN, originalRunExpectedRows: 11 });
  const originalRow = original.logicalRows.find(row => row.run_id === ORIGINAL_RUN);
  const results = [];
  const add = (id, errors, expectedCode, expectAccept = false) => results.push({
    test_id: id, mutation_applied: id === 'CLEAN_BASELINE' ? 'NO' : 'YES', oracle: 'validateAppendStableManifest', expected: expectAccept ? 'ACCEPT' : 'REJECT', expected_code: expectedCode,
    actual: errors.length ? 'REJECT' : 'ACCEPT', actual_codes: errors.join('|') || 'NONE', result: expectAccept ? (errors.length ? 'FAIL' : 'PASS') : (errors.some(error => error.startsWith(expectedCode)) ? 'PASS' : 'FAIL'),
  });
  add('CLEAN_BASELINE', original.errors, 'NONE', true);
  add('EXTRA_HEADER', validatePrivate(Buffer.concat([base, Buffer.from(`${PRIMARY_HEADER_TEXT}\n`)]), authority, { expectedPhysicalDelta: 1 }), 'UNAUTHORIZED_HEADER_SHAPED_ROW');
  add('ALTERED_ANOMALY_HEADER', validatePrivate(mutateRecord(base, 1605, record => record.replace('"case_id"', '"case_idx"')), authority), 'ANOMALY_HEADER_SHAPE');
  add('MISSING_ANOMALY_AUTHORITY', validatePrivate(base, []), 'UNAUTHORIZED_HEADER_SHAPED_ROW');
  const movedText = base.toString('utf8').split('\n');
  const anomalyLine = `${movedText.splice(1604, 1)[0]}\n`;
  add('MOVED_ANOMALY', validatePrivate(Buffer.from(`${movedText.join('\n')}${anomalyLine}`, 'utf8'), authority, { skipPrefix: true }), 'ANOMALY_HEADER_SHAPE');
  add('DUPLICATE_ORIGINAL_RUN_ROW', validatePrivate(Buffer.concat([base, Buffer.from(serializeManifestDataRows([originalRow]))]), authority), 'ORIGINAL_RUN_ROWS');
  const expected = { case_id: CASE_ID, run_id: 'NEGATIVE-RUN', batch_id: 'NEGATIVE-BATCH', artifact_path: 'tmp/negative.csv', sha256: 'a'.repeat(64), bytes: '1', mtime: '2026-07-30T00:00:00.000Z' };
  for (const field of MANIFEST_COLUMNS) {
    const mutated = { ...expected };
    mutated[field] = field === 'sha256' ? 'b'.repeat(64) : field === 'bytes' ? '2' : field === 'mtime' ? '2026-07-30T00:00:00.001Z' : `WRONG-${field}`;
    const candidate = Buffer.concat([base, Buffer.from(serializeManifestDataRows([mutated]))]);
    add(`WRONG_SEVEN_FIELD_${field.toUpperCase()}`, validatePrivate(candidate, authority, { expectedRunId: expected.run_id, expectedRunRows: [expected], expectedPhysicalDelta: 1 }), 'EXPECTED_RUN_FIELD');
  }
  const drift = Buffer.from(base); drift[0] = drift[0] === 34 ? 35 : 34;
  add('PREFIX_DRIFT', validatePrivate(drift, authority), 'MANIFEST_PREFIX_DRIFT');
  const withHeader = Buffer.concat([base, Buffer.from(serializeCsv([expected], MANIFEST_COLUMNS))]);
  add('FUTURE_WRITER_WITH_HEADER', validatePrivate(withHeader, authority, { expectedRunId: expected.run_id, expectedRunRows: [expected], expectedPhysicalDelta: 2 }), 'UNAUTHORIZED_HEADER_SHAPED_ROW');
  const dataOnly = Buffer.concat([base, Buffer.from(serializeManifestDataRows([expected]))]);
  add('DATA_ONLY_APPEND_ACCEPTED', validatePrivate(dataOnly, authority, { expectedRunId: expected.run_id, expectedRunRows: [expected], expectedPhysicalDelta: 1 }), 'NONE', true);
  return results;
}
 
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const mode = process.argv[2] ?? '--preview';
  if (mode === '--preview') {
    const authority = fs.existsSync(abs(ANOMALY_AUTHORITY)) ? anomalyRowsFromFile() : anomalyAuthorityRows();
    const buffer = fs.readFileSync(abs(MANIFEST));
    const state = validateAppendStableManifest(buffer.subarray(0, FROZEN_ANOMALOUS_MANIFEST.bytes), { anomalyRows: authority, frozenPrefix: FROZEN_ANOMALOUS_MANIFEST, originalRunId: ORIGINAL_RUN, originalRunExpectedRows: 11 });
    console.log(JSON.stringify({ status: state.errors.length ? 'FAIL' : 'PASS_PREVIEW_NO_WRITE', errors: state.errors, physical_records: state.physicalRecords, logical_data_rows: state.logicalDataRows, anomaly_count: state.anomalies.length, header_shape_count: state.headerShapeCount }, null, 2));
    if (state.errors.length) process.exitCode = 1;
  } else if (mode === '--self-test-json') {
    const rows = negativeRows();
    console.log(JSON.stringify(rows, null, 2));
    if (rows.some(row => row.result !== 'PASS')) process.exitCode = 1;
  } else if (mode === '--validate-design-inputs') {
    const errors = designInputErrors({ requireDesignManifest: fs.existsSync(abs(DESIGN_SET)) });
    console.log(JSON.stringify({ status: errors.length ? 'FAIL' : 'PASS_DESIGN_INPUTS', errors }, null, 2));
    if (errors.length) process.exitCode = 1;
  } else if (mode === '--validate-prewrite') {
    const errors = prewriteErrors({ token: EXEC_TOKEN, requireRelease: true });
    console.log(JSON.stringify({ status: errors.length ? 'HELD_PREWRITE' : 'PASS_PREWRITE', errors }, null, 2));
    if (errors.length) process.exitCode = 1;
  } else if (mode === '--execute') {
    const token = (process.argv.find(argument => argument.startsWith('--token=')) ?? '').slice(8);
    const result = execute({ token });
    console.log(JSON.stringify(result, null, 2));
    if (!result.status.startsWith('EXECUTED')) process.exitCode = 1;
  } else if (mode === '--validate-execution') {
    const errors = executionErrors();
    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}`);
  }
}