@adamchanadam/agent-handoff-kit 0.3.46 → 0.3.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { createInterface } from "node:readline/promises";
4
4
  import { stdin as input, stdout as output } from "node:process";
5
- import { chmod, copyFile, link, lstat, mkdir, open, readFile, readdir, realpath, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { chmod, copyFile, link, lstat, mkdir, open, readFile, readdir, realpath, rename, rmdir, stat, unlink, writeFile } from "node:fs/promises";
6
6
  import { createHash, randomUUID } from "node:crypto";
7
7
  import { hostname } from "node:os";
8
8
  import path from "node:path";
@@ -39,6 +39,11 @@ const directStatefulTargets = new Set([
39
39
  "dev/PROJECT_INDEX.md",
40
40
  "dev/SESSION_LOG.md"
41
41
  ]);
42
+ const closeoutFinalizeTargets = new Set([
43
+ ...directStatefulTargets,
44
+ "dev/DOC_SYNC_REGISTRY.md",
45
+ "dev/PROJECT_DECISIONS.md"
46
+ ]);
42
47
  const credentialLeakPatterns = [
43
48
  { pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key" },
44
49
  { pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "sk-prefixed token" },
@@ -593,7 +598,12 @@ async function main() {
593
598
  await runCloseoutStatus(root, version);
594
599
  return;
595
600
  }
596
-
601
+
602
+ if (command === "finalize-closeout") {
603
+ await runFinalizeCloseout(root, version);
604
+ return;
605
+ }
606
+
597
607
  throw new Error(`unknown command "${command}"`);
598
608
  }
599
609
 
@@ -625,6 +635,34 @@ async function runCloseoutStatus(root, version) {
625
635
  if (!result.ok) process.exitCode = 1;
626
636
  }
627
637
 
638
+ async function runFinalizeCloseout(root, version) {
639
+ await validateTransactionRoot(root, [], { createMissingRoot: false });
640
+ const archiveCasing = await checkSessionLogArchiveCasing(root);
641
+ if (!archiveCasing.ok) throw new Error(archiveCasing.finding);
642
+ const prior = await findCloseoutFinalizeBase(root);
643
+ if (!prior) {
644
+ console.log("closeout finalized: no post-upgrade current-state witness needed");
645
+ return;
646
+ }
647
+ const illegal = prior.mismatches.filter((item) => !isCloseoutFinalizeTarget(item.path));
648
+ if (illegal.length > 0) {
649
+ throw new Error(`non-closeout drift blocks finalize-closeout: ${illegal.map((item) => item.path).join(", ")}`);
650
+ }
651
+ if (prior.mismatches.length === 0) {
652
+ console.log("closeout finalized: current-state witness already matches project bytes");
653
+ return;
654
+ }
655
+ const transaction = await writeCloseoutFinalizeJournal(root, version, prior);
656
+ const doctorStatus = await runDoctor(root, version, {
657
+ silentCard: true,
658
+ context: "post-closeout-finalize-health",
659
+ expectedCurrentStateWitness: transaction.journal.currentStateWitness
660
+ });
661
+ if (doctorStatus !== "passed") throw new Error("post-closeout finalize doctor failed; finalize journal retained for inspection");
662
+ console.log(`closeout finalized: bound ${prior.mismatches.length} legal closeout state update(s)`);
663
+ console.log(`current-state digest: ${transaction.journal.currentStateWitness.currentStateDigest}`);
664
+ }
665
+
628
666
  function closeoutOutcome(value) {
629
667
  return /^(complete|completed)\b/i.test((value ?? "").trim()) ? "complete" : "blocked";
630
668
  }
@@ -892,21 +930,26 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
892
930
  // transaction already has a runtime acceptance, bind the pre-transaction
893
931
  // root-source witness into the same current-state digest before the journal
894
932
  // directory itself is created.
933
+ const archiveMigrations = command === "upgrade"
934
+ ? await prepareArchiveCasingMigrations(root)
935
+ : [];
895
936
  const sourceConservation = command === "upgrade" && resolveRuntimeAcceptance(outputs)
896
- ? await createSourceConservation(root, outputs)
937
+ ? await createSourceConservation(root, outputs, archiveMigrations)
897
938
  : null;
898
939
  // A repair may restore the exact bytes of a prior committed state. Keep the
899
940
  // causal replacement relation inside the existing sealed journal so ordinary
900
941
  // doctor can select the freshly read-back transaction without falling back
901
942
  // to mtime or a separate current-state registry.
902
943
  const supersedesCurrentStateDigests = command === "upgrade"
903
- ? await findRestoredCurrentStateDigests(root, outputs)
944
+ ? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations)
904
945
  : [];
905
- const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation, supersedesCurrentStateDigests);
946
+ const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation, supersedesCurrentStateDigests, archiveMigrations);
906
947
  try {
907
- transaction.journal.state = "committing";
908
- await writeSecureJson(transaction.journalPath, transaction.journal);
909
-
948
+ transaction.journal.state = "committing";
949
+ await writeSecureJson(transaction.journalPath, transaction.journal);
950
+
951
+ await applyArchiveCasingMigrations(root, transaction);
952
+
910
953
  let committedCount = 0;
911
954
  const qaFailAfterCommit = Number.parseInt(process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_COMMIT ?? "", 10);
912
955
  const qaFailAfterCommitTarget = process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_COMMIT_TARGET ?? null;
@@ -1005,7 +1048,13 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
1005
1048
  console.log("✅ project health: passed");
1006
1049
  }
1007
1050
  } catch (error) {
1008
- if (["ACK_QA_INTERRUPT_AFTER_REPLACE", "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT"].includes(error?.code)) throw error;
1051
+ if ([
1052
+ "ACK_QA_INTERRUPT_AFTER_REPLACE",
1053
+ "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT",
1054
+ "ACK_QA_INTERRUPT_AFTER_ARCHIVE_RELOCATE_BEFORE_STAGE",
1055
+ "ACK_QA_INTERRUPT_AFTER_ARCHIVE_STAGE",
1056
+ "ACK_QA_INTERRUPT_AFTER_ARCHIVE_MATERIALIZE_BEFORE_JOURNAL"
1057
+ ].includes(error?.code)) throw error;
1009
1058
  if (isNoClobberConflict(error)) {
1010
1059
  transaction.journal.state = "manual-recovery-required";
1011
1060
  transaction.journal.committedVersion = null;
@@ -1186,7 +1235,8 @@ async function synchronizeFormalUserRulesTransactionState(command, root, byTarge
1186
1235
  if (agentOutput.after) {
1187
1236
  const renderedBytes = encodeLikeExisting(renderedAgentsText, agentOutput.before, "AGENTS.md");
1188
1237
  if (!agentOutput.after.equals(renderedBytes)) {
1189
- throw new Error("formal user-rules transition would alter preserved AGENTS.md bytes; upgrade stops instead of rewriting a non-exact source");
1238
+ agentOutput.after = renderedBytes;
1239
+ agentOutput.reason = "formal user-rules acceptance digest transition";
1190
1240
  }
1191
1241
  }
1192
1242
  agentOutput.afterText = renderedAgentsText;
@@ -1230,18 +1280,20 @@ function createFormalUserRulesWitness(entries, state, acceptanceDigest) {
1230
1280
  });
1231
1281
  }
1232
1282
 
1233
- async function prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation = null, supersedesCurrentStateDigests = []) {
1283
+ async function prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation = null, supersedesCurrentStateDigests = [], archiveMigrations = []) {
1234
1284
  const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
1235
1285
  const migrationsRoot = path.join(root, "dev", "governance_migrations");
1236
1286
  const migrationDir = path.join(migrationsRoot, id);
1237
1287
  const backupDir = path.join(migrationDir, "backup");
1238
1288
  const stageDir = path.join(migrationDir, "stage");
1239
1289
  const escrowDir = path.join(migrationDir, "no-clobber-escrow");
1290
+ const archiveBackupDir = path.join(migrationDir, "archive-backup");
1240
1291
  const journalPath = path.join(migrationDir, "transaction.json");
1241
1292
  const lockPath = path.join(migrationsRoot, ".upgrade.lock");
1242
1293
  await mkdir(backupDir, { recursive: true });
1243
1294
  await mkdir(stageDir, { recursive: true });
1244
1295
  await mkdir(escrowDir, { recursive: true });
1296
+ await mkdir(archiveBackupDir, { recursive: true });
1245
1297
  await tightenPermissions(migrationsRoot, 0o700);
1246
1298
  await tightenPermissions(migrationDir, 0o700);
1247
1299
  const lock = await open(lockPath, "wx", 0o600).catch((error) => {
@@ -1282,6 +1334,11 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, s
1282
1334
  runtimeAcceptance: resolveRuntimeAcceptance(outputs),
1283
1335
  runtimeAcceptanceReadback: null,
1284
1336
  sourceConservation,
1337
+ archiveMigrations: archiveMigrations.map((migration, index) => ({
1338
+ ...migration,
1339
+ stageRel: `archive-backup/${index}`,
1340
+ state: "prepared"
1341
+ })),
1285
1342
  ...(supersedesCurrentStateDigests.length > 0 ? { supersedesCurrentStateDigests } : {}),
1286
1343
  currentStateWitness: null,
1287
1344
  currentStateReadback: null
@@ -1291,8 +1348,281 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, s
1291
1348
  // independently authorise doctor/report/success.
1292
1349
  journal.currentStateWitness = createCurrentStateWitness(journal);
1293
1350
  await writeSecureJson(journalPath, journal);
1294
- return { id, migrationDir, backupDir, stageDir, escrowDir, journalPath, lockPath, journal };
1295
- }
1351
+ return { id, migrationDir, backupDir, stageDir, escrowDir, archiveBackupDir, journalPath, lockPath, journal };
1352
+ }
1353
+
1354
+ async function prepareArchiveCasingMigrations(root) {
1355
+ const devDir = path.join(root, "dev");
1356
+ let entries;
1357
+ try {
1358
+ entries = await readdir(devDir, { withFileTypes: true });
1359
+ } catch (error) {
1360
+ if (error?.code === "ENOENT") return [];
1361
+ throw error;
1362
+ }
1363
+ const matches = entries
1364
+ .filter((entry) => entry.isDirectory() && entry.name.toLowerCase() === "session_log_archive")
1365
+ .map((entry) => entry.name)
1366
+ .sort((left, right) => left.localeCompare(right));
1367
+ if (matches.length === 0 || (matches.length === 1 && matches[0] === "SESSION_LOG_archive")) return [];
1368
+ if (matches.includes("SESSION_LOG_archive") || matches.length !== 1) {
1369
+ throw new Error(`archive casing migration is ambiguous: ${matches.map((name) => `dev/${name}`).join(", ")}`);
1370
+ }
1371
+ const originalRel = `dev/${matches[0]}`;
1372
+ return [{
1373
+ schemaVersion: 1,
1374
+ originalRel,
1375
+ canonicalRel: "dev/SESSION_LOG_archive",
1376
+ snapshot: await snapshotDirectoryTree(root, originalRel)
1377
+ }];
1378
+ }
1379
+
1380
+ async function applyArchiveCasingMigrations(root, transaction) {
1381
+ for (const migration of transaction.journal.archiveMigrations ?? []) {
1382
+ const migrationDir = transaction.migrationDir;
1383
+ const originalAbs = path.join(root, migration.originalRel);
1384
+ const canonicalAbs = path.join(root, migration.canonicalRel);
1385
+ const stageAbs = path.join(migrationDir, migration.stageRel);
1386
+ if (migration.state === "prepared") {
1387
+ await assertExactDirectorySnapshot(root, migration.originalRel, migration.snapshot, "archive migration source changed before transaction commit");
1388
+ await assertExactProjectDirectoryAbsent(root, migration.canonicalRel, "canonical archive path appeared before transaction commit");
1389
+ if (await pathExists(stageAbs)) throw noClobberConflict(`${migration.originalRel}: transaction archive backup already exists; recovery lock retained`);
1390
+ await mkdir(path.dirname(stageAbs), { recursive: true });
1391
+ migration.state = "relocating";
1392
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1393
+ }
1394
+ if (migration.state === "relocating") {
1395
+ await rename(originalAbs, stageAbs);
1396
+ await assertExactProjectDirectoryAbsent(root, migration.originalRel, "archive source remains after relocation");
1397
+ await assertDirectorySnapshotAtPath(stageAbs, migration.snapshot, "archive backup differs after relocation");
1398
+ if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_ARCHIVE_RELOCATE_BEFORE_STAGE === "1") {
1399
+ const interruption = new Error("QA interruption after archive relocation before staged journal");
1400
+ interruption.code = "ACK_QA_INTERRUPT_AFTER_ARCHIVE_RELOCATE_BEFORE_STAGE";
1401
+ throw interruption;
1402
+ }
1403
+ migration.state = "staged";
1404
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1405
+ if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_ARCHIVE_STAGE === "1") {
1406
+ const interruption = new Error("QA interruption after archive relocation");
1407
+ interruption.code = "ACK_QA_INTERRUPT_AFTER_ARCHIVE_STAGE";
1408
+ throw interruption;
1409
+ }
1410
+ }
1411
+ if (migration.state === "staged") {
1412
+ migration.state = "materializing";
1413
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1414
+ }
1415
+ if (migration.state === "materializing") {
1416
+ await materializeArchiveCanonicalPath(root, migration, stageAbs);
1417
+ if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_ARCHIVE_MATERIALIZE_BEFORE_JOURNAL === "1") {
1418
+ const interruption = new Error("QA interruption after archive canonical materialization before materialized journal");
1419
+ interruption.code = "ACK_QA_INTERRUPT_AFTER_ARCHIVE_MATERIALIZE_BEFORE_JOURNAL";
1420
+ throw interruption;
1421
+ }
1422
+ migration.state = "materialized";
1423
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1424
+ if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_ARCHIVE_MATERIALIZE === "1") {
1425
+ throw new Error("QA fault injection after archive canonical materialization");
1426
+ }
1427
+ }
1428
+ if (migration.state !== "materialized") throw new Error("archive migration journal state is invalid during commit");
1429
+ }
1430
+ }
1431
+
1432
+ async function materializeArchiveCanonicalPath(root, migration, stageAbs) {
1433
+ await assertDirectorySnapshotAtPath(stageAbs, migration.snapshot, "archive backup changed before canonical materialization");
1434
+ await assertExactProjectDirectoryAbsent(root, migration.canonicalRel, "canonical archive path appeared during transaction");
1435
+ const canonicalAbs = path.join(root, migration.canonicalRel);
1436
+ try {
1437
+ await mkdir(canonicalAbs);
1438
+ } catch (error) {
1439
+ if (error?.code === "EEXIST") throw noClobberConflict(`${migration.canonicalRel}: canonical archive path appeared during transaction; recovery lock retained`);
1440
+ throw error;
1441
+ }
1442
+ for (const directory of migration.snapshot.directories.filter((item) => item).sort((left, right) => left.localeCompare(right))) {
1443
+ try {
1444
+ await mkdir(path.join(canonicalAbs, directory));
1445
+ } catch (error) {
1446
+ if (error?.code === "EEXIST") throw noClobberConflict(`${migration.canonicalRel}/${directory}: archive directory appeared during transaction; recovery lock retained`);
1447
+ throw error;
1448
+ }
1449
+ }
1450
+ for (const file of migration.snapshot.files) {
1451
+ const source = path.join(stageAbs, file.path);
1452
+ const target = path.join(canonicalAbs, file.path);
1453
+ const sourceBytes = await readFile(source);
1454
+ if (sourceBytes.length !== file.bytes || sha256(sourceBytes) !== file.sha256) {
1455
+ throw new Error(`${migration.originalRel}/${file.path}: archive backup bytes changed before canonical materialization`);
1456
+ }
1457
+ try {
1458
+ await writeFile(target, sourceBytes, { mode: 0o600, flag: "wx" });
1459
+ } catch (error) {
1460
+ if (error?.code === "EEXIST") throw noClobberConflict(`${migration.canonicalRel}/${file.path}: archive file appeared during transaction; recovery lock retained`);
1461
+ throw error;
1462
+ }
1463
+ }
1464
+ await assertExactDirectorySnapshot(root, migration.canonicalRel, migration.snapshot, "canonical archive materialization did not retain source bytes");
1465
+ }
1466
+
1467
+ async function snapshotDirectoryTree(root, relative) {
1468
+ const absolute = path.join(root, relative);
1469
+ return snapshotDirectoryTreeAtPath(absolute);
1470
+ }
1471
+
1472
+ async function snapshotDirectoryTreeAtPath(absolute) {
1473
+ const rootStats = await lstat(absolute).catch((error) => error?.code === "ENOENT" ? null : Promise.reject(error));
1474
+ if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) throw new Error("archive migration directory is missing or unsafe");
1475
+ const directories = [""];
1476
+ const files = [];
1477
+ async function visit(current, relative) {
1478
+ const entries = await readdir(current, { withFileTypes: true });
1479
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
1480
+ const childRelative = relative ? `${relative}/${entry.name}` : entry.name;
1481
+ const child = path.join(current, entry.name);
1482
+ if (entry.isDirectory()) {
1483
+ const stats = await lstat(child);
1484
+ if (stats.isSymbolicLink()) throw new Error(`${childRelative}: archive migration does not accept symbolic links or junctions`);
1485
+ directories.push(childRelative);
1486
+ await visit(child, childRelative);
1487
+ } else if (entry.isFile()) {
1488
+ const stats = await lstat(child);
1489
+ if (stats.isSymbolicLink()) throw new Error(`${childRelative}: archive migration does not accept symbolic links`);
1490
+ const bytes = await readFile(child);
1491
+ files.push({ path: childRelative, sha256: sha256(bytes), bytes: bytes.length });
1492
+ } else {
1493
+ throw new Error(`${childRelative}: archive migration accepts only regular files and directories`);
1494
+ }
1495
+ }
1496
+ }
1497
+ await visit(absolute, "");
1498
+ directories.sort((left, right) => left.localeCompare(right));
1499
+ files.sort((left, right) => left.path.localeCompare(right.path));
1500
+ const body = { schemaVersion: 1, directories, files };
1501
+ return { ...body, manifestSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) };
1502
+ }
1503
+
1504
+ function validateArchiveSnapshot(snapshot) {
1505
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)
1506
+ || snapshot.schemaVersion !== 1
1507
+ || !Array.isArray(snapshot.directories) || snapshot.directories[0] !== ""
1508
+ || !Array.isArray(snapshot.files)
1509
+ || typeof snapshot.manifestSha256 !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.manifestSha256)) {
1510
+ throw new Error("archive migration snapshot is invalid; no recovery writes attempted");
1511
+ }
1512
+ const seenDirectories = new Set();
1513
+ let previousDirectory = null;
1514
+ for (const directory of snapshot.directories) {
1515
+ if (typeof directory !== "string" || (directory && !isSafeProjectRelative(directory)) || seenDirectories.has(directory)
1516
+ || (previousDirectory != null && previousDirectory.localeCompare(directory) >= 0)) {
1517
+ throw new Error("archive migration directory snapshot is invalid; no recovery writes attempted");
1518
+ }
1519
+ seenDirectories.add(directory);
1520
+ previousDirectory = directory;
1521
+ }
1522
+ const seenFiles = new Set();
1523
+ let previousFile = null;
1524
+ for (const file of snapshot.files) {
1525
+ if (!file || typeof file !== "object" || Array.isArray(file)
1526
+ || !isSafeProjectRelative(file.path) || seenFiles.has(file.path)
1527
+ || !Number.isInteger(file.bytes) || file.bytes < 0
1528
+ || typeof file.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(file.sha256)
1529
+ || (previousFile != null && previousFile.localeCompare(file.path) >= 0)) {
1530
+ throw new Error("archive migration file snapshot is invalid; no recovery writes attempted");
1531
+ }
1532
+ seenFiles.add(file.path);
1533
+ previousFile = file.path;
1534
+ }
1535
+ const body = { schemaVersion: snapshot.schemaVersion, directories: snapshot.directories, files: snapshot.files };
1536
+ if (sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) !== snapshot.manifestSha256) {
1537
+ throw new Error("archive migration snapshot digest is invalid; no recovery writes attempted");
1538
+ }
1539
+ return snapshot;
1540
+ }
1541
+
1542
+ function archiveMigrationWitness(migration) {
1543
+ return {
1544
+ schemaVersion: migration.schemaVersion,
1545
+ originalRel: migration.originalRel,
1546
+ canonicalRel: migration.canonicalRel,
1547
+ snapshot: migration.snapshot
1548
+ };
1549
+ }
1550
+
1551
+ function validateArchiveMigrations(value, { requireMaterialized = false } = {}) {
1552
+ if (!Array.isArray(value) || value.length === 0) {
1553
+ throw new Error("archive migration journal is missing or invalid; no recovery writes attempted");
1554
+ }
1555
+ const seenOriginal = new Set();
1556
+ const seenCanonical = new Set();
1557
+ let previous = null;
1558
+ for (const migration of value) {
1559
+ if (!migration || typeof migration !== "object" || Array.isArray(migration)
1560
+ || migration.schemaVersion !== 1
1561
+ || !isSafeProjectRelative(migration.originalRel) || !migration.originalRel.startsWith("dev/")
1562
+ || migration.canonicalRel !== "dev/SESSION_LOG_archive"
1563
+ || seenOriginal.has(migration.originalRel) || seenCanonical.has(migration.canonicalRel)
1564
+ || (previous != null && previous.localeCompare(migration.originalRel) >= 0)) {
1565
+ throw new Error("archive migration journal entry is invalid; no recovery writes attempted");
1566
+ }
1567
+ if (migration.stageRel !== undefined && (!isSafeProjectRelative(migration.stageRel) || !migration.stageRel.startsWith("archive-backup/"))) {
1568
+ throw new Error("archive migration backup path is invalid; no recovery writes attempted");
1569
+ }
1570
+ if (migration.state !== undefined && !["prepared", "relocating", "staged", "materializing", "materialized"].includes(migration.state)) {
1571
+ throw new Error("archive migration state is invalid; no recovery writes attempted");
1572
+ }
1573
+ if (requireMaterialized && migration.state !== undefined && migration.state !== "materialized") {
1574
+ throw new Error("committed archive migration is not materialized; no recovery writes attempted");
1575
+ }
1576
+ validateArchiveSnapshot(migration.snapshot);
1577
+ seenOriginal.add(migration.originalRel);
1578
+ seenCanonical.add(migration.canonicalRel);
1579
+ previous = migration.originalRel;
1580
+ }
1581
+ return value;
1582
+ }
1583
+
1584
+ async function assertDirectorySnapshotAtPath(absolute, expected, reason) {
1585
+ const actual = await snapshotDirectoryTreeAtPath(absolute);
1586
+ if (actual.manifestSha256 !== expected.manifestSha256) throw new Error(reason);
1587
+ }
1588
+
1589
+ async function assertExactDirectorySnapshot(root, relative, expected, reason) {
1590
+ const exact = await findExactProjectPath(root, relative);
1591
+ if (!exact) throw new Error(reason);
1592
+ await assertDirectorySnapshotAtPath(exact, expected, reason);
1593
+ }
1594
+
1595
+ async function assertExactProjectDirectoryAbsent(root, relative, reason) {
1596
+ if (await findExactProjectPath(root, relative)) throw noClobberConflict(reason);
1597
+ }
1598
+
1599
+ async function findExactProjectPath(root, relative) {
1600
+ if (!isSafeProjectRelative(relative)) throw new Error("archive migration path is unsafe");
1601
+ let current = root;
1602
+ for (const segment of relative.split("/")) {
1603
+ let entries;
1604
+ try {
1605
+ entries = await readdir(current, { withFileTypes: true });
1606
+ } catch (error) {
1607
+ if (error?.code === "ENOENT") return null;
1608
+ throw error;
1609
+ }
1610
+ const match = entries.find((entry) => entry.name === segment);
1611
+ if (!match) return null;
1612
+ current = path.join(current, match.name);
1613
+ }
1614
+ return current;
1615
+ }
1616
+
1617
+ async function pathExists(filePath) {
1618
+ try {
1619
+ await lstat(filePath);
1620
+ return true;
1621
+ } catch (error) {
1622
+ if (error?.code === "ENOENT") return false;
1623
+ throw error;
1624
+ }
1625
+ }
1296
1626
 
1297
1627
  async function validateTransactionRoot(root, plan, { createMissingRoot = true } = {}) {
1298
1628
  let rootStats;
@@ -1556,32 +1886,46 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1556
1886
  const seen = new Set();
1557
1887
  const formalWitness = validateFormalUserRulesWitness(journal.formalUserRules);
1558
1888
  const runtimeAcceptance = validateRuntimeAcceptance(journal.runtimeAcceptance);
1889
+ const hasArchiveMigrationField = journal.archiveMigrations !== undefined;
1890
+ const requiresArchiveBackup = journal.command === "upgrade" && hasArchiveMigrationField;
1891
+ if (journal.archiveMigrations != null && !Array.isArray(journal.archiveMigrations)) throw new Error("upgrade journal archive migrations are invalid; no recovery writes attempted");
1892
+ const archiveMigrations = (journal.archiveMigrations ?? []).length > 0
1893
+ ? validateArchiveMigrations(journal.archiveMigrations, { requireMaterialized: journal.state === "committed" })
1894
+ : [];
1895
+ if (requiresArchiveBackup && archiveMigrations.some((migration) => !migration.stageRel || migration.state === undefined)) {
1896
+ throw new Error("upgrade journal archive migration recovery fields are missing; no recovery writes attempted");
1897
+ }
1559
1898
  const rootStats = await lstat(root);
1560
1899
  if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) throw new Error("selected recovery root is not a safe directory; no recovery writes attempted");
1561
1900
  const rootReal = await realpath(root);
1562
1901
  const backupRoot = path.join(migrationDir, "backup");
1563
- const stageRoot = path.join(migrationDir, "stage");
1902
+ const stageRoot = path.join(migrationDir, "stage");
1903
+ const archiveBackupRoot = path.join(migrationDir, "archive-backup");
1564
1904
  const migrationsStats = await lstat(migrationsRoot).catch(() => null);
1565
1905
  const migrationStats = await lstat(migrationDir).catch(() => null);
1566
1906
  const journalStats = await lstat(journalPath).catch(() => null);
1567
1907
  const backupStats = await lstat(backupRoot).catch(() => null);
1568
- const stageStats = await lstat(stageRoot).catch(() => null);
1908
+ const stageStats = await lstat(stageRoot).catch(() => null);
1909
+ const archiveBackupStats = requiresArchiveBackup ? await lstat(archiveBackupRoot).catch(() => null) : null;
1569
1910
  if (!migrationsStats?.isDirectory() || migrationsStats.isSymbolicLink()
1570
1911
  || !migrationStats?.isDirectory() || migrationStats.isSymbolicLink()
1571
1912
  || !journalStats?.isFile() || journalStats.isSymbolicLink()
1572
1913
  || !backupStats?.isDirectory() || backupStats.isSymbolicLink()
1573
- || !stageStats?.isDirectory() || stageStats.isSymbolicLink()) {
1914
+ || !stageStats?.isDirectory() || stageStats.isSymbolicLink()
1915
+ || (requiresArchiveBackup && (!archiveBackupStats?.isDirectory() || archiveBackupStats.isSymbolicLink()))) {
1574
1916
  throw new Error("upgrade transaction directories or journal are missing or unsafe; no recovery writes attempted");
1575
1917
  }
1576
1918
  const migrationsReal = await realpath(migrationsRoot);
1577
1919
  const migrationReal = await realpath(migrationDir);
1578
1920
  const journalReal = await realpath(journalPath);
1579
1921
  const backupRealRoot = await realpath(backupRoot);
1580
- const stageRealRoot = await realpath(stageRoot);
1922
+ const stageRealRoot = await realpath(stageRoot);
1923
+ const archiveBackupRealRoot = requiresArchiveBackup ? await realpath(archiveBackupRoot) : null;
1581
1924
  if (!isInside(rootReal, migrationsReal) || !isInside(migrationsReal, migrationReal)
1582
1925
  || !isInside(migrationReal, journalReal) || !isInside(migrationReal, backupRealRoot) || !isInside(migrationReal, stageRealRoot)
1583
1926
  || !samePath(path.dirname(migrationReal), migrationsReal)
1584
- || !samePath(path.dirname(backupRealRoot), migrationReal) || !samePath(path.dirname(stageRealRoot), migrationReal)) {
1927
+ || !samePath(path.dirname(backupRealRoot), migrationReal) || !samePath(path.dirname(stageRealRoot), migrationReal)
1928
+ || (requiresArchiveBackup && !samePath(path.dirname(archiveBackupRealRoot), migrationReal))) {
1585
1929
  throw new Error("upgrade transaction paths resolve outside the selected root or transaction; no recovery writes attempted");
1586
1930
  }
1587
1931
  const validated = [];
@@ -1637,6 +1981,19 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1637
1981
  if (journal.state === "committed" && validated.some(({ entry }) => !entry.committed)) {
1638
1982
  throw new Error("committed upgrade journal contains an uncommitted entry; no recovery writes attempted");
1639
1983
  }
1984
+ if (requiresArchiveBackup) {
1985
+ for (const migration of archiveMigrations) {
1986
+ const stageAbs = path.resolve(migrationDir, migration.stageRel);
1987
+ if (!isInside(archiveBackupRoot, stageAbs)) throw new Error("upgrade archive migration backup escapes this transaction; no recovery writes attempted");
1988
+ const stageStats = await lstat(stageAbs).catch((error) => error?.code === "ENOENT" ? null : Promise.reject(error));
1989
+ if (stageStats) {
1990
+ if (!stageStats.isDirectory() || stageStats.isSymbolicLink()) throw new Error("upgrade archive migration backup is unsafe; no recovery writes attempted");
1991
+ const stageReal = await realpath(stageAbs);
1992
+ if (!isInside(archiveBackupRealRoot, stageReal)) throw new Error("upgrade archive migration backup resolves outside this transaction; no recovery writes attempted");
1993
+ await assertDirectorySnapshotAtPath(stageAbs, migration.snapshot, "upgrade archive migration backup hash does not match the recorded input; no recovery writes attempted");
1994
+ }
1995
+ }
1996
+ }
1640
1997
  if (runtimeAcceptance) {
1641
1998
  for (const accepted of runtimeAcceptance.entries) {
1642
1999
  const transactionEntry = validated.find(({ entry }) => entry.targetRel === accepted.targetRel)?.entry;
@@ -1654,10 +2011,11 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1654
2011
  return validated;
1655
2012
  }
1656
2013
 
1657
- async function rollbackTransaction(root, journal, journalPath, lockId = null) {
1658
- const validated = await validateRecoveryJournal(root, journal, journalPath, lockId);
1659
- const conflicts = [];
1660
- const operations = [];
2014
+ async function rollbackTransaction(root, journal, journalPath, lockId = null) {
2015
+ const validated = await validateRecoveryJournal(root, journal, journalPath, lockId);
2016
+ const conflicts = [];
2017
+ const operations = [];
2018
+ const archiveRollbackPlans = [];
1661
2019
  // Do not trust the committed flag: the process can stop after replacement
1662
2020
  // but before the journal flag is persisted. Inspect every target hash first.
1663
2021
  for (const item of [...validated].reverse()) {
@@ -1668,9 +2026,16 @@ async function rollbackTransaction(root, journal, journalPath, lockId = null) {
1668
2026
  conflicts.push(`${item.entry.targetRel}: current content differs from both transaction input and candidate`);
1669
2027
  continue;
1670
2028
  }
1671
- operations.push(item);
1672
- }
1673
- if (conflicts.length > 0) {
2029
+ operations.push(item);
2030
+ }
2031
+ for (const migration of [...(journal.archiveMigrations ?? [])].reverse()) {
2032
+ try {
2033
+ archiveRollbackPlans.push(await planArchiveRollback(root, path.dirname(journalPath), migration));
2034
+ } catch (error) {
2035
+ conflicts.push(safeErrorLabel(error));
2036
+ }
2037
+ }
2038
+ if (conflicts.length > 0) {
1674
2039
  journal.state = "manual-recovery-required";
1675
2040
  journal.committedVersion = null;
1676
2041
  journal.recoveryConflicts = conflicts;
@@ -1697,15 +2062,97 @@ async function rollbackTransaction(root, journal, journalPath, lockId = null) {
1697
2062
  }
1698
2063
  const restored = await readOptionalBuffer(targetAbs);
1699
2064
  const restoredHash = restored ? sha256(restored) : null;
1700
- if (restoredHash !== entry.beforeHash) throw new Error(`${entry.targetRel}: rollback verification failed; recovery lock retained`);
1701
- }
1702
- journal.state = "rolled-back";
2065
+ if (restoredHash !== entry.beforeHash) throw new Error(`${entry.targetRel}: rollback verification failed; recovery lock retained`);
2066
+ }
2067
+ for (const plan of archiveRollbackPlans) {
2068
+ try {
2069
+ await executeArchiveRollback(root, journal, plan, rollbackEscrowDir);
2070
+ } catch (error) {
2071
+ if (!isNoClobberConflict(error)) throw error;
2072
+ conflicts.push(safeErrorLabel(error));
2073
+ journal.state = "manual-recovery-required";
2074
+ journal.committedVersion = null;
2075
+ journal.recoveryConflicts = conflicts;
2076
+ await writeSecureJson(journalPath, journal);
2077
+ return { ok: false, conflicts };
2078
+ }
2079
+ }
2080
+ journal.state = "rolled-back";
1703
2081
  journal.committedVersion = null;
1704
2082
  journal.rollbackAt = new Date().toISOString();
1705
2083
  journal.recoveryConflicts = [];
1706
2084
  await writeSecureJson(journalPath, journal);
1707
- return { ok: true, conflicts: [] };
1708
- }
2085
+ return { ok: true, conflicts: [] };
2086
+ }
2087
+
2088
+ async function planArchiveRollback(root, migrationDir, migration) {
2089
+ const original = await findExactProjectPath(root, migration.originalRel);
2090
+ const canonical = await findExactProjectPath(root, migration.canonicalRel);
2091
+ const stage = path.join(migrationDir, migration.stageRel);
2092
+ const stageExists = await pathExists(stage);
2093
+ if (original) {
2094
+ await assertDirectorySnapshotAtPath(original, migration.snapshot, `${migration.originalRel}: original archive has concurrent bytes; recovery lock retained`);
2095
+ if (canonical) throw noClobberConflict(`${migration.canonicalRel}: both archive paths exist during rollback; recovery lock retained`);
2096
+ if (stageExists) throw noClobberConflict(`${migration.originalRel}: both original and backup archive paths exist during rollback; recovery lock retained`);
2097
+ return { migration, original, canonical: null, stage: null, restore: false };
2098
+ }
2099
+ if (!stageExists) throw noClobberConflict(`${migration.originalRel}: transaction archive backup is missing; recovery lock retained`);
2100
+ await assertDirectorySnapshotAtPath(stage, migration.snapshot, `${migration.originalRel}: transaction archive backup has concurrent bytes; recovery lock retained`);
2101
+ if (canonical) await assertDirectorySnapshotSubsetAtPath(canonical, migration.snapshot, `${migration.canonicalRel}: canonical archive has concurrent bytes; recovery lock retained`);
2102
+ return { migration, original: null, canonical, stage, restore: true };
2103
+ }
2104
+
2105
+ async function executeArchiveRollback(root, journal, plan, rollbackEscrowDir) {
2106
+ if (!plan.restore) return;
2107
+ if (plan.canonical) {
2108
+ await removeArchiveSubsetNoClobber(root, plan.migration, plan.canonical, rollbackEscrowDir, journal.id);
2109
+ await assertExactProjectDirectoryAbsent(root, plan.migration.canonicalRel, `${plan.migration.canonicalRel}: canonical archive remains after rollback cleanup`);
2110
+ }
2111
+ await assertExactProjectDirectoryAbsent(root, plan.migration.originalRel, `${plan.migration.originalRel}: original archive appeared during rollback; recovery lock retained`);
2112
+ await rename(plan.stage, path.join(root, plan.migration.originalRel));
2113
+ await assertExactDirectorySnapshot(root, plan.migration.originalRel, plan.migration.snapshot, `${plan.migration.originalRel}: rollback did not restore original archive bytes`);
2114
+ }
2115
+
2116
+ async function assertDirectorySnapshotSubsetAtPath(absolute, expected, reason) {
2117
+ const actual = await snapshotDirectoryTreeAtPath(absolute);
2118
+ const expectedFiles = new Map(expected.files.map((file) => [file.path, file]));
2119
+ const expectedDirectories = new Set(expected.directories);
2120
+ if (actual.directories.some((directory) => !expectedDirectories.has(directory))
2121
+ || actual.files.some((file) => {
2122
+ const source = expectedFiles.get(file.path);
2123
+ return !source || source.bytes !== file.bytes || source.sha256 !== file.sha256;
2124
+ })) {
2125
+ throw noClobberConflict(reason);
2126
+ }
2127
+ }
2128
+
2129
+ async function removeArchiveSubsetNoClobber(root, migration, canonicalAbs, escrowDir, id) {
2130
+ const actual = await snapshotDirectoryTreeAtPath(canonicalAbs);
2131
+ const expectedFiles = new Map(migration.snapshot.files.map((file) => [file.path, file]));
2132
+ for (const file of [...actual.files].reverse()) {
2133
+ const expected = expectedFiles.get(file.path);
2134
+ if (!expected || expected.sha256 !== file.sha256 || expected.bytes !== file.bytes) {
2135
+ throw noClobberConflict(`${migration.canonicalRel}/${file.path}: canonical archive has concurrent bytes; recovery lock retained`);
2136
+ }
2137
+ await atomicReplaceFromBuffer(root, path.join(canonicalAbs, file.path), null, `${id}-archive-rollback`, file.sha256, {
2138
+ targetRel: `${migration.canonicalRel}/${file.path}`,
2139
+ escrowDir,
2140
+ phase: "archive-rollback"
2141
+ });
2142
+ }
2143
+ for (const directory of [...actual.directories].sort((left, right) => right.localeCompare(left))) {
2144
+ const target = directory ? path.join(canonicalAbs, directory) : canonicalAbs;
2145
+ try {
2146
+ await rmdir(target);
2147
+ } catch (error) {
2148
+ if (error?.code === "ENOENT") continue;
2149
+ if (error?.code === "ENOTEMPTY" || error?.code === "EEXIST") {
2150
+ throw noClobberConflict(`${migration.canonicalRel}${directory ? `/${directory}` : ""}: archive directory changed during rollback; recovery lock retained`, error);
2151
+ }
2152
+ throw error;
2153
+ }
2154
+ }
2155
+ }
1709
2156
 
1710
2157
  async function recoverInterruptedTransaction(root) {
1711
2158
  const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
@@ -1890,15 +2337,36 @@ async function readOptionalBuffer(filePath) {
1890
2337
  try { return await readFile(filePath); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
1891
2338
  }
1892
2339
 
1893
- async function readOptionalText(filePath) {
1894
- const buffer = await readOptionalBuffer(filePath);
1895
- return buffer ? decodeUtf8(buffer, filePath).text : null;
1896
- }
1897
-
1898
- async function writeSecureJson(filePath, value) {
1899
- await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
1900
- await tightenPermissions(filePath, 0o600);
1901
- }
2340
+ async function readOptionalText(filePath) {
2341
+ const buffer = await readOptionalBuffer(filePath);
2342
+ return buffer ? decodeUtf8(buffer, filePath).text : null;
2343
+ }
2344
+
2345
+ async function checkSessionLogArchiveCasing(root) {
2346
+ const devDir = path.join(root, "dev");
2347
+ let entries;
2348
+ try {
2349
+ entries = await readdir(devDir, { withFileTypes: true });
2350
+ } catch (error) {
2351
+ if (error?.code === "ENOENT") return { ok: true, finding: null };
2352
+ throw error;
2353
+ }
2354
+ const matches = entries
2355
+ .filter((entry) => entry.isDirectory() && entry.name.toLowerCase() === "session_log_archive")
2356
+ .map((entry) => entry.name)
2357
+ .sort((left, right) => left.localeCompare(right));
2358
+ if (matches.length === 0) return { ok: true, finding: null };
2359
+ if (matches.length === 1 && matches[0] === "SESSION_LOG_archive") return { ok: true, finding: null };
2360
+ if (matches.includes("SESSION_LOG_archive")) {
2361
+ return { ok: false, finding: `mixed archive casing detected: ${matches.map((name) => `dev/${name}`).join(", ")}` };
2362
+ }
2363
+ return { ok: false, finding: `legacy archive casing detected: dev/${matches[0]}; use dev/SESSION_LOG_archive` };
2364
+ }
2365
+
2366
+ async function writeSecureJson(filePath, value) {
2367
+ await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
2368
+ await tightenPermissions(filePath, 0o600);
2369
+ }
1902
2370
 
1903
2371
  async function tightenPermissions(filePath, mode) {
1904
2372
  try { await chmod(filePath, mode); } catch { /* best effort on platforms without POSIX modes */ }
@@ -1958,7 +2426,7 @@ async function runDoctor(root, version, options = {}) {
1958
2426
  console.log(`${row.ok ? "ok" : "missing"} ${row.target}`);
1959
2427
  }
1960
2428
 
1961
- if (missing.length > 0) {
2429
+ if (missing.length > 0) {
1962
2430
  const misplacedRulePacks = await findMisplacedRulePacks(root, missing);
1963
2431
  printMisplacedRulePackWarnings(misplacedRulePacks);
1964
2432
  printDoctorSummary(version, root, "needs-fix", {
@@ -1975,6 +2443,21 @@ async function runDoctor(root, version, options = {}) {
1975
2443
  return "failed";
1976
2444
  }
1977
2445
 
2446
+ const archiveCasing = await checkSessionLogArchiveCasing(root);
2447
+ console.log(`\nSESSION_LOG archive casing checks: 1`);
2448
+ console.log(`${archiveCasing.ok ? "ok" : "missing"} dev/SESSION_LOG_archive canonical path`);
2449
+ if (!archiveCasing.ok) {
2450
+ console.log(` missing: ${archiveCasing.finding}`);
2451
+ printDoctorSummary(version, root, "needs-fix", {
2452
+ checked: rows.length + 1,
2453
+ failedKind: "SESSION_LOG archive casing checks",
2454
+ failedCount: 1,
2455
+ nextStep: "保留內容,先合併到 canonical dev/SESSION_LOG_archive;不要同時保留大小寫兩套路徑。"
2456
+ });
2457
+ process.exitCode = 1;
2458
+ return "failed";
2459
+ }
2460
+
1978
2461
  const currentStateResult = await checkCurrentStateWitness(root, currentStateWitness);
1979
2462
  console.log(`\nshared current-state checks: ${currentStateResult.checked}`);
1980
2463
  const currentStateLabel = currentStateWitness?.sourceConservation
@@ -2315,7 +2798,7 @@ function resolveRuntimeAcceptance(outputs) {
2315
2798
  return validateRuntimeAcceptance(witnesses[0]);
2316
2799
  }
2317
2800
 
2318
- async function createSourceConservation(root, outputs) {
2801
+ async function createSourceConservation(root, outputs, archiveMigrations = []) {
2319
2802
  // `freezeGate5Set` is an existing read-only discovery witness. Reuse it
2320
2803
  // here rather than creating a registry, pointer, or component authority.
2321
2804
  // Its ordered source records become one component of the journal's existing
@@ -2323,13 +2806,23 @@ async function createSourceConservation(root, outputs) {
2323
2806
  const frozen = await freezeGate5Set({ root });
2324
2807
  assertGate5FrozenSet(frozen);
2325
2808
  const outputByTarget = new Map(outputs.map((item) => [item.targetRel, item]));
2809
+ const pathRebindings = archiveMigrations.map((migration) => ({
2810
+ sourcePrefix: `${migration.originalRel}/`,
2811
+ targetPrefix: `${migration.canonicalRel}/`
2812
+ }));
2326
2813
  const entries = frozen.items.map((item) => {
2327
2814
  const output = outputByTarget.get(item.sourcePath) ?? null;
2815
+ const rebind = pathRebindings.find((candidate) => item.sourcePath.startsWith(candidate.sourcePrefix)) ?? null;
2816
+ const sourcePath = rebind
2817
+ ? `${rebind.targetPrefix}${item.sourcePath.slice(rebind.sourcePrefix.length)}`
2818
+ : item.sourcePath;
2328
2819
  const sourceWitness = Object.freeze({ sha256: item.sourceIdentity.sha256, bytes: item.sourceIdentity.bytes });
2329
2820
  const accepted = output
2330
2821
  ? Object.freeze({ sha256: output.afterHash, bytes: output.after.length })
2331
2822
  : sourceWitness;
2332
- const disposition = output?.preservedRuntimeItem
2823
+ const disposition = rebind
2824
+ ? "canonical-path-migration"
2825
+ : output?.preservedRuntimeItem
2333
2826
  ? "preserve"
2334
2827
  : output
2335
2828
  ? "transaction-output"
@@ -2339,7 +2832,8 @@ async function createSourceConservation(root, outputs) {
2339
2832
  ? "outside-known-kit-reachability"
2340
2833
  : "unchanged-source";
2341
2834
  return Object.freeze({
2342
- sourcePath: item.sourcePath,
2835
+ sourcePath,
2836
+ ...(rebind ? { sourceOriginPath: item.sourcePath } : {}),
2343
2837
  sourceWitness,
2344
2838
  accepted,
2345
2839
  // A single exact whole-file range proves the source itself was not
@@ -2353,7 +2847,7 @@ async function createSourceConservation(root, outputs) {
2353
2847
  });
2354
2848
  });
2355
2849
  return Object.freeze({
2356
- schemaVersion: 1,
2850
+ schemaVersion: archiveMigrations.length > 0 ? 2 : 1,
2357
2851
  frozenSetSha256: frozen.frozenSetSha256,
2358
2852
  entries: Object.freeze(entries)
2359
2853
  });
@@ -2369,8 +2863,9 @@ function currentStateWitnessBody(journal) {
2369
2863
  if (Array.isArray(journal.supersedesCurrentStateDigests) && journal.supersedesCurrentStateDigests.length > 0) {
2370
2864
  transaction.supersedesCurrentStateDigests = journal.supersedesCurrentStateDigests;
2371
2865
  }
2866
+ const hasArchiveMigrations = Array.isArray(journal.archiveMigrations) && journal.archiveMigrations.length > 0;
2372
2867
  const body = {
2373
- schemaVersion: journal.sourceConservation ? 2 : 1,
2868
+ schemaVersion: hasArchiveMigrations ? 3 : journal.sourceConservation ? 2 : 1,
2374
2869
  transaction,
2375
2870
  // `committed` changes while the transaction runs. The ordered target
2376
2871
  // identities below do not, so they are safe to seal before the first
@@ -2386,6 +2881,7 @@ function currentStateWitnessBody(journal) {
2386
2881
  runtimeAcceptance: journal.runtimeAcceptance ?? null
2387
2882
  };
2388
2883
  if (journal.sourceConservation) body.sourceConservation = journal.sourceConservation;
2884
+ if (hasArchiveMigrations) body.archiveMigrations = journal.archiveMigrations.map(archiveMigrationWitness);
2389
2885
  return body;
2390
2886
  }
2391
2887
 
@@ -2399,10 +2895,10 @@ function createCurrentStateWitness(journal) {
2399
2895
 
2400
2896
  function validateCurrentStateWitnessValue(value) {
2401
2897
  if (!value || typeof value !== "object" || Array.isArray(value)
2402
- || ![1, 2].includes(value.schemaVersion)
2898
+ || ![1, 2, 3].includes(value.schemaVersion)
2403
2899
  || !value.transaction || typeof value.transaction !== "object" || Array.isArray(value.transaction)
2404
2900
  || typeof value.transaction.id !== "string" || !value.transaction.id
2405
- || (value.transaction.command !== "init" && value.transaction.command !== "upgrade")
2901
+ || !["init", "upgrade", "finalize-closeout"].includes(value.transaction.command)
2406
2902
  || typeof value.transaction.mode !== "string" || !value.transaction.mode
2407
2903
  || !isStableSemver(value.transaction.attemptedVersion ?? "")
2408
2904
  || !Array.isArray(value.entries) || value.entries.length === 0
@@ -2422,7 +2918,13 @@ function validateCurrentStateWitnessValue(value) {
2422
2918
  if (value.schemaVersion === 1 && value.sourceConservation != null) {
2423
2919
  throw new Error("legacy shared current-state witness cannot contain source conservation; no recovery writes attempted");
2424
2920
  }
2425
- const sourceConservation = validateSourceConservation(value.sourceConservation, { required: value.schemaVersion === 2 });
2921
+ const sourceConservation = validateSourceConservation(value.sourceConservation, { required: value.schemaVersion >= 2 });
2922
+ if (value.schemaVersion < 3 && value.archiveMigrations != null) {
2923
+ throw new Error("legacy shared current-state witness cannot contain archive migrations; no recovery writes attempted");
2924
+ }
2925
+ const archiveMigrations = value.schemaVersion === 3
2926
+ ? validateArchiveMigrations(value.archiveMigrations, { requireMaterialized: true })
2927
+ : [];
2426
2928
  const knownTargets = new Set([
2427
2929
  ...requiredTargets,
2428
2930
  ...upgradeStateTargets,
@@ -2456,6 +2958,12 @@ function validateCurrentStateWitnessValue(value) {
2456
2958
  }
2457
2959
  }
2458
2960
  }
2961
+ for (const migration of archiveMigrations) {
2962
+ const migrated = sourceConservation?.entries.filter((entry) => entry.sourceOriginPath?.startsWith(`${migration.originalRel}/`) && entry.sourcePath.startsWith(`${migration.canonicalRel}/`)) ?? [];
2963
+ if (migrated.length !== migration.snapshot.files.length) {
2964
+ throw new Error("archive migration is detached from the rebound source witness; no recovery writes attempted");
2965
+ }
2966
+ }
2459
2967
  const body = {
2460
2968
  schemaVersion: value.schemaVersion,
2461
2969
  transaction: value.transaction,
@@ -2464,6 +2972,10 @@ function validateCurrentStateWitnessValue(value) {
2464
2972
  runtimeAcceptance: value.runtimeAcceptance ?? null
2465
2973
  };
2466
2974
  if (value.schemaVersion === 2) body.sourceConservation = value.sourceConservation;
2975
+ if (value.schemaVersion === 3) {
2976
+ body.sourceConservation = value.sourceConservation;
2977
+ body.archiveMigrations = value.archiveMigrations;
2978
+ }
2467
2979
  if (sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) !== value.currentStateDigest) {
2468
2980
  throw new Error("shared current-state witness digest does not match its ordered components; no recovery writes attempted");
2469
2981
  }
@@ -2476,7 +2988,7 @@ function validateSourceConservation(value, { required = false } = {}) {
2476
2988
  return null;
2477
2989
  }
2478
2990
  if (!value || typeof value !== "object" || Array.isArray(value)
2479
- || value.schemaVersion !== 1
2991
+ || ![1, 2].includes(value.schemaVersion)
2480
2992
  || typeof value.frozenSetSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.frozenSetSha256)
2481
2993
  || !Array.isArray(value.entries) || value.entries.length === 0) {
2482
2994
  throw new Error("shared current-state source conservation is invalid; no recovery writes attempted");
@@ -2490,7 +3002,7 @@ function validateSourceConservation(value, { required = false } = {}) {
2490
3002
  || !Array.isArray(entry.sourceByteRanges) || entry.sourceByteRanges.length !== 1
2491
3003
  || entry.sourceByteRanges[0]?.start !== 0 || entry.sourceByteRanges[0]?.end !== entry.sourceWitness.bytes
2492
3004
  || entry.sourceByteRanges[0]?.sha256 !== entry.sourceWitness.sha256
2493
- || !["preserve", "transaction-output", "unchanged-source", "retained-historical-state", "outside-known-kit-reachability"].includes(entry.disposition)
3005
+ || !["preserve", "transaction-output", "unchanged-source", "retained-historical-state", "outside-known-kit-reachability", "closeout-state-finalize", "canonical-path-migration", "canonical-path-migration-closeout"].includes(entry.disposition)
2494
3006
  || !Array.isArray(entry.existingReaders)
2495
3007
  || entry.existingReaders.some((reader) => !reader || typeof reader !== "object" || Array.isArray(reader) || typeof reader.reader !== "string" || !reader.reader || typeof reader.via !== "string" || !reader.via)
2496
3008
  || typeof entry.priorityRelation !== "string" || !entry.priorityRelation
@@ -2498,6 +3010,15 @@ function validateSourceConservation(value, { required = false } = {}) {
2498
3010
  || !Array.isArray(entry.classifications) || entry.classifications.length === 0 || entry.classifications.some((classification) => typeof classification !== "string" || !classification)) {
2499
3011
  throw new Error("shared current-state source conservation entry is invalid; no recovery writes attempted");
2500
3012
  }
3013
+ if (["canonical-path-migration", "canonical-path-migration-closeout"].includes(entry.disposition)) {
3014
+ if (value.schemaVersion !== 2 || !isSafeProjectRelative(entry.sourceOriginPath)
3015
+ || entry.sourceOriginPath === entry.sourcePath
3016
+ || !entry.sourceOriginPath.startsWith("dev/") || !entry.sourcePath.startsWith("dev/SESSION_LOG_archive/")) {
3017
+ throw new Error("archive source-path rebinding is invalid; no recovery writes attempted");
3018
+ }
3019
+ } else if (entry.sourceOriginPath !== undefined) {
3020
+ throw new Error("unexpected source-origin binding is invalid; no recovery writes attempted");
3021
+ }
2501
3022
  if (prior != null && prior.localeCompare(entry.sourcePath) >= 0) {
2502
3023
  throw new Error("shared current-state source conservation entries are not in source-path order; no recovery writes attempted");
2503
3024
  }
@@ -2523,7 +3044,8 @@ function validateCurrentStateWitness(journal) {
2523
3044
  formalUserRules: witness.formalUserRules ?? null,
2524
3045
  runtimeAcceptance: witness.runtimeAcceptance ?? null
2525
3046
  };
2526
- if (witness.schemaVersion === 2) actual.sourceConservation = witness.sourceConservation;
3047
+ if (witness.schemaVersion >= 2) actual.sourceConservation = witness.sourceConservation;
3048
+ if (witness.schemaVersion === 3) actual.archiveMigrations = witness.archiveMigrations;
2527
3049
  if (JSON.stringify(actual) !== JSON.stringify(expected)) {
2528
3050
  throw new Error("shared current-state witness is detached from its transaction components; no recovery writes attempted");
2529
3051
  }
@@ -2573,23 +3095,29 @@ async function createRuntimeAcceptance(root, outputs) {
2573
3095
 
2574
3096
  const entries = [];
2575
3097
  for (const item of directAgents) {
2576
- if (!item.before || !item.after.equals(item.before)) {
3098
+ const digestTransition = item.reason === "formal user-rules acceptance digest transition";
3099
+ if (!item.before || (!item.after.equals(item.before) && !digestTransition)) {
2577
3100
  throw new Error("direct AGENTS preservation must retain identical whole-file bytes");
2578
3101
  }
2579
3102
  const sourceWitness = byteWitness(item.before);
3103
+ const accepted = digestTransition ? byteWitness(item.after) : sourceWitness;
2580
3104
  const originalReader = await directAgentsEntryWitness(root, item.before);
2581
3105
  const activeReader = await directAgentsEntryWitness(root, item.after, outputByTarget);
2582
3106
  entries.push(Object.freeze({
2583
3107
  targetRel: item.targetRel,
2584
- accepted: sourceWitness,
3108
+ accepted,
2585
3109
  sourceWitness,
2586
3110
  sourceByteRanges: Object.freeze([Object.freeze({ start: 0, end: item.before.length, sha256: sourceWitness.sha256 })]),
2587
3111
  originalReader,
2588
3112
  activeReader,
2589
- priorityRelation: "direct AGENTS.md formal-entry byte order unchanged (single complete source range 0..N)",
3113
+ priorityRelation: digestTransition
3114
+ ? "direct AGENTS.md formal-entry byte order retained except the acceptance digest line"
3115
+ : "direct AGENTS.md formal-entry byte order unchanged (single complete source range 0..N)",
2590
3116
  conflictDecision: item.preservedRuntimeItem.conflictDecision,
2591
- effectDecision: "preserve-unmodified-through-direct-formal-entry",
2592
- disposition: item.preservedRuntimeItem.disposition
3117
+ effectDecision: digestTransition
3118
+ ? "update-formal-user-rules-digest-through-direct-formal-entry"
3119
+ : "preserve-unmodified-through-direct-formal-entry",
3120
+ disposition: digestTransition ? "formal-user-rules-digest-transition" : item.preservedRuntimeItem.disposition
2593
3121
  }));
2594
3122
  }
2595
3123
 
@@ -2928,7 +3456,7 @@ function validDirectAgentsAcceptanceEntry(entry, { requireReferences = false } =
2928
3456
  || entry.activeReader.bytes !== entry.accepted.bytes
2929
3457
  || typeof entry.priorityRelation !== "string" || !entry.priorityRelation.trim()) return false;
2930
3458
  if (entry.managedSegment) return validArtifactBoundManagedAgentsEntry(entry);
2931
- if (!sameByteWitness(entry.accepted, entry.sourceWitness)) return false;
3459
+ if (!sameByteWitness(entry.accepted, entry.sourceWitness) && !validFormalUserRulesDigestTransitionEntry(entry)) return false;
2932
3460
  const ranges = entry.sourceByteRanges;
2933
3461
  return Array.isArray(ranges) && ranges.length === 1
2934
3462
  && ranges[0]?.start === 0
@@ -2936,6 +3464,15 @@ function validDirectAgentsAcceptanceEntry(entry, { requireReferences = false } =
2936
3464
  && ranges[0]?.sha256 === entry.sourceWitness.sha256;
2937
3465
  }
2938
3466
 
3467
+ function validFormalUserRulesDigestTransitionEntry(entry) {
3468
+ return entry.disposition === "formal-user-rules-digest-transition"
3469
+ && entry.conflictDecision === "non-exact-package-bytes"
3470
+ && entry.effectDecision === "update-formal-user-rules-digest-through-direct-formal-entry"
3471
+ && entry.accepted.bytes === entry.sourceWitness.bytes
3472
+ && typeof entry.priorityRelation === "string"
3473
+ && entry.priorityRelation.includes("acceptance digest line");
3474
+ }
3475
+
2939
3476
  function validArtifactBoundManagedAgentsEntry(entry) {
2940
3477
  const segment = entry.managedSegment;
2941
3478
  if (!segment || typeof segment !== "object" || Array.isArray(segment)
@@ -3014,6 +3551,9 @@ function validRuntimeAcceptanceDecision(entry) {
3014
3551
  return (entry.disposition === "preserve"
3015
3552
  && entry.conflictDecision === "non-exact-package-bytes"
3016
3553
  && entry.effectDecision === "preserve-unmodified-through-direct-formal-entry")
3554
+ || (entry.disposition === "formal-user-rules-digest-transition"
3555
+ && entry.conflictDecision === "non-exact-package-bytes"
3556
+ && entry.effectDecision === "update-formal-user-rules-digest-through-direct-formal-entry")
3017
3557
  || (entry.disposition === "replace-managed-segment"
3018
3558
  && entry.conflictDecision === "artifact-bound-exact-managed-core"
3019
3559
  && entry.effectDecision === "replace-artifact-bound-managed-core-through-direct-formal-entry");
@@ -3241,7 +3781,7 @@ async function loadCommittedCurrentStateWitness(root) {
3241
3781
  return validateCurrentStateWitness(currentCandidates[0].journal);
3242
3782
  }
3243
3783
 
3244
- async function findRestoredCurrentStateDigests(root, outputs) {
3784
+ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations = []) {
3245
3785
  const migrationsRoot = path.join(root, "dev", "governance_migrations");
3246
3786
  let names;
3247
3787
  try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return []; throw error; }
@@ -3256,7 +3796,8 @@ async function findRestoredCurrentStateDigests(root, outputs) {
3256
3796
  const journal = JSON.parse(await readFile(journalPath, "utf8"));
3257
3797
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
3258
3798
  await validateRecoveryJournal(root, journal, journalPath);
3259
- if (await journalIsRestoredByOutputs(root, journal, outputWitnesses)) {
3799
+ if (await journalMatchesCurrentState(root, journal)
3800
+ || await journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations)) {
3260
3801
  restored.push(journal.currentStateWitness.currentStateDigest);
3261
3802
  }
3262
3803
  } catch (error) {
@@ -3266,8 +3807,19 @@ async function findRestoredCurrentStateDigests(root, outputs) {
3266
3807
  return [...new Set(restored)].sort((left, right) => left.localeCompare(right));
3267
3808
  }
3268
3809
 
3269
- async function journalIsRestoredByOutputs(root, journal, outputWitnesses) {
3810
+ async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations = []) {
3270
3811
  const witness = validateCurrentStateWitness(journal);
3812
+ const archiveRebindings = new Map();
3813
+ for (const migration of archiveMigrations) {
3814
+ for (const file of migration.snapshot.files) {
3815
+ archiveRebindings.set(`${migration.originalRel}/${file.path}`, {
3816
+ sourcePath: `${migration.originalRel}/${file.path}`,
3817
+ reboundPath: `${migration.canonicalRel}/${file.path}`,
3818
+ sha256: file.sha256,
3819
+ bytes: file.bytes
3820
+ });
3821
+ }
3822
+ }
3271
3823
  for (const entry of journal.entries) {
3272
3824
  const replacement = outputWitnesses.get(entry.targetRel);
3273
3825
  if (replacement) {
@@ -3283,6 +3835,11 @@ async function journalIsRestoredByOutputs(root, journal, outputWitnesses) {
3283
3835
  if (replacement.sha256 !== entry.accepted.sha256 || replacement.bytes !== entry.accepted.bytes) return false;
3284
3836
  continue;
3285
3837
  }
3838
+ const archiveRebinding = archiveRebindings.get(entry.sourcePath);
3839
+ if (archiveRebinding) {
3840
+ if (archiveRebinding.sha256 !== entry.accepted.sha256 || archiveRebinding.bytes !== entry.accepted.bytes) return false;
3841
+ continue;
3842
+ }
3286
3843
  const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
3287
3844
  if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
3288
3845
  }
@@ -3340,6 +3897,216 @@ async function journalMatchesCurrentState(root, journal) {
3340
3897
  return true;
3341
3898
  }
3342
3899
 
3900
+ async function findCloseoutFinalizeBase(root) {
3901
+ const migrationsRoot = path.join(root, "dev", "governance_migrations");
3902
+ let names;
3903
+ try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
3904
+ const inspected = [];
3905
+ const superseded = new Set();
3906
+ for (const name of names) {
3907
+ if (name === ".upgrade.lock") continue;
3908
+ const journalPath = path.join(migrationsRoot, name, "transaction.json");
3909
+ try {
3910
+ const stats = await lstat(journalPath);
3911
+ if (!stats.isFile() || stats.isSymbolicLink()) continue;
3912
+ const journal = JSON.parse(await readFile(journalPath, "utf8"));
3913
+ if (journal.state !== "committed" || !journal.currentStateWitness) continue;
3914
+ await validateRecoveryJournal(root, journal, journalPath);
3915
+ inspected.push({ journal, journalPath });
3916
+ for (const digest of journal.currentStateWitness.transaction.supersedesCurrentStateDigests ?? []) superseded.add(digest);
3917
+ } catch (error) {
3918
+ if (error?.code !== "ENOENT") throw error;
3919
+ }
3920
+ }
3921
+ const candidates = [];
3922
+ const illegal = [];
3923
+ for (const item of inspected) {
3924
+ if (superseded.has(item.journal.currentStateWitness.currentStateDigest)) continue;
3925
+ const mismatches = await currentStateMismatches(root, item.journal);
3926
+ if (mismatches.length > 0 && !item.journal.currentStateWitness.sourceConservation) continue;
3927
+ if (mismatches.some((mismatch) => !isCloseoutFinalizeTarget(mismatch.path))) illegal.push({ ...item, mismatches });
3928
+ else candidates.push({ ...item, mismatches });
3929
+ }
3930
+ if (illegal.length > 0) return illegal.sort((left, right) => right.mismatches.length - left.mismatches.length)[0];
3931
+ const stale = candidates.filter((item) => item.mismatches.length > 0);
3932
+ if (stale.length === 0) return candidates[0] ?? null;
3933
+ if (stale.length > 1) {
3934
+ const digests = stale.map(({ journal }) => journal.currentStateWitness.currentStateDigest).join(", ");
3935
+ throw new Error(`multiple closeout-finalize candidate witnesses are stale: ${digests}`);
3936
+ }
3937
+ return stale[0];
3938
+ }
3939
+
3940
+ async function currentStateMismatches(root, journal) {
3941
+ const witness = validateCurrentStateWitness(journal);
3942
+ const mismatches = new Map();
3943
+ for (const entry of journal.entries) {
3944
+ const bytes = await readOptionalBuffer(path.join(root, entry.targetRel));
3945
+ if (!bytes || sha256(bytes) !== entry.afterHash) mismatches.set(entry.targetRel, { path: entry.targetRel, kind: "transaction-entry" });
3946
+ }
3947
+ for (const entry of witness.sourceConservation?.entries ?? []) {
3948
+ const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
3949
+ if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) {
3950
+ mismatches.set(entry.sourcePath, { path: entry.sourcePath, kind: "source-conservation" });
3951
+ }
3952
+ }
3953
+ if (witness.sourceConservation) {
3954
+ const conserved = new Set(witness.sourceConservation.entries.map((entry) => entry.sourcePath));
3955
+ const currentFrozen = await freezeGate5Set({ root });
3956
+ assertGate5FrozenSet(currentFrozen);
3957
+ for (const item of currentFrozen.items) {
3958
+ if (conserved.has(item.sourcePath) || isFinalizeJournalState(item.sourcePath)) continue;
3959
+ mismatches.set(item.sourcePath, { path: item.sourcePath, kind: "new-source" });
3960
+ }
3961
+ }
3962
+ return [...mismatches.values()].sort((left, right) => left.path.localeCompare(right.path));
3963
+ }
3964
+
3965
+ async function writeCloseoutFinalizeJournal(root, version, prior) {
3966
+ const oldWitness = validateCurrentStateWitness(prior.journal);
3967
+ const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
3968
+ const migrationsRoot = path.join(root, "dev", "governance_migrations");
3969
+ const migrationDir = path.join(migrationsRoot, id);
3970
+ const backupDir = path.join(migrationDir, "backup");
3971
+ const stageDir = path.join(migrationDir, "stage");
3972
+ const journalPath = path.join(migrationDir, "transaction.json");
3973
+ const lockPath = path.join(migrationsRoot, ".upgrade.lock");
3974
+ await mkdir(backupDir, { recursive: true });
3975
+ await mkdir(stageDir, { recursive: true });
3976
+ await tightenPermissions(migrationsRoot, 0o700);
3977
+ await tightenPermissions(migrationDir, 0o700);
3978
+ const lock = await open(lockPath, "wx", 0o600).catch((error) => {
3979
+ if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
3980
+ throw error;
3981
+ });
3982
+ await lock.writeFile(JSON.stringify({ id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command: "finalize-closeout" }, null, 2));
3983
+ await lock.close();
3984
+
3985
+ try {
3986
+ const priorEntryByTarget = new Map(prior.journal.entries.map((entry) => [entry.targetRel, entry]));
3987
+ const entries = [];
3988
+ for (const oldEntry of oldWitness.entries) {
3989
+ const targetRel = oldEntry.targetRel;
3990
+ const current = await readOptionalBuffer(path.join(root, targetRel));
3991
+ if (!current) throw new Error(`${targetRel}: cannot finalize missing closeout target`);
3992
+ const previous = await readPriorAcceptedBytes(root, prior.journalPath, priorEntryByTarget.get(targetRel), oldEntry.afterHash);
3993
+ const backupRel = path.relative(root, path.join(backupDir, targetRel)).replaceAll("\\", "/");
3994
+ await writeJournalFile(backupDir, targetRel, previous);
3995
+ await writeJournalFile(stageDir, targetRel, current);
3996
+ entries.push({
3997
+ targetRel,
3998
+ existed: true,
3999
+ beforeHash: sha256(previous),
4000
+ afterHash: sha256(current),
4001
+ backupRel,
4002
+ committed: true
4003
+ });
4004
+ }
4005
+
4006
+ const currentFrozen = oldWitness.sourceConservation ? await freezeGate5Set({ root }) : null;
4007
+ if (currentFrozen) assertGate5FrozenSet(currentFrozen);
4008
+ const oldSourceByPath = new Map((oldWitness.sourceConservation?.entries ?? []).map((entry) => [entry.sourcePath, entry]));
4009
+ const sourceConservation = oldWitness.sourceConservation
4010
+ ? {
4011
+ schemaVersion: oldWitness.sourceConservation.schemaVersion,
4012
+ frozenSetSha256: currentFrozen.frozenSetSha256,
4013
+ entries: await Promise.all(currentFrozen.items
4014
+ .filter((item) => !isFinalizeJournalState(item.sourcePath))
4015
+ .map(async (item) => {
4016
+ const entry = oldSourceByPath.get(item.sourcePath) ?? null;
4017
+ const current = await readOptionalBuffer(path.join(root, item.sourcePath));
4018
+ if (!current) throw new Error(`${item.sourcePath}: cannot finalize missing source`);
4019
+ const currentWitness = { sha256: sha256(current), bytes: current.length };
4020
+ const sourceWitness = entry?.accepted ?? currentWitness;
4021
+ const changed = currentWitness.sha256 !== sourceWitness.sha256 || currentWitness.bytes !== sourceWitness.bytes;
4022
+ return {
4023
+ sourcePath: item.sourcePath,
4024
+ ...(entry?.sourceOriginPath ? { sourceOriginPath: entry.sourceOriginPath } : {}),
4025
+ sourceWitness,
4026
+ accepted: currentWitness,
4027
+ sourceByteRanges: [{ start: 0, end: sourceWitness.bytes, sha256: sourceWitness.sha256 }],
4028
+ disposition: isCloseoutFinalizeTarget(item.sourcePath) && changed
4029
+ ? entry?.sourceOriginPath
4030
+ ? "canonical-path-migration-closeout"
4031
+ : "closeout-state-finalize"
4032
+ : entry?.disposition ?? (item.classifications.includes("transaction-state") ? "retained-historical-state" : "unchanged-source"),
4033
+ existingReaders: entry?.existingReaders ?? item.existingReaders.map((reader) => ({ reader: reader.reader, via: reader.via })),
4034
+ priorityRelation: entry?.priorityRelation ?? item.priorityConflict.relation,
4035
+ effectDecision: entry?.effectDecision ?? item.effect.decision,
4036
+ classifications: entry?.classifications ?? [...item.classifications]
4037
+ };
4038
+ }))
4039
+ }
4040
+ : null;
4041
+
4042
+ const journal = {
4043
+ id,
4044
+ command: "finalize-closeout",
4045
+ mode: "stateful-closeout",
4046
+ attemptedVersion: version,
4047
+ committedVersion: version,
4048
+ plannedSkips: 0,
4049
+ host: hostname(),
4050
+ pid: process.pid,
4051
+ state: "committed",
4052
+ createdAt: new Date().toISOString(),
4053
+ committedAt: new Date().toISOString(),
4054
+ entries,
4055
+ formalUserRules: null,
4056
+ runtimeReadback: null,
4057
+ runtimeAcceptance: null,
4058
+ runtimeAcceptanceReadback: null,
4059
+ sourceConservation,
4060
+ archiveMigrations: oldWitness.archiveMigrations ?? [],
4061
+ supersedesCurrentStateDigests: [oldWitness.currentStateDigest],
4062
+ currentStateWitness: null,
4063
+ currentStateReadback: null
4064
+ };
4065
+ journal.currentStateWitness = createCurrentStateWitness(journal);
4066
+ journal.currentStateReadback = currentStateReadbackFromDoctorStates(journal.currentStateWitness, null, null);
4067
+ await writeSecureJson(journalPath, journal);
4068
+ await writeFile(path.join(migrationDir, "migration-report.md"), [
4069
+ "# Agent Handoff Kit Closeout Finalize Report",
4070
+ "",
4071
+ `- Command: finalize-closeout`,
4072
+ `- Attempted version: ${version}`,
4073
+ `- Supersedes current-state digest: ${oldWitness.currentStateDigest}`,
4074
+ `- Current-state digest: ${journal.currentStateWitness.currentStateDigest}`,
4075
+ `- Finalized paths: ${prior.mismatches.map((item) => item.path).join(", ") || "none"}`,
4076
+ ""
4077
+ ].join("\n"), { mode: 0o600 });
4078
+ await unlinkIfExists(lockPath);
4079
+ return { journalPath, journal };
4080
+ } catch (error) {
4081
+ await unlinkIfExists(lockPath).catch(() => {});
4082
+ throw error;
4083
+ }
4084
+ }
4085
+
4086
+ async function readPriorAcceptedBytes(root, priorJournalPath, priorEntry, expectedHash) {
4087
+ if (priorEntry) {
4088
+ const stageBytes = await readOptionalBuffer(path.join(path.dirname(priorJournalPath), "stage", priorEntry.targetRel));
4089
+ if (stageBytes && sha256(stageBytes) === expectedHash) return stageBytes;
4090
+ }
4091
+ const current = await readOptionalBuffer(path.join(root, priorEntry?.targetRel ?? ""));
4092
+ if (current && sha256(current) === expectedHash) return current;
4093
+ throw new Error(`cannot reconstruct prior accepted bytes for closeout finalize: ${priorEntry?.targetRel ?? "unknown"}`);
4094
+ }
4095
+
4096
+ async function writeJournalFile(base, targetRel, bytes) {
4097
+ const filePath = path.join(base, targetRel);
4098
+ await mkdir(path.dirname(filePath), { recursive: true });
4099
+ await writeFile(filePath, bytes, { mode: 0o600 });
4100
+ }
4101
+
4102
+ function isCloseoutFinalizeTarget(relative) {
4103
+ return closeoutFinalizeTargets.has(relative) || relative.startsWith("dev/SESSION_LOG_archive/");
4104
+ }
4105
+
4106
+ function isFinalizeJournalState(relative) {
4107
+ return relative.startsWith("dev/governance_migrations/");
4108
+ }
4109
+
3343
4110
  async function checkRuntimeAcceptance(root, options = {}) {
3344
4111
  const witness = options.expectedRuntimeAcceptance ?? null;
3345
4112
  if (!witness) return { ok: true, checked: 0, finding: null, state: null };
@@ -6962,12 +7729,14 @@ Usage:
6962
7729
  agent-handoff-kit upgrade [--dry-run] [--yes] [--root <path>]
6963
7730
  agent-handoff-kit doctor [--root <path>]
6964
7731
  agent-handoff-kit closeout-status [--root <path>]
7732
+ agent-handoff-kit finalize-closeout [--root <path>]
6965
7733
 
6966
7734
  Commands:
6967
7735
  init Plan or install missing core files and rule packs.
6968
7736
  upgrade Preserve existing files; merge safe core updates or report conflicts.
6969
7737
  doctor Check required installed files.
6970
7738
  closeout-status Render the state-bound closeout card after a full closeout.
7739
+ finalize-closeout Bind legal post-upgrade closeout state edits before doctor.
6971
7740
 
6972
7741
  中文速讀:
6973
7742
  ✅ 第一次用:先在項目資料夾執行 init。