@adamchanadam/agent-handoff-kit 0.4.0 → 0.4.2

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.
@@ -11,7 +11,9 @@ import path from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { assessPromptMirrorRoot, assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
13
13
  import { readHandoffChunk, formatHandoffChunk } from "./handoff-read.mjs";
14
- import { freshInstallMappings, installedFileContract, installedMappings, requiredInstalledTargets, upgradeStateMappings, upgradeStateTargets } from "./installed-file-contract.mjs";
14
+ import { freshInstallMappings, installedFileContract, installedMappings, requiredInstalledTargets, upgradeStateMappings, upgradeStateTargets, requiredShortcutTargets, SHORTCUT_INSTALL_CONTRACT } from "./installed-file-contract.mjs";
15
+ import { commands, commandFiles, planCommands, assertCommandPaths } from "./commands.mjs";
16
+ const legacyShortcutRecoveryPermit = Symbol("legacy shortcut recovery only");
15
17
  import { getArtifactBoundManagedSegment, getOfficialBaseline, identifyOfficialOrigin, loadOfficialOriginCatalog } from "./official-origin-catalog.mjs";
16
18
  import {
17
19
  markdownVisibleLinesOutsideHiddenBlocks,
@@ -560,17 +562,21 @@ const schemaChecks = [
560
562
  }
561
563
  ];
562
564
 
563
- main().catch((error) => {
564
- console.error(`agent-handoff-kit: ${error.message}`);
565
- process.exitCode = 1;
566
- });
565
+ // Importers can reuse the maintenance assessment without starting the CLI.
566
+ // Resolve the entry path so npm's symlink remains supported.
567
+ if (process.argv[1] && await realpath(process.argv[1]).catch(() => null) === fileURLToPath(import.meta.url)) {
568
+ main().catch((error) => {
569
+ console.error(`agent-handoff-kit: ${error.message}`);
570
+ process.exitCode = 1;
571
+ });
572
+ }
567
573
 
568
574
  async function main() {
569
575
  const { command, options } = parseArgs(process.argv.slice(2));
570
576
  const version = await readPackageVersion();
571
577
  // `doctor` renders version alignment itself. Let that single health run own
572
578
  // the lookup instead of checking once here and once again inside doctor.
573
- if (!new Set(["closeout-status", "doctor", "workspace-health", "progress", "commands", "handoff-read"]).has(command)) await maybePrintUpdateNotice(version);
579
+ if (!new Set(["closeout-status", "doctor", "workspace-health", "progress", "commands", "handoff-read", "update"]).has(command)) await maybePrintUpdateNotice(version);
574
580
  if (!command || options.help) {
575
581
  if (command === "handoff-read") {
576
582
  console.log("Usage: agent-handoff-kit handoff-read [--root <path>] [--max-chars <64..8192>] [--offset <n> --sha256 <digest>]\nRead-only, offline. Offsets count Unicode code points. Continue using nextOffset and the same sha256.\nContent served is not proof of reception, understanding or permission to act.");
@@ -595,6 +601,25 @@ async function main() {
595
601
  return;
596
602
  }
597
603
 
604
+ if (command === "update") {
605
+ assertCommandPaths(root);
606
+ await validateTransactionRoot(root, [], { createMissingRoot: false });
607
+ const installed = await readProjectIndexTemplateVersion(root);
608
+ if (!installed) throw new Error('Project version is unverified; check the existing Kit installation before updating. / 無法確認專案版本,未升級。');
609
+ const latest = await fetchLatestVersion();
610
+ if (!latest || !isStableSemver(latest)) throw new Error('npm latest could not be verified; no upgrade performed. / 未能確認 npm 最新版,未升級。');
611
+ console.log('Installed / 已安裝: ' + installed + '; npm latest / 最新版: ' + latest);
612
+ if (compareSemver(installed, latest) > 0) throw new Error('Project is newer than npm latest; refusing downgrade. / 專案版本較新,不會降級。');
613
+ if (version !== latest) throw new Error('Acquire the verified public CLI and retry: npx --yes @adamchanadam/agent-handoff-kit@' + latest + ' update --root <project-root> (quote the verified root as one argument in your active shell)');
614
+ if (installed === latest && !await exists(path.join(root, 'dev/governance_migrations/.upgrade.lock'))) {
615
+ console.log('Already current; checking installation without writing. / 已是最新版,唯讀核對安裝。');
616
+ await runDoctor(root, version);
617
+ return;
618
+ }
619
+ await runInstall('upgrade', root, { ...options, yes: true }, version);
620
+ return;
621
+ }
622
+
598
623
  if (command === "doctor") {
599
624
  await runDoctor(root, version);
600
625
  return;
@@ -610,7 +635,8 @@ async function main() {
610
635
  const result = installCommands({ root, agent: options.agent ?? "all", yes: options.yes, dryRun: options.dryRun });
611
636
  console.log("Agent Handoff Kit — Shortcuts / 快捷入口: " + result.status);
612
637
  for (const item of result.plan) console.log(item.action + " " + item.file);
613
- if (result.status === "conflict") { console.error("Existing command differs; no files written. Review the named conflict. / 同名入口有差異,未寫入任何檔案。"); process.exitCode = 1; }
638
+ if (result.status === "upgrade-required") { console.error('Official entries need a transactional update. Run upgrade --dry-run, then upgrade --yes. / 官方入口需要安全升級,請用 Kit 升級流程。'); process.exitCode = 1; }
639
+ else if (result.status === "conflict") { console.error("Existing command differs; no files written. Review the named conflict. / 同名入口有差異,未寫入任何檔案。"); process.exitCode = 1; }
614
640
  else if (result.status === "preview") console.log("Preview only. Add --yes to enable. / 只作預覽,加 --yes 才啟用。");
615
641
  else console.log("Ready. Reload your agent if needed. / 已啟用,必要時重新載入 AI。Claude / Gemini / Antigravity: /handoff-kit-help · Codex: $handoff-kit-help or /skills");
616
642
  return;
@@ -654,6 +680,11 @@ async function runCloseoutStatus(root, version) {
654
680
  const persistence = projectRequiredPersistence(fieldValueAfterMarker(handoffText, "project-required-persistence"));
655
681
  if (outcome !== "complete") findings.push("closeout outcome is not complete");
656
682
  if (!new Set(["complete", "not_required"]).has(persistence)) findings.push("project-required persistence is not complete or not required");
683
+ const declarations = assessCloseoutDeclarations(handoffText);
684
+ if (declarations.length > 0) {
685
+ findings.push("handoff reconciliation read-back is incomplete");
686
+ details.push(...declarations);
687
+ }
657
688
  const sufficiency = assessHandoffSufficiency(handoffText);
658
689
  if (sufficiency.length > 0) {
659
690
  findings.push("handoff sufficiency read-back is incomplete");
@@ -675,7 +706,7 @@ async function runCloseoutStatus(root, version) {
675
706
 
676
707
  // A closeout card needs a fresh local health readback, not a version-notice
677
708
  // network request. The caller has already completed the closeout workflow.
678
- const doctor = await assessUpgradeNoopHealth(root, version, { skipVersionRegistryLookup: true });
709
+ const doctor = await assessUpgradeNoopHealth(root, version, { skipVersionRegistryLookup: true, requireSessionLogMaintenance: true });
679
710
  if (!doctor.ok) {
680
711
  findings.push("fresh doctor read-back did not pass");
681
712
  details.push(...closeoutDoctorFailureDetails(doctor));
@@ -686,10 +717,10 @@ async function runCloseoutStatus(root, version) {
686
717
  if (!result.ok) process.exitCode = 1;
687
718
  }
688
719
 
689
- function assessHandoffSufficiency(text) {
720
+ function visibleHandoffLines(text) {
690
721
  // Only visible prose is a declaration. Preserve text outside inline comments,
691
722
  // but exclude fenced/indented examples and markers inside comments. This is
692
- // local to the sufficiency fields; no project source is opened by the check.
723
+ // shared by closeout field checks; no project source is opened by the parser.
693
724
  const original = text.replace(/\r\n/g, "\n").split("\n");
694
725
  const markerPattern = /^\s{0,3}<!-- (ack:(?:section|field):[\w-]+) -->\s*$/u;
695
726
  const visible = [];
@@ -726,6 +757,60 @@ function assessHandoffSufficiency(text) {
726
757
  if (opening && (opening[1][0] !== "`" || !opening[2].includes("`"))) { fence = opening[1]; continue; }
727
758
  visible.push({ text: prose.trim(), marker: null });
728
759
  }
760
+ return visible;
761
+ }
762
+
763
+ function assessCloseoutDeclarations(text) {
764
+ const visible = visibleHandoffLines(text);
765
+ const field = (id) => {
766
+ const indices = visible.map((line, index) => line.marker === `ack:field:${id}` ? index : -1).filter((index) => index >= 0);
767
+ if (indices.length !== 1) return "";
768
+ for (const line of visible.slice(indices[0] + 1)) {
769
+ if (line.marker || /^##\s/u.test(line.text)) break;
770
+ if (line.text) return line.text.match(/^[*-]\s+[^:]+:\s*(.*)$/u)?.[1] ?? "";
771
+ }
772
+ return "";
773
+ };
774
+ const findings = [];
775
+ if (!/^no(?:$|[\s,.;:—–-])/iu.test(field("stale-snapshots-left"))) {
776
+ findings.push("Handoff: stale snapshots must be reconciled; stale-snapshots-left must explicitly say no.");
777
+ }
778
+ for (const [id, label] of [["recommended-next-step-explicit", "recommended next step"], ["opening-message-matches-current-state", "opening message"]]) {
779
+ const value = field(id);
780
+ if (!isAffirmativeLifecycleFieldValue(value) || isUnresolvedLifecycleFieldValue(value)) {
781
+ findings.push(`Handoff: ${label} declaration is missing, negative or unverified; reconcile it before closeout.`);
782
+ }
783
+ }
784
+ const priorityContent = (line) => {
785
+ let value = (line || "").trim();
786
+ if (!value || /^#{1,6}(?:\s|$)/u.test(value) || /^(?:[-*_]\s*){3,}$/u.test(value)) return "";
787
+ value = value.replace(/^(?:(?:[-+*])|\d+[.)])\s+/u, "").replace(/^\[(?: |x|X)\]\s*/u, "");
788
+ let previous;
789
+ do {
790
+ previous = value;
791
+ value = value.replace(/^(\*{1,3}|_{1,3}|`{1,3})([\s\S]*?)\1$/u, "$2").trim();
792
+ } while (value && value !== previous);
793
+ return value;
794
+ };
795
+ const priorities = visibleHandoffLines(extractSectionText(text, "next-priorities", "Next Priorities"))
796
+ .map((line) => priorityContent(line.text))
797
+ .filter(Boolean);
798
+ const placeholder = (value) => /^<[^>]*>$/u.test(value)
799
+ || /^(?:TBD|todo|pending|unverified|unconfirmed|unknown|needs-review|no|blocked|uncertain|still unresolved|not resolved|not confirmed|待核對|待確認|待定|否|阻擋|不確定|(?:仍|尚)?未(?:解決|確認|核對|完成))[.!。]?$/iu.test(value);
800
+ // `Next Priorities` must be visible and usable, but its action/reason,
801
+ // decision, and blocker meaning are semantic closeout-pack review—not a
802
+ // machine-enforced English narrative grammar.
803
+ const knownUnfilledPriorityTemplate = /^Recommended next step:\s*TBD\s*—\s*reason:\s*TBD[.!。]?$/iu;
804
+ if (priorities.some((value) => knownUnfilledPriorityTemplate.test(value))) {
805
+ findings.push("Handoff: recommended next step is still an unfilled template; reconcile it before closeout.");
806
+ } else if (!priorities.some((value) => !placeholder(value))) {
807
+ findings.push("Handoff: Next Priorities must contain a visible, non-empty, non-placeholder statement; review its semantic adequacy under the closeout pack.");
808
+ }
809
+ return findings;
810
+ }
811
+
812
+ function assessHandoffSufficiency(text) {
813
+ const visible = visibleHandoffLines(text);
729
814
  const marked = (id) => visible.map((line, index) => line.marker === id ? index : -1).filter((index) => index >= 0);
730
815
  const indices = marked("ack:section:handoff-sufficiency-check");
731
816
  if (indices.length !== 1) return ["Handoff: require one active handoff-sufficiency-check section."];
@@ -786,6 +871,9 @@ function closeoutDoctorFailureDetails(doctor) {
786
871
  };
787
872
 
788
873
  add("Doctor: ", lines.find((line) => /^status:\s*failed\b/iu.test(line)));
874
+ for (const line of lines.filter((line) => /^\s*warn: (?:SESSION_LOG|dev\/SESSION_LOG\.md)/u.test(line))) {
875
+ add("Doctor maintenance: ", line.trim());
876
+ }
789
877
  const firstProblemIndex = lines.findIndex((line) => /^(missing|warn|failed)\s{2,}\S/iu.test(line.trim()));
790
878
  if (firstProblemIndex >= 0) {
791
879
  add("Doctor first problem: ", lines[firstProblemIndex].trim());
@@ -1154,7 +1242,13 @@ function workspaceValueMeansNoGit(value) {
1154
1242
 
1155
1243
  function workspaceRootMeansNoGit(value) {
1156
1244
  // Absence labels apply to the repository root, never to a branch/commit name.
1157
- return /^\s*(?:none|not_applicable|n\/a)(?:$|\s*[;(—–])/iu.test(value ?? "") || workspaceValueMeansNoGit(value);
1245
+ return /^\s*(?:none|not[ _]applicable|n\/a)(?:$|\s*[;(—–])/iu.test(value ?? "") || workspaceValueMeansNoGit(value);
1246
+ }
1247
+
1248
+ function workspaceValueIsNaturalNotApplicable(value) {
1249
+ // Git branch names cannot contain spaces. This spelling is therefore an
1250
+ // absence label in a known non-Git workspace, not Git identity.
1251
+ return /^\s*not[ _]applicable(?:$|\s*[;(—–])/iu.test(value ?? "");
1158
1252
  }
1159
1253
 
1160
1254
  function workspaceSectionClaimsNoGit(section) {
@@ -1169,7 +1263,9 @@ function workspaceSectionClaimsGitRepository(section) {
1169
1263
  workspaceFieldValue(section, "Commit")
1170
1264
  ];
1171
1265
  return (hasSubstantiveWorkspaceValue(gitRoot) && !workspaceRootMeansNoGit(gitRoot))
1172
- || values.some((value) => hasSubstantiveWorkspaceValue(value) && !workspaceValueMeansNoGit(value));
1266
+ || values.some((value) => hasSubstantiveWorkspaceValue(value)
1267
+ && !workspaceValueMeansNoGit(value)
1268
+ && !workspaceValueIsNaturalNotApplicable(value));
1173
1269
  }
1174
1270
 
1175
1271
  function workspaceSectionClaimsVerifiedState(section) {
@@ -1280,6 +1376,7 @@ async function needsProjectIndexVersionInject(root, command, version) {
1280
1376
  }
1281
1377
 
1282
1378
  async function runInstall(command, root, options, version) {
1379
+ assertCommandPaths(root); // Before recovery: recovery itself can write.
1283
1380
  // Guard the selected root before reading or recovering any persisted
1284
1381
  // transaction. Recovery is a write path and must not run through a junction.
1285
1382
  await validateTransactionRoot(root, [], { createMissingRoot: false });
@@ -1572,7 +1669,9 @@ async function executeDirectNoClobberCreateInstall(command, root, mode, plan, ve
1572
1669
  }
1573
1670
 
1574
1671
  for (const output of outputs) {
1672
+ await validateTransactionRoot(root, plan, { createMissingRoot: false });
1575
1673
  await mkdir(path.dirname(output.targetAbs), { recursive: true });
1674
+ assertCommandPaths(root);
1576
1675
  await writeFile(output.targetAbs, output.after, { mode: 0o600, flag: "wx" });
1577
1676
  const written = await readOptionalBuffer(output.targetAbs);
1578
1677
  if (!written || sha256(written) !== output.afterHash) {
@@ -1717,6 +1816,7 @@ async function buildTransactionOutputs(command, root, plan, version, options = {
1717
1816
  for (const item of plan) {
1718
1817
  if (item.action !== "create" && item.action !== "merge" && item.action !== "preserve") continue;
1719
1818
  const before = await readOptionalBuffer(item.targetAbs);
1819
+ if (item.generatedText != null && item.action === "create" && before) throw new Error(`${item.targetRel}: target appeared after shortcut planning; restart the read-only plan`);
1720
1820
  if (item.plannedInputHash && (!before || sha256(before) !== item.plannedInputHash)) {
1721
1821
  throw new Error(`${item.targetRel}: input changed after official-region proof; restart the read-only plan`);
1722
1822
  }
@@ -1737,7 +1837,7 @@ async function buildTransactionOutputs(command, root, plan, version, options = {
1737
1837
  after = Buffer.from(before);
1738
1838
  }
1739
1839
  } else if (item.action === "create") {
1740
- const sourceText = await readTemplateSource(command, item.sourceRel, item.targetRel, item.sourceAbs);
1840
+ const sourceText = item.generatedText ?? await readTemplateSource(command, item.sourceRel, item.targetRel, item.sourceAbs);
1741
1841
  afterText = item.targetRel === "AGENTS.md" ? mergeManagedBlock("", sourceText) : sourceText;
1742
1842
  } else if (item.action === "merge" && item.targetRel === "dev/PROJECT_INDEX.md" && item.metadataTransition === projectIndexTemplateVersionMetadataTransition) {
1743
1843
  if (!before) throw new Error(`${item.targetRel}: template-version metadata transition disappeared before preparation`);
@@ -1785,6 +1885,9 @@ async function buildTransactionOutputs(command, root, plan, version, options = {
1785
1885
  if (materializedText !== indexOutput.afterText) {
1786
1886
  indexOutput.after = Buffer.from(materializedText, "utf8");
1787
1887
  indexOutput.afterText = null;
1888
+ } else if (indexOutput.before && decodeUtf8(indexOutput.before, indexRel).text === materializedText) {
1889
+ indexOutput.after = Buffer.from(indexOutput.before);
1890
+ indexOutput.afterText = null; // Preserve mixed line endings when only shortcuts need repair.
1788
1891
  } else {
1789
1892
  indexOutput.afterText = materializedText;
1790
1893
  }
@@ -1976,6 +2079,7 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, a
1976
2079
  command,
1977
2080
  mode,
1978
2081
  attemptedVersion: version,
2082
+ shortcutInstallContract: SHORTCUT_INSTALL_CONTRACT,
1979
2083
  committedVersion: null,
1980
2084
  plannedSkips: plan.filter((item) => item.action === "skip").length,
1981
2085
  host: hostname(),
@@ -2269,6 +2373,7 @@ async function pathExists(filePath) {
2269
2373
  }
2270
2374
 
2271
2375
  async function validateTransactionRoot(root, plan, { createMissingRoot = true } = {}) {
2376
+ assertCommandPaths(root);
2272
2377
  let rootStats;
2273
2378
  try {
2274
2379
  rootStats = await lstat(root);
@@ -2316,6 +2421,7 @@ async function validateTransactionOverlay(root, outputs) {
2316
2421
  .map((item) => [item.targetRel, decodeUtf8(item.after, item.targetRel).text]));
2317
2422
  const finalText = async (relative) => outputMap.get(relative) ?? await readOptionalText(path.join(root, relative));
2318
2423
  const failures = [];
2424
+ for (const item of commandFiles()) if ((await finalText(item.file)) !== item.text) failures.push(`${item.file}: required shortcut missing or different after transaction`);
2319
2425
  for (const target of requiredTargets) if ((await finalText(target)) == null) failures.push(`${target}: missing after transaction`);
2320
2426
  for (const rule of requiredAnchors) {
2321
2427
  if (preservedRuntimeTargets.has(rule.target)) continue;
@@ -2386,6 +2492,7 @@ function bridgeTextFailure(targetRel, text) {
2386
2492
  }
2387
2493
 
2388
2494
  async function atomicReplaceFromBuffer(root, targetAbs, buffer, id, expectedHash, options = {}) {
2495
+ assertCommandPaths(root);
2389
2496
  const targetRel = options.targetRel ?? path.relative(root, targetAbs);
2390
2497
  const phase = options.phase ?? "forward";
2391
2498
  const escrowDir = options.escrowDir;
@@ -2537,6 +2644,7 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
2537
2644
  }
2538
2645
  if (!Array.isArray(journal.entries) || journal.entries.length === 0) throw new Error("upgrade journal has no valid entries; no recovery writes attempted");
2539
2646
  if (!isStableSemver(journal.attemptedVersion ?? "")) throw new Error("upgrade journal attempted version is invalid; no recovery writes attempted");
2647
+ if (journal.shortcutInstallContract !== undefined && journal.shortcutInstallContract !== SHORTCUT_INSTALL_CONTRACT) throw new Error("unknown shortcut install contract; no recovery writes attempted");
2540
2648
  const allowedStates = new Set(["prepared", "committing", "rollback-needed", "manual-recovery-required", "committed", "rolled-back"]);
2541
2649
  if (!allowedStates.has(journal.state)) throw new Error("upgrade journal state is invalid; no recovery writes attempted");
2542
2650
 
@@ -2594,6 +2702,7 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
2594
2702
  if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new Error("upgrade journal entry schema is invalid; no recovery writes attempted");
2595
2703
  const allowedTarget = requiredTargets.includes(entry.targetRel)
2596
2704
  || upgradeStateTargets.includes(entry.targetRel)
2705
+ || (journal.shortcutInstallContract === SHORTCUT_INSTALL_CONTRACT && requiredShortcutTargets.includes(entry.targetRel))
2597
2706
  || formalWitness?.contentPaths.has(entry.targetRel);
2598
2707
  if (!allowedTarget || seen.has(entry.targetRel)) throw new Error("upgrade journal target is unknown or duplicated; no recovery writes attempted");
2599
2708
  seen.add(entry.targetRel);
@@ -2837,6 +2946,7 @@ async function recoverInterruptedTransaction(root, options = {}) {
2837
2946
  const doctorStatus = await runDoctor(root, journal.committedVersion, {
2838
2947
  silentCard: true,
2839
2948
  context: "recovered-committed-transaction-health",
2949
+ legacyShortcutRecovery: journal.shortcutInstallContract === undefined ? legacyShortcutRecoveryPermit : null,
2840
2950
  skipVersionRegistryLookup: true,
2841
2951
  allowActiveTransaction: true,
2842
2952
  captureFormalUserRules: (state) => { formalRuntimeState = state; }
@@ -3129,6 +3239,22 @@ async function runDoctor(root, version, options = {}) {
3129
3239
  return "failed";
3130
3240
  }
3131
3241
 
3242
+ if (options.legacyShortcutRecovery !== legacyShortcutRecoveryPermit) {
3243
+ let shortcutFailures;
3244
+ try { shortcutFailures = planCommands(root).filter(item => item.action !== "keep").map(item => item.file); }
3245
+ catch (error) { shortcutFailures = [safeErrorLabel(error)]; }
3246
+ console.log(`\nproject shortcut checks: 1 (${commands.length} entries / ${requiredShortcutTargets.length} files)`);
3247
+ console.log(shortcutFailures.length ? "missing or different project shortcuts" : "ok project shortcuts ready");
3248
+ rows.push({target: "project shortcuts", ok: shortcutFailures.length === 0});
3249
+ if (shortcutFailures.length) {
3250
+ for (const failure of shortcutFailures) console.log(' ' + failure);
3251
+ printDoctorSummary(version, root, "needs-fix", {checked: rows.length, failedKind: "project shortcuts", failedCount: shortcutFailures.length,
3252
+ nextStep: "Kit 安裝未齊備。請執行 upgrade --dry-run;缺少的入口會一併補齊,同名差異需先處理。"});
3253
+ process.exitCode = 1;
3254
+ return "failed";
3255
+ }
3256
+ } else console.log("legacy transaction recovery: shortcut acceptance deferred to the current install plan");
3257
+
3132
3258
  const archiveCasing = await checkSessionLogArchiveCasing(root);
3133
3259
  console.log(`\nSESSION_LOG archive casing checks: 1`);
3134
3260
  console.log(`${archiveCasing.ok ? "ok" : "missing"} dev/SESSION_LOG_archive canonical path`);
@@ -3286,13 +3412,24 @@ async function runDoctor(root, version, options = {}) {
3286
3412
  return "failed";
3287
3413
  }
3288
3414
 
3289
- // R-010 SESSION_LOG handoff-role discipline check (warn-only; does not change mode or exit).
3415
+ // R-010 SESSION_LOG handoff-role discipline is advisory during ordinary
3416
+ // doctor use, but its existing maintenance triggers must be cleared at closeout.
3290
3417
  const disciplineResult = await assessSessionLogDiscipline(root);
3291
3418
  console.log(`\nSESSION_LOG 接力角色紀律: ${disciplineResult.ok ? "ok" : "warn"}`);
3292
3419
  if (!disciplineResult.ok) {
3293
3420
  for (const warning of disciplineResult.warnings) {
3294
3421
  console.log(` warn: ${warning}`);
3295
3422
  }
3423
+ if (options.requireSessionLogMaintenance) {
3424
+ printDoctorSummary(version, root, "needs-fix", {
3425
+ checked: rows.length + historicalReceiptChecks + anchorRows.length + schemaRows.length + userRulesResult.checked + researchTraceResult.checked + temperatureResult.checked + mirrorRows.length + 1,
3426
+ failedKind: "SESSION_LOG maintenance checks",
3427
+ failedCount: disciplineResult.warnings.length,
3428
+ nextStep: "先依 closeout pack 完成 SESSION_LOG 維護及歸檔讀回,再重跑 closeout-status;未完成維護不能宣告收工完成。"
3429
+ });
3430
+ process.exitCode = 1;
3431
+ return "failed";
3432
+ }
3296
3433
  }
3297
3434
 
3298
3435
  // R-030 v0.3.0+: credential leak prevention sweep over governance files.
@@ -3725,7 +3862,7 @@ function printDoctorSummary(version, root, mode, details) {
3725
3862
  }
3726
3863
  } else {
3727
3864
  console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
3728
- console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "formal user-rules checks" ? "AGENTS.md 與 dev/USER_RULES.md 的接受見證不一致。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : "下次開工提示副本與 handoff 真源不同。"}`);
3865
+ console.log(`⚠️ 檢查未通過:${doctorFailureExplanation(details.failedKind)}`);
3729
3866
  }
3730
3867
  console.log("");
3731
3868
  console.log(`📦 版本:v${version}`);
@@ -3734,6 +3871,24 @@ function printDoctorSummary(version, root, mode, details) {
3734
3871
  console.log(`🚀 下一步:${details.nextStep}`);
3735
3872
  }
3736
3873
 
3874
+ export function doctorFailureExplanation(kind) {
3875
+ const explanations = {
3876
+ "missing files": "有必要檔案不存在。",
3877
+ "project shortcuts": "專案快捷入口缺少或內容不一致。",
3878
+ "SESSION_LOG archive casing checks": "SESSION_LOG 歸檔目錄的大小寫或位置不符合規定。",
3879
+ "formal user-rules checks": "AGENTS.md 與 dev/USER_RULES.md 的接受見證不一致。",
3880
+ "anchor checks": "有檔案存在,但內容缺少必要段落。",
3881
+ "schema checks": "交接或索引文件結構不完整。",
3882
+ "bridge checks": "CLAUDE.md / GEMINI.md 未正確連到 AGENTS.md。",
3883
+ "research decision trace checks": "研究導向決策缺少可追溯來源鏈。",
3884
+ "handoff temperature boundary checks": "當前交接內容混入一次性或歷史證據。",
3885
+ "prompt mirror checks": "下次開工提示副本與 handoff 真源不同。",
3886
+ "SESSION_LOG maintenance checks": "SESSION_LOG 維護尚未完成。",
3887
+ "credential leak": "治理檔案出現疑似機密值;請依上列位置處理。"
3888
+ };
3889
+ return Object.hasOwn(explanations, kind) ? explanations[kind] : "檢查未通過;請依上列失敗種類、明細與下一步處理。";
3890
+ }
3891
+
3737
3892
  function formalUserRulesRepairNextStep(finding) {
3738
3893
  const reason = String(finding ?? "");
3739
3894
  if (reason.includes("AGENTS.md managed core does not match")) {
@@ -3984,19 +4139,19 @@ function compactLifecycleDiagnosticLine(line) {
3984
4139
 
3985
4140
  function isAffirmativeLifecycleFieldValue(value) {
3986
4141
  const trimmed = (value || "").trim();
3987
- return /^(yes|resolved|confirmed|complete|completed|ok|passed|all clear)\b|^(是|已|完成|已完成|已解決|已核對|已確認|通過)\b/i.test(trimmed);
4142
+ return /^(yes|resolved|confirmed|complete|completed|ok|passed|all clear)\b|^(?:是|完成|已完成|已解決|已核對|已確認|通過)(?=$|[\s,。;:、,.!:;—–-])/iu.test(trimmed);
3988
4143
  }
3989
4144
 
3990
4145
  function isUnresolvedLifecycleFieldValue(value) {
3991
4146
  const trimmed = normalizeLifecycleFieldValue(value);
3992
- return /^(no|blocked|uncertain)\b|^(否|阻擋|不確定)\b/i.test(trimmed)
3993
- || /\b(still unresolved|not resolved)\b|仍未解決|尚未解決/i.test(trimmed);
4147
+ return /^(no|blocked|uncertain)\b|^(?:否|阻擋|不確定|未確認|未核對|未完成)/iu.test(trimmed)
4148
+ || /\b(still unresolved|not resolved|not confirmed|unverified)\b|(?:仍|尚)?未(?:解決|確認|核對|完成)/iu.test(trimmed);
3994
4149
  }
3995
4150
 
3996
4151
  function isPlaceholderLifecycleFieldValue(value) {
3997
4152
  const trimmed = normalizeLifecycleFieldValue(value);
3998
4153
  return !trimmed
3999
- || /^(TBD|todo|pending|unverified|unknown|needs-review)\b|^(待核對|待確認|未核對|未確認)\b/i.test(trimmed);
4154
+ || /^(TBD|todo|pending|unverified|unknown|needs-review)\b|^(?:待核對|待確認|待定|未核對|未確認)/iu.test(trimmed);
4000
4155
  }
4001
4156
 
4002
4157
  function normalizeLifecycleFieldValue(value) {
@@ -4255,6 +4410,12 @@ async function buildPlan(root, command, version = null) {
4255
4410
  ...(reason ? { reason } : {})
4256
4411
  });
4257
4412
  }
4413
+ for (const item of planCommands(root)) plan.push({
4414
+ targetRel: item.file, targetAbs: item.target, generatedText: item.text,
4415
+ action: item.action === 'keep' ? 'skip' : item.action,
4416
+ ...(item.action === 'merge' ? { mergedText: item.text, plannedInputHash: item.plannedInputHash } : {}),
4417
+ reason: item.action === 'conflict' ? 'project shortcut differs; preserve it and resolve before installation' : item.action === 'merge' ? `verified official v${item.officialVersion} shortcut update` : 'required project shortcut'
4418
+ });
4258
4419
  return plan;
4259
4420
  }
4260
4421
 
@@ -4547,7 +4708,7 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
4547
4708
  return { ...base, action: "skip", reason: "SESSION_HANDOFF.md lifecycle and startup contracts current" };
4548
4709
  }
4549
4710
  if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade") {
4550
- const migratedLog = migrateSessionLog(targetText, sourceText);
4711
+ const migratedLog = migrateSessionLog(targetText, sourceText, context);
4551
4712
  if (!migratedLog) {
4552
4713
  return { ...base, action: "conflict", reason: "SESSION_LOG.md lacks a unique trusted entry-template boundary; migration stopped without replacing trace history" };
4553
4714
  }
@@ -5705,9 +5866,11 @@ function restoreMissingCurrentOpeningLines(targetPrompt, sourcePrompt) {
5705
5866
  return targetLines.join("\n");
5706
5867
  }
5707
5868
 
5708
- function migrateSessionLog(targetText, sourceText) {
5869
+ function migrateSessionLog(targetText, sourceText, context = {}) {
5709
5870
  let merged = mergeSessionLogTemplateContract(targetText, sourceText);
5710
5871
  if (!merged) return null;
5872
+ merged = replaceVerifiedOfficialSessionLogPreamble(merged, sourceText, context, targetText);
5873
+ if (!merged) return null;
5711
5874
  merged = mergeSessionLogEvidenceDispositionField(merged);
5712
5875
  if (!merged) return null;
5713
5876
 
@@ -5718,6 +5881,60 @@ function migrateSessionLog(targetText, sourceText) {
5718
5881
  return merged;
5719
5882
  }
5720
5883
 
5884
+ function sessionLogPreambleBounds(text) {
5885
+ const startMarker = "<!-- ack:section:session-log-preamble -->";
5886
+ const endMarker = "<!-- ack:section:session-log-entry-template -->";
5887
+ const start = text.indexOf(startMarker);
5888
+ if (start < 0 || text.indexOf(startMarker, start + startMarker.length) >= 0) return null;
5889
+ const templateStart = text.indexOf(endMarker, start + startMarker.length);
5890
+ if (templateStart < 0 || text.indexOf(endMarker, templateStart + endMarker.length) >= 0) return null;
5891
+ // Historical entries are allowed immediately before the template marker.
5892
+ // They are trace data, never part of the replaceable official preamble.
5893
+ const firstEntry = text.indexOf("<!-- ack:log-entry:start -->", start + startMarker.length);
5894
+ const end = firstEntry >= 0 && firstEntry < templateStart ? firstEntry : templateStart;
5895
+ return { start, end };
5896
+ }
5897
+
5898
+ function officialSessionLogPreambleBounds(text) {
5899
+ const currentBounds = sessionLogPreambleBounds(text);
5900
+ if (currentBounds) return { ...currentBounds, format: "marked" };
5901
+
5902
+ // The verified v0.1.0 catalog predates both SESSION_LOG boundary markers.
5903
+ // Its single legacy title/template boundary is only a candidate boundary;
5904
+ // callers still require exact equality with the trusted catalog baseline
5905
+ // before replacing project-owned content.
5906
+ const titles = [...text.matchAll(/^# Session Log\s*$/gm)];
5907
+ const templates = [...text.matchAll(/^## Entry Template\s*$/gm)];
5908
+ if (titles.length !== 1 || templates.length !== 1 || titles[0].index !== 0 || templates[0].index <= titles[0].index) return null;
5909
+ return { start: titles[0].index + titles[0][0].length, end: templates[0].index, format: "legacy" };
5910
+ }
5911
+
5912
+ function replaceVerifiedOfficialSessionLogPreamble(targetText, sourceText, context, originalTargetText = targetText) {
5913
+ const baselineVersion = context.trustedBaselineVersion;
5914
+ if (!baselineVersion || !context.officialCatalog) return targetText;
5915
+ const baseline = getOfficialBaseline({
5916
+ version: baselineVersion,
5917
+ targetRel: "dev/SESSION_LOG.md",
5918
+ catalog: context.officialCatalog
5919
+ });
5920
+ if (baseline?.state !== "present") return targetText;
5921
+
5922
+ const targetBounds = sessionLogPreambleBounds(targetText);
5923
+ const sourceBounds = sessionLogPreambleBounds(sourceText);
5924
+ const baselineBounds = officialSessionLogPreambleBounds(baseline.text);
5925
+ if (!targetBounds || !sourceBounds || !baselineBounds) return null;
5926
+
5927
+ const originalBounds = officialSessionLogPreambleBounds(originalTargetText);
5928
+ if (!originalBounds || originalBounds.format !== baselineBounds.format) return targetText;
5929
+
5930
+ const targetPreamble = originalTargetText.slice(originalBounds.start, originalBounds.end).replace(/\r\n?/g, "\n").trimEnd();
5931
+ const officialPreamble = baseline.text.slice(baselineBounds.start, baselineBounds.end).replace(/\r\n?/g, "\n").trimEnd();
5932
+ // Only the catalog's complete, verified historical preamble may be replaced.
5933
+ // A local line (even beside an otherwise old preamble) remains user content.
5934
+ if (targetPreamble !== officialPreamble) return targetText;
5935
+ return `${targetText.slice(0, targetBounds.start)}${sourceText.slice(sourceBounds.start, sourceBounds.end).trimEnd()}\n\n${targetText.slice(targetBounds.end)}`;
5936
+ }
5937
+
5721
5938
  function mergeHandoffLifecycleField(targetText) {
5722
5939
  const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
5723
5940
  if (!targetText.includes(openingMarker)) return null;
@@ -6184,8 +6401,8 @@ function printProjectAge(result) {
6184
6401
  // Thresholds (all warn-only; doctor exit unaffected):
6185
6402
  // - H2 entry count ≥ 11 → warn (archive boundary; AI closeout flow should auto-advance)
6186
6403
  // - H2 entry count ≥ 25 → warn (severe drift; suggest AI re-do closeout)
6187
- // - line count ≥ 1500 → warn (anomalous entry size; safety net)
6188
- async function assessSessionLogDiscipline(root) {
6404
+ // - line count > 1500 → warn (anomalous entry size; safety net)
6405
+ export async function assessSessionLogDiscipline(root) {
6189
6406
  const logPath = path.join(root, "dev/SESSION_LOG.md");
6190
6407
  let text = "";
6191
6408
  try {
@@ -6205,7 +6422,7 @@ async function assessSessionLogDiscipline(root) {
6205
6422
  warnings.push(`SESSION_LOG entry count = ${entryCount}(達 N=11+ archive 邊界;下次 closeout 時 AI 應自動執行 N 規則推進,如未動請提醒)`);
6206
6423
  }
6207
6424
 
6208
- if (lineCount >= 1500) {
6425
+ if (lineCount > 1500) {
6209
6426
  warnings.push(`SESSION_LOG line count = ${lineCount}(超過 1500 安全網閾值;可能 entry 異常長)`);
6210
6427
  }
6211
6428
 
@@ -6623,29 +6840,9 @@ function printCard(version, status, eyes) {
6623
6840
  function printInstallNextSteps(root, conflictCount, mode = "first-install", skippedCount = 0, options = {}) {
6624
6841
  console.log("");
6625
6842
  console.log("============================================================");
6626
- const needsPartialRepairStep = skippedCount > 0 && options.directCreateOnly !== true;
6627
- if (needsPartialRepairStep) {
6628
- console.log("⚠️ 已補齊缺少檔案,但仍要檢查入口連接");
6629
- } else {
6630
- console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
6631
- }
6843
+ console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
6844
+ console.log("✅ 專案快捷入口已就緒;進度頁可直接由 handoff-kit-progress 開啟。");
6632
6845
  console.log("============================================================");
6633
- if (conflictCount > 0) {
6634
- console.log("⚠️ 狀態:有既有檔案未能證明可安全合併。");
6635
- console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
6636
- console.log(conflictRepairNextStepLine());
6637
- console.log("");
6638
- }
6639
- if (needsPartialRepairStep) {
6640
- console.log("你原本已有部分 AI 記憶檔,工具已保留它們,沒有覆寫。");
6641
- console.log("下一步先不要開始新任務;請在終端機執行以下預演,讓工具檢查能否安全補入口連接:");
6642
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run");
6643
- console.log("");
6644
- console.log("如預演顯示沒有 conflict,再執行:");
6645
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade");
6646
- console.log("============================================================");
6647
- return;
6648
- }
6649
6846
  console.log("------------------------------------------------------------");
6650
6847
  console.log("⚠️ 下面這句不是終端機指令。");
6651
6848
  console.log("📋 不用再留在終端機;請打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,新增對話後輸入:");
@@ -6681,6 +6878,7 @@ function printUpgradeNextSteps(root, conflictCount) {
6681
6878
  console.log("============================================================");
6682
6879
  return;
6683
6880
  }
6881
+ console.log("✅ 專案快捷入口已就緒;進度頁可直接由 handoff-kit-progress 開啟。");
6684
6882
  console.log("🛠️ Kit migration 已通過離線遷移驗收;已由正式 doctor 的同輪讀回確認提交與健康使用同一狀態");
6685
6883
  console.log("============================================================");
6686
6884
  console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
@@ -6709,7 +6907,8 @@ async function assessUpgradeNoopHealth(root, version, options = {}) {
6709
6907
  const status = await runDoctor(root, version, {
6710
6908
  silentCard: true,
6711
6909
  context: "upgrade-noop-health-check",
6712
- skipVersionRegistryLookup: options.skipVersionRegistryLookup === true
6910
+ skipVersionRegistryLookup: options.skipVersionRegistryLookup === true,
6911
+ requireSessionLogMaintenance: options.requireSessionLogMaintenance === true
6713
6912
  });
6714
6913
  const doctorExitCode = process.exitCode;
6715
6914
  return {
@@ -6787,6 +6986,7 @@ Usage:
6787
6986
 
6788
6987
  Commands:
6789
6988
  init Plan or install missing core files and rule packs.
6989
+ update Check npm latest; safely upgrade this project if newer.
6790
6990
  upgrade Preserve existing files; merge safe core updates or report conflicts.
6791
6991
  doctor Check required installed files.
6792
6992
  workspace-health Read live root / Git / worktree state without writing files.