@adamchanadam/agent-handoff-kit 0.3.39 → 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/"));
@@ -56,6 +35,15 @@ const credentialLeakPatterns = [
56
35
  { pattern: /\bAKIA[A-Z0-9]{16}/, label: "AWS access key" },
57
36
  { pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key" }
58
37
  ];
38
+
39
+ // Exact v0.3.38 continuity quick-fix packs observed in real projects before the
40
+ // product migration shipped. They contain no project-specific state. Matching
41
+ // is whole-file and newline-normalized so an extra local edit still takes the
42
+ // conservative three-way merge/conflict path instead of being overwritten.
43
+ const knownV038ContinuityQuickFixHashes = new Map([
44
+ ["packs/onboarding.md", "5dc32d9e164604379eb60f7ea0a731a2accb3da945ac5f28654ac253add187cf"],
45
+ ["packs/integrations.md", "8110bfb1e09fb503463072909c06027de0b39850c22a4f4c208c5752cf380826"]
46
+ ]);
59
47
 
60
48
  const requiredAnchors = [
61
49
  {
@@ -362,12 +350,16 @@ const schemaChecks = [
362
350
  }
363
351
  ]
364
352
  },
365
- {
366
- target: "dev/SESSION_LOG.md",
367
- label: "session log entry fields",
368
- checks: [
369
- heading("Entry Template"),
370
- marker("section", "session-log-preamble", "Handoff role"),
353
+ {
354
+ target: "dev/SESSION_LOG.md",
355
+ label: "session log entry fields",
356
+ checks: [
357
+ heading("Entry Template"),
358
+ {
359
+ label: "SESSION_LOG has one trusted current entry-template boundary",
360
+ test: (text) => Boolean(sessionLogEntryTemplateContract(text))
361
+ },
362
+ marker("section", "session-log-preamble", "Handoff role"),
371
363
  marker("section", "session-log-entry-template", "Entry Template"),
372
364
  includes("ack:log-entry:start"),
373
365
  includes("ack:log-entry:end"),
@@ -612,6 +604,9 @@ async function needsProjectIndexVersionInject(root, command, version) {
612
604
  }
613
605
 
614
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 });
615
610
  if (options.dryRun) await assertDryRunHasNoPendingTransaction(root);
616
611
  else await recoverInterruptedTransaction(root);
617
612
  const installedVersion = await readInstalledTemplateVersion(root);
@@ -629,7 +624,9 @@ async function runInstall(command, root, options, version) {
629
624
  // Validate the operator-selected path before every exit path, including
630
625
  // dry-run, conflicts, and already-current no-op upgrades. Otherwise a
631
626
  // junction can be silently accepted whenever there is nothing to write.
632
- 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 });
633
630
 
634
631
  // R-031 v0.3.1+: plan-time upgrade no-op detection. When upgrade has zero
635
632
  // create/merge/conflict actions (skip-only), skip the full plan listing +
@@ -653,11 +650,12 @@ async function runInstall(command, root, options, version) {
653
650
 
654
651
  if (isUpgradeNoopAtPlanTime) {
655
652
  const noOpHealth = await assessUpgradeNoopHealth(root, version);
656
- printCard(version, "continuity ready", "o.o");
657
- console.log(`command: ${command}`);
658
- console.log(`current directory: ${process.cwd()}`);
659
- console.log(`selected root: ${root}`);
660
- 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}`);
661
659
  console.log("");
662
660
  console.log(`📋 計劃預覽:create 0 / merge 0 / skip ${planSkipCount} / conflict 0 — 沒有檔案需要建立或合併。`);
663
661
  if (options.dryRun) {
@@ -669,7 +667,30 @@ async function runInstall(command, root, options, version) {
669
667
  return;
670
668
  }
671
669
 
672
- 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);
673
694
 
674
695
  if (options.dryRun) {
675
696
  console.log("\ndry-run: no files written");
@@ -681,7 +702,7 @@ async function runInstall(command, root, options, version) {
681
702
  if (plan.some((item) => item.action === "conflict")) {
682
703
  console.log("");
683
704
  console.log("⛔ 升級預檢發現 conflict;治理目標檔、版本與 migration artifact 均沒有寫入。");
684
- console.log("📋 下一步:根據上方 conflict 資料作非破壞性合併;不要以舊版本資料列當作已完成。");
705
+ console.log("📋 下一步:由 Kit 開發者或可讀取檔案的 AI 核對來源、差異與安全合併路徑;一般使用者毋須判斷技術差異。不要把歷史 stage、舊報告或版本列當作目前交易。");
685
706
  process.exitCode = 1;
686
707
  return;
687
708
  }
@@ -694,7 +715,7 @@ async function runInstall(command, root, options, version) {
694
715
  }
695
716
  }
696
717
 
697
- await executeInstallTransaction(command, root, mode, plan, version);
718
+ await executeInstallTransaction(command, root, mode, plan, version, candidateOutputs);
698
719
  }
699
720
 
700
721
  async function readInstalledTemplateVersion(root) {
@@ -707,8 +728,8 @@ async function readInstalledTemplateVersion(root) {
707
728
  }
708
729
  }
709
730
 
710
- async function executeInstallTransaction(command, root, mode, plan, version) {
711
- 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);
712
733
  if (outputs.length === 0) {
713
734
  const health = await assessUpgradeNoopHealth(root, version);
714
735
  printUpgradeNoopShortCircuit(version, health);
@@ -716,12 +737,7 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
716
737
  return;
717
738
  }
718
739
 
719
- const credentialInputs = [];
720
- for (const relative of requiredTargets) {
721
- const buffer = await readOptionalBuffer(path.join(root, relative));
722
- if (buffer) credentialInputs.push({ relative, text: decodeUtf8(buffer, relative).text });
723
- }
724
- const credentialFindings = detectCredentialValues(credentialInputs);
740
+ const credentialFindings = await detectInstalledCredentialFindings(root);
725
741
  if (credentialFindings.length > 0) {
726
742
  console.log("⛔ 升級已停止:待備份的治理檔疑似含有 credential value。");
727
743
  console.log("機密值不會顯示或複製;請先移除並輪換機密,再重跑 upgrade。");
@@ -730,9 +746,14 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
730
746
  return;
731
747
  }
732
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 });
733
755
  const transaction = await prepareTransaction(root, command, version, outputs, mode, plan);
734
756
  try {
735
- await validateTransactionOverlay(root, outputs);
736
757
  transaction.journal.state = "committing";
737
758
  await writeSecureJson(transaction.journalPath, transaction.journal);
738
759
 
@@ -741,6 +762,11 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
741
762
  for (const entry of transaction.journal.entries) {
742
763
  const output = outputs.find((item) => item.targetRel === entry.targetRel);
743
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
+ }
744
770
  entry.committed = true;
745
771
  committedCount += 1;
746
772
  await writeSecureJson(transaction.journalPath, transaction.journal);
@@ -783,7 +809,7 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
783
809
  else console.log("⚠️ project health: needs attention; migration remains committed because the deterministic migration gate passed");
784
810
  }
785
811
  } catch (error) {
786
- 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;
787
813
  transaction.journal.state = "rollback-needed";
788
814
  transaction.journal.error = safeErrorLabel(error);
789
815
  await writeSecureJson(transaction.journalPath, transaction.journal).catch(() => {});
@@ -799,6 +825,15 @@ async function executeInstallTransaction(command, root, mode, plan, version) {
799
825
  }
800
826
  }
801
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
+
802
837
  async function buildTransactionOutputs(command, root, plan, version) {
803
838
  const byTarget = new Map();
804
839
  for (const item of plan) {
@@ -1018,31 +1053,140 @@ async function atomicReplaceFromBuffer(root, targetAbs, buffer, id) {
1018
1053
  await rename(tempPath, targetAbs);
1019
1054
  }
1020
1055
 
1021
- 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);
1022
1155
  const conflicts = [];
1023
- for (const entry of [...journal.entries].reverse()) {
1024
- if (!entry.committed) continue;
1025
- const targetAbs = path.join(root, entry.targetRel);
1026
- 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);
1027
1161
  const currentHash = current ? sha256(current) : null;
1028
- if (currentHash === entry.beforeHash) continue;
1029
- if (currentHash !== entry.afterHash) {
1030
- 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`);
1031
1165
  continue;
1032
1166
  }
1033
- if (entry.existed) {
1034
- const backup = await readFile(path.join(root, entry.backupRel));
1035
- await atomicReplaceFromBuffer(root, targetAbs, backup, `${journal.id}-rollback`);
1036
- } else {
1037
- await unlink(targetAbs);
1038
- }
1167
+ operations.push(item);
1168
+ }
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 };
1039
1175
  }
1040
- journal.state = conflicts.length === 0 ? "rolled-back" : "manual-recovery-required";
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";
1041
1185
  journal.committedVersion = null;
1042
1186
  journal.rollbackAt = new Date().toISOString();
1043
- journal.recoveryConflicts = conflicts;
1044
- await writeSecureJson(journalPath, journal).catch(() => {});
1045
- return { ok: conflicts.length === 0, conflicts };
1187
+ journal.recoveryConflicts = [];
1188
+ await writeSecureJson(journalPath, journal);
1189
+ return { ok: true, conflicts: [] };
1046
1190
  }
1047
1191
 
1048
1192
  async function recoverInterruptedTransaction(root) {
@@ -1054,6 +1198,10 @@ async function recoverInterruptedTransaction(root) {
1054
1198
  if (error?.code === "ENOENT") return;
1055
1199
  throw new Error("upgrade lock exists but is unreadable; no writes attempted");
1056
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
+ }
1057
1205
  if (lock.host === hostname() && processIsAlive(lock.pid)) throw new Error(`another upgrade process is active (pid ${lock.pid})`);
1058
1206
  if (lock.host && lock.host !== hostname()) throw new Error(`upgrade lock belongs to another host (${lock.host}); no automatic recovery attempted`);
1059
1207
  const journalPath = path.resolve(root, lock.journal ?? "");
@@ -1064,6 +1212,7 @@ async function recoverInterruptedTransaction(root) {
1064
1212
  } catch {
1065
1213
  throw new Error("incomplete upgrade lock has no readable journal; no automatic recovery attempted");
1066
1214
  }
1215
+ await validateRecoveryJournal(root, journal, journalPath, lock.id);
1067
1216
  if (journal.state === "committed") {
1068
1217
  if (!journal.committedVersion) journal.committedVersion = journal.attemptedVersion;
1069
1218
  const migrationDir = path.dirname(journalPath);
@@ -1077,7 +1226,7 @@ async function recoverInterruptedTransaction(root) {
1077
1226
  await unlinkIfExists(lockPath);
1078
1227
  return;
1079
1228
  }
1080
- const rollback = await rollbackTransaction(root, journal, journalPath);
1229
+ const rollback = await rollbackTransaction(root, journal, journalPath, lock.id);
1081
1230
  if (!rollback.ok) throw new Error(`interrupted upgrade has third-state edits: ${rollback.conflicts.join("; ")}`);
1082
1231
  await unlinkIfExists(lockPath);
1083
1232
  console.log("⚠️ recovered interrupted upgrade: transaction-owned changes were safely rolled back before planning this run");
@@ -1914,34 +2063,91 @@ function assessHandoffLifecycleConsistency(text) {
1914
2063
  }
1915
2064
 
1916
2065
  function handoffStateLines(text, markerId, headingTitle) {
1917
- return extractSectionText(text, markerId, headingTitle)
2066
+ const sectionText = markerId === "next-session-opening-message"
2067
+ ? (extractOpeningMessage(text) ?? "")
2068
+ : extractSectionText(text, markerId, headingTitle);
2069
+ return sectionText
1918
2070
  .replace(/```[\s\S]*?```/g, "")
1919
2071
  .split(/\r?\n/)
1920
2072
  .map((line) => line.replace(/^[-*\d.)\s]+/, "").trim())
1921
- .filter((line) => line.length > 3 && !line.startsWith("##") && !line.startsWith("<!--") && !/^(TBD|none|n\/a|未適用|無)$/i.test(line));
2073
+ .filter((line) => line.length > 3 && !line.startsWith("##") && !line.startsWith("<!--") && !/^(TBD|none|n\/a|未適用|無)$/i.test(line))
2074
+ .filter((line) => markerId !== "next-session-opening-message" || !isOwnedOpeningLifecycleBoilerplate(line));
2075
+ }
2076
+
2077
+ function isOwnedOpeningLifecycleBoilerplate(line) {
2078
+ return /^Resume the current objective\. If my message or the handoff already gives an executable task, begin its first safe action in this response\./i.test(line)
2079
+ || /^A fresh install only makes guidance available; it does not force onboarding\./i.test(line)
2080
+ || /^Load onboarding only when I explicitly ask for guidance or no executable objective remains after state reading\./i.test(line);
2081
+ }
2082
+
2083
+ function stripResolvedNegatedActionClauses(line) {
2084
+ return line.split(/(?<=[.;;。])\s*/).filter((clause) => {
2085
+ const negated = /\b(?:no|not|never|without|did not|has not|have not)\b/i.test(clause);
2086
+ const action = /\b(?:commit|push|tag|release|publish|deploy|deployment|sync|write|upgrade)\b/i.test(clause);
2087
+ return !(negated && action);
2088
+ }).join(" ");
1922
2089
  }
1923
2090
 
1924
- function lifecycleTopicTokens(line) {
1925
- const latin = (line.toLowerCase().match(/[a-z0-9][a-z0-9_-]{3,}/g) ?? [])
1926
- .filter((token) => !new Set(["completed", "complete", "passed", "verified", "pending", "blocked", "follow-up", "monitor-only", "reopened", "session", "current", "next", "work", "task", "with", "from", "that", "this", "handoff", "lifecycle", "migration", "regression", "agent"]).has(token));
1927
- const chineseRuns = line.match(/[\u3400-\u9fff]{2,}/g) ?? [];
1928
- const chinese = chineseRuns.flatMap((run) => Array.from({ length: Math.max(0, run.length - 1) }, (_, index) => run.slice(index, index + 2)));
1929
- return new Set([...latin, ...chinese]);
2091
+ const ignoredLifecycleEnglish = new Set([
2092
+ "completed", "complete", "finish", "finished", "continue", "incomplete", "passed", "verified", "pending", "blocked", "follow", "scope",
2093
+ "monitor", "only", "reopened", "recommended", "next", "step", "session", "current", "work", "task", "with",
2094
+ "from", "that", "this", "handoff", "lifecycle", "migration", "regression", "agent", "reason", "condition",
2095
+ "the", "and", "for", "into", "still", "remains"
2096
+ ]);
2097
+
2098
+ function lifecycleEnglishTokens(line, stripNegated = false) {
2099
+ const source = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
2100
+ return (source.toLowerCase().match(/[a-z0-9][a-z0-9_-]{2,}/g) ?? [])
2101
+ .filter((token) => !ignoredLifecycleEnglish.has(token));
2102
+ }
2103
+
2104
+ function lifecycleTopicWindows(line, stripNegated = false) {
2105
+ const source = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
2106
+ const englishTokens = lifecycleEnglishTokens(source);
2107
+ const english = Array.from({ length: Math.max(0, englishTokens.length - 2) }, (_, index) => englishTokens.slice(index, index + 3).join(" "));
2108
+ const chineseRuns = source.match(/[\u3400-\u9fff]{6,}/g) ?? [];
2109
+ const chinese = chineseRuns.flatMap((run) => Array.from({ length: Math.max(0, run.length - 5) }, (_, index) => run.slice(index, index + 6)));
2110
+ return new Set([...english, ...chinese]);
2111
+ }
2112
+
2113
+ function lifecycleShortChineseCore(line, stripNegated = false) {
2114
+ const rawSource = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
2115
+ const source = rawSource.split(/(?:\s+[—–-]\s*)?(?:reason|condition)\s*[::]|(?:原因|條件)\s*[::]/i)[0];
2116
+ const ignored = /(後續追蹤|只監察|尚未完成|已經完成|重新開啟|完成|已驗證|繼續|下一步|待辦|尚未|未完成|通過|風險|受阻|重開|監察|追蹤|修復|修補|修正)/g;
2117
+ const core = (source.match(/[\u3400-\u9fff]+/g) ?? []).join("").replace(ignored, "");
2118
+ return core.length >= 2 && core.length <= 5 ? core : null;
1930
2119
  }
1931
2120
 
1932
2121
  function lifecycleTopicsOverlap(left, right) {
1933
- const leftCompact = left.toLowerCase().replace(/[^a-z0-9\u3400-\u9fff]+/g, "");
1934
- const rightCompact = right.toLowerCase().replace(/[^a-z0-9\u3400-\u9fff]+/g, "");
1935
- if (leftCompact.length >= 8 && rightCompact.length >= 8 && (leftCompact.includes(rightCompact) || rightCompact.includes(leftCompact))) return true;
1936
- const leftTokens = lifecycleTopicTokens(left);
1937
- const common = [...lifecycleTopicTokens(right)].filter((token) => leftTokens.has(token));
1938
- return common.length >= 2;
2122
+ const leftWindows = lifecycleTopicWindows(left, true);
2123
+ if ([...lifecycleTopicWindows(right)].some((window) => leftWindows.has(window))) return true;
2124
+ const leftEnglish = lifecycleEnglishTokens(left, true);
2125
+ const rightEnglish = lifecycleEnglishTokens(right);
2126
+ if (leftEnglish.length === 2 && rightEnglish.length === 2 && leftEnglish.join(" ") === rightEnglish.join(" ")) return true;
2127
+ const leftChinese = lifecycleShortChineseCore(left, true);
2128
+ return Boolean(leftChinese && leftChinese === lifecycleShortChineseCore(right));
1939
2129
  }
1940
2130
 
1941
2131
  function isExplicitLifecycleReclassification(line) {
1942
- const category = /(monitor-only|follow-up scope|blocked|reopened|只監察|後續追蹤|受阻|重開)/i.test(line);
1943
- const condition = /(trigger|until|when|missing evidence|reason|條件|證據|原因|待.+(?:時|後))/i.test(line);
1944
- return category && condition;
2132
+ const normalized = line
2133
+ .replace(/^recommended next step\s*:\s*/i, "")
2134
+ .replace(/^[\s—–:-]+/, "")
2135
+ .trim();
2136
+ if (!/^(?:(?:monitor-only|follow-up scope|blocked|reopened)\b|只監察|後續追蹤|受阻|重開)/i.test(normalized)) return false;
2137
+ if (/\b(no condition|without condition|unconditional)\b|無條件|沒有條件/i.test(normalized)) return false;
2138
+
2139
+ const labelled = normalized.match(/(?:\bcondition|\btrigger|\bmissing evidence|條件|觸發條件|缺少證據|證據|原因|\breason)\s*[::-]\s*([^;;\n]+)/i);
2140
+ if (labelled) return isSubstantiveLifecycleCondition(labelled[1]);
2141
+ const temporal = normalized.match(/(?:\bwhen|\buntil|待)(?:\s+|:|:)([^;;\n]+)/i);
2142
+ return temporal ? isSubstantiveLifecycleCondition(temporal[1]) : false;
2143
+ }
2144
+
2145
+ function isSubstantiveLifecycleCondition(value) {
2146
+ const normalized = (value ?? "").trim().replace(/[.。]+$/, "");
2147
+ if (normalized.length < 4) return false;
2148
+ if (/^(TBD|todo|pending|unknown|unverified|none|n\/a|待定|待確認|未知|無)$/i.test(normalized)) return false;
2149
+ if (/\b(no condition|without condition|unconditional)\b|無條件|沒有條件/i.test(normalized)) return false;
2150
+ return true;
1945
2151
  }
1946
2152
 
1947
2153
  function findHandoffLifecycleContradictions(text) {
@@ -2151,13 +2357,19 @@ async function buildPlan(root, command, version = null) {
2151
2357
  const context = {
2152
2358
  currentVersion: version,
2153
2359
  rootTemplateVersion: command === "upgrade" ? await readRootTemplateVersion(root) : null,
2154
- migrationBaselines: new Map()
2360
+ officialCatalog: command === "upgrade" ? await loadOfficialOriginCatalog() : null,
2361
+ officialOrigins: new Map(),
2362
+ trustedBaselineVersion: null,
2363
+ historicalOfficialEvidence: false
2155
2364
  };
2156
- if (command === "upgrade" && context.rootTemplateVersion === "0.3.38") {
2157
- for (const relative of ["packs/integrations.md", "packs/onboarding.md", "packs/safety.md"]) {
2158
- const baseline = await readOptionalText(path.join(packageRoot, "bin", "migration-baselines", "v0.3.38", path.basename(relative)));
2159
- 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 }));
2160
2370
  }
2371
+ context.trustedBaselineVersion = selectTrustedOfficialBaseline(context);
2372
+ context.historicalOfficialEvidence = countHistoricalOfficialSignals(context) >= 2;
2161
2373
  }
2162
2374
  for (const [sourceRel, targetRel] of mappings) {
2163
2375
  const sourceAbs = path.join(packageRoot, sourceRel);
@@ -2183,8 +2395,53 @@ async function buildPlan(root, command, version = null) {
2183
2395
  ...(reason ? { reason } : {})
2184
2396
  });
2185
2397
  }
2186
- return plan;
2187
- }
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
+ }
2188
2445
 
2189
2446
  async function readRootTemplateVersion(root) {
2190
2447
  try {
@@ -2233,13 +2490,34 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2233
2490
  if (hasRequiredAnchor(targetRel, targetText)) {
2234
2491
  return { ...base, action: "skip", reason: "managed core clean and required anchors present" };
2235
2492
  }
2236
- return {
2237
- ...base,
2238
- action: "merge",
2239
- reason: "add managed core while preserving existing AGENTS.md content",
2240
- mergedText: mergeManagedBlock(targetText, sourceText)
2241
- };
2242
- }
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
+ }
2243
2521
  // R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
2244
2522
  // user-added rows. Missing maintainer rows are merged into the existing table
2245
2523
  // instead of replacing the whole file.
@@ -2293,21 +2571,33 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2293
2571
  return { ...base, action: "conflict", reason: "SESSION_LOG.md lacks a unique trusted entry-template boundary; migration stopped without replacing trace history" };
2294
2572
  }
2295
2573
  if (migratedLog !== targetText) {
2296
- return { ...base, action: "merge", reason: "update only the log preamble/template and remove Kit-shaped full prompt copies while preserving trace entries", mergedText: migratedLog };
2574
+ return { ...base, action: "merge", reason: "update only the trusted current log preamble/template while preserving every historical trace entry", mergedText: migratedLog };
2297
2575
  }
2298
2576
  return { ...base, action: "skip", reason: "SESSION_LOG.md trace/template boundary current" };
2299
2577
  }
2300
- if (command === "upgrade" && ["dev/rules/integrations.md", "dev/rules/onboarding.md", "dev/rules/safety.md"].includes(targetRel)) {
2301
- const baseline = context.migrationBaselines?.get(sourceRel);
2302
- if (baseline != null) {
2303
- const mergedPack = threeWayPreserveLocalChanges(baseline, targetText, sourceText);
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") {
2585
+ if (isKnownV038ContinuityQuickFix(sourceRel, targetText)) {
2586
+ return {
2587
+ ...base,
2588
+ action: "merge",
2589
+ reason: `replace the exact known v0.3.38 continuity quick-fix ${path.basename(targetRel)} with the current official pack`,
2590
+ mergedText: sourceText
2591
+ };
2592
+ }
2593
+ const mergedPack = threeWayPreserveLocalAppendix(baselineRecord.text, targetText, sourceText);
2304
2594
  if (!mergedPack) {
2305
- 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` };
2306
2596
  }
2307
2597
  if (mergedPack !== targetText) {
2308
- 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 };
2309
2599
  }
2310
- 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` };
2311
2601
  }
2312
2602
  }
2313
2603
  // Governance bridge v0.3.27+: add the triggered review workflow to the
@@ -2392,14 +2682,6 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2392
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" };
2393
2683
  }
2394
2684
  if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
2395
- if (looksLikeExpandedKitBridge(targetRel, targetText)) {
2396
- return {
2397
- ...base,
2398
- action: "merge",
2399
- reason: `${targetRel} appears to be an expanded Kit bridge; restore short bridge so AGENTS.md remains the single source of truth`,
2400
- mergedText: sourceText
2401
- };
2402
- }
2403
2685
  const bridgeFailure = bridgeTextFailure(targetRel, targetText);
2404
2686
  if (bridgeFailure) {
2405
2687
  return { ...base, action: "conflict", reason: `existing bridge is not an active one-hop route (${bridgeFailure})` };
@@ -2415,22 +2697,6 @@ function isUpgradeFromOlderTemplate(context) {
2415
2697
  && compareSemver(rootTemplateVersion, currentVersion) < 0;
2416
2698
  }
2417
2699
 
2418
- function looksLikeExpandedKitBridge(targetRel, text) {
2419
- if (text.includes("This file is a bridge only")) return false;
2420
- if (targetRel === "CLAUDE.md") {
2421
- return (text.includes("This file provides guidance to Claude Code") && text.includes("## Session Startup"))
2422
- || text.includes("## Architecture")
2423
- || text.includes("## CLI Commands")
2424
- || text.includes("Every non-trivial task follows");
2425
- }
2426
- if (targetRel === "GEMINI.md") {
2427
- return text.includes("## Architecture")
2428
- || text.includes("## CLI Commands")
2429
- || text.includes("Every non-trivial task follows");
2430
- }
2431
- return false;
2432
- }
2433
-
2434
2700
  function mergeOnboardingScenarioALabel(targetText) {
2435
2701
  let merged = targetText;
2436
2702
  merged = merged.replace(
@@ -2638,12 +2904,11 @@ function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
2638
2904
  return rule.placement ? rule.placement(snippet, text) : true;
2639
2905
  }
2640
2906
 
2641
- function sessionLogAnchorPlacement(snippet, text) {
2642
- if (snippet === "ack:section:session-log-preamble") return text.includes("ack:section:session-log-preamble");
2643
- if (snippet === "ack:section:session-log-entry-template") return text.includes("ack:section:session-log-entry-template");
2644
- if (snippet === "## Entry Template") return /^## Entry Template\s*$/m.test(text);
2645
- if (snippet === "ack:log-entry:start" || snippet === "ack:log-entry:end") {
2646
- return sessionLogEntryTemplateContains(text, snippet);
2907
+ function sessionLogAnchorPlacement(snippet, text) {
2908
+ if (snippet === "ack:section:session-log-preamble") return countText(text, "ack:section:session-log-preamble") === 1;
2909
+ if (snippet === "ack:section:session-log-entry-template" || snippet === "## Entry Template") return Boolean(sessionLogEntryTemplateContract(text));
2910
+ if (snippet === "ack:log-entry:start" || snippet === "ack:log-entry:end") {
2911
+ return sessionLogEntryTemplateContains(text, snippet);
2647
2912
  }
2648
2913
  const preamble = [
2649
2914
  "Record what actually happened in the session",
@@ -2663,11 +2928,10 @@ function sessionLogPreambleContains(text, snippet) {
2663
2928
  return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
2664
2929
  }
2665
2930
 
2666
- function sessionLogEntryTemplateContains(text, snippet) {
2667
- const markerIndex = text.indexOf("<!-- ack:section:session-log-entry-template -->");
2668
- if (markerIndex >= 0) return text.slice(markerIndex).includes(snippet);
2669
- return snippetAppearsAfterHeading(text, snippet, "## Entry Template");
2670
- }
2931
+ function sessionLogEntryTemplateContains(text, snippet) {
2932
+ const contract = sessionLogEntryTemplateContract(text);
2933
+ return Boolean(contract && contract.templateText.includes(snippet));
2934
+ }
2671
2935
 
2672
2936
  function handoffContinuityAnchorPlacement(snippet, text) {
2673
2937
  const suffixContinuityAnchors = [
@@ -2946,6 +3210,53 @@ function parseMarkdownH2Sections(text) {
2946
3210
  return sections;
2947
3211
  }
2948
3212
 
3213
+ function uniqueSessionLogEntryTemplateSection(text) {
3214
+ const matches = parseMarkdownH2Sections(text).filter((section) => section.title === "Entry Template");
3215
+ return matches.length === 1 ? matches[0] : null;
3216
+ }
3217
+
3218
+ function sessionLogTemplateFence(text, section) {
3219
+ if (!section) return null;
3220
+ const sectionText = text.slice(section.start, section.end);
3221
+ const matches = [...sectionText.matchAll(/^````markdown\s*\r?\n([\s\S]*?)\r?\n````\s*$/gm)];
3222
+ if (matches.length !== 1) return null;
3223
+ const match = matches[0];
3224
+ const templateOffset = match.index + match[0].indexOf(match[1]);
3225
+ return {
3226
+ start: section.start + match.index,
3227
+ end: section.start + match.index + match[0].length,
3228
+ templateStart: section.start + templateOffset,
3229
+ templateEnd: section.start + templateOffset + match[1].length,
3230
+ templateText: match[1]
3231
+ };
3232
+ }
3233
+
3234
+ function sessionLogEntryTemplateContract(text) {
3235
+ const section = uniqueSessionLogEntryTemplateSection(text);
3236
+ if (!section) return null;
3237
+ const sectionMarker = "<!-- ack:section:session-log-entry-template -->";
3238
+ if (countText(text, sectionMarker) !== 1) return null;
3239
+ const markerIndex = text.indexOf(sectionMarker);
3240
+ if (markerIndex >= section.start || text.slice(markerIndex + sectionMarker.length, section.start).trim() !== "") return null;
3241
+
3242
+ const fence = sessionLogTemplateFence(text, section);
3243
+ if (!fence) return null;
3244
+ const sectionText = text.slice(section.start, section.end);
3245
+ const startMarker = "<!-- ack:log-entry:start -->";
3246
+ const endMarker = "<!-- ack:log-entry:end -->";
3247
+ if (countText(sectionText, startMarker) !== 1 || countText(sectionText, endMarker) !== 1) return null;
3248
+ if (countText(fence.templateText, startMarker) !== 1 || countText(fence.templateText, endMarker) !== 1) return null;
3249
+ const relativeStart = fence.templateText.indexOf(startMarker);
3250
+ const relativeEnd = fence.templateText.indexOf(endMarker);
3251
+ if (relativeStart >= relativeEnd) return null;
3252
+ return {
3253
+ ...section,
3254
+ ...fence,
3255
+ entryStart: fence.templateStart + relativeStart,
3256
+ entryEnd: fence.templateStart + relativeEnd + endMarker.length
3257
+ };
3258
+ }
3259
+
2949
3260
  function lcsLinePairs(left, right) {
2950
3261
  const rows = left.length + 1;
2951
3262
  const cols = right.length + 1;
@@ -3029,6 +3340,31 @@ function threeWayPreserveLocalChanges(baseText, localText, currentText) {
3029
3340
  return `${merged.join(newline)}${localHadFinalNewline || baseHadFinalNewline ? newline : ""}`;
3030
3341
  }
3031
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
+
3362
+ function isKnownV038ContinuityQuickFix(sourceRel, text) {
3363
+ const expected = knownV038ContinuityQuickFixHashes.get(sourceRel);
3364
+ if (!expected) return false;
3365
+ return sha256(Buffer.from(text.replace(/\r\n/g, "\n"), "utf8")) === expected;
3366
+ }
3367
+
3032
3368
  function uniqueH2Section(text, title) {
3033
3369
  const matches = parseMarkdownH2Sections(text).filter((section) => section.title === title);
3034
3370
  return matches.length === 1 ? matches[0] : null;
@@ -3451,24 +3787,13 @@ function migrateSessionHandoff(targetText, sourceText, context = {}) {
3451
3787
  function migrateSessionLog(targetText, sourceText) {
3452
3788
  let merged = mergeSessionLogTemplateContract(targetText, sourceText);
3453
3789
  if (!merged) return null;
3454
- merged = mergeSessionLogEvidenceDispositionField(merged) ?? merged;
3790
+ merged = mergeSessionLogEvidenceDispositionField(merged);
3791
+ if (!merged) return null;
3455
3792
 
3456
- const startMarker = "<!-- ack:log-entry:start -->";
3457
- const endMarker = "<!-- ack:log-entry:end -->";
3458
- if (countText(merged, startMarker) !== 1 || countText(merged, endMarker) !== 1
3459
- || countText(sourceText, startMarker) !== 1 || countText(sourceText, endMarker) !== 1) return null;
3460
- const targetStart = merged.indexOf(startMarker);
3461
- const targetEnd = merged.indexOf(endMarker, targetStart) + endMarker.length;
3462
- const sourceStart = sourceText.indexOf(startMarker);
3463
- const sourceEnd = sourceText.indexOf(endMarker, sourceStart) + endMarker.length;
3464
- merged = `${merged.slice(0, targetStart)}${sourceText.slice(sourceStart, sourceEnd)}${merged.slice(targetEnd)}`;
3465
-
3466
- merged = merged.replace(/```(?:text)?\s*\r?\n([\s\S]*?)\r?\n```/g, (block, content) => {
3467
- const signatures = ["Work in ", "Read AGENTS.md", "SESSION_HANDOFF.md", "PROJECT_INDEX.md"];
3468
- return signatures.every((signature) => content.includes(signature))
3469
- ? "Opening-message mirror: migrated; full text omitted by design."
3470
- : block;
3471
- });
3793
+ const targetContract = sessionLogEntryTemplateContract(merged);
3794
+ const sourceContract = sessionLogEntryTemplateContract(sourceText);
3795
+ if (!targetContract || !sourceContract) return null;
3796
+ merged = `${merged.slice(0, targetContract.entryStart)}${sourceText.slice(sourceContract.entryStart, sourceContract.entryEnd)}${merged.slice(targetContract.entryEnd)}`;
3472
3797
  return merged;
3473
3798
  }
3474
3799
 
@@ -3572,17 +3897,22 @@ function ensureHandoffStateReconciliationRules(targetText) {
3572
3897
  return `${targetText.trimEnd()}\n\n${ruleBlock}`;
3573
3898
  }
3574
3899
 
3575
- function mergeSessionLogEvidenceDispositionField(targetText) {
3576
- if (targetText.includes("- **Evidence disposition:**")) return mergeSessionLogTemplateContract(targetText, null) ?? targetText;
3577
- const qcField = "- **QC:**";
3578
- if (!targetText.includes(qcField)) return null;
3579
- const withEvidence = targetText.replace(qcField, `${qcField}\n- **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>`);
3580
- return mergeSessionLogTemplateContract(withEvidence, null) ?? withEvidence;
3581
- }
3582
-
3583
- function mergeSessionLogTemplateContract(targetText, sourceText = null) {
3584
- let merged = targetText;
3585
- let changed = false;
3900
+ function mergeSessionLogEvidenceDispositionField(targetText) {
3901
+ const contract = sessionLogEntryTemplateContract(targetText);
3902
+ if (!contract) return null;
3903
+ if (contract.templateText.includes("- **Evidence disposition:**")) return targetText;
3904
+ const qcField = "- **QC:**";
3905
+ if (countText(contract.templateText, qcField) !== 1) return null;
3906
+ const withEvidenceTemplate = contract.templateText.replace(qcField, `${qcField}\n- **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>`);
3907
+ return `${targetText.slice(0, contract.templateStart)}${withEvidenceTemplate}${targetText.slice(contract.templateEnd)}`;
3908
+ }
3909
+
3910
+ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
3911
+ let merged = targetText;
3912
+ let changed = false;
3913
+
3914
+ const initialSection = uniqueSessionLogEntryTemplateSection(merged);
3915
+ if (!initialSection) return null;
3586
3916
 
3587
3917
  if (!merged.includes("ack:section:session-log-preamble")) {
3588
3918
  const titleMatch = /^# Session Log\s*$/m.exec(merged);
@@ -3597,13 +3927,19 @@ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
3597
3927
  }
3598
3928
  }
3599
3929
 
3600
- if (!merged.includes("ack:section:session-log-entry-template")) {
3601
- const headingMatch = /^## Entry Template\s*$/m.exec(merged);
3602
- if (headingMatch) {
3603
- merged = `${merged.slice(0, headingMatch.index)}<!-- ack:section:session-log-entry-template -->\n\n${merged.slice(headingMatch.index)}`;
3604
- changed = true;
3605
- }
3606
- }
3930
+ const sectionMarker = "<!-- ack:section:session-log-entry-template -->";
3931
+ const sectionMarkerCount = countText(merged, sectionMarker);
3932
+ if (sectionMarkerCount > 1) return null;
3933
+ if (sectionMarkerCount === 0) {
3934
+ const currentSection = uniqueSessionLogEntryTemplateSection(merged);
3935
+ if (!currentSection) return null;
3936
+ merged = `${merged.slice(0, currentSection.start)}${sectionMarker}\n\n${merged.slice(currentSection.start)}`;
3937
+ changed = true;
3938
+ } else {
3939
+ const currentSection = uniqueSessionLogEntryTemplateSection(merged);
3940
+ const markerIndex = merged.indexOf(sectionMarker);
3941
+ if (!currentSection || markerIndex >= currentSection.start || merged.slice(markerIndex + sectionMarker.length, currentSection.start).trim() !== "") return null;
3942
+ }
3607
3943
 
3608
3944
  if (sourceText) {
3609
3945
  const restored = restoreMissingSessionLogPreambleLines(merged, sourceText);
@@ -3613,32 +3949,30 @@ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
3613
3949
  }
3614
3950
  }
3615
3951
 
3616
- const entryTemplateIndex = merged.search(/^## Entry Template\s*$/m);
3617
- if (entryTemplateIndex >= 0) {
3618
- const beforeTemplate = merged.slice(0, entryTemplateIndex);
3619
- let templateAndAfter = merged.slice(entryTemplateIndex);
3620
- if (!templateAndAfter.includes("ack:log-entry:start")) {
3621
- const replaced = templateAndAfter.replace(/````markdown(\r?\n)/, "````markdown$1<!-- ack:log-entry:start -->$1");
3622
- if (replaced !== templateAndAfter) {
3623
- templateAndAfter = replaced;
3624
- changed = true;
3625
- }
3626
- }
3627
- if (!templateAndAfter.includes("ack:log-entry:end")) {
3628
- const openingIndex = templateAndAfter.indexOf("````markdown");
3629
- const closingIndex = openingIndex >= 0
3630
- ? templateAndAfter.indexOf("\n````", openingIndex + "````markdown".length)
3631
- : -1;
3632
- if (closingIndex >= 0) {
3633
- templateAndAfter = `${templateAndAfter.slice(0, closingIndex)}\n<!-- ack:log-entry:end -->${templateAndAfter.slice(closingIndex)}`;
3634
- changed = true;
3635
- }
3636
- }
3637
- merged = `${beforeTemplate}${templateAndAfter}`;
3638
- }
3639
-
3640
- return changed ? merged : targetText;
3641
- }
3952
+ const section = uniqueSessionLogEntryTemplateSection(merged);
3953
+ const fence = sessionLogTemplateFence(merged, section);
3954
+ if (!section || !fence) return null;
3955
+ const startMarker = "<!-- ack:log-entry:start -->";
3956
+ const endMarker = "<!-- ack:log-entry:end -->";
3957
+ const sectionText = merged.slice(section.start, section.end);
3958
+ if (countText(sectionText, startMarker) > 1 || countText(sectionText, endMarker) > 1) return null;
3959
+ let templateText = fence.templateText;
3960
+ if (!templateText.includes(startMarker)) {
3961
+ templateText = `${startMarker}\n${templateText}`;
3962
+ changed = true;
3963
+ }
3964
+ if (!templateText.includes(endMarker)) {
3965
+ templateText = `${templateText.trimEnd()}\n${endMarker}`;
3966
+ changed = true;
3967
+ }
3968
+ if (templateText !== fence.templateText) {
3969
+ merged = `${merged.slice(0, fence.templateStart)}${templateText}${merged.slice(fence.templateEnd)}`;
3970
+ }
3971
+
3972
+ if (!sessionLogEntryTemplateContract(merged)) return null;
3973
+
3974
+ return changed ? merged : targetText;
3975
+ }
3642
3976
 
3643
3977
  function restoreMissingSessionLogPreambleLines(targetText, sourceText) {
3644
3978
  const sourceEntryIndex = sourceText.search(/^## Entry Template\s*$/m);
@@ -4114,12 +4448,15 @@ async function detectMode(root) {
4114
4448
  return "partial";
4115
4449
  }
4116
4450
 
4117
- function printPlan(command, root, mode, plan, version, isDryRun = false) {
4451
+ function printPlan(command, root, mode, plan, version, isDryRun = false, installedVersion = null) {
4118
4452
  printCard(version, "continuity ready", "o.o");
4119
4453
  console.log(`command: ${command}`);
4120
- console.log(`current directory: ${process.cwd()}`);
4121
- console.log(`selected root: ${root}`);
4122
- 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}`);
4123
4460
  console.log("");
4124
4461
  const planIntro = planIntroFor(command, mode, isDryRun);
4125
4462
  console.log(planIntro);
@@ -4143,7 +4480,7 @@ function planIntroFor(command, mode, isDryRun) {
4143
4480
  if (command === "upgrade") {
4144
4481
  return `${prefix} 工具會檢查既有 Kit 檔案;能安全合併才合併,不能判斷時會停手並列為 conflict。`;
4145
4482
  }
4146
- return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具停手等你判斷。`;
4483
+ return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具零寫入停手並提供技術證據。`;
4147
4484
  }
4148
4485
 
4149
4486
  // R-026 CLI Output Contract: install/upgrade 完成必含四項(版本/模式/剛完成/下一步)。
@@ -4159,7 +4496,7 @@ function printInstallSummary(version, command, mode, root, counts) {
4159
4496
  console.log(`🛠️ 模式:${mode}`);
4160
4497
  console.log(`🔎 剛完成:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
4161
4498
  if (counts.conflicts > 0) {
4162
- console.log("🚀 下一步:把 migration report 或這段輸出貼給 AI,請它判斷衝突檔案怎樣處理;工具已停手,沒有覆寫 conflict 檔案。");
4499
+ console.log("🚀 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對正式來源及差異;一般使用者毋須裁決技術內容。工具已停手,沒有覆寫 conflict 檔案。");
4163
4500
  } else if (command === "upgrade") {
4164
4501
  console.log("🚀 下一步:留意下方 migration committed 與 project health 的分開結果。");
4165
4502
  } else if (counts.skipped > 0) {
@@ -4186,9 +4523,9 @@ function printDryRunExplanation(command, mode, plan) {
4186
4523
  console.log("✅ 沒有發現 conflict。請按你剛才預演的命令去掉 --dry-run 後正式執行。");
4187
4524
  return;
4188
4525
  }
4189
- console.log(`⚠️ 需要人工確認:有 ${conflicts.length} 個既有檔案,工具不能安全判斷怎樣合併。`);
4526
+ console.log(`⚠️ 技術核對未完成:有 ${conflicts.length} 個既有檔案,工具目前不能證明可安全合併。`);
4190
4527
  console.log("⚠️ 這不是檔案壞掉,也沒有覆寫你的檔案。");
4191
- console.log("📋 下一步:把這段輸出貼給 AI,叫它幫你判斷要保留、合併,還是手動修改。");
4528
+ console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI,由它核對正式來源及差異;一般使用者毋須閱讀或裁決檔案內容。");
4192
4529
  }
4193
4530
 
4194
4531
  async function confirmWrite() {
@@ -4360,9 +4697,9 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
4360
4697
  }
4361
4698
  console.log("============================================================");
4362
4699
  if (conflictCount > 0) {
4363
- console.log("⚠️ 狀態:有既有檔案需要人工確認,詳情見 migration report。");
4700
+ console.log("⚠️ 狀態:有既有檔案未能證明可安全合併。");
4364
4701
  console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
4365
- console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
4702
+ console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對來源與差異;一般使用者毋須判斷檔案內容。");
4366
4703
  console.log("");
4367
4704
  }
4368
4705
  if (skippedCount > 0) {
@@ -4401,11 +4738,11 @@ function printUpgradeNextSteps(root, conflictCount) {
4401
4738
  console.log("");
4402
4739
  console.log("============================================================");
4403
4740
  if (conflictCount > 0) {
4404
- console.log("⚠️ 升級未完成:有檔案需要人工確認");
4741
+ console.log("⚠️ 升級未完成:有檔案未能證明可安全合併");
4405
4742
  console.log("============================================================");
4406
- console.log("⚠️ 狀態:有既有檔案需要人工確認,詳情見 migration report。");
4743
+ console.log("⚠️ 狀態:工具已保守停手,沒有建立目前交易或覆寫檔案。");
4407
4744
  console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
4408
- console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
4745
+ console.log("📋 下一步:把這段輸出交給 Kit 開發者或可讀取專案的 AI 核對正式來源及差異;一般使用者毋須裁決技術內容。");
4409
4746
  console.log("============================================================");
4410
4747
  return;
4411
4748
  }