@adamchanadam/agent-handoff-kit 0.3.47 → 0.3.49

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";
@@ -873,13 +873,14 @@ async function runInstall(command, root, options, version) {
873
873
  return;
874
874
  }
875
875
 
876
- if (plan.some((item) => item.action === "conflict")) {
877
- console.log("");
878
- console.log("⛔ 升級預檢發現 conflict;治理目標檔、版本與 migration artifact 均沒有寫入。");
879
- console.log("📋 下一步:由 Kit 開發者或可讀取檔案的 AI 核對來源、差異與安全合併路徑;一般使用者毋須判斷技術差異。不要把歷史 stage、舊報告或版本列當作目前交易。");
880
- process.exitCode = 1;
881
- return;
882
- }
876
+ if (plan.some((item) => item.action === "conflict")) {
877
+ console.log("");
878
+ console.log("⛔ 升級預檢發現 conflict;治理目標檔、版本與 migration artifact 均沒有寫入。");
879
+ console.log("📌 舊 migration stage、已回滾報告或版本列只屬證據,不代表目前交易。");
880
+ console.log(conflictRepairNextStepLine());
881
+ process.exitCode = 1;
882
+ return;
883
+ }
883
884
 
884
885
  if (!options.yes) {
885
886
  const ok = await confirmWrite();
@@ -930,21 +931,26 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
930
931
  // transaction already has a runtime acceptance, bind the pre-transaction
931
932
  // root-source witness into the same current-state digest before the journal
932
933
  // directory itself is created.
934
+ const archiveMigrations = command === "upgrade"
935
+ ? await prepareArchiveCasingMigrations(root)
936
+ : [];
933
937
  const sourceConservation = command === "upgrade" && resolveRuntimeAcceptance(outputs)
934
- ? await createSourceConservation(root, outputs)
938
+ ? await createSourceConservation(root, outputs, archiveMigrations)
935
939
  : null;
936
940
  // A repair may restore the exact bytes of a prior committed state. Keep the
937
941
  // causal replacement relation inside the existing sealed journal so ordinary
938
942
  // doctor can select the freshly read-back transaction without falling back
939
943
  // to mtime or a separate current-state registry.
940
944
  const supersedesCurrentStateDigests = command === "upgrade"
941
- ? await findRestoredCurrentStateDigests(root, outputs)
945
+ ? await findRestoredCurrentStateDigests(root, outputs, archiveMigrations)
942
946
  : [];
943
- const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation, supersedesCurrentStateDigests);
947
+ const transaction = await prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation, supersedesCurrentStateDigests, archiveMigrations);
944
948
  try {
945
- transaction.journal.state = "committing";
946
- await writeSecureJson(transaction.journalPath, transaction.journal);
947
-
949
+ transaction.journal.state = "committing";
950
+ await writeSecureJson(transaction.journalPath, transaction.journal);
951
+
952
+ await applyArchiveCasingMigrations(root, transaction);
953
+
948
954
  let committedCount = 0;
949
955
  const qaFailAfterCommit = Number.parseInt(process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_COMMIT ?? "", 10);
950
956
  const qaFailAfterCommitTarget = process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_COMMIT_TARGET ?? null;
@@ -1043,7 +1049,13 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
1043
1049
  console.log("✅ project health: passed");
1044
1050
  }
1045
1051
  } catch (error) {
1046
- if (["ACK_QA_INTERRUPT_AFTER_REPLACE", "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT"].includes(error?.code)) throw error;
1052
+ if ([
1053
+ "ACK_QA_INTERRUPT_AFTER_REPLACE",
1054
+ "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT",
1055
+ "ACK_QA_INTERRUPT_AFTER_ARCHIVE_RELOCATE_BEFORE_STAGE",
1056
+ "ACK_QA_INTERRUPT_AFTER_ARCHIVE_STAGE",
1057
+ "ACK_QA_INTERRUPT_AFTER_ARCHIVE_MATERIALIZE_BEFORE_JOURNAL"
1058
+ ].includes(error?.code)) throw error;
1047
1059
  if (isNoClobberConflict(error)) {
1048
1060
  transaction.journal.state = "manual-recovery-required";
1049
1061
  transaction.journal.committedVersion = null;
@@ -1269,18 +1281,20 @@ function createFormalUserRulesWitness(entries, state, acceptanceDigest) {
1269
1281
  });
1270
1282
  }
1271
1283
 
1272
- async function prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation = null, supersedesCurrentStateDigests = []) {
1284
+ async function prepareTransaction(root, command, version, outputs, mode, plan, sourceConservation = null, supersedesCurrentStateDigests = [], archiveMigrations = []) {
1273
1285
  const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
1274
1286
  const migrationsRoot = path.join(root, "dev", "governance_migrations");
1275
1287
  const migrationDir = path.join(migrationsRoot, id);
1276
1288
  const backupDir = path.join(migrationDir, "backup");
1277
1289
  const stageDir = path.join(migrationDir, "stage");
1278
1290
  const escrowDir = path.join(migrationDir, "no-clobber-escrow");
1291
+ const archiveBackupDir = path.join(migrationDir, "archive-backup");
1279
1292
  const journalPath = path.join(migrationDir, "transaction.json");
1280
1293
  const lockPath = path.join(migrationsRoot, ".upgrade.lock");
1281
1294
  await mkdir(backupDir, { recursive: true });
1282
1295
  await mkdir(stageDir, { recursive: true });
1283
1296
  await mkdir(escrowDir, { recursive: true });
1297
+ await mkdir(archiveBackupDir, { recursive: true });
1284
1298
  await tightenPermissions(migrationsRoot, 0o700);
1285
1299
  await tightenPermissions(migrationDir, 0o700);
1286
1300
  const lock = await open(lockPath, "wx", 0o600).catch((error) => {
@@ -1321,6 +1335,11 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, s
1321
1335
  runtimeAcceptance: resolveRuntimeAcceptance(outputs),
1322
1336
  runtimeAcceptanceReadback: null,
1323
1337
  sourceConservation,
1338
+ archiveMigrations: archiveMigrations.map((migration, index) => ({
1339
+ ...migration,
1340
+ stageRel: `archive-backup/${index}`,
1341
+ state: "prepared"
1342
+ })),
1324
1343
  ...(supersedesCurrentStateDigests.length > 0 ? { supersedesCurrentStateDigests } : {}),
1325
1344
  currentStateWitness: null,
1326
1345
  currentStateReadback: null
@@ -1330,8 +1349,281 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, s
1330
1349
  // independently authorise doctor/report/success.
1331
1350
  journal.currentStateWitness = createCurrentStateWitness(journal);
1332
1351
  await writeSecureJson(journalPath, journal);
1333
- return { id, migrationDir, backupDir, stageDir, escrowDir, journalPath, lockPath, journal };
1334
- }
1352
+ return { id, migrationDir, backupDir, stageDir, escrowDir, archiveBackupDir, journalPath, lockPath, journal };
1353
+ }
1354
+
1355
+ async function prepareArchiveCasingMigrations(root) {
1356
+ const devDir = path.join(root, "dev");
1357
+ let entries;
1358
+ try {
1359
+ entries = await readdir(devDir, { withFileTypes: true });
1360
+ } catch (error) {
1361
+ if (error?.code === "ENOENT") return [];
1362
+ throw error;
1363
+ }
1364
+ const matches = entries
1365
+ .filter((entry) => entry.isDirectory() && entry.name.toLowerCase() === "session_log_archive")
1366
+ .map((entry) => entry.name)
1367
+ .sort((left, right) => left.localeCompare(right));
1368
+ if (matches.length === 0 || (matches.length === 1 && matches[0] === "SESSION_LOG_archive")) return [];
1369
+ if (matches.includes("SESSION_LOG_archive") || matches.length !== 1) {
1370
+ throw new Error(`archive casing migration is ambiguous: ${matches.map((name) => `dev/${name}`).join(", ")}`);
1371
+ }
1372
+ const originalRel = `dev/${matches[0]}`;
1373
+ return [{
1374
+ schemaVersion: 1,
1375
+ originalRel,
1376
+ canonicalRel: "dev/SESSION_LOG_archive",
1377
+ snapshot: await snapshotDirectoryTree(root, originalRel)
1378
+ }];
1379
+ }
1380
+
1381
+ async function applyArchiveCasingMigrations(root, transaction) {
1382
+ for (const migration of transaction.journal.archiveMigrations ?? []) {
1383
+ const migrationDir = transaction.migrationDir;
1384
+ const originalAbs = path.join(root, migration.originalRel);
1385
+ const canonicalAbs = path.join(root, migration.canonicalRel);
1386
+ const stageAbs = path.join(migrationDir, migration.stageRel);
1387
+ if (migration.state === "prepared") {
1388
+ await assertExactDirectorySnapshot(root, migration.originalRel, migration.snapshot, "archive migration source changed before transaction commit");
1389
+ await assertExactProjectDirectoryAbsent(root, migration.canonicalRel, "canonical archive path appeared before transaction commit");
1390
+ if (await pathExists(stageAbs)) throw noClobberConflict(`${migration.originalRel}: transaction archive backup already exists; recovery lock retained`);
1391
+ await mkdir(path.dirname(stageAbs), { recursive: true });
1392
+ migration.state = "relocating";
1393
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1394
+ }
1395
+ if (migration.state === "relocating") {
1396
+ await rename(originalAbs, stageAbs);
1397
+ await assertExactProjectDirectoryAbsent(root, migration.originalRel, "archive source remains after relocation");
1398
+ await assertDirectorySnapshotAtPath(stageAbs, migration.snapshot, "archive backup differs after relocation");
1399
+ if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_ARCHIVE_RELOCATE_BEFORE_STAGE === "1") {
1400
+ const interruption = new Error("QA interruption after archive relocation before staged journal");
1401
+ interruption.code = "ACK_QA_INTERRUPT_AFTER_ARCHIVE_RELOCATE_BEFORE_STAGE";
1402
+ throw interruption;
1403
+ }
1404
+ migration.state = "staged";
1405
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1406
+ if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_ARCHIVE_STAGE === "1") {
1407
+ const interruption = new Error("QA interruption after archive relocation");
1408
+ interruption.code = "ACK_QA_INTERRUPT_AFTER_ARCHIVE_STAGE";
1409
+ throw interruption;
1410
+ }
1411
+ }
1412
+ if (migration.state === "staged") {
1413
+ migration.state = "materializing";
1414
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1415
+ }
1416
+ if (migration.state === "materializing") {
1417
+ await materializeArchiveCanonicalPath(root, migration, stageAbs);
1418
+ if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_ARCHIVE_MATERIALIZE_BEFORE_JOURNAL === "1") {
1419
+ const interruption = new Error("QA interruption after archive canonical materialization before materialized journal");
1420
+ interruption.code = "ACK_QA_INTERRUPT_AFTER_ARCHIVE_MATERIALIZE_BEFORE_JOURNAL";
1421
+ throw interruption;
1422
+ }
1423
+ migration.state = "materialized";
1424
+ await writeSecureJson(transaction.journalPath, transaction.journal);
1425
+ if (process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_ARCHIVE_MATERIALIZE === "1") {
1426
+ throw new Error("QA fault injection after archive canonical materialization");
1427
+ }
1428
+ }
1429
+ if (migration.state !== "materialized") throw new Error("archive migration journal state is invalid during commit");
1430
+ }
1431
+ }
1432
+
1433
+ async function materializeArchiveCanonicalPath(root, migration, stageAbs) {
1434
+ await assertDirectorySnapshotAtPath(stageAbs, migration.snapshot, "archive backup changed before canonical materialization");
1435
+ await assertExactProjectDirectoryAbsent(root, migration.canonicalRel, "canonical archive path appeared during transaction");
1436
+ const canonicalAbs = path.join(root, migration.canonicalRel);
1437
+ try {
1438
+ await mkdir(canonicalAbs);
1439
+ } catch (error) {
1440
+ if (error?.code === "EEXIST") throw noClobberConflict(`${migration.canonicalRel}: canonical archive path appeared during transaction; recovery lock retained`);
1441
+ throw error;
1442
+ }
1443
+ for (const directory of migration.snapshot.directories.filter((item) => item).sort((left, right) => left.localeCompare(right))) {
1444
+ try {
1445
+ await mkdir(path.join(canonicalAbs, directory));
1446
+ } catch (error) {
1447
+ if (error?.code === "EEXIST") throw noClobberConflict(`${migration.canonicalRel}/${directory}: archive directory appeared during transaction; recovery lock retained`);
1448
+ throw error;
1449
+ }
1450
+ }
1451
+ for (const file of migration.snapshot.files) {
1452
+ const source = path.join(stageAbs, file.path);
1453
+ const target = path.join(canonicalAbs, file.path);
1454
+ const sourceBytes = await readFile(source);
1455
+ if (sourceBytes.length !== file.bytes || sha256(sourceBytes) !== file.sha256) {
1456
+ throw new Error(`${migration.originalRel}/${file.path}: archive backup bytes changed before canonical materialization`);
1457
+ }
1458
+ try {
1459
+ await writeFile(target, sourceBytes, { mode: 0o600, flag: "wx" });
1460
+ } catch (error) {
1461
+ if (error?.code === "EEXIST") throw noClobberConflict(`${migration.canonicalRel}/${file.path}: archive file appeared during transaction; recovery lock retained`);
1462
+ throw error;
1463
+ }
1464
+ }
1465
+ await assertExactDirectorySnapshot(root, migration.canonicalRel, migration.snapshot, "canonical archive materialization did not retain source bytes");
1466
+ }
1467
+
1468
+ async function snapshotDirectoryTree(root, relative) {
1469
+ const absolute = path.join(root, relative);
1470
+ return snapshotDirectoryTreeAtPath(absolute);
1471
+ }
1472
+
1473
+ async function snapshotDirectoryTreeAtPath(absolute) {
1474
+ const rootStats = await lstat(absolute).catch((error) => error?.code === "ENOENT" ? null : Promise.reject(error));
1475
+ if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) throw new Error("archive migration directory is missing or unsafe");
1476
+ const directories = [""];
1477
+ const files = [];
1478
+ async function visit(current, relative) {
1479
+ const entries = await readdir(current, { withFileTypes: true });
1480
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
1481
+ const childRelative = relative ? `${relative}/${entry.name}` : entry.name;
1482
+ const child = path.join(current, entry.name);
1483
+ if (entry.isDirectory()) {
1484
+ const stats = await lstat(child);
1485
+ if (stats.isSymbolicLink()) throw new Error(`${childRelative}: archive migration does not accept symbolic links or junctions`);
1486
+ directories.push(childRelative);
1487
+ await visit(child, childRelative);
1488
+ } else if (entry.isFile()) {
1489
+ const stats = await lstat(child);
1490
+ if (stats.isSymbolicLink()) throw new Error(`${childRelative}: archive migration does not accept symbolic links`);
1491
+ const bytes = await readFile(child);
1492
+ files.push({ path: childRelative, sha256: sha256(bytes), bytes: bytes.length });
1493
+ } else {
1494
+ throw new Error(`${childRelative}: archive migration accepts only regular files and directories`);
1495
+ }
1496
+ }
1497
+ }
1498
+ await visit(absolute, "");
1499
+ directories.sort((left, right) => left.localeCompare(right));
1500
+ files.sort((left, right) => left.path.localeCompare(right.path));
1501
+ const body = { schemaVersion: 1, directories, files };
1502
+ return { ...body, manifestSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) };
1503
+ }
1504
+
1505
+ function validateArchiveSnapshot(snapshot) {
1506
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)
1507
+ || snapshot.schemaVersion !== 1
1508
+ || !Array.isArray(snapshot.directories) || snapshot.directories[0] !== ""
1509
+ || !Array.isArray(snapshot.files)
1510
+ || typeof snapshot.manifestSha256 !== "string" || !/^[a-f0-9]{64}$/.test(snapshot.manifestSha256)) {
1511
+ throw new Error("archive migration snapshot is invalid; no recovery writes attempted");
1512
+ }
1513
+ const seenDirectories = new Set();
1514
+ let previousDirectory = null;
1515
+ for (const directory of snapshot.directories) {
1516
+ if (typeof directory !== "string" || (directory && !isSafeProjectRelative(directory)) || seenDirectories.has(directory)
1517
+ || (previousDirectory != null && previousDirectory.localeCompare(directory) >= 0)) {
1518
+ throw new Error("archive migration directory snapshot is invalid; no recovery writes attempted");
1519
+ }
1520
+ seenDirectories.add(directory);
1521
+ previousDirectory = directory;
1522
+ }
1523
+ const seenFiles = new Set();
1524
+ let previousFile = null;
1525
+ for (const file of snapshot.files) {
1526
+ if (!file || typeof file !== "object" || Array.isArray(file)
1527
+ || !isSafeProjectRelative(file.path) || seenFiles.has(file.path)
1528
+ || !Number.isInteger(file.bytes) || file.bytes < 0
1529
+ || typeof file.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(file.sha256)
1530
+ || (previousFile != null && previousFile.localeCompare(file.path) >= 0)) {
1531
+ throw new Error("archive migration file snapshot is invalid; no recovery writes attempted");
1532
+ }
1533
+ seenFiles.add(file.path);
1534
+ previousFile = file.path;
1535
+ }
1536
+ const body = { schemaVersion: snapshot.schemaVersion, directories: snapshot.directories, files: snapshot.files };
1537
+ if (sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) !== snapshot.manifestSha256) {
1538
+ throw new Error("archive migration snapshot digest is invalid; no recovery writes attempted");
1539
+ }
1540
+ return snapshot;
1541
+ }
1542
+
1543
+ function archiveMigrationWitness(migration) {
1544
+ return {
1545
+ schemaVersion: migration.schemaVersion,
1546
+ originalRel: migration.originalRel,
1547
+ canonicalRel: migration.canonicalRel,
1548
+ snapshot: migration.snapshot
1549
+ };
1550
+ }
1551
+
1552
+ function validateArchiveMigrations(value, { requireMaterialized = false } = {}) {
1553
+ if (!Array.isArray(value) || value.length === 0) {
1554
+ throw new Error("archive migration journal is missing or invalid; no recovery writes attempted");
1555
+ }
1556
+ const seenOriginal = new Set();
1557
+ const seenCanonical = new Set();
1558
+ let previous = null;
1559
+ for (const migration of value) {
1560
+ if (!migration || typeof migration !== "object" || Array.isArray(migration)
1561
+ || migration.schemaVersion !== 1
1562
+ || !isSafeProjectRelative(migration.originalRel) || !migration.originalRel.startsWith("dev/")
1563
+ || migration.canonicalRel !== "dev/SESSION_LOG_archive"
1564
+ || seenOriginal.has(migration.originalRel) || seenCanonical.has(migration.canonicalRel)
1565
+ || (previous != null && previous.localeCompare(migration.originalRel) >= 0)) {
1566
+ throw new Error("archive migration journal entry is invalid; no recovery writes attempted");
1567
+ }
1568
+ if (migration.stageRel !== undefined && (!isSafeProjectRelative(migration.stageRel) || !migration.stageRel.startsWith("archive-backup/"))) {
1569
+ throw new Error("archive migration backup path is invalid; no recovery writes attempted");
1570
+ }
1571
+ if (migration.state !== undefined && !["prepared", "relocating", "staged", "materializing", "materialized"].includes(migration.state)) {
1572
+ throw new Error("archive migration state is invalid; no recovery writes attempted");
1573
+ }
1574
+ if (requireMaterialized && migration.state !== undefined && migration.state !== "materialized") {
1575
+ throw new Error("committed archive migration is not materialized; no recovery writes attempted");
1576
+ }
1577
+ validateArchiveSnapshot(migration.snapshot);
1578
+ seenOriginal.add(migration.originalRel);
1579
+ seenCanonical.add(migration.canonicalRel);
1580
+ previous = migration.originalRel;
1581
+ }
1582
+ return value;
1583
+ }
1584
+
1585
+ async function assertDirectorySnapshotAtPath(absolute, expected, reason) {
1586
+ const actual = await snapshotDirectoryTreeAtPath(absolute);
1587
+ if (actual.manifestSha256 !== expected.manifestSha256) throw new Error(reason);
1588
+ }
1589
+
1590
+ async function assertExactDirectorySnapshot(root, relative, expected, reason) {
1591
+ const exact = await findExactProjectPath(root, relative);
1592
+ if (!exact) throw new Error(reason);
1593
+ await assertDirectorySnapshotAtPath(exact, expected, reason);
1594
+ }
1595
+
1596
+ async function assertExactProjectDirectoryAbsent(root, relative, reason) {
1597
+ if (await findExactProjectPath(root, relative)) throw noClobberConflict(reason);
1598
+ }
1599
+
1600
+ async function findExactProjectPath(root, relative) {
1601
+ if (!isSafeProjectRelative(relative)) throw new Error("archive migration path is unsafe");
1602
+ let current = root;
1603
+ for (const segment of relative.split("/")) {
1604
+ let entries;
1605
+ try {
1606
+ entries = await readdir(current, { withFileTypes: true });
1607
+ } catch (error) {
1608
+ if (error?.code === "ENOENT") return null;
1609
+ throw error;
1610
+ }
1611
+ const match = entries.find((entry) => entry.name === segment);
1612
+ if (!match) return null;
1613
+ current = path.join(current, match.name);
1614
+ }
1615
+ return current;
1616
+ }
1617
+
1618
+ async function pathExists(filePath) {
1619
+ try {
1620
+ await lstat(filePath);
1621
+ return true;
1622
+ } catch (error) {
1623
+ if (error?.code === "ENOENT") return false;
1624
+ throw error;
1625
+ }
1626
+ }
1335
1627
 
1336
1628
  async function validateTransactionRoot(root, plan, { createMissingRoot = true } = {}) {
1337
1629
  let rootStats;
@@ -1595,32 +1887,46 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1595
1887
  const seen = new Set();
1596
1888
  const formalWitness = validateFormalUserRulesWitness(journal.formalUserRules);
1597
1889
  const runtimeAcceptance = validateRuntimeAcceptance(journal.runtimeAcceptance);
1890
+ const hasArchiveMigrationField = journal.archiveMigrations !== undefined;
1891
+ const requiresArchiveBackup = journal.command === "upgrade" && hasArchiveMigrationField;
1892
+ if (journal.archiveMigrations != null && !Array.isArray(journal.archiveMigrations)) throw new Error("upgrade journal archive migrations are invalid; no recovery writes attempted");
1893
+ const archiveMigrations = (journal.archiveMigrations ?? []).length > 0
1894
+ ? validateArchiveMigrations(journal.archiveMigrations, { requireMaterialized: journal.state === "committed" })
1895
+ : [];
1896
+ if (requiresArchiveBackup && archiveMigrations.some((migration) => !migration.stageRel || migration.state === undefined)) {
1897
+ throw new Error("upgrade journal archive migration recovery fields are missing; no recovery writes attempted");
1898
+ }
1598
1899
  const rootStats = await lstat(root);
1599
1900
  if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) throw new Error("selected recovery root is not a safe directory; no recovery writes attempted");
1600
1901
  const rootReal = await realpath(root);
1601
1902
  const backupRoot = path.join(migrationDir, "backup");
1602
- const stageRoot = path.join(migrationDir, "stage");
1903
+ const stageRoot = path.join(migrationDir, "stage");
1904
+ const archiveBackupRoot = path.join(migrationDir, "archive-backup");
1603
1905
  const migrationsStats = await lstat(migrationsRoot).catch(() => null);
1604
1906
  const migrationStats = await lstat(migrationDir).catch(() => null);
1605
1907
  const journalStats = await lstat(journalPath).catch(() => null);
1606
1908
  const backupStats = await lstat(backupRoot).catch(() => null);
1607
- const stageStats = await lstat(stageRoot).catch(() => null);
1909
+ const stageStats = await lstat(stageRoot).catch(() => null);
1910
+ const archiveBackupStats = requiresArchiveBackup ? await lstat(archiveBackupRoot).catch(() => null) : null;
1608
1911
  if (!migrationsStats?.isDirectory() || migrationsStats.isSymbolicLink()
1609
1912
  || !migrationStats?.isDirectory() || migrationStats.isSymbolicLink()
1610
1913
  || !journalStats?.isFile() || journalStats.isSymbolicLink()
1611
1914
  || !backupStats?.isDirectory() || backupStats.isSymbolicLink()
1612
- || !stageStats?.isDirectory() || stageStats.isSymbolicLink()) {
1915
+ || !stageStats?.isDirectory() || stageStats.isSymbolicLink()
1916
+ || (requiresArchiveBackup && (!archiveBackupStats?.isDirectory() || archiveBackupStats.isSymbolicLink()))) {
1613
1917
  throw new Error("upgrade transaction directories or journal are missing or unsafe; no recovery writes attempted");
1614
1918
  }
1615
1919
  const migrationsReal = await realpath(migrationsRoot);
1616
1920
  const migrationReal = await realpath(migrationDir);
1617
1921
  const journalReal = await realpath(journalPath);
1618
1922
  const backupRealRoot = await realpath(backupRoot);
1619
- const stageRealRoot = await realpath(stageRoot);
1923
+ const stageRealRoot = await realpath(stageRoot);
1924
+ const archiveBackupRealRoot = requiresArchiveBackup ? await realpath(archiveBackupRoot) : null;
1620
1925
  if (!isInside(rootReal, migrationsReal) || !isInside(migrationsReal, migrationReal)
1621
1926
  || !isInside(migrationReal, journalReal) || !isInside(migrationReal, backupRealRoot) || !isInside(migrationReal, stageRealRoot)
1622
1927
  || !samePath(path.dirname(migrationReal), migrationsReal)
1623
- || !samePath(path.dirname(backupRealRoot), migrationReal) || !samePath(path.dirname(stageRealRoot), migrationReal)) {
1928
+ || !samePath(path.dirname(backupRealRoot), migrationReal) || !samePath(path.dirname(stageRealRoot), migrationReal)
1929
+ || (requiresArchiveBackup && !samePath(path.dirname(archiveBackupRealRoot), migrationReal))) {
1624
1930
  throw new Error("upgrade transaction paths resolve outside the selected root or transaction; no recovery writes attempted");
1625
1931
  }
1626
1932
  const validated = [];
@@ -1676,6 +1982,19 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1676
1982
  if (journal.state === "committed" && validated.some(({ entry }) => !entry.committed)) {
1677
1983
  throw new Error("committed upgrade journal contains an uncommitted entry; no recovery writes attempted");
1678
1984
  }
1985
+ if (requiresArchiveBackup) {
1986
+ for (const migration of archiveMigrations) {
1987
+ const stageAbs = path.resolve(migrationDir, migration.stageRel);
1988
+ if (!isInside(archiveBackupRoot, stageAbs)) throw new Error("upgrade archive migration backup escapes this transaction; no recovery writes attempted");
1989
+ const stageStats = await lstat(stageAbs).catch((error) => error?.code === "ENOENT" ? null : Promise.reject(error));
1990
+ if (stageStats) {
1991
+ if (!stageStats.isDirectory() || stageStats.isSymbolicLink()) throw new Error("upgrade archive migration backup is unsafe; no recovery writes attempted");
1992
+ const stageReal = await realpath(stageAbs);
1993
+ if (!isInside(archiveBackupRealRoot, stageReal)) throw new Error("upgrade archive migration backup resolves outside this transaction; no recovery writes attempted");
1994
+ await assertDirectorySnapshotAtPath(stageAbs, migration.snapshot, "upgrade archive migration backup hash does not match the recorded input; no recovery writes attempted");
1995
+ }
1996
+ }
1997
+ }
1679
1998
  if (runtimeAcceptance) {
1680
1999
  for (const accepted of runtimeAcceptance.entries) {
1681
2000
  const transactionEntry = validated.find(({ entry }) => entry.targetRel === accepted.targetRel)?.entry;
@@ -1693,10 +2012,11 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
1693
2012
  return validated;
1694
2013
  }
1695
2014
 
1696
- async function rollbackTransaction(root, journal, journalPath, lockId = null) {
1697
- const validated = await validateRecoveryJournal(root, journal, journalPath, lockId);
1698
- const conflicts = [];
1699
- const operations = [];
2015
+ async function rollbackTransaction(root, journal, journalPath, lockId = null) {
2016
+ const validated = await validateRecoveryJournal(root, journal, journalPath, lockId);
2017
+ const conflicts = [];
2018
+ const operations = [];
2019
+ const archiveRollbackPlans = [];
1700
2020
  // Do not trust the committed flag: the process can stop after replacement
1701
2021
  // but before the journal flag is persisted. Inspect every target hash first.
1702
2022
  for (const item of [...validated].reverse()) {
@@ -1707,9 +2027,16 @@ async function rollbackTransaction(root, journal, journalPath, lockId = null) {
1707
2027
  conflicts.push(`${item.entry.targetRel}: current content differs from both transaction input and candidate`);
1708
2028
  continue;
1709
2029
  }
1710
- operations.push(item);
1711
- }
1712
- if (conflicts.length > 0) {
2030
+ operations.push(item);
2031
+ }
2032
+ for (const migration of [...(journal.archiveMigrations ?? [])].reverse()) {
2033
+ try {
2034
+ archiveRollbackPlans.push(await planArchiveRollback(root, path.dirname(journalPath), migration));
2035
+ } catch (error) {
2036
+ conflicts.push(safeErrorLabel(error));
2037
+ }
2038
+ }
2039
+ if (conflicts.length > 0) {
1713
2040
  journal.state = "manual-recovery-required";
1714
2041
  journal.committedVersion = null;
1715
2042
  journal.recoveryConflicts = conflicts;
@@ -1736,15 +2063,97 @@ async function rollbackTransaction(root, journal, journalPath, lockId = null) {
1736
2063
  }
1737
2064
  const restored = await readOptionalBuffer(targetAbs);
1738
2065
  const restoredHash = restored ? sha256(restored) : null;
1739
- if (restoredHash !== entry.beforeHash) throw new Error(`${entry.targetRel}: rollback verification failed; recovery lock retained`);
1740
- }
1741
- journal.state = "rolled-back";
2066
+ if (restoredHash !== entry.beforeHash) throw new Error(`${entry.targetRel}: rollback verification failed; recovery lock retained`);
2067
+ }
2068
+ for (const plan of archiveRollbackPlans) {
2069
+ try {
2070
+ await executeArchiveRollback(root, journal, plan, rollbackEscrowDir);
2071
+ } catch (error) {
2072
+ if (!isNoClobberConflict(error)) throw error;
2073
+ conflicts.push(safeErrorLabel(error));
2074
+ journal.state = "manual-recovery-required";
2075
+ journal.committedVersion = null;
2076
+ journal.recoveryConflicts = conflicts;
2077
+ await writeSecureJson(journalPath, journal);
2078
+ return { ok: false, conflicts };
2079
+ }
2080
+ }
2081
+ journal.state = "rolled-back";
1742
2082
  journal.committedVersion = null;
1743
2083
  journal.rollbackAt = new Date().toISOString();
1744
2084
  journal.recoveryConflicts = [];
1745
2085
  await writeSecureJson(journalPath, journal);
1746
- return { ok: true, conflicts: [] };
1747
- }
2086
+ return { ok: true, conflicts: [] };
2087
+ }
2088
+
2089
+ async function planArchiveRollback(root, migrationDir, migration) {
2090
+ const original = await findExactProjectPath(root, migration.originalRel);
2091
+ const canonical = await findExactProjectPath(root, migration.canonicalRel);
2092
+ const stage = path.join(migrationDir, migration.stageRel);
2093
+ const stageExists = await pathExists(stage);
2094
+ if (original) {
2095
+ await assertDirectorySnapshotAtPath(original, migration.snapshot, `${migration.originalRel}: original archive has concurrent bytes; recovery lock retained`);
2096
+ if (canonical) throw noClobberConflict(`${migration.canonicalRel}: both archive paths exist during rollback; recovery lock retained`);
2097
+ if (stageExists) throw noClobberConflict(`${migration.originalRel}: both original and backup archive paths exist during rollback; recovery lock retained`);
2098
+ return { migration, original, canonical: null, stage: null, restore: false };
2099
+ }
2100
+ if (!stageExists) throw noClobberConflict(`${migration.originalRel}: transaction archive backup is missing; recovery lock retained`);
2101
+ await assertDirectorySnapshotAtPath(stage, migration.snapshot, `${migration.originalRel}: transaction archive backup has concurrent bytes; recovery lock retained`);
2102
+ if (canonical) await assertDirectorySnapshotSubsetAtPath(canonical, migration.snapshot, `${migration.canonicalRel}: canonical archive has concurrent bytes; recovery lock retained`);
2103
+ return { migration, original: null, canonical, stage, restore: true };
2104
+ }
2105
+
2106
+ async function executeArchiveRollback(root, journal, plan, rollbackEscrowDir) {
2107
+ if (!plan.restore) return;
2108
+ if (plan.canonical) {
2109
+ await removeArchiveSubsetNoClobber(root, plan.migration, plan.canonical, rollbackEscrowDir, journal.id);
2110
+ await assertExactProjectDirectoryAbsent(root, plan.migration.canonicalRel, `${plan.migration.canonicalRel}: canonical archive remains after rollback cleanup`);
2111
+ }
2112
+ await assertExactProjectDirectoryAbsent(root, plan.migration.originalRel, `${plan.migration.originalRel}: original archive appeared during rollback; recovery lock retained`);
2113
+ await rename(plan.stage, path.join(root, plan.migration.originalRel));
2114
+ await assertExactDirectorySnapshot(root, plan.migration.originalRel, plan.migration.snapshot, `${plan.migration.originalRel}: rollback did not restore original archive bytes`);
2115
+ }
2116
+
2117
+ async function assertDirectorySnapshotSubsetAtPath(absolute, expected, reason) {
2118
+ const actual = await snapshotDirectoryTreeAtPath(absolute);
2119
+ const expectedFiles = new Map(expected.files.map((file) => [file.path, file]));
2120
+ const expectedDirectories = new Set(expected.directories);
2121
+ if (actual.directories.some((directory) => !expectedDirectories.has(directory))
2122
+ || actual.files.some((file) => {
2123
+ const source = expectedFiles.get(file.path);
2124
+ return !source || source.bytes !== file.bytes || source.sha256 !== file.sha256;
2125
+ })) {
2126
+ throw noClobberConflict(reason);
2127
+ }
2128
+ }
2129
+
2130
+ async function removeArchiveSubsetNoClobber(root, migration, canonicalAbs, escrowDir, id) {
2131
+ const actual = await snapshotDirectoryTreeAtPath(canonicalAbs);
2132
+ const expectedFiles = new Map(migration.snapshot.files.map((file) => [file.path, file]));
2133
+ for (const file of [...actual.files].reverse()) {
2134
+ const expected = expectedFiles.get(file.path);
2135
+ if (!expected || expected.sha256 !== file.sha256 || expected.bytes !== file.bytes) {
2136
+ throw noClobberConflict(`${migration.canonicalRel}/${file.path}: canonical archive has concurrent bytes; recovery lock retained`);
2137
+ }
2138
+ await atomicReplaceFromBuffer(root, path.join(canonicalAbs, file.path), null, `${id}-archive-rollback`, file.sha256, {
2139
+ targetRel: `${migration.canonicalRel}/${file.path}`,
2140
+ escrowDir,
2141
+ phase: "archive-rollback"
2142
+ });
2143
+ }
2144
+ for (const directory of [...actual.directories].sort((left, right) => right.localeCompare(left))) {
2145
+ const target = directory ? path.join(canonicalAbs, directory) : canonicalAbs;
2146
+ try {
2147
+ await rmdir(target);
2148
+ } catch (error) {
2149
+ if (error?.code === "ENOENT") continue;
2150
+ if (error?.code === "ENOTEMPTY" || error?.code === "EEXIST") {
2151
+ throw noClobberConflict(`${migration.canonicalRel}${directory ? `/${directory}` : ""}: archive directory changed during rollback; recovery lock retained`, error);
2152
+ }
2153
+ throw error;
2154
+ }
2155
+ }
2156
+ }
1748
2157
 
1749
2158
  async function recoverInterruptedTransaction(root) {
1750
2159
  const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
@@ -2390,7 +2799,7 @@ function resolveRuntimeAcceptance(outputs) {
2390
2799
  return validateRuntimeAcceptance(witnesses[0]);
2391
2800
  }
2392
2801
 
2393
- async function createSourceConservation(root, outputs) {
2802
+ async function createSourceConservation(root, outputs, archiveMigrations = []) {
2394
2803
  // `freezeGate5Set` is an existing read-only discovery witness. Reuse it
2395
2804
  // here rather than creating a registry, pointer, or component authority.
2396
2805
  // Its ordered source records become one component of the journal's existing
@@ -2398,13 +2807,23 @@ async function createSourceConservation(root, outputs) {
2398
2807
  const frozen = await freezeGate5Set({ root });
2399
2808
  assertGate5FrozenSet(frozen);
2400
2809
  const outputByTarget = new Map(outputs.map((item) => [item.targetRel, item]));
2810
+ const pathRebindings = archiveMigrations.map((migration) => ({
2811
+ sourcePrefix: `${migration.originalRel}/`,
2812
+ targetPrefix: `${migration.canonicalRel}/`
2813
+ }));
2401
2814
  const entries = frozen.items.map((item) => {
2402
2815
  const output = outputByTarget.get(item.sourcePath) ?? null;
2816
+ const rebind = pathRebindings.find((candidate) => item.sourcePath.startsWith(candidate.sourcePrefix)) ?? null;
2817
+ const sourcePath = rebind
2818
+ ? `${rebind.targetPrefix}${item.sourcePath.slice(rebind.sourcePrefix.length)}`
2819
+ : item.sourcePath;
2403
2820
  const sourceWitness = Object.freeze({ sha256: item.sourceIdentity.sha256, bytes: item.sourceIdentity.bytes });
2404
2821
  const accepted = output
2405
2822
  ? Object.freeze({ sha256: output.afterHash, bytes: output.after.length })
2406
2823
  : sourceWitness;
2407
- const disposition = output?.preservedRuntimeItem
2824
+ const disposition = rebind
2825
+ ? "canonical-path-migration"
2826
+ : output?.preservedRuntimeItem
2408
2827
  ? "preserve"
2409
2828
  : output
2410
2829
  ? "transaction-output"
@@ -2414,7 +2833,8 @@ async function createSourceConservation(root, outputs) {
2414
2833
  ? "outside-known-kit-reachability"
2415
2834
  : "unchanged-source";
2416
2835
  return Object.freeze({
2417
- sourcePath: item.sourcePath,
2836
+ sourcePath,
2837
+ ...(rebind ? { sourceOriginPath: item.sourcePath } : {}),
2418
2838
  sourceWitness,
2419
2839
  accepted,
2420
2840
  // A single exact whole-file range proves the source itself was not
@@ -2428,7 +2848,7 @@ async function createSourceConservation(root, outputs) {
2428
2848
  });
2429
2849
  });
2430
2850
  return Object.freeze({
2431
- schemaVersion: 1,
2851
+ schemaVersion: archiveMigrations.length > 0 ? 2 : 1,
2432
2852
  frozenSetSha256: frozen.frozenSetSha256,
2433
2853
  entries: Object.freeze(entries)
2434
2854
  });
@@ -2444,8 +2864,9 @@ function currentStateWitnessBody(journal) {
2444
2864
  if (Array.isArray(journal.supersedesCurrentStateDigests) && journal.supersedesCurrentStateDigests.length > 0) {
2445
2865
  transaction.supersedesCurrentStateDigests = journal.supersedesCurrentStateDigests;
2446
2866
  }
2867
+ const hasArchiveMigrations = Array.isArray(journal.archiveMigrations) && journal.archiveMigrations.length > 0;
2447
2868
  const body = {
2448
- schemaVersion: journal.sourceConservation ? 2 : 1,
2869
+ schemaVersion: hasArchiveMigrations ? 3 : journal.sourceConservation ? 2 : 1,
2449
2870
  transaction,
2450
2871
  // `committed` changes while the transaction runs. The ordered target
2451
2872
  // identities below do not, so they are safe to seal before the first
@@ -2461,6 +2882,7 @@ function currentStateWitnessBody(journal) {
2461
2882
  runtimeAcceptance: journal.runtimeAcceptance ?? null
2462
2883
  };
2463
2884
  if (journal.sourceConservation) body.sourceConservation = journal.sourceConservation;
2885
+ if (hasArchiveMigrations) body.archiveMigrations = journal.archiveMigrations.map(archiveMigrationWitness);
2464
2886
  return body;
2465
2887
  }
2466
2888
 
@@ -2474,7 +2896,7 @@ function createCurrentStateWitness(journal) {
2474
2896
 
2475
2897
  function validateCurrentStateWitnessValue(value) {
2476
2898
  if (!value || typeof value !== "object" || Array.isArray(value)
2477
- || ![1, 2].includes(value.schemaVersion)
2899
+ || ![1, 2, 3].includes(value.schemaVersion)
2478
2900
  || !value.transaction || typeof value.transaction !== "object" || Array.isArray(value.transaction)
2479
2901
  || typeof value.transaction.id !== "string" || !value.transaction.id
2480
2902
  || !["init", "upgrade", "finalize-closeout"].includes(value.transaction.command)
@@ -2497,7 +2919,13 @@ function validateCurrentStateWitnessValue(value) {
2497
2919
  if (value.schemaVersion === 1 && value.sourceConservation != null) {
2498
2920
  throw new Error("legacy shared current-state witness cannot contain source conservation; no recovery writes attempted");
2499
2921
  }
2500
- const sourceConservation = validateSourceConservation(value.sourceConservation, { required: value.schemaVersion === 2 });
2922
+ const sourceConservation = validateSourceConservation(value.sourceConservation, { required: value.schemaVersion >= 2 });
2923
+ if (value.schemaVersion < 3 && value.archiveMigrations != null) {
2924
+ throw new Error("legacy shared current-state witness cannot contain archive migrations; no recovery writes attempted");
2925
+ }
2926
+ const archiveMigrations = value.schemaVersion === 3
2927
+ ? validateArchiveMigrations(value.archiveMigrations, { requireMaterialized: true })
2928
+ : [];
2501
2929
  const knownTargets = new Set([
2502
2930
  ...requiredTargets,
2503
2931
  ...upgradeStateTargets,
@@ -2531,6 +2959,12 @@ function validateCurrentStateWitnessValue(value) {
2531
2959
  }
2532
2960
  }
2533
2961
  }
2962
+ for (const migration of archiveMigrations) {
2963
+ const migrated = sourceConservation?.entries.filter((entry) => entry.sourceOriginPath?.startsWith(`${migration.originalRel}/`) && entry.sourcePath.startsWith(`${migration.canonicalRel}/`)) ?? [];
2964
+ if (migrated.length !== migration.snapshot.files.length) {
2965
+ throw new Error("archive migration is detached from the rebound source witness; no recovery writes attempted");
2966
+ }
2967
+ }
2534
2968
  const body = {
2535
2969
  schemaVersion: value.schemaVersion,
2536
2970
  transaction: value.transaction,
@@ -2539,6 +2973,10 @@ function validateCurrentStateWitnessValue(value) {
2539
2973
  runtimeAcceptance: value.runtimeAcceptance ?? null
2540
2974
  };
2541
2975
  if (value.schemaVersion === 2) body.sourceConservation = value.sourceConservation;
2976
+ if (value.schemaVersion === 3) {
2977
+ body.sourceConservation = value.sourceConservation;
2978
+ body.archiveMigrations = value.archiveMigrations;
2979
+ }
2542
2980
  if (sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) !== value.currentStateDigest) {
2543
2981
  throw new Error("shared current-state witness digest does not match its ordered components; no recovery writes attempted");
2544
2982
  }
@@ -2551,7 +2989,7 @@ function validateSourceConservation(value, { required = false } = {}) {
2551
2989
  return null;
2552
2990
  }
2553
2991
  if (!value || typeof value !== "object" || Array.isArray(value)
2554
- || value.schemaVersion !== 1
2992
+ || ![1, 2].includes(value.schemaVersion)
2555
2993
  || typeof value.frozenSetSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.frozenSetSha256)
2556
2994
  || !Array.isArray(value.entries) || value.entries.length === 0) {
2557
2995
  throw new Error("shared current-state source conservation is invalid; no recovery writes attempted");
@@ -2565,7 +3003,7 @@ function validateSourceConservation(value, { required = false } = {}) {
2565
3003
  || !Array.isArray(entry.sourceByteRanges) || entry.sourceByteRanges.length !== 1
2566
3004
  || entry.sourceByteRanges[0]?.start !== 0 || entry.sourceByteRanges[0]?.end !== entry.sourceWitness.bytes
2567
3005
  || entry.sourceByteRanges[0]?.sha256 !== entry.sourceWitness.sha256
2568
- || !["preserve", "transaction-output", "unchanged-source", "retained-historical-state", "outside-known-kit-reachability", "closeout-state-finalize"].includes(entry.disposition)
3006
+ || !["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)
2569
3007
  || !Array.isArray(entry.existingReaders)
2570
3008
  || entry.existingReaders.some((reader) => !reader || typeof reader !== "object" || Array.isArray(reader) || typeof reader.reader !== "string" || !reader.reader || typeof reader.via !== "string" || !reader.via)
2571
3009
  || typeof entry.priorityRelation !== "string" || !entry.priorityRelation
@@ -2573,6 +3011,15 @@ function validateSourceConservation(value, { required = false } = {}) {
2573
3011
  || !Array.isArray(entry.classifications) || entry.classifications.length === 0 || entry.classifications.some((classification) => typeof classification !== "string" || !classification)) {
2574
3012
  throw new Error("shared current-state source conservation entry is invalid; no recovery writes attempted");
2575
3013
  }
3014
+ if (["canonical-path-migration", "canonical-path-migration-closeout"].includes(entry.disposition)) {
3015
+ if (value.schemaVersion !== 2 || !isSafeProjectRelative(entry.sourceOriginPath)
3016
+ || entry.sourceOriginPath === entry.sourcePath
3017
+ || !entry.sourceOriginPath.startsWith("dev/") || !entry.sourcePath.startsWith("dev/SESSION_LOG_archive/")) {
3018
+ throw new Error("archive source-path rebinding is invalid; no recovery writes attempted");
3019
+ }
3020
+ } else if (entry.sourceOriginPath !== undefined) {
3021
+ throw new Error("unexpected source-origin binding is invalid; no recovery writes attempted");
3022
+ }
2576
3023
  if (prior != null && prior.localeCompare(entry.sourcePath) >= 0) {
2577
3024
  throw new Error("shared current-state source conservation entries are not in source-path order; no recovery writes attempted");
2578
3025
  }
@@ -2598,7 +3045,8 @@ function validateCurrentStateWitness(journal) {
2598
3045
  formalUserRules: witness.formalUserRules ?? null,
2599
3046
  runtimeAcceptance: witness.runtimeAcceptance ?? null
2600
3047
  };
2601
- if (witness.schemaVersion === 2) actual.sourceConservation = witness.sourceConservation;
3048
+ if (witness.schemaVersion >= 2) actual.sourceConservation = witness.sourceConservation;
3049
+ if (witness.schemaVersion === 3) actual.archiveMigrations = witness.archiveMigrations;
2602
3050
  if (JSON.stringify(actual) !== JSON.stringify(expected)) {
2603
3051
  throw new Error("shared current-state witness is detached from its transaction components; no recovery writes attempted");
2604
3052
  }
@@ -3334,7 +3782,7 @@ async function loadCommittedCurrentStateWitness(root) {
3334
3782
  return validateCurrentStateWitness(currentCandidates[0].journal);
3335
3783
  }
3336
3784
 
3337
- async function findRestoredCurrentStateDigests(root, outputs) {
3785
+ async function findRestoredCurrentStateDigests(root, outputs, archiveMigrations = []) {
3338
3786
  const migrationsRoot = path.join(root, "dev", "governance_migrations");
3339
3787
  let names;
3340
3788
  try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return []; throw error; }
@@ -3349,7 +3797,8 @@ async function findRestoredCurrentStateDigests(root, outputs) {
3349
3797
  const journal = JSON.parse(await readFile(journalPath, "utf8"));
3350
3798
  if (journal.state !== "committed" || !journal.currentStateWitness) continue;
3351
3799
  await validateRecoveryJournal(root, journal, journalPath);
3352
- if (await journalIsRestoredByOutputs(root, journal, outputWitnesses)) {
3800
+ if (await journalMatchesCurrentState(root, journal)
3801
+ || await journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations)) {
3353
3802
  restored.push(journal.currentStateWitness.currentStateDigest);
3354
3803
  }
3355
3804
  } catch (error) {
@@ -3359,8 +3808,19 @@ async function findRestoredCurrentStateDigests(root, outputs) {
3359
3808
  return [...new Set(restored)].sort((left, right) => left.localeCompare(right));
3360
3809
  }
3361
3810
 
3362
- async function journalIsRestoredByOutputs(root, journal, outputWitnesses) {
3811
+ async function journalIsRestoredByOutputs(root, journal, outputWitnesses, archiveMigrations = []) {
3363
3812
  const witness = validateCurrentStateWitness(journal);
3813
+ const archiveRebindings = new Map();
3814
+ for (const migration of archiveMigrations) {
3815
+ for (const file of migration.snapshot.files) {
3816
+ archiveRebindings.set(`${migration.originalRel}/${file.path}`, {
3817
+ sourcePath: `${migration.originalRel}/${file.path}`,
3818
+ reboundPath: `${migration.canonicalRel}/${file.path}`,
3819
+ sha256: file.sha256,
3820
+ bytes: file.bytes
3821
+ });
3822
+ }
3823
+ }
3364
3824
  for (const entry of journal.entries) {
3365
3825
  const replacement = outputWitnesses.get(entry.targetRel);
3366
3826
  if (replacement) {
@@ -3376,6 +3836,11 @@ async function journalIsRestoredByOutputs(root, journal, outputWitnesses) {
3376
3836
  if (replacement.sha256 !== entry.accepted.sha256 || replacement.bytes !== entry.accepted.bytes) return false;
3377
3837
  continue;
3378
3838
  }
3839
+ const archiveRebinding = archiveRebindings.get(entry.sourcePath);
3840
+ if (archiveRebinding) {
3841
+ if (archiveRebinding.sha256 !== entry.accepted.sha256 || archiveRebinding.bytes !== entry.accepted.bytes) return false;
3842
+ continue;
3843
+ }
3379
3844
  const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
3380
3845
  if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) return false;
3381
3846
  }
@@ -3557,11 +4022,14 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
3557
4022
  const changed = currentWitness.sha256 !== sourceWitness.sha256 || currentWitness.bytes !== sourceWitness.bytes;
3558
4023
  return {
3559
4024
  sourcePath: item.sourcePath,
4025
+ ...(entry?.sourceOriginPath ? { sourceOriginPath: entry.sourceOriginPath } : {}),
3560
4026
  sourceWitness,
3561
4027
  accepted: currentWitness,
3562
4028
  sourceByteRanges: [{ start: 0, end: sourceWitness.bytes, sha256: sourceWitness.sha256 }],
3563
4029
  disposition: isCloseoutFinalizeTarget(item.sourcePath) && changed
3564
- ? "closeout-state-finalize"
4030
+ ? entry?.sourceOriginPath
4031
+ ? "canonical-path-migration-closeout"
4032
+ : "closeout-state-finalize"
3565
4033
  : entry?.disposition ?? (item.classifications.includes("transaction-state") ? "retained-historical-state" : "unchanged-source"),
3566
4034
  existingReaders: entry?.existingReaders ?? item.existingReaders.map((reader) => ({ reader: reader.reader, via: reader.via })),
3567
4035
  priorityRelation: entry?.priorityRelation ?? item.priorityConflict.relation,
@@ -3590,6 +4058,7 @@ async function writeCloseoutFinalizeJournal(root, version, prior) {
3590
4058
  runtimeAcceptance: null,
3591
4059
  runtimeAcceptanceReadback: null,
3592
4060
  sourceConservation,
4061
+ archiveMigrations: oldWitness.archiveMigrations ?? [],
3593
4062
  supersedesCurrentStateDigests: [oldWitness.currentStateDigest],
3594
4063
  currentStateWitness: null,
3595
4064
  currentStateReadback: null
@@ -6878,8 +7347,8 @@ function ensureHandoffCloseoutOutcomeFields(targetText) {
6878
7347
  return targetText.replace(openingMarker, `${fields}${openingMarker}`);
6879
7348
  }
6880
7349
 
6881
- function planIntroFor(command, mode, isDryRun) {
6882
- const prefix = isDryRun ? "📋 預演結果:這次不會寫入檔案。" : "📋 寫入前確認:工具準備這樣處理目前資料夾。";
7350
+ function planIntroFor(command, mode, isDryRun) {
7351
+ const prefix = isDryRun ? "📋 預演結果:這次不會寫入檔案。" : "📋 寫入前確認:工具準備這樣處理目前資料夾。";
6883
7352
  if (command === "init" && mode === "first-install") {
6884
7353
  return `${prefix} 目前資料夾未見 Kit 檔案;工具會建立交接文件、AI 入口檔與工作規則。沒有既有檔案會被覆寫。`;
6885
7354
  }
@@ -6888,12 +7357,17 @@ function planIntroFor(command, mode, isDryRun) {
6888
7357
  }
6889
7358
  if (command === "upgrade") {
6890
7359
  return `${prefix} 工具會檢查既有 Kit 檔案;能安全合併才合併,不能判斷時會停手並列為 conflict。`;
6891
- }
6892
- return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具零寫入停手並提供技術證據。`;
6893
- }
6894
-
6895
- // R-026 CLI Output Contract: install/upgrade 完成必含四項(版本/模式/剛完成/下一步)。
6896
- function printInstallSummary(version, command, mode, root, counts) {
7360
+ }
7361
+ return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具零寫入停手並提供技術證據。`;
7362
+ }
7363
+
7364
+ function conflictRepairNextStepLine(icon = "📋", suffix = "") {
7365
+ const suffixText = suffix ? ` ${suffix}` : "";
7366
+ return `${icon} 下一步:你不用判斷技術差異,也不要重裝或整檔覆寫。請回到能讀寫這個資料夾的 AI,讓 AI 依這段輸出、本地檔案與正式來源做授權合併;合併後重新執行 upgrade --dry-run,再用 doctor 與 hash 讀回驗收。未知本地 hash 只作內容 witness,不代表 Kit 可以理解或覆寫。只有能證明這是 Kit 誤判未改動的正式舊檔時,才把版本、來源與 hash 證據回報 Kit maintainer。${suffixText}`;
7367
+ }
7368
+
7369
+ // R-026 CLI Output Contract: install/upgrade 完成必含四項(版本/模式/剛完成/下一步)。
7370
+ function printInstallSummary(version, command, mode, root, counts) {
6897
7371
  console.log(`\n✅ created: ${counts.created}`);
6898
7372
  console.log(`🔀 merged: ${counts.merged}`);
6899
7373
  console.log(`⏭️ skipped existing: ${counts.skipped}`);
@@ -6902,10 +7376,10 @@ function printInstallSummary(version, command, mode, root, counts) {
6902
7376
  if (counts.reportRel) console.log(`📄 migration report: ${counts.reportRel}`);
6903
7377
  console.log("");
6904
7378
  console.log(`📦 版本:v${version}`);
6905
- console.log(`🛠️ 模式:${mode}`);
6906
- console.log(`🔎 剛完成:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
7379
+ console.log(`🛠️ 模式:${mode}`);
7380
+ console.log(`🔎 剛完成:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
6907
7381
  if (counts.conflicts > 0) {
6908
- console.log("🚀 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對正式來源及差異;一般使用者毋須裁決技術內容。工具已停手,沒有覆寫 conflict 檔案。");
7382
+ console.log(conflictRepairNextStepLine("🚀", "工具已停手,沒有覆寫 conflict 檔案。"));
6909
7383
  } else if (command === "upgrade") {
6910
7384
  console.log("🚀 下一步:本次提交已先經同一輪正式 doctor 讀回;請留意下方提交與健康結果。");
6911
7385
  } else if (counts.skipped > 0) {
@@ -6931,11 +7405,11 @@ function printDryRunExplanation(command, mode, plan) {
6931
7405
  }
6932
7406
  console.log("✅ 沒有發現 conflict。請按你剛才預演的命令去掉 --dry-run 後正式執行。");
6933
7407
  return;
6934
- }
6935
- console.log(`⚠️ 技術核對未完成:有 ${conflicts.length} 個既有檔案,工具目前不能證明可安全合併。`);
6936
- console.log("⚠️ 這不是檔案壞掉,也沒有覆寫你的檔案。");
6937
- console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI,由它核對正式來源及差異;一般使用者毋須閱讀或裁決檔案內容。");
6938
- }
7408
+ }
7409
+ console.log(`⚠️ 技術核對未完成:有 ${conflicts.length} 個既有檔案,工具目前不能證明可安全合併。`);
7410
+ console.log("⚠️ 這不是檔案壞掉,也沒有覆寫你的檔案。");
7411
+ console.log(conflictRepairNextStepLine());
7412
+ }
6939
7413
 
6940
7414
  async function confirmWrite() {
6941
7415
  const rl = createInterface({ input, output });
@@ -7110,12 +7584,12 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
7110
7584
  console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
7111
7585
  }
7112
7586
  console.log("============================================================");
7113
- if (conflictCount > 0) {
7114
- console.log("⚠️ 狀態:有既有檔案未能證明可安全合併。");
7115
- console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
7116
- console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對來源與差異;一般使用者毋須判斷檔案內容。");
7117
- console.log("");
7118
- }
7587
+ if (conflictCount > 0) {
7588
+ console.log("⚠️ 狀態:有既有檔案未能證明可安全合併。");
7589
+ console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
7590
+ console.log(conflictRepairNextStepLine());
7591
+ console.log("");
7592
+ }
7119
7593
  if (skippedCount > 0) {
7120
7594
  console.log("你原本已有部分 AI 記憶檔,工具已保留它們,沒有覆寫。");
7121
7595
  console.log("下一步先不要開始新任務;請在終端機執行以下預演,讓工具檢查能否安全補入口連接:");
@@ -7153,13 +7627,13 @@ function printUpgradeNextSteps(root, conflictCount) {
7153
7627
  console.log("============================================================");
7154
7628
  if (conflictCount > 0) {
7155
7629
  console.log("⚠️ 升級未完成:有檔案未能證明可安全合併");
7156
- console.log("============================================================");
7157
- console.log("⚠️ 狀態:工具已保守停手,沒有建立目前交易或覆寫檔案。");
7158
- console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
7159
- console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對正式來源及差異;一般使用者毋須裁決技術內容。");
7160
- console.log("============================================================");
7161
- return;
7162
- }
7630
+ console.log("============================================================");
7631
+ console.log("⚠️ 狀態:工具已保守停手,沒有建立目前交易或覆寫檔案。");
7632
+ console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
7633
+ console.log(conflictRepairNextStepLine());
7634
+ console.log("============================================================");
7635
+ return;
7636
+ }
7163
7637
  console.log("🛠️ Kit migration 已通過離線遷移驗收;已由正式 doctor 的同輪讀回確認提交與健康使用同一狀態");
7164
7638
  console.log("============================================================");
7165
7639
  console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");