@adamchanadam/agent-handoff-kit 0.3.40 → 0.3.41

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.
@@ -8,35 +8,14 @@ import { hostname } from "node:os";
8
8
  import path from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { assessPromptMirrorRoot, assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
11
+ import { installedFileContract, installedMappings, requiredInstalledTargets } from "./installed-file-contract.mjs";
12
+ import { getOfficialBaseline, identifyOfficialOrigin, loadOfficialOriginCatalog } from "./official-origin-catalog.mjs";
11
13
 
12
14
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
13
15
  const packageRoot = path.resolve(__dirname, "..");
14
16
 
15
- const mappings = [
16
- ["runtime-core/AGENTS.core.md", "AGENTS.md"],
17
- ["runtime-core/CLAUDE.md", "CLAUDE.md"],
18
- ["runtime-core/GEMINI.md", "GEMINI.md"],
19
- ["runtime-core/START_NEXT_SESSION_PROMPT.txt", "START_NEXT_SESSION_PROMPT.txt"],
20
- ["runtime-core/SESSION_HANDOFF.md", "dev/SESSION_HANDOFF.md"],
21
- ["runtime-core/SESSION_LOG.md", "dev/SESSION_LOG.md"],
22
- ["runtime-core/PROJECT_INDEX.md", "dev/PROJECT_INDEX.md"],
23
- ["runtime-core/DOC_SYNC_REGISTRY.md", "dev/DOC_SYNC_REGISTRY.md"],
24
- ["runtime-core/RULE_PACKS.md", "dev/RULE_PACKS.md"],
25
- ["runtime-core/PROJECT_DECISIONS.md", "dev/PROJECT_DECISIONS.md"],
26
- ["packs/safety.md", "dev/rules/safety.md"],
27
- ["packs/coding.md", "dev/rules/coding.md"],
28
- ["packs/writing.md", "dev/rules/writing.md"],
29
- ["packs/research.md", "dev/rules/research.md"],
30
- ["packs/agent-governance.md", "dev/rules/agent-governance.md"],
31
- ["packs/release.md", "dev/rules/release.md"],
32
- ["packs/knowledge.md", "dev/rules/knowledge.md"],
33
- ["packs/communication.md", "dev/rules/communication.md"],
34
- ["packs/closeout.md", "dev/rules/closeout.md"],
35
- ["packs/onboarding.md", "dev/rules/onboarding.md"],
36
- ["packs/integrations.md", "dev/rules/integrations.md"]
37
- ];
38
-
39
- const requiredTargets = mappings.map(([, target]) => target);
17
+ const mappings = installedMappings;
18
+ const requiredTargets = requiredInstalledTargets;
40
19
  const rulePackTargets = mappings
41
20
  .map(([, target]) => target)
42
21
  .filter((target) => target.startsWith("dev/rules/"));
@@ -625,6 +604,9 @@ async function needsProjectIndexVersionInject(root, command, version) {
625
604
  }
626
605
 
627
606
  async function runInstall(command, root, options, version) {
607
+ // Guard the selected root before reading or recovering any persisted
608
+ // transaction. Recovery is a write path and must not run through a junction.
609
+ await validateTransactionRoot(root, [], { createMissingRoot: false });
628
610
  if (options.dryRun) await assertDryRunHasNoPendingTransaction(root);
629
611
  else await recoverInterruptedTransaction(root);
630
612
  const installedVersion = await readInstalledTemplateVersion(root);
@@ -642,7 +624,9 @@ async function runInstall(command, root, options, version) {
642
624
  // Validate the operator-selected path before every exit path, including
643
625
  // dry-run, conflicts, and already-current no-op upgrades. Otherwise a
644
626
  // junction can be silently accepted whenever there is nothing to write.
645
- await validateTransactionRoot(root, plan, { createMissingRoot: !options.dryRun });
627
+ // Before confirmation, validate the selected path without creating it. A
628
+ // cancelled init/upgrade must leave a previously missing root absent.
629
+ await validateTransactionRoot(root, plan, { createMissingRoot: false });
646
630
 
647
631
  // R-031 v0.3.1+: plan-time upgrade no-op detection. When upgrade has zero
648
632
  // create/merge/conflict actions (skip-only), skip the full plan listing +
@@ -666,11 +650,12 @@ async function runInstall(command, root, options, version) {
666
650
 
667
651
  if (isUpgradeNoopAtPlanTime) {
668
652
  const noOpHealth = await assessUpgradeNoopHealth(root, version);
669
- printCard(version, "continuity ready", "o.o");
670
- console.log(`command: ${command}`);
671
- console.log(`current directory: ${process.cwd()}`);
672
- console.log(`selected root: ${root}`);
673
- console.log(`mode: ${mode}`);
653
+ printCard(version, "continuity ready", "o.o");
654
+ console.log(`command: ${command}`);
655
+ console.log(`current directory: ${process.cwd()}`);
656
+ console.log(`selected root: ${root}`);
657
+ console.log(`version state: live ${installedVersion ? `v${installedVersion}` : "unverified"} -> target v${version}; current transaction: none (historical migration folders are evidence only)`);
658
+ console.log(`mode: ${mode}`);
674
659
  console.log("");
675
660
  console.log(`📋 計劃預覽:create 0 / merge 0 / skip ${planSkipCount} / conflict 0 — 沒有檔案需要建立或合併。`);
676
661
  if (options.dryRun) {
@@ -682,7 +667,30 @@ async function runInstall(command, root, options, version) {
682
667
  return;
683
668
  }
684
669
 
685
- printPlan(command, root, mode, plan, version, options.dryRun);
670
+ let candidateOutputs = null;
671
+ if (planConflictCount === 0) {
672
+ candidateOutputs = await buildTransactionOutputs(command, root, plan, version);
673
+ const credentialFindings = await detectInstalledCredentialFindings(root);
674
+ if (credentialFindings.length > 0) {
675
+ plan.push({
676
+ targetRel: "transaction preflight",
677
+ action: "conflict",
678
+ reason: `existing governance contains ${credentialFindings.length} possible credential value(s); remove and rotate them before upgrade`
679
+ });
680
+ } else {
681
+ try {
682
+ await validateTransactionOverlay(root, candidateOutputs);
683
+ } catch (error) {
684
+ plan.push({
685
+ targetRel: "transaction preflight",
686
+ action: "conflict",
687
+ reason: safeErrorLabel(error)
688
+ });
689
+ }
690
+ }
691
+ }
692
+
693
+ printPlan(command, root, mode, plan, version, options.dryRun, installedVersion);
686
694
 
687
695
  if (options.dryRun) {
688
696
  console.log("\ndry-run: no files written");
@@ -694,7 +702,7 @@ async function runInstall(command, root, options, version) {
694
702
  if (plan.some((item) => item.action === "conflict")) {
695
703
  console.log("");
696
704
  console.log("⛔ 升級預檢發現 conflict;治理目標檔、版本與 migration artifact 均沒有寫入。");
697
- console.log("📋 下一步:根據上方 conflict 資料作非破壞性合併;不要以舊版本資料列當作已完成。");
705
+ console.log("📋 下一步:由 Kit 開發者或可讀取檔案的 AI 核對來源、差異與安全合併路徑;一般使用者毋須判斷技術差異。不要把歷史 stage、舊報告或版本列當作目前交易。");
698
706
  process.exitCode = 1;
699
707
  return;
700
708
  }
@@ -707,7 +715,7 @@ async function runInstall(command, root, options, version) {
707
715
  }
708
716
  }
709
717
 
710
- await executeInstallTransaction(command, root, mode, plan, version);
718
+ await executeInstallTransaction(command, root, mode, plan, version, candidateOutputs);
711
719
  }
712
720
 
713
721
  async function readInstalledTemplateVersion(root) {
@@ -720,8 +728,8 @@ async function readInstalledTemplateVersion(root) {
720
728
  }
721
729
  }
722
730
 
723
- async function executeInstallTransaction(command, root, mode, plan, version) {
724
- const outputs = await buildTransactionOutputs(command, root, plan, version);
731
+ async function executeInstallTransaction(command, root, mode, plan, version, candidateOutputs = null) {
732
+ const outputs = candidateOutputs ?? await buildTransactionOutputs(command, root, plan, version);
725
733
  if (outputs.length === 0) {
726
734
  const health = await assessUpgradeNoopHealth(root, version);
727
735
  printUpgradeNoopShortCircuit(version, health);
@@ -729,12 +737,7 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
729
737
  return;
730
738
  }
731
739
 
732
- const credentialInputs = [];
733
- for (const relative of requiredTargets) {
734
- const buffer = await readOptionalBuffer(path.join(root, relative));
735
- if (buffer) credentialInputs.push({ relative, text: decodeUtf8(buffer, relative).text });
736
- }
737
- const credentialFindings = detectCredentialValues(credentialInputs);
740
+ const credentialFindings = await detectInstalledCredentialFindings(root);
738
741
  if (credentialFindings.length > 0) {
739
742
  console.log("⛔ 升級已停止:待備份的治理檔疑似含有 credential value。");
740
743
  console.log("機密值不會顯示或複製;請先移除並輪換機密,再重跑 upgrade。");
@@ -743,9 +746,14 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
743
746
  return;
744
747
  }
745
748
 
749
+ // Run the same deterministic acceptance gate used by dry-run before creating
750
+ // a lock, stage, backup, journal, or migration directory.
751
+ await validateTransactionOverlay(root, outputs);
752
+ // The user has confirmed writes. Create and revalidate a missing root only
753
+ // now, immediately before transaction artifacts are prepared.
754
+ await validateTransactionRoot(root, plan, { createMissingRoot: true });
746
755
  const transaction = await prepareTransaction(root, command, version, outputs, mode, plan);
747
756
  try {
748
- await validateTransactionOverlay(root, outputs);
749
757
  transaction.journal.state = "committing";
750
758
  await writeSecureJson(transaction.journalPath, transaction.journal);
751
759
 
@@ -754,6 +762,11 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
754
762
  for (const entry of transaction.journal.entries) {
755
763
  const output = outputs.find((item) => item.targetRel === entry.targetRel);
756
764
  await atomicReplaceFromBuffer(root, output.targetAbs, output.after, transaction.id);
765
+ if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_REPLACE === "1") {
766
+ const interruption = new Error("QA interruption after target replacement before journal update");
767
+ interruption.code = "ACK_QA_INTERRUPT_AFTER_REPLACE";
768
+ throw interruption;
769
+ }
757
770
  entry.committed = true;
758
771
  committedCount += 1;
759
772
  await writeSecureJson(transaction.journalPath, transaction.journal);
@@ -796,7 +809,7 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
796
809
  else console.log("⚠️ project health: needs attention; migration remains committed because the deterministic migration gate passed");
797
810
  }
798
811
  } catch (error) {
799
- if (error?.code === "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT") throw error;
812
+ if (["ACK_QA_INTERRUPT_AFTER_REPLACE", "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT"].includes(error?.code)) throw error;
800
813
  transaction.journal.state = "rollback-needed";
801
814
  transaction.journal.error = safeErrorLabel(error);
802
815
  await writeSecureJson(transaction.journalPath, transaction.journal).catch(() => {});
@@ -812,6 +825,15 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
812
825
  }
813
826
  }
814
827
 
828
+ async function detectInstalledCredentialFindings(root) {
829
+ const credentialInputs = [];
830
+ for (const relative of requiredTargets) {
831
+ const buffer = await readOptionalBuffer(path.join(root, relative));
832
+ if (buffer) credentialInputs.push({ relative, text: decodeUtf8(buffer, relative).text });
833
+ }
834
+ return detectCredentialValues(credentialInputs);
835
+ }
836
+
815
837
  async function buildTransactionOutputs(command, root, plan, version) {
816
838
  const byTarget = new Map();
817
839
  for (const item of plan) {
@@ -1031,31 +1053,140 @@ async function atomicReplaceFromBuffer(root, targetAbs, buffer, id) {
1031
1053
  await rename(tempPath, targetAbs);
1032
1054
  }
1033
1055
 
1034
- async function rollbackTransaction(root, journal, journalPath) {
1056
+ async function validateRecoveryJournal(root, journal, journalPath, lockId = null) {
1057
+ const migrationsRoot = path.resolve(root, "dev", "governance_migrations");
1058
+ const migrationDir = path.dirname(journalPath);
1059
+ if (path.basename(journalPath) !== "transaction.json" || !samePath(path.dirname(migrationDir), migrationsRoot)) {
1060
+ throw new Error("upgrade journal is not in one direct transaction directory; no recovery writes attempted");
1061
+ }
1062
+ if (!journal || typeof journal !== "object" || Array.isArray(journal)) throw new Error("upgrade journal schema is invalid; no recovery writes attempted");
1063
+ if (typeof journal.id !== "string" || journal.id !== path.basename(migrationDir) || (lockId && journal.id !== lockId)) {
1064
+ throw new Error("upgrade journal identity does not match its lock and directory; no recovery writes attempted");
1065
+ }
1066
+ if (!Array.isArray(journal.entries) || journal.entries.length === 0) throw new Error("upgrade journal has no valid entries; no recovery writes attempted");
1067
+ if (!isStableSemver(journal.attemptedVersion ?? "")) throw new Error("upgrade journal attempted version is invalid; no recovery writes attempted");
1068
+ const allowedStates = new Set(["prepared", "committing", "rollback-needed", "manual-recovery-required", "committed", "rolled-back"]);
1069
+ if (!allowedStates.has(journal.state)) throw new Error("upgrade journal state is invalid; no recovery writes attempted");
1070
+
1071
+ const seen = new Set();
1072
+ const rootStats = await lstat(root);
1073
+ if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) throw new Error("selected recovery root is not a safe directory; no recovery writes attempted");
1074
+ const rootReal = await realpath(root);
1075
+ const backupRoot = path.join(migrationDir, "backup");
1076
+ const stageRoot = path.join(migrationDir, "stage");
1077
+ const migrationsStats = await lstat(migrationsRoot).catch(() => null);
1078
+ const migrationStats = await lstat(migrationDir).catch(() => null);
1079
+ const journalStats = await lstat(journalPath).catch(() => null);
1080
+ const backupStats = await lstat(backupRoot).catch(() => null);
1081
+ const stageStats = await lstat(stageRoot).catch(() => null);
1082
+ if (!migrationsStats?.isDirectory() || migrationsStats.isSymbolicLink()
1083
+ || !migrationStats?.isDirectory() || migrationStats.isSymbolicLink()
1084
+ || !journalStats?.isFile() || journalStats.isSymbolicLink()
1085
+ || !backupStats?.isDirectory() || backupStats.isSymbolicLink()
1086
+ || !stageStats?.isDirectory() || stageStats.isSymbolicLink()) {
1087
+ throw new Error("upgrade transaction directories or journal are missing or unsafe; no recovery writes attempted");
1088
+ }
1089
+ const migrationsReal = await realpath(migrationsRoot);
1090
+ const migrationReal = await realpath(migrationDir);
1091
+ const journalReal = await realpath(journalPath);
1092
+ const backupRealRoot = await realpath(backupRoot);
1093
+ const stageRealRoot = await realpath(stageRoot);
1094
+ if (!isInside(rootReal, migrationsReal) || !isInside(migrationsReal, migrationReal)
1095
+ || !isInside(migrationReal, journalReal) || !isInside(migrationReal, backupRealRoot) || !isInside(migrationReal, stageRealRoot)
1096
+ || !samePath(path.dirname(migrationReal), migrationsReal)
1097
+ || !samePath(path.dirname(backupRealRoot), migrationReal) || !samePath(path.dirname(stageRealRoot), migrationReal)) {
1098
+ throw new Error("upgrade transaction paths resolve outside the selected root or transaction; no recovery writes attempted");
1099
+ }
1100
+ const validated = [];
1101
+ const validHash = (value) => typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
1102
+ for (const entry of journal.entries) {
1103
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new Error("upgrade journal entry schema is invalid; no recovery writes attempted");
1104
+ if (!requiredTargets.includes(entry.targetRel) || seen.has(entry.targetRel)) throw new Error("upgrade journal target is unknown or duplicated; no recovery writes attempted");
1105
+ seen.add(entry.targetRel);
1106
+ if (typeof entry.existed !== "boolean" || typeof entry.committed !== "boolean" || !validHash(entry.afterHash)) {
1107
+ throw new Error("upgrade journal entry flags or candidate hash are invalid; no recovery writes attempted");
1108
+ }
1109
+ if (entry.existed ? !validHash(entry.beforeHash) : entry.beforeHash !== null) {
1110
+ throw new Error("upgrade journal input hash is invalid; no recovery writes attempted");
1111
+ }
1112
+
1113
+ const targetAbs = path.resolve(root, entry.targetRel);
1114
+ if (!isInside(root, targetAbs)) throw new Error("upgrade journal target escapes selected root; no recovery writes attempted");
1115
+ const targetParent = await nearestExistingRealParent(path.dirname(targetAbs));
1116
+ if (!isInside(rootReal, targetParent)) throw new Error("upgrade journal target parent escapes selected root; no recovery writes attempted");
1117
+ try {
1118
+ if ((await lstat(targetAbs)).isSymbolicLink()) throw new Error("upgrade journal target is a symbolic link; no recovery writes attempted");
1119
+ } catch (error) {
1120
+ if (error?.code !== "ENOENT") throw error;
1121
+ }
1122
+
1123
+ const stageAbs = path.resolve(stageRoot, entry.targetRel);
1124
+ const stageStats = await lstat(stageAbs).catch(() => null);
1125
+ if (!stageStats?.isFile() || stageStats.isSymbolicLink()) throw new Error("upgrade journal stage is missing or unsafe; no recovery writes attempted");
1126
+ const stageReal = await realpath(stageAbs);
1127
+ if (!isInside(stageRealRoot, stageReal)) throw new Error("upgrade journal stage resolves outside this transaction; no recovery writes attempted");
1128
+ if (sha256(await readFile(stageAbs)) !== entry.afterHash) throw new Error("upgrade journal stage hash does not match the recorded candidate; no recovery writes attempted");
1129
+
1130
+ let backup = null;
1131
+ if (entry.existed) {
1132
+ if (typeof entry.backupRel !== "string" || !entry.backupRel) throw new Error("upgrade journal backup path is missing; no recovery writes attempted");
1133
+ const backupAbs = path.resolve(root, entry.backupRel);
1134
+ const expectedBackup = path.resolve(backupRoot, entry.targetRel);
1135
+ if (!samePath(backupAbs, expectedBackup) || !isInside(backupRoot, backupAbs)) throw new Error("upgrade journal backup path is outside this transaction; no recovery writes attempted");
1136
+ const backupFileStats = await lstat(backupAbs).catch(() => null);
1137
+ if (!backupFileStats?.isFile() || backupFileStats.isSymbolicLink()) throw new Error("upgrade journal backup is missing or unsafe; no recovery writes attempted");
1138
+ const backupReal = await realpath(backupAbs);
1139
+ if (!isInside(backupRealRoot, backupReal)) throw new Error("upgrade journal backup resolves outside this transaction; no recovery writes attempted");
1140
+ backup = await readFile(backupAbs);
1141
+ if (sha256(backup) !== entry.beforeHash) throw new Error("upgrade journal backup hash does not match the recorded input; no recovery writes attempted");
1142
+ } else if (entry.backupRel !== null) {
1143
+ throw new Error("upgrade journal has an unexpected backup for a created target; no recovery writes attempted");
1144
+ }
1145
+ validated.push({ entry, targetAbs, backup });
1146
+ }
1147
+ if (journal.state === "committed" && validated.some(({ entry }) => !entry.committed)) {
1148
+ throw new Error("committed upgrade journal contains an uncommitted entry; no recovery writes attempted");
1149
+ }
1150
+ return validated;
1151
+ }
1152
+
1153
+ async function rollbackTransaction(root, journal, journalPath, lockId = null) {
1154
+ const validated = await validateRecoveryJournal(root, journal, journalPath, lockId);
1035
1155
  const conflicts = [];
1036
- for (const entry of [...journal.entries].reverse()) {
1037
- if (!entry.committed) continue;
1038
- const targetAbs = path.join(root, entry.targetRel);
1039
- const current = await readOptionalBuffer(targetAbs);
1156
+ const operations = [];
1157
+ // Do not trust the committed flag: the process can stop after replacement
1158
+ // but before the journal flag is persisted. Inspect every target hash first.
1159
+ for (const item of [...validated].reverse()) {
1160
+ const current = await readOptionalBuffer(item.targetAbs);
1040
1161
  const currentHash = current ? sha256(current) : null;
1041
- if (currentHash === entry.beforeHash) continue;
1042
- if (currentHash !== entry.afterHash) {
1043
- conflicts.push(`${entry.targetRel}: current content differs from both transaction input and candidate`);
1162
+ if (currentHash === item.entry.beforeHash) continue;
1163
+ if (currentHash !== item.entry.afterHash) {
1164
+ conflicts.push(`${item.entry.targetRel}: current content differs from both transaction input and candidate`);
1044
1165
  continue;
1045
1166
  }
1046
- if (entry.existed) {
1047
- const backup = await readFile(path.join(root, entry.backupRel));
1048
- await atomicReplaceFromBuffer(root, targetAbs, backup, `${journal.id}-rollback`);
1049
- } else {
1050
- await unlink(targetAbs);
1051
- }
1167
+ operations.push(item);
1052
1168
  }
1053
- journal.state = conflicts.length === 0 ? "rolled-back" : "manual-recovery-required";
1169
+ if (conflicts.length > 0) {
1170
+ journal.state = "manual-recovery-required";
1171
+ journal.committedVersion = null;
1172
+ journal.recoveryConflicts = conflicts;
1173
+ await writeSecureJson(journalPath, journal);
1174
+ return { ok: false, conflicts };
1175
+ }
1176
+
1177
+ for (const { entry, targetAbs, backup } of operations) {
1178
+ if (entry.existed) await atomicReplaceFromBuffer(root, targetAbs, backup, `${journal.id}-rollback`);
1179
+ else await unlink(targetAbs);
1180
+ const restored = await readOptionalBuffer(targetAbs);
1181
+ const restoredHash = restored ? sha256(restored) : null;
1182
+ if (restoredHash !== entry.beforeHash) throw new Error(`${entry.targetRel}: rollback verification failed; recovery lock retained`);
1183
+ }
1184
+ journal.state = "rolled-back";
1054
1185
  journal.committedVersion = null;
1055
1186
  journal.rollbackAt = new Date().toISOString();
1056
- journal.recoveryConflicts = conflicts;
1057
- await writeSecureJson(journalPath, journal).catch(() => {});
1058
- return { ok: conflicts.length === 0, conflicts };
1187
+ journal.recoveryConflicts = [];
1188
+ await writeSecureJson(journalPath, journal);
1189
+ return { ok: true, conflicts: [] };
1059
1190
  }
1060
1191
 
1061
1192
  async function recoverInterruptedTransaction(root) {
@@ -1067,6 +1198,10 @@ async function recoverInterruptedTransaction(root) {
1067
1198
  if (error?.code === "ENOENT") return;
1068
1199
  throw new Error("upgrade lock exists but is unreadable; no writes attempted");
1069
1200
  }
1201
+ if (!lock || typeof lock !== "object" || Array.isArray(lock) || typeof lock.id !== "string" || typeof lock.journal !== "string"
1202
+ || typeof lock.host !== "string" || !Number.isInteger(lock.pid) || lock.pid <= 0) {
1203
+ throw new Error("upgrade lock schema is invalid; no automatic recovery attempted");
1204
+ }
1070
1205
  if (lock.host === hostname() && processIsAlive(lock.pid)) throw new Error(`another upgrade process is active (pid ${lock.pid})`);
1071
1206
  if (lock.host && lock.host !== hostname()) throw new Error(`upgrade lock belongs to another host (${lock.host}); no automatic recovery attempted`);
1072
1207
  const journalPath = path.resolve(root, lock.journal ?? "");
@@ -1077,6 +1212,7 @@ async function recoverInterruptedTransaction(root) {
1077
1212
  } catch {
1078
1213
  throw new Error("incomplete upgrade lock has no readable journal; no automatic recovery attempted");
1079
1214
  }
1215
+ await validateRecoveryJournal(root, journal, journalPath, lock.id);
1080
1216
  if (journal.state === "committed") {
1081
1217
  if (!journal.committedVersion) journal.committedVersion = journal.attemptedVersion;
1082
1218
  const migrationDir = path.dirname(journalPath);
@@ -1090,7 +1226,7 @@ async function recoverInterruptedTransaction(root) {
1090
1226
  await unlinkIfExists(lockPath);
1091
1227
  return;
1092
1228
  }
1093
- const rollback = await rollbackTransaction(root, journal, journalPath);
1229
+ const rollback = await rollbackTransaction(root, journal, journalPath, lock.id);
1094
1230
  if (!rollback.ok) throw new Error(`interrupted upgrade has third-state edits: ${rollback.conflicts.join("; ")}`);
1095
1231
  await unlinkIfExists(lockPath);
1096
1232
  console.log("⚠️ recovered interrupted upgrade: transaction-owned changes were safely rolled back before planning this run");
@@ -2221,13 +2357,19 @@ async function buildPlan(root, command, version = null) {
2221
2357
  const context = {
2222
2358
  currentVersion: version,
2223
2359
  rootTemplateVersion: command === "upgrade" ? await readRootTemplateVersion(root) : null,
2224
- migrationBaselines: new Map()
2360
+ officialCatalog: command === "upgrade" ? await loadOfficialOriginCatalog() : null,
2361
+ officialOrigins: new Map(),
2362
+ trustedBaselineVersion: null,
2363
+ historicalOfficialEvidence: false
2225
2364
  };
2226
- if (command === "upgrade" && context.rootTemplateVersion === "0.3.38") {
2227
- for (const relative of ["packs/integrations.md", "packs/onboarding.md", "packs/safety.md"]) {
2228
- const baseline = await readOptionalText(path.join(packageRoot, "bin", "migration-baselines", "v0.3.38", path.basename(relative)));
2229
- if (baseline != null) context.migrationBaselines.set(relative, baseline);
2365
+ if (command === "upgrade") {
2366
+ for (const [, targetRel] of mappings) {
2367
+ const targetText = await readOptionalText(path.join(root, targetRel));
2368
+ if (targetText == null) continue;
2369
+ context.officialOrigins.set(targetRel, identifyOfficialOrigin({ targetRel, text: targetText, catalog: context.officialCatalog }));
2230
2370
  }
2371
+ context.trustedBaselineVersion = selectTrustedOfficialBaseline(context);
2372
+ context.historicalOfficialEvidence = countHistoricalOfficialSignals(context) >= 2;
2231
2373
  }
2232
2374
  for (const [sourceRel, targetRel] of mappings) {
2233
2375
  const sourceAbs = path.join(packageRoot, sourceRel);
@@ -2253,8 +2395,53 @@ async function buildPlan(root, command, version = null) {
2253
2395
  ...(reason ? { reason } : {})
2254
2396
  });
2255
2397
  }
2256
- return plan;
2257
- }
2398
+ return plan;
2399
+ }
2400
+
2401
+ function countHistoricalOfficialSignals(context) {
2402
+ if (!isStableSemver(context.currentVersion)) return 0;
2403
+ return [...context.officialOrigins.values()].filter((origin) => (
2404
+ origin.exactVersions.length > 0
2405
+ && !origin.exactVersions.includes(context.currentVersion)
2406
+ && origin.exactVersions.every((version) => isStableSemver(version) && compareSemver(version, context.currentVersion) < 0)
2407
+ )).length;
2408
+ }
2409
+
2410
+ function selectTrustedOfficialBaseline(context) {
2411
+ const version = context.rootTemplateVersion;
2412
+ if (!isStableSemver(version) || !context.officialCatalog?.releases?.[version]) return null;
2413
+ const dynamicTargets = new Set(["START_NEXT_SESSION_PROMPT.txt", "dev/SESSION_HANDOFF.md", "dev/PROJECT_INDEX.md"]);
2414
+ let exactSupport = 0;
2415
+ let contradiction = false;
2416
+ for (const [targetRel, origin] of context.officialOrigins) {
2417
+ const candidates = dynamicTargets.has(targetRel)
2418
+ ? [...new Set([...origin.exactVersions, ...origin.canonicalVersions])]
2419
+ : origin.exactVersions;
2420
+ if (candidates.length === 0) continue;
2421
+ if (!candidates.includes(version)) contradiction = true;
2422
+ else if (!dynamicTargets.has(targetRel)) exactSupport += 1;
2423
+ }
2424
+ return !contradiction && exactSupport >= 2 ? version : null;
2425
+ }
2426
+
2427
+ function trustedOfficialOrigin(targetRel, context) {
2428
+ const origin = context.officialOrigins?.get(targetRel);
2429
+ if (!origin) return null;
2430
+ if (origin.exact) return { kind: "exact", versions: origin.exactVersions };
2431
+ const baseline = context.trustedBaselineVersion;
2432
+ if (baseline && origin.canonicalVersions.includes(baseline)) return { kind: "canonical", versions: [baseline] };
2433
+ return null;
2434
+ }
2435
+
2436
+ function requiresHistoricalBaselineProof(context) {
2437
+ if (!isStableSemver(context.currentVersion)) return false;
2438
+ if (!context.rootTemplateVersion) return context.historicalOfficialEvidence;
2439
+ return Boolean(
2440
+ isStableSemver(context.rootTemplateVersion)
2441
+ && context.officialCatalog?.releases?.[context.rootTemplateVersion]
2442
+ && compareSemver(context.rootTemplateVersion, context.currentVersion) < 0
2443
+ );
2444
+ }
2258
2445
 
2259
2446
  async function readRootTemplateVersion(root) {
2260
2447
  try {
@@ -2303,13 +2490,34 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2303
2490
  if (hasRequiredAnchor(targetRel, targetText)) {
2304
2491
  return { ...base, action: "skip", reason: "managed core clean and required anchors present" };
2305
2492
  }
2306
- return {
2307
- ...base,
2308
- action: "merge",
2309
- reason: "add managed core while preserving existing AGENTS.md content",
2310
- mergedText: mergeManagedBlock(targetText, sourceText)
2311
- };
2312
- }
2493
+ return {
2494
+ ...base,
2495
+ action: "merge",
2496
+ reason: "add managed core while preserving existing AGENTS.md content",
2497
+ mergedText: mergeManagedBlock(targetText, sourceText)
2498
+ };
2499
+ }
2500
+ const officialOrigin = command === "upgrade" ? trustedOfficialOrigin(targetRel, context) : null;
2501
+ if (officialOrigin) {
2502
+ return {
2503
+ ...base,
2504
+ action: "merge",
2505
+ reason: `replace unchanged official ${officialOrigin.kind === "exact" ? "historical" : "root-bound historical"} ${targetRel} with the current Kit file`,
2506
+ mergedText: sourceText
2507
+ };
2508
+ }
2509
+ if (
2510
+ command === "upgrade"
2511
+ && installedFileContract(targetRel)?.strategy === "rule-pack"
2512
+ && requiresHistoricalBaselineProof(context)
2513
+ && !context.trustedBaselineVersion
2514
+ ) {
2515
+ return {
2516
+ ...base,
2517
+ action: "conflict",
2518
+ reason: `${targetRel} has local content but the version row and official file fingerprints do not identify one consistent historical baseline; upgrade stopped instead of guessing`
2519
+ };
2520
+ }
2313
2521
  // R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
2314
2522
  // user-added rows. Missing maintainer rows are merged into the existing table
2315
2523
  // instead of replacing the whole file.
@@ -2367,9 +2575,13 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2367
2575
  }
2368
2576
  return { ...base, action: "skip", reason: "SESSION_LOG.md trace/template boundary current" };
2369
2577
  }
2370
- if (command === "upgrade" && ["dev/rules/integrations.md", "dev/rules/onboarding.md", "dev/rules/safety.md"].includes(targetRel)) {
2371
- const baseline = context.migrationBaselines?.get(sourceRel);
2372
- if (baseline != null) {
2578
+ if (command === "upgrade" && installedFileContract(targetRel)?.strategy === "rule-pack" && context.trustedBaselineVersion) {
2579
+ const baselineRecord = getOfficialBaseline({
2580
+ version: context.trustedBaselineVersion,
2581
+ targetRel,
2582
+ catalog: context.officialCatalog
2583
+ });
2584
+ if (baselineRecord?.state === "present") {
2373
2585
  if (isKnownV038ContinuityQuickFix(sourceRel, targetText)) {
2374
2586
  return {
2375
2587
  ...base,
@@ -2378,14 +2590,14 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2378
2590
  mergedText: sourceText
2379
2591
  };
2380
2592
  }
2381
- const mergedPack = threeWayPreserveLocalChanges(baseline, targetText, sourceText);
2593
+ const mergedPack = threeWayPreserveLocalAppendix(baselineRecord.text, targetText, sourceText);
2382
2594
  if (!mergedPack) {
2383
- return { ...base, action: "conflict", reason: `${targetRel} has local edits that overlap changed Kit rules; upgrade stopped without replacing custom content` };
2595
+ return { ...base, action: "conflict", reason: `${targetRel} differs from its verified official baseline outside a clearly headed local appendix; arbitrary line-level non-overlap is not treated as proof that rule changes are compatible` };
2384
2596
  }
2385
2597
  if (mergedPack !== targetText) {
2386
- return { ...base, action: "merge", reason: `three-way merge v0.3.38 official rules while preserving non-overlapping local ${path.basename(targetRel)} changes`, mergedText: mergedPack };
2598
+ return { ...base, action: "merge", reason: `update verified official rules while preserving the clearly headed local ${path.basename(targetRel)} appendix`, mergedText: mergedPack };
2387
2599
  }
2388
- return { ...base, action: "skip", reason: `${targetRel} current after three-way preservation check` };
2600
+ return { ...base, action: "skip", reason: `${targetRel} current after verified-baseline preservation check` };
2389
2601
  }
2390
2602
  }
2391
2603
  // Governance bridge v0.3.27+: add the triggered review workflow to the
@@ -2470,14 +2682,6 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2470
2682
  return { ...base, action: "conflict", reason: "required Kit anchors are missing but no safe semantic repair path exists; upgrade stopped without appending naked anchor text" };
2471
2683
  }
2472
2684
  if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
2473
- if (looksLikeExpandedKitBridge(targetRel, targetText)) {
2474
- return {
2475
- ...base,
2476
- action: "merge",
2477
- reason: `${targetRel} appears to be an expanded Kit bridge; restore short bridge so AGENTS.md remains the single source of truth`,
2478
- mergedText: sourceText
2479
- };
2480
- }
2481
2685
  const bridgeFailure = bridgeTextFailure(targetRel, targetText);
2482
2686
  if (bridgeFailure) {
2483
2687
  return { ...base, action: "conflict", reason: `existing bridge is not an active one-hop route (${bridgeFailure})` };
@@ -2493,22 +2697,6 @@ function isUpgradeFromOlderTemplate(context) {
2493
2697
  && compareSemver(rootTemplateVersion, currentVersion) < 0;
2494
2698
  }
2495
2699
 
2496
- function looksLikeExpandedKitBridge(targetRel, text) {
2497
- if (text.includes("This file is a bridge only")) return false;
2498
- if (targetRel === "CLAUDE.md") {
2499
- return (text.includes("This file provides guidance to Claude Code") && text.includes("## Session Startup"))
2500
- || text.includes("## Architecture")
2501
- || text.includes("## CLI Commands")
2502
- || text.includes("Every non-trivial task follows");
2503
- }
2504
- if (targetRel === "GEMINI.md") {
2505
- return text.includes("## Architecture")
2506
- || text.includes("## CLI Commands")
2507
- || text.includes("Every non-trivial task follows");
2508
- }
2509
- return false;
2510
- }
2511
-
2512
2700
  function mergeOnboardingScenarioALabel(targetText) {
2513
2701
  let merged = targetText;
2514
2702
  merged = merged.replace(
@@ -3152,6 +3340,25 @@ function threeWayPreserveLocalChanges(baseText, localText, currentText) {
3152
3340
  return `${merged.join(newline)}${localHadFinalNewline || baseHadFinalNewline ? newline : ""}`;
3153
3341
  }
3154
3342
 
3343
+ // Rule packs and other normative Kit files may preserve a clearly separated
3344
+ // local appendix, but must not treat arbitrary line-level non-overlap as proof
3345
+ // that two rule changes are semantically compatible. Existing-line edits,
3346
+ // insertions inside the official body, or a missing local heading are conflicts.
3347
+ function threeWayPreserveLocalAppendix(baseText, localText, currentText) {
3348
+ const baseNormalized = baseText.replace(/\r\n/g, "\n").trimEnd();
3349
+ const localNormalized = localText.replace(/\r\n/g, "\n").trimEnd();
3350
+ if (localNormalized === baseNormalized) return currentText;
3351
+ if (!localNormalized.startsWith(`${baseNormalized}\n`)) return null;
3352
+
3353
+ const appendix = localNormalized.slice(baseNormalized.length).trimStart();
3354
+ if (!/^## (?:Local|Project[- ]specific|Project Specific|Custom)(?:\s|$)/i.test(appendix)) return null;
3355
+ const currentNormalized = currentText.replace(/\r\n/g, "\n").trimEnd();
3356
+ if (currentNormalized.includes(appendix)) return localText;
3357
+ const newline = localText.includes("\r\n") ? "\r\n" : "\n";
3358
+ const appendixWithNewlines = appendix.replace(/\n/g, newline);
3359
+ return `${currentText.trimEnd()}${newline}${newline}${appendixWithNewlines}${newline}`;
3360
+ }
3361
+
3155
3362
  function isKnownV038ContinuityQuickFix(sourceRel, text) {
3156
3363
  const expected = knownV038ContinuityQuickFixHashes.get(sourceRel);
3157
3364
  if (!expected) return false;
@@ -4241,12 +4448,15 @@ async function detectMode(root) {
4241
4448
  return "partial";
4242
4449
  }
4243
4450
 
4244
- function printPlan(command, root, mode, plan, version, isDryRun = false) {
4451
+ function printPlan(command, root, mode, plan, version, isDryRun = false, installedVersion = null) {
4245
4452
  printCard(version, "continuity ready", "o.o");
4246
4453
  console.log(`command: ${command}`);
4247
- console.log(`current directory: ${process.cwd()}`);
4248
- console.log(`selected root: ${root}`);
4249
- console.log(`mode: ${mode}`);
4454
+ console.log(`current directory: ${process.cwd()}`);
4455
+ console.log(`selected root: ${root}`);
4456
+ console.log(`live project version: ${installedVersion ? `v${installedVersion}` : "unverified"}`);
4457
+ console.log(`target CLI version: v${version}`);
4458
+ console.log("current transaction: none (historical migration folders are evidence only)");
4459
+ console.log(`mode: ${mode}`);
4250
4460
  console.log("");
4251
4461
  const planIntro = planIntroFor(command, mode, isDryRun);
4252
4462
  console.log(planIntro);
@@ -4270,7 +4480,7 @@ function planIntroFor(command, mode, isDryRun) {
4270
4480
  if (command === "upgrade") {
4271
4481
  return `${prefix} 工具會檢查既有 Kit 檔案;能安全合併才合併,不能判斷時會停手並列為 conflict。`;
4272
4482
  }
4273
- return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具停手等你判斷。`;
4483
+ return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具零寫入停手並提供技術證據。`;
4274
4484
  }
4275
4485
 
4276
4486
  // R-026 CLI Output Contract: install/upgrade 完成必含四項(版本/模式/剛完成/下一步)。
@@ -4286,7 +4496,7 @@ function printInstallSummary(version, command, mode, root, counts) {
4286
4496
  console.log(`🛠️ 模式:${mode}`);
4287
4497
  console.log(`🔎 剛完成:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
4288
4498
  if (counts.conflicts > 0) {
4289
- console.log("🚀 下一步:把 migration report 或這段輸出貼給 AI,請它判斷衝突檔案怎樣處理;工具已停手,沒有覆寫 conflict 檔案。");
4499
+ console.log("🚀 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對正式來源及差異;一般使用者毋須裁決技術內容。工具已停手,沒有覆寫 conflict 檔案。");
4290
4500
  } else if (command === "upgrade") {
4291
4501
  console.log("🚀 下一步:留意下方 migration committed 與 project health 的分開結果。");
4292
4502
  } else if (counts.skipped > 0) {
@@ -4313,9 +4523,9 @@ function printDryRunExplanation(command, mode, plan) {
4313
4523
  console.log("✅ 沒有發現 conflict。請按你剛才預演的命令去掉 --dry-run 後正式執行。");
4314
4524
  return;
4315
4525
  }
4316
- console.log(`⚠️ 需要人工確認:有 ${conflicts.length} 個既有檔案,工具不能安全判斷怎樣合併。`);
4526
+ console.log(`⚠️ 技術核對未完成:有 ${conflicts.length} 個既有檔案,工具目前不能證明可安全合併。`);
4317
4527
  console.log("⚠️ 這不是檔案壞掉,也沒有覆寫你的檔案。");
4318
- console.log("📋 下一步:把這段輸出貼給 AI,叫它幫你判斷要保留、合併,還是手動修改。");
4528
+ console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI,由它核對正式來源及差異;一般使用者毋須閱讀或裁決檔案內容。");
4319
4529
  }
4320
4530
 
4321
4531
  async function confirmWrite() {
@@ -4487,9 +4697,9 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
4487
4697
  }
4488
4698
  console.log("============================================================");
4489
4699
  if (conflictCount > 0) {
4490
- console.log("⚠️ 狀態:有既有檔案需要人工確認,詳情見 migration report。");
4700
+ console.log("⚠️ 狀態:有既有檔案未能證明可安全合併。");
4491
4701
  console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
4492
- console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
4702
+ console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對來源與差異;一般使用者毋須判斷檔案內容。");
4493
4703
  console.log("");
4494
4704
  }
4495
4705
  if (skippedCount > 0) {
@@ -4528,11 +4738,11 @@ function printUpgradeNextSteps(root, conflictCount) {
4528
4738
  console.log("");
4529
4739
  console.log("============================================================");
4530
4740
  if (conflictCount > 0) {
4531
- console.log("⚠️ 升級未完成:有檔案需要人工確認");
4741
+ console.log("⚠️ 升級未完成:有檔案未能證明可安全合併");
4532
4742
  console.log("============================================================");
4533
- console.log("⚠️ 狀態:有既有檔案需要人工確認,詳情見 migration report。");
4743
+ console.log("⚠️ 狀態:工具已保守停手,沒有建立目前交易或覆寫檔案。");
4534
4744
  console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
4535
- console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
4745
+ console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對正式來源及差異;一般使用者毋須裁決技術內容。");
4536
4746
  console.log("============================================================");
4537
4747
  return;
4538
4748
  }