@adamchanadam/agent-handoff-kit 0.3.12 → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,9 +2,10 @@
2
2
 
3
3
  import { createInterface } from "node:readline/promises";
4
4
  import { stdin as input, stdout as output } from "node:process";
5
- import { copyFile, mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
6
- import path from "node:path";
7
- import { fileURLToPath } from "node:url";
5
+ import { copyFile, mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import { assessPromptMirrorTexts } from "./prompt-mirror-core.mjs";
8
9
 
9
10
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
11
  const packageRoot = path.resolve(__dirname, "..");
@@ -71,20 +72,10 @@ const requiredAnchors = [
71
72
  "fenced `text` code block",
72
73
  "handoff saved",
73
74
  "📋 Next session: copy and paste the whole block below",
74
- "State Reconciliation Check",
75
- "handoff lifecycle consistency",
76
- "Do not append a new state snapshot",
77
- "START_NEXT_SESSION_PROMPT.txt"
78
- ]
79
- },
80
- {
81
- target: "START_NEXT_SESSION_PROMPT.txt",
82
- label: "next-session prompt convenience copy",
83
- snippets: [
84
- "Work in ",
85
- "Read in order:",
86
- "dev/PROJECT_INDEX.md",
87
- "If this root does not match the expected project root"
75
+ "State Reconciliation Check",
76
+ "handoff lifecycle consistency",
77
+ "Do not append a new state snapshot",
78
+ "START_NEXT_SESSION_PROMPT.txt"
88
79
  ]
89
80
  },
90
81
  {
@@ -102,12 +93,12 @@ const requiredAnchors = [
102
93
  "ack:section:workspace-identity",
103
94
  "ack:section:sync-status",
104
95
  "ack:section:next-task-required-reading",
105
- "ack:section:state-reconciliation-check",
106
- "ack:section:next-session-opening-message",
107
- "ack:field:lifecycle-conflicts-resolved",
108
- "📋 Next session: copy and paste the whole block below",
109
- "```text",
110
- "Read in order:",
96
+ "ack:section:state-reconciliation-check",
97
+ "ack:section:next-session-opening-message",
98
+ "ack:field:lifecycle-conflicts-resolved",
99
+ "📋 Next session: copy and paste the whole block below",
100
+ "```text",
101
+ "Read in order:",
111
102
  "dev/DOC_SYNC_REGISTRY.md"
112
103
  ]
113
104
  },
@@ -193,7 +184,7 @@ const requiredAnchors = [
193
184
  "明確 onboarding signal keywords",
194
185
  "5-step walk-through pattern",
195
186
  "Application Scenario Library",
196
- "Scenario A. 建構系統 / 工具 / 平台 / 網站或應用",
187
+ "Scenario A. 建構系統 / 工具 / 平台 / 網站或應用",
197
188
  "Scenario B. 整理研究資料",
198
189
  "Scenario C. 整理電腦檔案",
199
190
  "Scenario D. 學寫代碼",
@@ -249,11 +240,11 @@ const schemaChecks = [
249
240
  section("state-reconciliation-check", "State Reconciliation Check"),
250
241
  section("handoff-sufficiency-check", "Handoff Sufficiency Check"),
251
242
  section("next-session-opening-message", "Next Session Opening Message"),
252
- marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
253
- marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
254
- marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
255
- marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
256
- marker("field", "user-intent", "User intent:"),
243
+ marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
244
+ marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
245
+ marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
246
+ marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
247
+ marker("field", "user-intent", "User intent:"),
257
248
  marker("field", "task-essence", "Task essence:"),
258
249
  marker("field", "success-criteria", "Success criteria:")
259
250
  ]
@@ -266,22 +257,22 @@ const schemaChecks = [
266
257
  includes("```text"),
267
258
  includes("Work in "),
268
259
  includes("Read in order:"),
269
- includes("If this root does not match the expected project root")
270
- ]
271
- },
272
- {
273
- target: "dev/SESSION_HANDOFF.md",
274
- label: "handoff lifecycle consistency",
275
- checks: [
276
- {
277
- label: "completed work is not carried forward as unresolved next work",
278
- test: (text) => assessHandoffLifecycleConsistency(text).ok
279
- }
280
- ]
281
- },
282
- {
283
- target: "dev/SESSION_LOG.md",
284
- label: "session log entry fields",
260
+ includes("If this root does not match the expected project root")
261
+ ]
262
+ },
263
+ {
264
+ target: "dev/SESSION_HANDOFF.md",
265
+ label: "handoff lifecycle consistency",
266
+ checks: [
267
+ {
268
+ label: "completed work is not carried forward as unresolved next work",
269
+ test: (text) => assessHandoffLifecycleConsistency(text).ok
270
+ }
271
+ ]
272
+ },
273
+ {
274
+ target: "dev/SESSION_LOG.md",
275
+ label: "session log entry fields",
285
276
  checks: [
286
277
  heading("Entry Template"),
287
278
  includes("- **ID:**"),
@@ -490,22 +481,22 @@ async function runInstall(command, root, options, version) {
490
481
  && planConflictCount === 0
491
482
  && !projectIndexVersionNeedsInject;
492
483
 
493
- if (isUpgradeNoopAtPlanTime) {
494
- const noOpHealth = await assessUpgradeNoopHealth(root);
495
- printCard(version, "continuity ready", "o.o");
496
- console.log(`command: ${command}`);
497
- console.log(`current directory: ${process.cwd()}`);
498
- console.log(`selected root: ${root}`);
499
- console.log(`mode: ${mode}`);
484
+ if (isUpgradeNoopAtPlanTime) {
485
+ const noOpHealth = await assessUpgradeNoopHealth(root);
486
+ printCard(version, "continuity ready", "o.o");
487
+ console.log(`command: ${command}`);
488
+ console.log(`current directory: ${process.cwd()}`);
489
+ console.log(`selected root: ${root}`);
490
+ console.log(`mode: ${mode}`);
500
491
  console.log("");
501
492
  console.log(`📋 計劃預覽:create 0 / merge 0 / skip ${planSkipCount} / conflict 0 — 沒有檔案需要建立或合併。`);
502
493
  if (options.dryRun) {
503
- console.log("");
504
- console.log("dry-run: no files written");
505
- }
506
- printUpgradeNoopShortCircuit(version, noOpHealth);
507
- return;
508
- }
494
+ console.log("");
495
+ console.log("dry-run: no files written");
496
+ }
497
+ printUpgradeNoopShortCircuit(version, noOpHealth);
498
+ return;
499
+ }
509
500
 
510
501
  // R-031.3 v0.3.3+: For upgrade scenarios, capture pre-upgrade root template version
511
502
  // before the create/merge/inject loops mutate PROJECT_INDEX. This snapshot is later
@@ -524,14 +515,14 @@ async function runInstall(command, root, options, version) {
524
515
  }
525
516
  }
526
517
 
527
- printPlan(command, root, mode, plan, version, options.dryRun);
528
-
529
- if (options.dryRun) {
530
- console.log("\ndry-run: no files written");
531
- printDryRunExplanation(command, mode, plan);
532
- if (plan.some((item) => item.action === "conflict")) process.exitCode = 1;
533
- return;
534
- }
518
+ printPlan(command, root, mode, plan, version, options.dryRun);
519
+
520
+ if (options.dryRun) {
521
+ console.log("\ndry-run: no files written");
522
+ printDryRunExplanation(command, mode, plan);
523
+ if (plan.some((item) => item.action === "conflict")) process.exitCode = 1;
524
+ return;
525
+ }
535
526
 
536
527
  if (!options.yes) {
537
528
  const ok = await confirmWrite();
@@ -548,14 +539,14 @@ async function runInstall(command, root, options, version) {
548
539
  const migrationDir = path.join(root, "dev/governance_migrations", stamp);
549
540
  const backupDir = path.join(migrationDir, "backup");
550
541
 
551
- for (const item of plan) {
552
- if (item.action !== "create") continue;
553
- await mkdir(path.dirname(item.targetAbs), { recursive: true });
554
- await copyFile(item.sourceAbs, item.targetAbs);
555
- created.push(item.targetRel);
556
- }
557
-
558
- await hydrateInitialOpeningPrompt(root, created);
542
+ for (const item of plan) {
543
+ if (item.action !== "create") continue;
544
+ await mkdir(path.dirname(item.targetAbs), { recursive: true });
545
+ await copyFile(item.sourceAbs, item.targetAbs);
546
+ created.push(item.targetRel);
547
+ }
548
+
549
+ await hydrateInitialOpeningPrompt(root, created);
559
550
 
560
551
  for (const item of plan) {
561
552
  if (item.action !== "merge") continue;
@@ -632,30 +623,30 @@ async function runInstall(command, root, options, version) {
632
623
  // R-031.2 v0.3.2+: printUpgradeNextSteps async (awaits inline whatsnew print).
633
624
  // R-031.3 v0.3.3+: pass preUpgradeRootVersion so whatsnew narrative reflects the
634
625
  // actual user journey (v{pre-upgrade} → v{current}), not the post-inject state.
635
- if (command === "upgrade") {
636
- await printUpgradeNextSteps(root, conflicts.length, version, preUpgradeRootVersion);
637
- } else {
638
- printInstallNextSteps(root, conflicts.length, mode, skippedCount);
639
- }
626
+ if (command === "upgrade") {
627
+ await printUpgradeNextSteps(root, conflicts.length, version, preUpgradeRootVersion);
628
+ } else {
629
+ printInstallNextSteps(root, conflicts.length, mode, skippedCount);
630
+ }
640
631
 
641
632
  // R-024 upgrade.done self-check: after substantive upgrade writes, run doctor automatically.
642
633
  // The user must see whether the merged state actually reaches a clean health state.
643
634
  if (command === "upgrade" && conflicts.length === 0) {
644
635
  console.log("");
645
636
  console.log("------------------------------------------------------------");
646
- console.log("🩺 升級後自動檢查:正在檢查升級後的資料夾");
637
+ console.log("🩺 升級後自動檢查:正在檢查升級後的資料夾");
647
638
  console.log("------------------------------------------------------------");
648
- const doctorStatus = await runDoctor(root, version, { silentCard: true, context: "upgrade-self-check" });
649
- if (doctorStatus !== "passed") {
650
- console.log("");
651
- console.log("⚠️ 升級後自動檢查未通過;請看上方檢查輸出。");
652
- console.log("📋 下一步:把上面 doctor 輸出貼給 AI,請它先按提示修補後再宣稱 upgrade 完成。");
653
- process.exitCode = 1;
654
- } else {
655
- console.log("");
656
- console.log("✅ 升級驗收完成:doctor 已通過;可以繼續使用這個項目。");
657
- }
658
- }
639
+ const doctorStatus = await runDoctor(root, version, { silentCard: true, context: "upgrade-self-check" });
640
+ if (doctorStatus !== "passed") {
641
+ console.log("");
642
+ console.log("⚠️ 升級後自動檢查未通過;請看上方檢查輸出。");
643
+ console.log("📋 下一步:把上面 doctor 輸出貼給 AI,請它先按提示修補後再宣稱 upgrade 完成。");
644
+ process.exitCode = 1;
645
+ } else {
646
+ console.log("");
647
+ console.log("✅ 升級驗收完成:doctor 已通過;可以繼續使用這個項目。");
648
+ }
649
+ }
659
650
 
660
651
  if (conflicts.length > 0) process.exitCode = 1;
661
652
  }
@@ -674,17 +665,17 @@ async function runDoctor(root, version, options = {}) {
674
665
  console.log(`${row.ok ? "ok" : "missing"} ${row.target}`);
675
666
  }
676
667
 
677
- if (missing.length > 0) {
678
- printDoctorSummary(version, root, "needs-fix", {
679
- checked: rows.length,
680
- failedKind: "missing files",
681
- failedCount: missing.length,
682
- nextStep: missing.length === rows.length
683
- ? "這個資料夾未安裝 Kit。若這就是你的項目資料夾,請執行:npx --yes @adamchanadam/agent-handoff-kit@latest init"
684
- : "這個資料夾只裝了一部分 Kit 檔案。請先確認路徑;如路徑正確,執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run"
685
- });
686
- process.exitCode = 1;
687
- return "failed";
668
+ if (missing.length > 0) {
669
+ printDoctorSummary(version, root, "needs-fix", {
670
+ checked: rows.length,
671
+ failedKind: "missing files",
672
+ failedCount: missing.length,
673
+ nextStep: missing.length === rows.length
674
+ ? "這個資料夾未安裝 Kit。若這就是你的項目資料夾,請執行:npx --yes @adamchanadam/agent-handoff-kit@latest init"
675
+ : "這個資料夾只裝了一部分 Kit 檔案。請先確認路徑;如路徑正確,執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run"
676
+ });
677
+ process.exitCode = 1;
678
+ return "failed";
688
679
  }
689
680
 
690
681
  const anchorRows = await checkRequiredAnchors(root);
@@ -692,15 +683,19 @@ async function runDoctor(root, version, options = {}) {
692
683
  console.log(`\nrequired anchors: ${anchorRows.length}`);
693
684
  for (const row of anchorRows) {
694
685
  console.log(`${row.ok ? "ok" : "missing"} ${row.target} (${row.label})`);
686
+ if (!row.ok && row.missing && row.missing.length > 0) {
687
+ console.log(` missing anchor text: ${row.missing.map((snippet) => JSON.stringify(snippet)).join("; ")}`);
688
+ }
695
689
  }
696
690
 
697
691
  if (anchorFailures.length > 0) {
698
- printDoctorSummary(version, root, "needs-fix", {
699
- checked: rows.length + anchorRows.length,
700
- failedKind: "anchor checks",
701
- failedCount: anchorFailures.length,
702
- nextStep: "有入口檔存在,但缺少 Kit 需要的橋接段落。請執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run;不要手動覆寫既有檔案。"
703
- });
692
+ printAnchorRepairGuidance(anchorFailures, options.context);
693
+ printDoctorSummary(version, root, "needs-fix", {
694
+ checked: rows.length + anchorRows.length,
695
+ failedKind: "anchor checks",
696
+ failedCount: anchorFailures.length,
697
+ nextStep: anchorRepairNextStep(options.context)
698
+ });
704
699
  process.exitCode = 1;
705
700
  return "failed";
706
701
  }
@@ -726,25 +721,25 @@ async function runDoctor(root, version, options = {}) {
726
721
  return "failed";
727
722
  }
728
723
 
729
- const mirrorRows = await checkPromptMirror(root);
730
- const mirrorBlockingFailures = mirrorRows.filter((row) => !row.ok && row.reason !== "convenience copy differs from dev/SESSION_HANDOFF.md");
731
- const mirrorWarnings = mirrorRows.filter((row) => !row.ok && row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md");
732
- console.log(`\nprompt mirror checks: ${mirrorRows.length}`);
733
- for (const row of mirrorRows) {
734
- const status = row.ok ? "ok" : row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md" ? "warn" : "missing";
735
- console.log(`${status} ${row.target} (${row.label})`);
736
- if (!row.ok && row.reason) console.log(` reason: ${row.reason}`);
737
- }
738
-
739
- if (mirrorBlockingFailures.length > 0) {
740
- printDoctorSummary(version, root, "needs-fix", {
741
- checked: rows.length + anchorRows.length + schemaRows.length + mirrorRows.length,
742
- failedKind: "prompt mirror checks",
743
- failedCount: mirrorBlockingFailures.length,
744
- nextStep: "以 dev/SESSION_HANDOFF.md 的 Next Session Opening Message 為準,重生 START_NEXT_SESSION_PROMPT.txt。"
745
- });
746
- process.exitCode = 1;
747
- return "failed";
724
+ const mirrorRows = await checkPromptMirror(root);
725
+ const mirrorBlockingFailures = mirrorRows.filter((row) => !row.ok && row.reason !== "convenience copy differs from dev/SESSION_HANDOFF.md");
726
+ const mirrorWarnings = mirrorRows.filter((row) => !row.ok && row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md");
727
+ console.log(`\nprompt mirror checks: ${mirrorRows.length}`);
728
+ for (const row of mirrorRows) {
729
+ const status = row.ok ? "ok" : row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md" ? "warn" : "missing";
730
+ console.log(`${status} ${row.target} (${row.label})`);
731
+ if (!row.ok && row.reason) console.log(` reason: ${row.reason}`);
732
+ }
733
+
734
+ if (mirrorBlockingFailures.length > 0) {
735
+ printDoctorSummary(version, root, "needs-fix", {
736
+ checked: rows.length + anchorRows.length + schemaRows.length + mirrorRows.length,
737
+ failedKind: "prompt mirror checks",
738
+ failedCount: mirrorBlockingFailures.length,
739
+ nextStep: "以 dev/SESSION_HANDOFF.md 的 Next Session Opening Message 為準,重生 START_NEXT_SESSION_PROMPT.txt。"
740
+ });
741
+ process.exitCode = 1;
742
+ return "failed";
748
743
  }
749
744
 
750
745
  // R-010 SESSION_LOG handoff-role discipline check (warn-only; does not change mode or exit).
@@ -770,38 +765,38 @@ async function runDoctor(root, version, options = {}) {
770
765
  // suspect drift / curious about version / continuity awareness),唔等用戶 ask AI。
771
766
  console.log("");
772
767
  console.log("項目狀態速覽:");
773
- const versionAlignment = await assessVersionAlignment(root, version);
774
- printVersionAlignment(versionAlignment);
775
- const versionNextStep = getVersionAlignmentNextStep(versionAlignment);
776
- const lastCloseout = await assessLastCloseout(root);
777
- printLastCloseout(lastCloseout);
778
- const projectAge = await assessProjectAge(root);
779
- printProjectAge(projectAge);
780
- const onboardingNextStep = options.context === "upgrade-self-check" ? null : getFirstUseNextStep(root, lastCloseout);
781
- const promptMirrorNextStep = mirrorWarnings.length > 0
782
- ? "檢查已通過。START_NEXT_SESSION_PROMPT.txt 只是下次開工便利副本;session 進行中不用手動重生,收工 closeout 時 AI 會從 dev/SESSION_HANDOFF.md 重生。"
783
- : null;
784
-
785
- const overallHealthy = credentialResult.ok;
786
- printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
787
- checked: rows.length + anchorRows.length + schemaRows.length + mirrorRows.length + 2,
788
- failedKind: !credentialResult.ok ? "credential leak" : null,
789
- failedCount: !credentialResult.ok ? credentialResult.findings.length : 0,
790
- warningKind: mirrorWarnings.length > 0 ? "prompt mirror warning" : null,
791
- warningCount: mirrorWarnings.length,
792
- nextStep: !credentialResult.ok
793
- ? "立即從相關檔案 redact credential value + rotate 已泄露 token;credential 應該由 AI 工具自身 secure storage 管理,永不寫入 dev/* 任何檔。"
794
- : disciplineResult.ok
795
- ? versionNextStep ?? promptMirrorNextStep ?? onboardingNextStep ?? "檢查已通過。繼續使用你原本的 AI 開工方式;如剛完成一個任務,記得在 AI 對話輸入「收工」保存交接。"
796
- : "繼續使用;下次 closeout 時 AI 應自動執行 SESSION_LOG N 規則推進(見上面 warn 行)。如未動請要求 AI 重做 closeout。"
797
- });
798
- return overallHealthy ? "passed" : "failed";
799
- }
800
-
801
- function getFirstUseNextStep(root, lastCloseout) {
802
- if (lastCloseout.date) return null;
803
- return `檢查已通過。下一步不要再留在終端機;打開 Claude Code / Claude Cowork / OpenAI Codex / Google Antigravity,或任何能讀寫此資料夾的 AI 工具,貼上:Work in ${root}. I just installed agent-handoff-kit. Help me get started.`;
804
- }
768
+ const versionAlignment = await assessVersionAlignment(root, version);
769
+ printVersionAlignment(versionAlignment);
770
+ const versionNextStep = getVersionAlignmentNextStep(versionAlignment);
771
+ const lastCloseout = await assessLastCloseout(root);
772
+ printLastCloseout(lastCloseout);
773
+ const projectAge = await assessProjectAge(root);
774
+ printProjectAge(projectAge);
775
+ const onboardingNextStep = options.context === "upgrade-self-check" ? null : getFirstUseNextStep(root, lastCloseout);
776
+ const promptMirrorNextStep = mirrorWarnings.length > 0
777
+ ? "檢查已通過。START_NEXT_SESSION_PROMPT.txt 只是下次開工便利副本;session 進行中不用手動重生,收工 closeout 時 AI 會從 dev/SESSION_HANDOFF.md 重生。"
778
+ : null;
779
+
780
+ const overallHealthy = credentialResult.ok;
781
+ printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
782
+ checked: rows.length + anchorRows.length + schemaRows.length + mirrorRows.length + 2,
783
+ failedKind: !credentialResult.ok ? "credential leak" : null,
784
+ failedCount: !credentialResult.ok ? credentialResult.findings.length : 0,
785
+ warningKind: mirrorWarnings.length > 0 ? "prompt mirror warning" : null,
786
+ warningCount: mirrorWarnings.length,
787
+ nextStep: !credentialResult.ok
788
+ ? "立即從相關檔案 redact credential value + rotate 已泄露 token;credential 應該由 AI 工具自身 secure storage 管理,永不寫入 dev/* 任何檔。"
789
+ : disciplineResult.ok
790
+ ? versionNextStep ?? promptMirrorNextStep ?? onboardingNextStep ?? "檢查已通過。繼續使用你原本的 AI 開工方式;如剛完成一個任務,記得在 AI 對話輸入「收工」保存交接。"
791
+ : "繼續使用;下次 closeout 時 AI 應自動執行 SESSION_LOG N 規則推進(見上面 warn 行)。如未動請要求 AI 重做 closeout。"
792
+ });
793
+ return overallHealthy ? "passed" : "failed";
794
+ }
795
+
796
+ function getFirstUseNextStep(root, lastCloseout) {
797
+ if (lastCloseout.date) return null;
798
+ return `檢查已通過。下一步不要再留在終端機;打開 Claude Code / Claude Cowork / OpenAI Codex / Google Antigravity,或任何能讀寫此資料夾的 AI 工具,貼上:Work in ${root}. I just installed agent-handoff-kit. Help me get started.`;
799
+ }
805
800
 
806
801
  // R-030 v0.3.0+: Credential leak prevention sweep. Scans dev/PROJECT_INDEX.md,
807
802
  // dev/SESSION_HANDOFF.md, dev/SESSION_LOG.md for common credential prefix patterns.
@@ -848,43 +843,83 @@ async function checkInstalledIntegrationsCredentialLeak(root) {
848
843
  return { ok: findings.length === 0, findings };
849
844
  }
850
845
 
851
- // R-026 CLI Output Contract: doctor 完成必含四項(版本/模式/剛完成/下一步)。
852
- function printDoctorSummary(version, root, mode, details) {
853
- console.log("");
854
- if (mode === "healthy") {
855
- console.log("status: passed");
856
- if (details.warningCount > 0) {
857
- console.log("✅ 檢查通過:必要文件存在,基本結構完整。");
858
- console.log("⚠️ 提醒:下次開工提示便利副本目前落後於 handoff;這只需要在收工 closeout 時重生。");
859
- } else {
860
- console.log("✅ 檢查通過:必要文件存在,基本結構完整,下次開工提示副本已與 handoff 一致。");
861
- }
862
- } else {
863
- console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
864
- console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : "下次開工提示副本與 handoff 真源不同。"}`);
865
- }
866
- console.log("");
867
- console.log(`📦 版本:v${version}`);
868
- console.log(`🩺 模式:${mode}`);
869
- console.log(`🔎 剛完成:檢查 ${details.checked} 項;${mode === "healthy" ? (details.warningCount > 0 ? `0 項未通過;${details.warningCount} 項提醒(${details.warningKind})` : "全部通過") : `${details.failedCount} 項未通過(${details.failedKind})`}。`);
870
- console.log(`🚀 下一步:${details.nextStep}`);
871
- }
872
-
873
- async function hydrateInitialOpeningPrompt(root, created) {
874
- if (!created.includes("dev/SESSION_HANDOFF.md") && !created.includes("START_NEXT_SESSION_PROMPT.txt")) return;
875
- for (const rel of ["dev/SESSION_HANDOFF.md", "START_NEXT_SESSION_PROMPT.txt"]) {
876
- const filePath = path.join(root, rel);
877
- try {
878
- const text = await readFile(filePath, "utf8");
879
- if (!text.includes("<absolute project root>")) continue;
880
- await writeFile(filePath, text.replaceAll("<absolute project root>", root), "utf8");
881
- } catch {
882
- // Leave template untouched; doctor will warn about convenience-copy drift if any.
883
- }
884
- }
885
- }
846
+ // R-026 CLI Output Contract: doctor 完成必含四項(版本/模式/剛完成/下一步)。
847
+ function printDoctorSummary(version, root, mode, details) {
848
+ console.log("");
849
+ if (mode === "healthy") {
850
+ console.log("status: passed");
851
+ if (details.warningCount > 0) {
852
+ console.log("✅ 檢查通過:必要文件存在,基本結構完整。");
853
+ console.log("⚠️ 提醒:下次開工提示便利副本目前落後於 handoff;這只需要在收工 closeout 時重生。");
854
+ } else {
855
+ console.log("✅ 檢查通過:必要文件存在,基本結構完整,下次開工提示副本已與 handoff 一致。");
856
+ }
857
+ } else {
858
+ console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
859
+ console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : "下次開工提示副本與 handoff 真源不同。"}`);
860
+ }
861
+ console.log("");
862
+ console.log(`📦 版本:v${version}`);
863
+ console.log(`🩺 模式:${mode}`);
864
+ console.log(`🔎 剛完成:檢查 ${details.checked} 項;${mode === "healthy" ? (details.warningCount > 0 ? `0 項未通過;${details.warningCount} 項提醒(${details.warningKind})` : "全部通過") : `${details.failedCount} 項未通過(${details.failedKind})`}。`);
865
+ console.log(`🚀 下一步:${details.nextStep}`);
866
+ }
867
+
868
+ // Anchor failures mean a required file is missing fixed Kit text. The fix is a
869
+ // content repair the CLI deliberately does NOT perform itself: every anchor-checked
870
+ // file outside the bounded upgrade-merge set is preserved verbatim (R-016), so
871
+ // re-running upgrade would skip the same file again — the old "run upgrade --dry-run"
872
+ // next step was a dead end. Route the repair to the AI as a non-destructive patch,
873
+ // and give the novice an explicit, ordered walk-through.
874
+ function printAnchorRepairGuidance(anchorFailures, context) {
875
+ console.log("");
876
+ console.log("------------------------------------------------------------");
877
+ console.log("🔧 怎樣修這個「缺少段落」的問題(一步一步):");
878
+ console.log("------------------------------------------------------------");
879
+ if (context === "upgrade-self-check") {
880
+ console.log("⚠️ 升級本身已完成,也沒有覆寫你的檔案。剩下的是個別檔案缺少 Kit 需要的固定段落,需要補回。");
881
+ } else {
882
+ console.log("⚠️ 這不是檔案壞掉,工具也沒有覆寫你的檔案。只是有檔案缺少 Kit 需要的固定段落(多數因為該檔較舊或曾被改動)。");
883
+ }
884
+ console.log("缺段的檔案:");
885
+ for (const row of anchorFailures) {
886
+ console.log(` • ${row.target}(${row.label})`);
887
+ if (row.missing && row.missing.length > 0) {
888
+ for (const snippet of row.missing) console.log(` 缺:${JSON.stringify(snippet)}`);
889
+ }
890
+ }
891
+ console.log("");
892
+ console.log("步驟:");
893
+ console.log(" 1. 不要重跑 upgrade —— 這些是 upgrade 會「保留不動」的檔,重跑不會補回缺段。");
894
+ console.log(" 2. 複製上面整段 doctor 輸出。");
895
+ console.log(" 3. 打開你的 AI 工具(Claude Code / Claude Cowork / OpenAI Codex 等),貼上並說:");
896
+ console.log(" 「請按 doctor 指出的缺失 anchor,非破壞性補回對應檔案的段落,不要覆寫我其他內容。」");
897
+ console.log(" 4. AI 補完後,再執行:npx --yes @adamchanadam/agent-handoff-kit@latest doctor 確認轉綠。");
898
+ console.log("------------------------------------------------------------");
899
+ }
900
+
901
+ function anchorRepairNextStep(context) {
902
+ const lead = context === "upgrade-self-check"
903
+ ? "升級已完成且沒有覆寫你的檔;剩下的是內容缺段,需由 AI 補。"
904
+ : "有入口檔存在,但個別檔案缺少 Kit 需要的固定段落。";
905
+ return `${lead}按上面「怎樣修」步驟:把整段 doctor 輸出貼給 AI,請它非破壞性補回缺失 anchor,補完再執行 doctor 確認。不要重跑 upgrade(這些檔會被保留不動,重跑修不到)。`;
906
+ }
886
907
 
887
- async function checkPromptMirror(root) {
908
+ async function hydrateInitialOpeningPrompt(root, created) {
909
+ if (!created.includes("dev/SESSION_HANDOFF.md") && !created.includes("START_NEXT_SESSION_PROMPT.txt")) return;
910
+ for (const rel of ["dev/SESSION_HANDOFF.md", "START_NEXT_SESSION_PROMPT.txt"]) {
911
+ const filePath = path.join(root, rel);
912
+ try {
913
+ const text = await readFile(filePath, "utf8");
914
+ if (!text.includes("<absolute project root>")) continue;
915
+ await writeFile(filePath, text.replaceAll("<absolute project root>", root), "utf8");
916
+ } catch {
917
+ // Leave template untouched; doctor will warn about convenience-copy drift if any.
918
+ }
919
+ }
920
+ }
921
+
922
+ async function checkPromptMirror(root) {
888
923
  const handoffPath = path.join(root, "dev/SESSION_HANDOFF.md");
889
924
  const promptPath = path.join(root, "START_NEXT_SESSION_PROMPT.txt");
890
925
  let handoffText = "";
@@ -899,120 +934,110 @@ async function checkPromptMirror(root) {
899
934
  } catch {
900
935
  return [{ target: "START_NEXT_SESSION_PROMPT.txt", label: "matches handoff opening message", ok: false, reason: "prompt copy unreadable" }];
901
936
  }
902
- const openingMessage = extractOpeningMessage(handoffText);
903
- if (!openingMessage) {
904
- return [{ target: "START_NEXT_SESSION_PROMPT.txt", label: "matches handoff opening message", ok: false, reason: "handoff opening message missing" }];
937
+ const mirror = assessPromptMirrorTexts(handoffText, promptText);
938
+ return [{
939
+ target: "START_NEXT_SESSION_PROMPT.txt",
940
+ label: "matches handoff opening message",
941
+ ok: mirror.ok,
942
+ reason: mirror.ok ? "" : mirror.reason
943
+ }];
944
+ }
945
+
946
+ function assessHandoffLifecycleConsistency(text) {
947
+ const fieldValue = fieldValueAfterMarker(text, "lifecycle-conflicts-resolved");
948
+ if (isAffirmativeLifecycleFieldValue(fieldValue)) {
949
+ return { ok: true, reason: "" };
950
+ }
951
+ if (isUnresolvedLifecycleFieldValue(fieldValue)) {
952
+ return { ok: false, reason: "lifecycle field is explicitly unresolved" };
905
953
  }
906
- const ok = normalizePrompt(promptText) === normalizePrompt(openingMessage);
907
- return [{ target: "START_NEXT_SESSION_PROMPT.txt", label: "matches handoff opening message", ok, reason: ok ? "" : "convenience copy differs from dev/SESSION_HANDOFF.md" }];
954
+ if (isPlaceholderLifecycleFieldValue(fieldValue) && hasSubstantiveHandoffState(text)) {
955
+ return { ok: false, reason: "lifecycle field is still placeholder after handoff content changed" };
956
+ }
957
+ return { ok: true, reason: "" };
908
958
  }
909
959
 
910
- function extractOpeningMessage(text) {
911
- const marker = "📋 Next session: copy and paste the whole block below";
912
- const markerIndex = text.indexOf(marker);
913
- if (markerIndex < 0) return null;
914
- const fenceStart = text.indexOf("```text", markerIndex);
915
- if (fenceStart < 0) return null;
916
- const contentStart = text.indexOf("\n", fenceStart);
917
- const fenceEnd = text.indexOf("```", contentStart + 1);
918
- if (contentStart < 0 || fenceEnd < 0) return null;
919
- return text.slice(contentStart + 1, fenceEnd).trim();
960
+ function isAffirmativeLifecycleFieldValue(value) {
961
+ const trimmed = (value || "").trim();
962
+ return /^(yes|resolved|confirmed|complete|completed|ok|passed|all clear)\b|^(是|已|完成|已完成|已解決|已核對|已確認|通過)\b/i.test(trimmed);
920
963
  }
921
964
 
922
- function normalizePrompt(text) {
923
- return text.replace(/\r\n/g, "\n").trim();
924
- }
925
-
926
- function assessHandoffLifecycleConsistency(text) {
927
- const fieldValue = fieldValueAfterMarker(text, "lifecycle-conflicts-resolved");
928
- if (isAffirmativeLifecycleFieldValue(fieldValue)) {
929
- return { ok: true, reason: "" };
930
- }
931
- if (isUnresolvedLifecycleFieldValue(fieldValue)) {
932
- return { ok: false, reason: "lifecycle field is explicitly unresolved" };
933
- }
934
- if (isPlaceholderLifecycleFieldValue(fieldValue) && hasSubstantiveHandoffState(text)) {
935
- return { ok: false, reason: "lifecycle field is still placeholder after handoff content changed" };
936
- }
937
- return { ok: true, reason: "" };
938
- }
939
-
940
- function isAffirmativeLifecycleFieldValue(value) {
941
- const trimmed = (value || "").trim();
942
- return /^(yes|resolved|confirmed|complete|completed|ok|passed|all clear)\b|^(是|已|完成|已完成|已解決|已核對|已確認|通過)\b/i.test(trimmed);
943
- }
944
-
945
- function isUnresolvedLifecycleFieldValue(value) {
946
- return /\b(no|blocked|uncertain)\b|否|阻擋|不確定/i.test(value || "");
947
- }
948
-
949
- function isPlaceholderLifecycleFieldValue(value) {
950
- return !value || /\b(TBD|todo|pending|unverified|unknown|needs-review)\b|待核對|待確認|未核對|未確認/i.test(value);
951
- }
952
-
953
- function hasSubstantiveHandoffState(text) {
954
- const sections = [
955
- extractSectionText(text, "completed-this-session", "Completed This Session"),
956
- extractSectionText(text, "validation-qc", "Validation / QC")
957
- ].join("\n");
958
- const body = sections.replace(/```[\s\S]*?```/g, "");
959
- return body.split(/\r?\n/).some((line) => {
960
- const trimmed = line.trim();
961
- if (!trimmed || trimmed.startsWith("##") || trimmed.startsWith("<!--")) return false;
962
- if (/^Record only work actually completed/i.test(trimmed)) return false;
963
- if (/\bTBD\b|待定|待核對|未適用/i.test(trimmed)) return false;
964
- const normalized = trimmed.replace(/^[\d.*\-)\s]+/, "").replace(/[`\s#|:\-*/()[\].,;,。;、]/g, "");
965
- return normalized.length > 20;
966
- });
967
- }
968
-
969
- function fieldValueAfterMarker(text, fieldId) {
970
- const markerText = `ack:field:${fieldId}`;
971
- const markerIndex = text.indexOf(markerText);
972
- if (markerIndex >= 0) {
973
- const after = text.slice(markerIndex).split(/\r?\n/).slice(1);
974
- const line = after.find((candidate) => candidate.trim().startsWith("- "));
975
- if (!line) return "";
976
- const colonIndex = line.indexOf(":");
977
- return colonIndex >= 0 ? line.slice(colonIndex + 1).trim() : line.trim();
978
- }
979
- const fallback = text.match(/Completed \/ pending \/ risk \/ opening-message lifecycle conflicts resolved or explicitly reclassified:\s*([^\n]+)/i);
980
- return fallback ? fallback[1].trim() : "";
981
- }
982
-
983
- function extractSectionText(text, markerId, headingTitle) {
984
- const markerText = `ack:section:${markerId}`;
985
- const markerIndex = text.indexOf(markerText);
986
- if (markerIndex >= 0) {
987
- const start = text.indexOf("\n", markerIndex);
988
- if (start < 0) return "";
989
- const nextMarker = text.indexOf("<!-- ack:section:", start + 1);
990
- return text.slice(start + 1, nextMarker >= 0 ? nextMarker : text.length);
991
- }
992
-
993
- const headingMatch = new RegExp(`^## ${escapeRegExp(headingTitle)}\\s*$`, "m").exec(text);
994
- if (!headingMatch) return "";
995
- const start = headingMatch.index + headingMatch[0].length;
996
- const nextHeading = /\n##\s+/.exec(text.slice(start));
997
- return text.slice(start, nextHeading ? start + nextHeading.index : text.length);
998
- }
999
-
1000
- async function checkRequiredAnchors(root) {
1001
- const rows = [];
1002
- for (const rule of requiredAnchors) {
965
+ function isUnresolvedLifecycleFieldValue(value) {
966
+ return /\b(no|blocked|uncertain)\b|否|阻擋|不確定/i.test(value || "");
967
+ }
968
+
969
+ function isPlaceholderLifecycleFieldValue(value) {
970
+ return !value || /\b(TBD|todo|pending|unverified|unknown|needs-review)\b|待核對|待確認|未核對|未確認/i.test(value);
971
+ }
972
+
973
+ function hasSubstantiveHandoffState(text) {
974
+ const sections = [
975
+ extractSectionText(text, "completed-this-session", "Completed This Session"),
976
+ extractSectionText(text, "validation-qc", "Validation / QC")
977
+ ].join("\n");
978
+ const body = sections.replace(/```[\s\S]*?```/g, "");
979
+ return body.split(/\r?\n/).some((line) => {
980
+ const trimmed = line.trim();
981
+ if (!trimmed || trimmed.startsWith("##") || trimmed.startsWith("<!--")) return false;
982
+ if (/^Record only work actually completed/i.test(trimmed)) return false;
983
+ if (/\bTBD\b|待定|待核對|未適用/i.test(trimmed)) return false;
984
+ const normalized = trimmed.replace(/^[\d.*\-)\s]+/, "").replace(/[`\s#|:\-*/()[\].,;,。;、]/g, "");
985
+ return normalized.length > 20;
986
+ });
987
+ }
988
+
989
+ function fieldValueAfterMarker(text, fieldId) {
990
+ const markerText = `ack:field:${fieldId}`;
991
+ const markerIndex = text.indexOf(markerText);
992
+ if (markerIndex >= 0) {
993
+ const after = text.slice(markerIndex).split(/\r?\n/).slice(1);
994
+ const line = after.find((candidate) => candidate.trim().startsWith("- "));
995
+ if (!line) return "";
996
+ const colonIndex = line.indexOf(":");
997
+ return colonIndex >= 0 ? line.slice(colonIndex + 1).trim() : line.trim();
998
+ }
999
+ const fallback = text.match(/Completed \/ pending \/ risk \/ opening-message lifecycle conflicts resolved or explicitly reclassified:\s*([^\n]+)/i);
1000
+ return fallback ? fallback[1].trim() : "";
1001
+ }
1002
+
1003
+ function extractSectionText(text, markerId, headingTitle) {
1004
+ const markerText = `ack:section:${markerId}`;
1005
+ const markerIndex = text.indexOf(markerText);
1006
+ if (markerIndex >= 0) {
1007
+ const start = text.indexOf("\n", markerIndex);
1008
+ if (start < 0) return "";
1009
+ const nextMarker = text.indexOf("<!-- ack:section:", start + 1);
1010
+ return text.slice(start + 1, nextMarker >= 0 ? nextMarker : text.length);
1011
+ }
1012
+
1013
+ const headingMatch = new RegExp(`^## ${escapeRegExp(headingTitle)}\\s*$`, "m").exec(text);
1014
+ if (!headingMatch) return "";
1015
+ const start = headingMatch.index + headingMatch[0].length;
1016
+ const nextHeading = /\n##\s+/.exec(text.slice(start));
1017
+ return text.slice(start, nextHeading ? start + nextHeading.index : text.length);
1018
+ }
1019
+
1020
+ async function checkRequiredAnchors(root) {
1021
+ const rows = [];
1022
+ for (const rule of requiredAnchors) {
1003
1023
  const filePath = path.join(root, rule.target);
1004
1024
  let text = "";
1005
1025
  try {
1006
1026
  text = await readFile(filePath, "utf8");
1007
1027
  } catch {
1008
- rows.push({ target: rule.target, label: rule.label, ok: false });
1028
+ rows.push({ target: rule.target, label: rule.label, ok: false, missing: ["file unreadable"] });
1009
1029
  continue;
1010
1030
  }
1011
1031
 
1032
+ // Report which specific anchor snippets are absent, not just pass/fail. Mirrors
1033
+ // the schema-check contract (checkSchema returns `missing`) so an anchor failure
1034
+ // is self-diagnosing: the user and the AI can see the exact text to restore.
1035
+ const missing = rule.snippets.filter((snippet) => !text.includes(snippet));
1012
1036
  rows.push({
1013
1037
  target: rule.target,
1014
1038
  label: rule.label,
1015
- ok: rule.snippets.every((snippet) => text.includes(snippet))
1039
+ ok: missing.length === 0,
1040
+ missing
1016
1041
  });
1017
1042
  }
1018
1043
  return rows;
@@ -1102,7 +1127,7 @@ async function buildPlan(root, command) {
1102
1127
  return plan;
1103
1128
  }
1104
1129
 
1105
- function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText) {
1130
+ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText) {
1106
1131
  const base = { sourceRel, targetRel, sourceAbs, targetAbs };
1107
1132
  if (targetText === sourceText) return { ...base, action: "skip", reason: "already current" };
1108
1133
  if (command !== "upgrade") return { ...base, action: "skip", reason: "init preserves existing files" };
@@ -1146,34 +1171,34 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1146
1171
  mergedText: mergeManagedBlock(targetText, sourceText)
1147
1172
  };
1148
1173
  }
1149
- // R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
1150
- // user-added rows. Missing maintainer rows are merged into the existing table
1151
- // instead of replacing the whole file.
1152
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("First-time user signals")) {
1153
- const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1154
- if (!mergedRulePacks) {
1155
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1156
- }
1157
- return {
1158
- ...base,
1159
- action: "merge",
1160
- reason: "merge missing v0.2.0+ routing rows while preserving existing custom rows (新手引導 signal routing)",
1161
- mergedText: mergedRulePacks
1162
- };
1163
- }
1164
- // R-030 v0.3.0+: dev/RULE_PACKS.md must also include integrations pack routing row.
1165
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool integrations")) {
1166
- const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1167
- if (!mergedRulePacks) {
1168
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1169
- }
1170
- return {
1171
- ...base,
1172
- action: "merge",
1173
- reason: "merge missing v0.3.0+ routing rows while preserving existing custom rows (Integration governance routing)",
1174
- mergedText: mergedRulePacks
1175
- };
1176
- }
1174
+ // R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
1175
+ // user-added rows. Missing maintainer rows are merged into the existing table
1176
+ // instead of replacing the whole file.
1177
+ if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("First-time user signals")) {
1178
+ const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1179
+ if (!mergedRulePacks) {
1180
+ return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1181
+ }
1182
+ return {
1183
+ ...base,
1184
+ action: "merge",
1185
+ reason: "merge missing v0.2.0+ routing rows while preserving existing custom rows (新手引導 signal routing)",
1186
+ mergedText: mergedRulePacks
1187
+ };
1188
+ }
1189
+ // R-030 v0.3.0+: dev/RULE_PACKS.md must also include integrations pack routing row.
1190
+ if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool integrations")) {
1191
+ const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1192
+ if (!mergedRulePacks) {
1193
+ return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1194
+ }
1195
+ return {
1196
+ ...base,
1197
+ action: "merge",
1198
+ reason: "merge missing v0.3.0+ routing rows while preserving existing custom rows (Integration governance routing)",
1199
+ mergedText: mergedRulePacks
1200
+ };
1201
+ }
1177
1202
  // R-030 v0.3.0+: dev/PROJECT_INDEX.md gets ## Installed Integrations section auto-inserted before
1178
1203
  // ## Local QC Commands on upgrade if missing. NON-DESTRUCTIVE: existing ## External Sources content
1179
1204
  // is fully preserved (including any user-filled rows). User can later manually add the `via` column
@@ -1196,146 +1221,146 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1196
1221
  // content and any user customization preserved. Step 1 micro-question additions to Scenarios A-E
1197
1222
  // are NOT auto-migrated (user-customizable inline sample wording, not anchor-enforced); users get
1198
1223
  // those on fresh install only or can manually patch following CHANGELOG migration guidance.
1199
- if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. 審視已裝外部工具")) {
1200
- const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. 審視已裝外部工具[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1201
- if (sourceScenarioFMatch && targetText.includes("## Cross-reference to guide.html")) {
1202
- const scenarioFBlock = sourceScenarioFMatch[1];
1203
- return {
1224
+ if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. 審視已裝外部工具")) {
1225
+ const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. 審視已裝外部工具[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1226
+ if (sourceScenarioFMatch && targetText.includes("## Cross-reference to guide.html")) {
1227
+ const scenarioFBlock = sourceScenarioFMatch[1];
1228
+ return {
1204
1229
  ...base,
1205
1230
  action: "merge",
1206
1231
  reason: "insert ### Scenario F block before ## Cross-reference to guide.html (R-030 onboarding pack migration; existing Scenarios A-E content preserved non-destructively)",
1207
1232
  mergedText: targetText.replace("## Cross-reference to guide.html", scenarioFBlock + "## Cross-reference to guide.html")
1208
- };
1209
- }
1210
- }
1211
- if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario A. 建構系統 / 工具 / 平台 / 網站或應用")) {
1212
- const mergedOnboarding = mergeOnboardingScenarioALabel(targetText);
1213
- if (mergedOnboarding !== targetText) {
1214
- return {
1215
- ...base,
1216
- action: "merge",
1217
- reason: "update onboarding Scenario A wording from narrow coding label to broader system/tool/platform/app label",
1218
- mergedText: mergedOnboarding
1219
- };
1220
- }
1221
- }
1222
- // v0.3.6+: SESSION_HANDOFF.md gains a non-destructive lifecycle consistency
1223
- // field. Existing handoff content stays intact; only the missing field and
1224
- // rule note are inserted around stable ack markers.
1225
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
1226
- const mergedHandoff = mergeHandoffLifecycleField(targetText);
1227
- if (!mergedHandoff) {
1228
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add lifecycle consistency field" };
1229
- }
1230
- return {
1231
- ...base,
1232
- action: "merge",
1233
- reason: "insert lifecycle consistency field into State Reconciliation Check (completed work must not carry forward as unresolved next work)",
1234
- mergedText: mergedHandoff
1235
- };
1236
- }
1237
- if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
1238
- if (!targetText.includes("AGENTS.md")) {
1239
- return { ...base, action: "conflict", reason: "existing bridge does not route to AGENTS.md" };
1240
- }
1241
- if (looksLikeExpandedKitBridge(targetRel, targetText)) {
1242
- return {
1243
- ...base,
1244
- action: "merge",
1245
- reason: `${targetRel} appears to be an expanded Kit bridge; restore short bridge so AGENTS.md remains the single source of truth`,
1246
- mergedText: sourceText
1247
- };
1248
- }
1249
- }
1250
- return { ...base, action: "skip", reason: "preserve existing file" };
1251
- }
1252
-
1253
- function looksLikeExpandedKitBridge(targetRel, text) {
1254
- if (text.includes("This file is a bridge only")) return false;
1255
- if (targetRel === "CLAUDE.md") {
1256
- return (text.includes("This file provides guidance to Claude Code") && text.includes("## Session Startup"))
1257
- || text.includes("## Architecture")
1258
- || text.includes("## CLI Commands")
1259
- || text.includes("Every non-trivial task follows");
1260
- }
1261
- if (targetRel === "GEMINI.md") {
1262
- return text.includes("## Architecture")
1263
- || text.includes("## CLI Commands")
1264
- || text.includes("Every non-trivial task follows");
1265
- }
1266
- return false;
1267
- }
1268
-
1269
- function mergeOnboardingScenarioALabel(targetText) {
1270
- let merged = targetText;
1271
- merged = merged.replace(
1272
- /\*\*A\. 寫 \/ 改代碼項目\*\* —— 你有一個(?: project 的 codebase|程式項目)想長期維護/g,
1273
- "**A. 建構系統 / 工具 / 平台 / 網站或應用** —— 你想由 AI 協助建立或長期維護一個可運作的項目"
1274
- );
1275
- merged = merged.replace(
1276
- /### Scenario A\. 寫 \/ 改代碼項目/g,
1277
- "### Scenario A. 建構系統 / 工具 / 平台 / 網站或應用"
1278
- );
1279
- return merged;
1280
- }
1281
-
1282
- function mergeHandoffLifecycleField(targetText) {
1283
- const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
1284
- if (!targetText.includes(openingMarker)) return null;
1285
-
1286
- const fieldBlock = "<!-- ack:field:lifecycle-conflicts-resolved -->\n- Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified: TBD\n";
1287
- let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
1288
-
1289
- if (!merged.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
1290
- const ruleBlock = "Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.\n\n";
1291
- const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
1292
- if (merged.includes(sufficiencyMarker)) {
1293
- merged = merged.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
1294
- } else {
1295
- merged = `${merged.trimEnd()}\n\n${ruleBlock}`;
1296
- }
1297
- }
1298
-
1299
- return merged;
1300
- }
1301
-
1302
- function mergeRulePacksRows(targetText, sourceText) {
1303
- const requiredPacks = [
1304
- "dev/rules/onboarding.md",
1305
- "dev/rules/integrations.md"
1306
- ];
1307
- const sourceRows = sourceText
1308
- .split(/\r?\n/)
1309
- .filter((line) => line.startsWith("|") && requiredPacks.some((pack) => line.includes(pack)));
1310
- if (sourceRows.length === 0) return targetText;
1311
-
1312
- const lines = targetText.split(/\r?\n/);
1313
- const tableStart = lines.findIndex((line) => line.trim() === "| Task signal | Pack | Purpose |");
1314
- if (tableStart < 0) return null;
1315
-
1316
- let tableEnd = tableStart;
1317
- while (tableEnd < lines.length && lines[tableEnd].startsWith("|")) tableEnd++;
1318
-
1319
- const before = lines.slice(0, tableStart);
1320
- const table = lines.slice(tableStart, tableEnd);
1321
- const after = lines.slice(tableEnd);
1322
- const sourceRowsToApply = sourceRows.filter((row) => {
1323
- if (row.includes("dev/rules/onboarding.md")) return !targetText.includes("First-time user signals");
1324
- if (row.includes("dev/rules/integrations.md")) return !targetText.includes("External tool integrations");
1325
- return false;
1326
- });
1327
- if (sourceRowsToApply.length === 0) return targetText;
1328
-
1329
- const merged = [
1330
- ...before,
1331
- ...table,
1332
- ...sourceRowsToApply,
1333
- ...after
1334
- ];
1335
- return merged.join("\n");
1336
- }
1337
-
1338
- // R-031.2 v0.3.2+: Version alignment assessment for doctor "項目狀態速覽".
1233
+ };
1234
+ }
1235
+ }
1236
+ if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario A. 建構系統 / 工具 / 平台 / 網站或應用")) {
1237
+ const mergedOnboarding = mergeOnboardingScenarioALabel(targetText);
1238
+ if (mergedOnboarding !== targetText) {
1239
+ return {
1240
+ ...base,
1241
+ action: "merge",
1242
+ reason: "update onboarding Scenario A wording from narrow coding label to broader system/tool/platform/app label",
1243
+ mergedText: mergedOnboarding
1244
+ };
1245
+ }
1246
+ }
1247
+ // v0.3.6+: SESSION_HANDOFF.md gains a non-destructive lifecycle consistency
1248
+ // field. Existing handoff content stays intact; only the missing field and
1249
+ // rule note are inserted around stable ack markers.
1250
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
1251
+ const mergedHandoff = mergeHandoffLifecycleField(targetText);
1252
+ if (!mergedHandoff) {
1253
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add lifecycle consistency field" };
1254
+ }
1255
+ return {
1256
+ ...base,
1257
+ action: "merge",
1258
+ reason: "insert lifecycle consistency field into State Reconciliation Check (completed work must not carry forward as unresolved next work)",
1259
+ mergedText: mergedHandoff
1260
+ };
1261
+ }
1262
+ if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
1263
+ if (!targetText.includes("AGENTS.md")) {
1264
+ return { ...base, action: "conflict", reason: "existing bridge does not route to AGENTS.md" };
1265
+ }
1266
+ if (looksLikeExpandedKitBridge(targetRel, targetText)) {
1267
+ return {
1268
+ ...base,
1269
+ action: "merge",
1270
+ reason: `${targetRel} appears to be an expanded Kit bridge; restore short bridge so AGENTS.md remains the single source of truth`,
1271
+ mergedText: sourceText
1272
+ };
1273
+ }
1274
+ }
1275
+ return { ...base, action: "skip", reason: "preserve existing file" };
1276
+ }
1277
+
1278
+ function looksLikeExpandedKitBridge(targetRel, text) {
1279
+ if (text.includes("This file is a bridge only")) return false;
1280
+ if (targetRel === "CLAUDE.md") {
1281
+ return (text.includes("This file provides guidance to Claude Code") && text.includes("## Session Startup"))
1282
+ || text.includes("## Architecture")
1283
+ || text.includes("## CLI Commands")
1284
+ || text.includes("Every non-trivial task follows");
1285
+ }
1286
+ if (targetRel === "GEMINI.md") {
1287
+ return text.includes("## Architecture")
1288
+ || text.includes("## CLI Commands")
1289
+ || text.includes("Every non-trivial task follows");
1290
+ }
1291
+ return false;
1292
+ }
1293
+
1294
+ function mergeOnboardingScenarioALabel(targetText) {
1295
+ let merged = targetText;
1296
+ merged = merged.replace(
1297
+ /\*\*A\. 寫 \/ 改代碼項目\*\* —— 你有一個(?: project 的 codebase|程式項目)想長期維護/g,
1298
+ "**A. 建構系統 / 工具 / 平台 / 網站或應用** —— 你想由 AI 協助建立或長期維護一個可運作的項目"
1299
+ );
1300
+ merged = merged.replace(
1301
+ /### Scenario A\. 寫 \/ 改代碼項目/g,
1302
+ "### Scenario A. 建構系統 / 工具 / 平台 / 網站或應用"
1303
+ );
1304
+ return merged;
1305
+ }
1306
+
1307
+ function mergeHandoffLifecycleField(targetText) {
1308
+ const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
1309
+ if (!targetText.includes(openingMarker)) return null;
1310
+
1311
+ const fieldBlock = "<!-- ack:field:lifecycle-conflicts-resolved -->\n- Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified: Reclassified at upgrade: field added by v0.3.6+ migration; pre-existing handoff state predates it; reconcile at next closeout.\n";
1312
+ let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
1313
+
1314
+ if (!merged.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
1315
+ const ruleBlock = "Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.\n\n";
1316
+ const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
1317
+ if (merged.includes(sufficiencyMarker)) {
1318
+ merged = merged.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
1319
+ } else {
1320
+ merged = `${merged.trimEnd()}\n\n${ruleBlock}`;
1321
+ }
1322
+ }
1323
+
1324
+ return merged;
1325
+ }
1326
+
1327
+ function mergeRulePacksRows(targetText, sourceText) {
1328
+ const requiredPacks = [
1329
+ "dev/rules/onboarding.md",
1330
+ "dev/rules/integrations.md"
1331
+ ];
1332
+ const sourceRows = sourceText
1333
+ .split(/\r?\n/)
1334
+ .filter((line) => line.startsWith("|") && requiredPacks.some((pack) => line.includes(pack)));
1335
+ if (sourceRows.length === 0) return targetText;
1336
+
1337
+ const lines = targetText.split(/\r?\n/);
1338
+ const tableStart = lines.findIndex((line) => line.trim() === "| Task signal | Pack | Purpose |");
1339
+ if (tableStart < 0) return null;
1340
+
1341
+ let tableEnd = tableStart;
1342
+ while (tableEnd < lines.length && lines[tableEnd].startsWith("|")) tableEnd++;
1343
+
1344
+ const before = lines.slice(0, tableStart);
1345
+ const table = lines.slice(tableStart, tableEnd);
1346
+ const after = lines.slice(tableEnd);
1347
+ const sourceRowsToApply = sourceRows.filter((row) => {
1348
+ if (row.includes("dev/rules/onboarding.md")) return !targetText.includes("First-time user signals");
1349
+ if (row.includes("dev/rules/integrations.md")) return !targetText.includes("External tool integrations");
1350
+ return false;
1351
+ });
1352
+ if (sourceRowsToApply.length === 0) return targetText;
1353
+
1354
+ const merged = [
1355
+ ...before,
1356
+ ...table,
1357
+ ...sourceRowsToApply,
1358
+ ...after
1359
+ ];
1360
+ return merged.join("\n");
1361
+ }
1362
+
1363
+ // R-031.2 v0.3.2+: Version alignment assessment for doctor "項目狀態速覽".
1339
1364
  // Compares CLI version (running), root template metadata version (in dev/PROJECT_INDEX.md),
1340
1365
  // and npm latest. Surfaces drift awareness because previous design relied on startup
1341
1366
  // maybePrintUpdateNotice which silently fails when npx auto-fetches latest (CLI version
@@ -1361,45 +1386,45 @@ async function assessVersionAlignment(root, cliVersion) {
1361
1386
  return { cliVersion, rootVersion, npmLatest };
1362
1387
  }
1363
1388
 
1364
- function printVersionAlignment(result) {
1365
- const { cliVersion, rootVersion, npmLatest } = result;
1366
- if (rootVersion === null) {
1367
- console.log(` 📦 版本:工具 v${cliVersion} / 項目版本記錄缺失(可能曾經手動編輯)/ npm latest ${npmLatest ? "v" + npmLatest : "無法查詢"}`);
1368
- return;
1369
- }
1370
- if (npmLatest === null) {
1371
- console.log(` 📦 版本:工具 v${cliVersion} / 項目記錄 v${rootVersion} / npm latest 無法查詢(網絡可能不通)`);
1372
- return;
1373
- }
1374
- const aligned = cliVersion === rootVersion && rootVersion === npmLatest;
1375
- if (aligned) {
1376
- console.log(` 📦 版本:工具 / 項目記錄 / npm latest 三向對齊 v${cliVersion} ✅`);
1377
- return;
1378
- }
1379
- console.log(` 📦 版本:工具 v${cliVersion} / 項目記錄 v${rootVersion} / npm latest v${npmLatest}`);
1380
- if (npmLatest && compareSemver(npmLatest, cliVersion) > 0) {
1381
- console.log(` npm 有新版(v${npmLatest});doctor 只檢查不修改。要升級時先執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run`);
1382
- console.log(" --dry-run 只預覽、不寫入;確認計劃沒問題後,再去掉 --dry-run 正式升級。");
1383
- } else if (cliVersion !== rootVersion) {
1384
- console.log(" 項目內記錄的 Kit 版本與目前工具版本不同;doctor 只檢查不修改。要對齊時先執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run");
1385
- console.log(" --dry-run 只預覽、不寫入;確認計劃沒問題後,再去掉 --dry-run 正式升級。");
1386
- }
1387
- }
1388
-
1389
- function getVersionAlignmentNextStep(result) {
1390
- const { cliVersion, rootVersion, npmLatest } = result;
1391
- if (npmLatest && compareSemver(npmLatest, cliVersion) > 0) {
1392
- return `檢查已通過,但 npm 有新版 v${npmLatest}。doctor 沒有修改檔案;建議先執行 npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run。--dry-run 只預覽、不寫入;確認計劃沒問題後,再去掉 --dry-run 正式升級。`;
1393
- }
1394
- if (rootVersion === null) {
1395
- return "檢查已通過,但項目版本記錄缺失。doctor 沒有修改檔案;建議先執行 npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run。--dry-run 只預覽、不寫入;確認只會補齊工具維護的版本記錄後,再去掉 --dry-run 正式升級。";
1396
- }
1397
- if (cliVersion !== rootVersion) {
1398
- return "檢查已通過,但項目版本記錄未與目前工具對齊。doctor 沒有修改檔案;建議先執行 npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run。--dry-run 只預覽、不寫入;確認後再去掉 --dry-run 正式升級。";
1399
- }
1400
- return null;
1401
- }
1402
-
1389
+ function printVersionAlignment(result) {
1390
+ const { cliVersion, rootVersion, npmLatest } = result;
1391
+ if (rootVersion === null) {
1392
+ console.log(` 📦 版本:工具 v${cliVersion} / 項目版本記錄缺失(可能曾經手動編輯)/ npm latest ${npmLatest ? "v" + npmLatest : "無法查詢"}`);
1393
+ return;
1394
+ }
1395
+ if (npmLatest === null) {
1396
+ console.log(` 📦 版本:工具 v${cliVersion} / 項目記錄 v${rootVersion} / npm latest 無法查詢(網絡可能不通)`);
1397
+ return;
1398
+ }
1399
+ const aligned = cliVersion === rootVersion && rootVersion === npmLatest;
1400
+ if (aligned) {
1401
+ console.log(` 📦 版本:工具 / 項目記錄 / npm latest 三向對齊 v${cliVersion} ✅`);
1402
+ return;
1403
+ }
1404
+ console.log(` 📦 版本:工具 v${cliVersion} / 項目記錄 v${rootVersion} / npm latest v${npmLatest}`);
1405
+ if (npmLatest && compareSemver(npmLatest, cliVersion) > 0) {
1406
+ console.log(` npm 有新版(v${npmLatest});doctor 只檢查不修改。要升級時先執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run`);
1407
+ console.log(" --dry-run 只預覽、不寫入;確認計劃沒問題後,再去掉 --dry-run 正式升級。");
1408
+ } else if (cliVersion !== rootVersion) {
1409
+ console.log(" 項目內記錄的 Kit 版本與目前工具版本不同;doctor 只檢查不修改。要對齊時先執行:npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run");
1410
+ console.log(" --dry-run 只預覽、不寫入;確認計劃沒問題後,再去掉 --dry-run 正式升級。");
1411
+ }
1412
+ }
1413
+
1414
+ function getVersionAlignmentNextStep(result) {
1415
+ const { cliVersion, rootVersion, npmLatest } = result;
1416
+ if (npmLatest && compareSemver(npmLatest, cliVersion) > 0) {
1417
+ return `檢查已通過,但 npm 有新版 v${npmLatest}。doctor 沒有修改檔案;建議先執行 npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run。--dry-run 只預覽、不寫入;確認計劃沒問題後,再去掉 --dry-run 正式升級。`;
1418
+ }
1419
+ if (rootVersion === null) {
1420
+ return "檢查已通過,但項目版本記錄缺失。doctor 沒有修改檔案;建議先執行 npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run。--dry-run 只預覽、不寫入;確認只會補齊工具維護的版本記錄後,再去掉 --dry-run 正式升級。";
1421
+ }
1422
+ if (cliVersion !== rootVersion) {
1423
+ return "檢查已通過,但項目版本記錄未與目前工具對齊。doctor 沒有修改檔案;建議先執行 npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run。--dry-run 只預覽、不寫入;確認後再去掉 --dry-run 正式升級。";
1424
+ }
1425
+ return null;
1426
+ }
1427
+
1403
1428
  // R-031.2 v0.3.2+: Last closeout assessment. Reads dev/SESSION_HANDOFF.md "Last Updated:"
1404
1429
  // line (strict format, reliable). Falls back to dev/SESSION_LOG.md first H2 date if
1405
1430
  // HANDOFF missing or unparseable.
@@ -1428,24 +1453,24 @@ async function assessLastCloseout(root) {
1428
1453
  return { date };
1429
1454
  }
1430
1455
 
1431
- function printLastCloseout(result) {
1432
- if (!result.date) {
1433
- console.log(" 📅 上次收工:尚未收工過。第一次完成任務後,可以在 AI 對話輸入「收工」。");
1434
- return;
1435
- }
1456
+ function printLastCloseout(result) {
1457
+ if (!result.date) {
1458
+ console.log(" 📅 上次收工:尚未收工過。第一次完成任務後,可以在 AI 對話輸入「收工」。");
1459
+ return;
1460
+ }
1436
1461
  const today = new Date();
1437
1462
  const closeout = new Date(result.date);
1438
1463
  const daysDiff = Math.floor((today - closeout) / (1000 * 60 * 60 * 24));
1439
- if (daysDiff < 0) {
1440
- console.log(` 📅 上次收工:${result.date}(日期超前?檢查系統時鐘)`);
1441
- } else if (daysDiff === 0) {
1442
- console.log(` 📅 上次收工:今日(${result.date})`);
1443
- } else if (daysDiff <= 30) {
1444
- console.log(` 📅 上次收工:${daysDiff} 日前(${result.date})`);
1445
- } else {
1446
- console.log(` 📅 上次收工:${daysDiff} 日前(${result.date})— 建議輸入「收工」整理進度`);
1447
- }
1448
- }
1464
+ if (daysDiff < 0) {
1465
+ console.log(` 📅 上次收工:${result.date}(日期超前?檢查系統時鐘)`);
1466
+ } else if (daysDiff === 0) {
1467
+ console.log(` 📅 上次收工:今日(${result.date})`);
1468
+ } else if (daysDiff <= 30) {
1469
+ console.log(` 📅 上次收工:${daysDiff} 日前(${result.date})`);
1470
+ } else {
1471
+ console.log(` 📅 上次收工:${daysDiff} 日前(${result.date})— 建議輸入「收工」整理進度`);
1472
+ }
1473
+ }
1449
1474
 
1450
1475
  // R-031.2 v0.3.2+: Project age assessment. Reads the oldest folder timestamp in
1451
1476
  // dev/governance_migrations/ which records the first install date. Read-only; doctor
@@ -1707,92 +1732,92 @@ async function detectMode(root) {
1707
1732
  return "partial";
1708
1733
  }
1709
1734
 
1710
- function printPlan(command, root, mode, plan, version, isDryRun = false) {
1711
- printCard(version, "continuity ready", "o.o");
1712
- console.log(`command: ${command}`);
1713
- console.log(`current directory: ${process.cwd()}`);
1714
- console.log(`selected root: ${root}`);
1715
- console.log(`mode: ${mode}`);
1716
- console.log("");
1717
- const planIntro = planIntroFor(command, mode, isDryRun);
1718
- console.log(planIntro);
1719
- console.log("");
1735
+ function printPlan(command, root, mode, plan, version, isDryRun = false) {
1736
+ printCard(version, "continuity ready", "o.o");
1737
+ console.log(`command: ${command}`);
1738
+ console.log(`current directory: ${process.cwd()}`);
1739
+ console.log(`selected root: ${root}`);
1740
+ console.log(`mode: ${mode}`);
1741
+ console.log("");
1742
+ const planIntro = planIntroFor(command, mode, isDryRun);
1743
+ console.log(planIntro);
1744
+ console.log("");
1720
1745
  for (const action of ["create", "merge", "skip", "conflict"]) {
1721
1746
  const items = plan.filter((item) => item.action === action);
1722
1747
  console.log(`${action}: ${items.length}`);
1723
1748
  for (const item of items) console.log(` ${item.targetRel}${item.reason ? ` - ${item.reason}` : ""}`);
1724
1749
  }
1725
- console.log(`\nbackup: ${plan.filter((item) => item.action === "merge").length}`);
1726
- }
1727
-
1728
- function planIntroFor(command, mode, isDryRun) {
1729
- const prefix = isDryRun ? "📋 預演結果:這次不會寫入檔案。" : "📋 寫入前確認:工具準備這樣處理目前資料夾。";
1730
- if (command === "init" && mode === "first-install") {
1731
- return `${prefix} 目前資料夾未見 Kit 檔案;工具會建立交接文件、AI 入口檔與工作規則。沒有既有檔案會被覆寫。`;
1732
- }
1733
- if (command === "init" && mode === "partial") {
1734
- return `${prefix} 目前資料夾已有部分 AI 或 Kit 檔案;工具會補齊缺少檔案,保留既有檔案。安裝後可能仍要用 upgrade 補入口連接。`;
1735
- }
1736
- if (command === "upgrade") {
1737
- return `${prefix} 工具會檢查既有 Kit 檔案;能安全合併才合併,不能判斷時會停手並列為 conflict。`;
1738
- }
1739
- return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具停手等你判斷。`;
1740
- }
1750
+ console.log(`\nbackup: ${plan.filter((item) => item.action === "merge").length}`);
1751
+ }
1752
+
1753
+ function planIntroFor(command, mode, isDryRun) {
1754
+ const prefix = isDryRun ? "📋 預演結果:這次不會寫入檔案。" : "📋 寫入前確認:工具準備這樣處理目前資料夾。";
1755
+ if (command === "init" && mode === "first-install") {
1756
+ return `${prefix} 目前資料夾未見 Kit 檔案;工具會建立交接文件、AI 入口檔與工作規則。沒有既有檔案會被覆寫。`;
1757
+ }
1758
+ if (command === "init" && mode === "partial") {
1759
+ return `${prefix} 目前資料夾已有部分 AI 或 Kit 檔案;工具會補齊缺少檔案,保留既有檔案。安裝後可能仍要用 upgrade 補入口連接。`;
1760
+ }
1761
+ if (command === "upgrade") {
1762
+ return `${prefix} 工具會檢查既有 Kit 檔案;能安全合併才合併,不能判斷時會停手並列為 conflict。`;
1763
+ }
1764
+ return `${prefix} create 代表建立缺少檔案;merge 代表先備份再合併;skip 代表保留既有檔案;conflict 代表工具停手等你判斷。`;
1765
+ }
1741
1766
 
1742
- // R-026 CLI Output Contract: install/upgrade 完成必含四項(版本/模式/剛完成/下一步)。
1743
- function printInstallSummary(version, command, mode, root, counts) {
1767
+ // R-026 CLI Output Contract: install/upgrade 完成必含四項(版本/模式/剛完成/下一步)。
1768
+ function printInstallSummary(version, command, mode, root, counts) {
1744
1769
  console.log(`\n✅ created: ${counts.created}`);
1745
1770
  console.log(`🔀 merged: ${counts.merged}`);
1746
1771
  console.log(`⏭️ skipped existing: ${counts.skipped}`);
1747
1772
  console.log(`${counts.conflicts > 0 ? "⚠️ " : "✅ "}conflict: ${counts.conflicts}`);
1748
1773
  if (counts.backupRel) console.log(`💾 backup: ${counts.backupRel}`);
1749
1774
  if (counts.reportRel) console.log(`📄 migration report: ${counts.reportRel}`);
1750
- console.log("");
1751
- console.log(`📦 版本:v${version}`);
1752
- console.log(`🛠️ 模式:${mode}`);
1753
- console.log(`🔎 剛完成:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
1754
- if (counts.conflicts > 0) {
1755
- console.log("🚀 下一步:把 migration report 或這段輸出貼給 AI,請它判斷衝突檔案怎樣處理;工具已停手,沒有覆寫 conflict 檔案。");
1756
- } else if (command === "upgrade") {
1757
- console.log("🚀 下一步:留意下方升級後自動檢查;若全綠即升級完成。");
1758
- } else if (mode === "partial" || counts.skipped > 0) {
1759
- console.log("🚀 下一步:先看下方提示。若你原本已有 AGENTS.md 或其他 AI 規則,請先執行 upgrade --dry-run 補入口連接,再執行 doctor。");
1760
- } else {
1761
- console.log("🚀 下一步:不用再留在終端機。打開 AI 工具,貼下方起步句。");
1762
- }
1763
- }
1764
-
1765
- function printDryRunExplanation(command, mode, plan) {
1766
- const conflicts = plan.filter((item) => item.action === "conflict");
1767
- console.log("✅ 這次沒有改動任何檔案。");
1768
- if (conflicts.length === 0) {
1769
- if (command === "init") {
1770
- console.log("✅ 沒有發現 conflict。若這是你要安裝 Kit 的資料夾,下一步執行:");
1771
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest init");
1772
- return;
1773
- }
1774
- if (mode === "upgrade-existing") {
1775
- console.log("✅ 沒有發現 conflict。若你想正式套用以上升級計劃,下一步執行:");
1776
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade");
1777
- return;
1778
- }
1779
- console.log("✅ 沒有發現 conflict。請按你剛才預演的命令去掉 --dry-run 後正式執行。");
1780
- return;
1781
- }
1782
- console.log(`⚠️ 需要人工確認:有 ${conflicts.length} 個既有檔案,工具不能安全判斷怎樣合併。`);
1783
- console.log("⚠️ 這不是檔案壞掉,也沒有覆寫你的檔案。");
1784
- console.log("📋 下一步:把這段輸出貼給 AI,叫它幫你判斷要保留、合併,還是手動修改。");
1785
- }
1786
-
1787
- async function confirmWrite() {
1788
- const rl = createInterface({ input, output });
1789
- try {
1790
- const answer = await rl.question("要按上面計劃寫入 / 合併 Kit 檔案嗎?輸入 yes 繼續:");
1791
- return answer.trim().toLowerCase() === "yes";
1792
- } finally {
1793
- rl.close();
1794
- }
1795
- }
1775
+ console.log("");
1776
+ console.log(`📦 版本:v${version}`);
1777
+ console.log(`🛠️ 模式:${mode}`);
1778
+ console.log(`🔎 剛完成:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
1779
+ if (counts.conflicts > 0) {
1780
+ console.log("🚀 下一步:把 migration report 或這段輸出貼給 AI,請它判斷衝突檔案怎樣處理;工具已停手,沒有覆寫 conflict 檔案。");
1781
+ } else if (command === "upgrade") {
1782
+ console.log("🚀 下一步:留意下方升級後自動檢查;若全綠即升級完成。");
1783
+ } else if (mode === "partial" || counts.skipped > 0) {
1784
+ console.log("🚀 下一步:先看下方提示。若你原本已有 AGENTS.md 或其他 AI 規則,請先執行 upgrade --dry-run 補入口連接,再執行 doctor。");
1785
+ } else {
1786
+ console.log("🚀 下一步:不用再留在終端機。打開 AI 工具,貼下方起步句。");
1787
+ }
1788
+ }
1789
+
1790
+ function printDryRunExplanation(command, mode, plan) {
1791
+ const conflicts = plan.filter((item) => item.action === "conflict");
1792
+ console.log("✅ 這次沒有改動任何檔案。");
1793
+ if (conflicts.length === 0) {
1794
+ if (command === "init") {
1795
+ console.log("✅ 沒有發現 conflict。若這是你要安裝 Kit 的資料夾,下一步執行:");
1796
+ console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest init");
1797
+ return;
1798
+ }
1799
+ if (mode === "upgrade-existing") {
1800
+ console.log("✅ 沒有發現 conflict。若你想正式套用以上升級計劃,下一步執行:");
1801
+ console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade");
1802
+ return;
1803
+ }
1804
+ console.log("✅ 沒有發現 conflict。請按你剛才預演的命令去掉 --dry-run 後正式執行。");
1805
+ return;
1806
+ }
1807
+ console.log(`⚠️ 需要人工確認:有 ${conflicts.length} 個既有檔案,工具不能安全判斷怎樣合併。`);
1808
+ console.log("⚠️ 這不是檔案壞掉,也沒有覆寫你的檔案。");
1809
+ console.log("📋 下一步:把這段輸出貼給 AI,叫它幫你判斷要保留、合併,還是手動修改。");
1810
+ }
1811
+
1812
+ async function confirmWrite() {
1813
+ const rl = createInterface({ input, output });
1814
+ try {
1815
+ const answer = await rl.question("要按上面計劃寫入 / 合併 Kit 檔案嗎?輸入 yes 繼續:");
1816
+ return answer.trim().toLowerCase() === "yes";
1817
+ } finally {
1818
+ rl.close();
1819
+ }
1820
+ }
1796
1821
 
1797
1822
  async function writeMigrationReport(root, command, mode, plan, created, merged, conflicts, migrationDir, backupDir, metadataUpdated = null) {
1798
1823
  const reportPath = path.join(migrationDir, "migration-report.md");
@@ -1909,15 +1934,15 @@ function compareSemver(left, right) {
1909
1934
  return 0;
1910
1935
  }
1911
1936
 
1912
- function printUpdateNotice(currentVersion, latestVersion) {
1913
- const releaseUrl = "https://github.com/Adamchanadam/agent-handoff-kit/releases/latest";
1914
- const command = "npx --yes @adamchanadam/agent-handoff-kit@latest <command>";
1915
- const lines = [
1916
- `✨ 有新版可用:${currentVersion} -> ${latestVersion}`,
1917
- `如要使用最新版,執行:${command}`,
1918
- "這只讓 npm 取得執行工具;doctor 只檢查,不會安裝項目文件。",
1919
- "",
1920
- "如果你是全域安裝:",
1937
+ function printUpdateNotice(currentVersion, latestVersion) {
1938
+ const releaseUrl = "https://github.com/Adamchanadam/agent-handoff-kit/releases/latest";
1939
+ const command = "npx --yes @adamchanadam/agent-handoff-kit@latest <command>";
1940
+ const lines = [
1941
+ `✨ 有新版可用:${currentVersion} -> ${latestVersion}`,
1942
+ `如要使用最新版,執行:${command}`,
1943
+ "這只讓 npm 取得執行工具;doctor 只檢查,不會安裝項目文件。",
1944
+ "",
1945
+ "如果你是全域安裝:",
1921
1946
  "npm install -g @adamchanadam/agent-handoff-kit",
1922
1947
  "",
1923
1948
  "完整 release notes:",
@@ -1943,74 +1968,74 @@ function printCard(version, status, eyes) {
1943
1968
  console.log("");
1944
1969
  }
1945
1970
 
1946
- function printInstallNextSteps(root, conflictCount, mode = "first-install", skippedCount = 0) {
1947
- console.log("");
1948
- console.log("============================================================");
1949
- if (mode === "partial" || skippedCount > 0) {
1950
- console.log("⚠️ 已補齊缺少檔案,但仍要檢查入口連接");
1951
- } else {
1952
- console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
1953
- }
1954
- console.log("============================================================");
1971
+ function printInstallNextSteps(root, conflictCount, mode = "first-install", skippedCount = 0) {
1972
+ console.log("");
1973
+ console.log("============================================================");
1974
+ if (mode === "partial" || skippedCount > 0) {
1975
+ console.log("⚠️ 已補齊缺少檔案,但仍要檢查入口連接");
1976
+ } else {
1977
+ console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
1978
+ }
1979
+ console.log("============================================================");
1955
1980
  if (conflictCount > 0) {
1956
1981
  console.log("⚠️ 狀態:有既有檔案需要人工確認,詳情見 migration report。");
1957
1982
  console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
1958
- console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
1959
- console.log("");
1960
- }
1961
- if (mode === "partial" || skippedCount > 0) {
1962
- console.log("你原本已有部分 AI 記憶檔,工具已保留它們,沒有覆寫。");
1963
- console.log("下一步先不要開始新任務;請在終端機執行以下預演,讓工具檢查能否安全補入口連接:");
1964
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run");
1965
- console.log("");
1966
- console.log("如預演顯示沒有 conflict,再執行:");
1967
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade");
1968
- console.log("============================================================");
1969
- return;
1970
- }
1971
- console.log("------------------------------------------------------------");
1972
- console.log("⚠️ 下面這句不是終端機指令。");
1973
- console.log("📋 請打開 Claude Code / Claude Cowork / OpenAI Codex / Google Antigravity,");
1974
- console.log(" 或任何能讀寫此資料夾的 AI 工具,新增對話後貼上:");
1975
- console.log("------------------------------------------------------------");
1976
- console.log(`Work in ${root}. I just installed agent-handoff-kit. Help me get started.`);
1977
- console.log("------------------------------------------------------------");
1978
- console.log("");
1979
- console.log("🚀 AI 會先確認這個資料夾,然後帶你選擇第一個任務情景:建構系統 / 工具 / 平台 / 網站或應用、研究報告、知識庫整理、學寫代碼,或其他。");
1980
- console.log("============================================================");
1981
- }
1983
+ console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
1984
+ console.log("");
1985
+ }
1986
+ if (mode === "partial" || skippedCount > 0) {
1987
+ console.log("你原本已有部分 AI 記憶檔,工具已保留它們,沒有覆寫。");
1988
+ console.log("下一步先不要開始新任務;請在終端機執行以下預演,讓工具檢查能否安全補入口連接:");
1989
+ console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run");
1990
+ console.log("");
1991
+ console.log("如預演顯示沒有 conflict,再執行:");
1992
+ console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade");
1993
+ console.log("============================================================");
1994
+ return;
1995
+ }
1996
+ console.log("------------------------------------------------------------");
1997
+ console.log("⚠️ 下面這句不是終端機指令。");
1998
+ console.log("📋 請打開 Claude Code / Claude Cowork / OpenAI Codex / Google Antigravity,");
1999
+ console.log(" 或任何能讀寫此資料夾的 AI 工具,新增對話後貼上:");
2000
+ console.log("------------------------------------------------------------");
2001
+ console.log(`Work in ${root}. I just installed agent-handoff-kit. Help me get started.`);
2002
+ console.log("------------------------------------------------------------");
2003
+ console.log("");
2004
+ console.log("🚀 AI 會先確認這個資料夾,然後帶你選擇第一個任務情景:建構系統 / 工具 / 平台 / 網站或應用、研究報告、知識庫整理、學寫代碼,或其他。");
2005
+ console.log("============================================================");
2006
+ }
1982
2007
 
1983
2008
  // R-031 v0.3.1+: Upgrade substantive next-step block. Distinct from install
1984
2009
  // (`printInstallNextSteps`) because the user is not first-time; pushing them through
1985
2010
  // the onboarding canonical phrase resets context they already have.
1986
- async function printUpgradeNextSteps(root, conflictCount, version, preUpgradeRootVersion) {
1987
- console.log("");
1988
- console.log("============================================================");
1989
- if (conflictCount > 0) {
1990
- console.log("⚠️ 升級未完成:有檔案需要人工確認");
1991
- console.log("============================================================");
1992
- console.log("⚠️ 狀態:有既有檔案需要人工確認,詳情見 migration report。");
1993
- console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
1994
- console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
1995
- console.log("============================================================");
1996
- return;
1997
- }
1998
- console.log("✅ 升級完成:Kit 檔案已更新到最新版本");
1999
- console.log("============================================================");
2000
- // R-031.2 v0.3.2+: Inline whatsnew summary — directly surface what changed in this
2011
+ async function printUpgradeNextSteps(root, conflictCount, version, preUpgradeRootVersion) {
2012
+ console.log("");
2013
+ console.log("============================================================");
2014
+ if (conflictCount > 0) {
2015
+ console.log("⚠️ 升級未完成:有檔案需要人工確認");
2016
+ console.log("============================================================");
2017
+ console.log("⚠️ 狀態:有既有檔案需要人工確認,詳情見 migration report。");
2018
+ console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
2019
+ console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
2020
+ console.log("============================================================");
2021
+ return;
2022
+ }
2023
+ console.log("✅ 升級完成:Kit 檔案已更新到最新版本");
2024
+ console.log("============================================================");
2025
+ // R-031.2 v0.3.2+: Inline whatsnew summary — directly surface what changed in this
2001
2026
  // version (and any intermediate versions the user skipped).
2002
2027
  // R-031.3 v0.3.3+: fromVersion now uses pre-upgrade snapshot (captured before
2003
2028
  // inject mutated PROJECT_INDEX), so the range narrative reflects actual user
2004
2029
  // journey instead of degenerate v{current} → v{current}.
2005
2030
  await printWhatsnew(root, version, preUpgradeRootVersion);
2006
- console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
2031
+ console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
2007
2032
  console.log("");
2008
2033
  console.log("💡 如想了解本版本新加了甚麼功能,可選用以下開工句(非強制):");
2009
2034
  console.log("------------------------------------------------------------");
2010
2035
  console.log(`Work in ${root}. I just upgraded agent-handoff-kit. Brief me on what changed in this version and what I should pay attention to.`);
2011
2036
  console.log("------------------------------------------------------------");
2012
2037
  console.log("");
2013
- console.log("🩺 升級驗收會在下方自動執行 doctor;若全綠即升級完成。");
2038
+ console.log("🩺 升級驗收會在下方自動執行 doctor;若全綠即升級完成。");
2014
2039
  console.log("============================================================");
2015
2040
  }
2016
2041
 
@@ -2056,7 +2081,7 @@ async function printWhatsnew(root, toVersion, fromVersionOverride) {
2056
2081
 
2057
2082
  if (relevant.length === 0) {
2058
2083
  console.log(`💡 本版 release notes:https://github.com/Adamchanadam/agent-handoff-kit/releases`);
2059
- console.log(` (v${fromVersion} → v${toVersion} 跨版本的完整變更見 GitHub Release 全列表)`);
2084
+ console.log(` (v${fromVersion} → v${toVersion} 跨版本的完整變更見 GitHub Release 全列表)`);
2060
2085
  console.log("");
2061
2086
  return;
2062
2087
  }
@@ -2072,12 +2097,12 @@ async function printWhatsnew(root, toVersion, fromVersionOverride) {
2072
2097
  const [oldMajor, oldMinor] = oldestAvailable.split(".").map((n) => Number.parseInt(n, 10));
2073
2098
  const isDeepRange = (fromMajor < oldMajor) || (fromMajor === oldMajor && fromMinor < oldMinor);
2074
2099
  if (isDeepRange) {
2075
- console.log(`💡 注意:本次升級 v${fromVersion} → v${toVersion} 跨度較大;本工具的版本說明只涵蓋由 v${oldestAvailable} 起的 ${relevant.length} 個版本。較舊版本(v${fromVersion} 至 v${oldestAvailable} 之前)的完整變更見:`);
2100
+ console.log(`💡 注意:本次升級 v${fromVersion} → v${toVersion} 跨度較大;本工具的版本說明只涵蓋由 v${oldestAvailable} 起的 ${relevant.length} 個版本。較舊版本(v${fromVersion} 至 v${oldestAvailable} 之前)的完整變更見:`);
2076
2101
  console.log(` https://github.com/Adamchanadam/agent-handoff-kit/releases`);
2077
2102
  console.log("");
2078
2103
  }
2079
2104
 
2080
- console.log(`📰 本次升級涵蓋 ${relevant.length} 個版本的版本說明(${isDeepRange ? `由 v${oldestAvailable} 起` : `v${fromVersion} → v${toVersion}`}):`);
2105
+ console.log(`📰 本次升級涵蓋 ${relevant.length} 個版本的版本說明(${isDeepRange ? `由 v${oldestAvailable} 起` : `v${fromVersion} → v${toVersion}`}):`);
2081
2106
  console.log("");
2082
2107
 
2083
2108
  const toShow = relevant.length <= 3 ? relevant : [relevant[0], relevant[relevant.length - 1]];
@@ -2091,7 +2116,7 @@ async function printWhatsnew(root, toVersion, fromVersionOverride) {
2091
2116
  console.log(content.trimEnd());
2092
2117
  console.log("");
2093
2118
  if (i === 0 && elidedCount > 0) {
2094
- console.log(` ⋯ 中間 ${elidedCount} 個版本的版本說明略;完整列表見 https://github.com/Adamchanadam/agent-handoff-kit/releases ⋯`);
2119
+ console.log(` ⋯ 中間 ${elidedCount} 個版本的版本說明略;完整列表見 https://github.com/Adamchanadam/agent-handoff-kit/releases ⋯`);
2095
2120
  console.log("");
2096
2121
  }
2097
2122
  } catch {
@@ -2108,33 +2133,33 @@ async function printWhatsnew(root, toVersion, fromVersionOverride) {
2108
2133
  // short factual message and return. Saves disk (no migration report) + reduces noise
2109
2134
  // (no self-check doctor) + avoids misleading "安裝完成" framing for an idempotent
2110
2135
  // operation where nothing changed.
2111
- async function assessUpgradeNoopHealth(root) {
2112
- try {
2113
- const handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
2114
- return { handoffLifecycle: assessHandoffLifecycleConsistency(handoffText) };
2115
- } catch {
2116
- return { handoffLifecycle: { ok: false, reason: "dev/SESSION_HANDOFF.md unreadable" } };
2117
- }
2118
- }
2119
-
2120
- function printUpgradeNoopShortCircuit(version, health = { handoffLifecycle: { ok: true } }) {
2121
- console.log("");
2122
- console.log(`📦 版本:v${version}`);
2123
- console.log("🛠️ 模式:upgrade-existing");
2124
- console.log("🔎 剛完成:檢查所有 Kit 檔案的狀態(含 AGENTS.md、dev/SESSION_HANDOFF.md、dev/PROJECT_INDEX.md 等)。");
2125
- if (health.handoffLifecycle?.ok) {
2126
- console.log("✅ 結果:你已經是最新版本,沒有檔案需要建立或合併;用戶填寫的內容全部保留現狀。");
2127
- console.log("");
2128
- console.log("🚀 下一步:回到原本的 AI 對話或開工句即可;如果剛完成任務,記得在 AI 對話輸入「收工」保存交接。");
2129
- console.log("");
2130
- return;
2131
- }
2132
- console.log("⚠️ 結果:Kit 檔案已是最新版本,沒有檔案需要建立或合併;但交接狀態仍需 AI closeout 核對。");
2133
- console.log("");
2134
- console.log("🚀 下一步:先執行 doctor 取得待修項,再把輸出貼給 AI;不要重裝或覆寫用戶內容。");
2135
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest doctor");
2136
- console.log("");
2137
- }
2136
+ async function assessUpgradeNoopHealth(root) {
2137
+ try {
2138
+ const handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
2139
+ return { handoffLifecycle: assessHandoffLifecycleConsistency(handoffText) };
2140
+ } catch {
2141
+ return { handoffLifecycle: { ok: false, reason: "dev/SESSION_HANDOFF.md unreadable" } };
2142
+ }
2143
+ }
2144
+
2145
+ function printUpgradeNoopShortCircuit(version, health = { handoffLifecycle: { ok: true } }) {
2146
+ console.log("");
2147
+ console.log(`📦 版本:v${version}`);
2148
+ console.log("🛠️ 模式:upgrade-existing");
2149
+ console.log("🔎 剛完成:檢查所有 Kit 檔案的狀態(含 AGENTS.md、dev/SESSION_HANDOFF.md、dev/PROJECT_INDEX.md 等)。");
2150
+ if (health.handoffLifecycle?.ok) {
2151
+ console.log("✅ 結果:你已經是最新版本,沒有檔案需要建立或合併;用戶填寫的內容全部保留現狀。");
2152
+ console.log("");
2153
+ console.log("🚀 下一步:回到原本的 AI 對話或開工句即可;如果剛完成任務,記得在 AI 對話輸入「收工」保存交接。");
2154
+ console.log("");
2155
+ return;
2156
+ }
2157
+ console.log("⚠️ 結果:Kit 檔案已是最新版本,沒有檔案需要建立或合併;但交接狀態仍需 AI closeout 核對。");
2158
+ console.log("");
2159
+ console.log("🚀 下一步:先執行 doctor 取得待修項,再把輸出貼給 AI;不要重裝或覆寫用戶內容。");
2160
+ console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest doctor");
2161
+ console.log("");
2162
+ }
2138
2163
 
2139
2164
  function listOrNone(items) {
2140
2165
  if (items.length === 0) return ["- none"];
@@ -2159,38 +2184,38 @@ Usage:
2159
2184
  agent-handoff-kit upgrade [--dry-run] [--yes] [--root <path>]
2160
2185
  agent-handoff-kit doctor [--root <path>]
2161
2186
 
2162
- Commands:
2163
- init Plan or install missing core files and rule packs.
2164
- upgrade Preserve existing files; merge safe core updates or report conflicts.
2165
- doctor Check required installed files.
2166
-
2167
- 中文速讀:
2168
- ✅ 第一次用:先在項目資料夾執行 init。
2169
- 🔄 已裝過:先用 upgrade --dry-run 預演,再決定是否正式升級。
2170
- 🩺 不確定狀態:用 doctor 檢查;doctor 只檢查,不會改檔。
2171
-
2172
- 安裝之後:
2173
- 不要把顯示出來的 "Work in ..." 文字輸入終端機。
2174
- 請打開 Claude Code / Claude Cowork / OpenAI Codex / Google Antigravity,
2175
- 或任何能讀寫此資料夾的 AI 工具,新增對話後貼上那句起步句。
2176
- 這句會啟動新手引導;AI 會先帶你選擇情境,
2177
- 再一步一步整理第一個任務。
2178
-
2179
- 終端機範例:
2180
- npx --yes @adamchanadam/agent-handoff-kit@latest init
2181
- npx --yes @adamchanadam/agent-handoff-kit@latest doctor
2182
- npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run
2183
-
2184
- 以上才是建議的 npx 用戶路徑。裸寫不帶 --yes / @latest 的 npx doctor
2185
- 不是本工具的建議用戶路徑,容易先出現 npm 自己的安裝提示。
2186
-
2187
- 即使資料夾已有 AGENTS.md 或 dev/,電腦也未必已經有可直接執行的工具;
2188
- npx --yes 只是先取得工具,然後才執行你指定的 init / doctor / upgrade。
2189
-
2190
- 放在 package 名稱前的 --yes 只讓 npm 先取得執行工具,避免額外出現
2191
- "Need to install" 提示。真正會建立項目文件的是 init;doctor 只檢查。
2192
- `);
2193
- console.log(`📦 版本:v${version}`);
2194
- console.log(`🛠️ 模式:help ready`);
2195
- console.log(`🚀 下一步:新項目先執行 init;舊項目先執行 upgrade --dry-run;只想檢查才執行 doctor。`);
2196
- }
2187
+ Commands:
2188
+ init Plan or install missing core files and rule packs.
2189
+ upgrade Preserve existing files; merge safe core updates or report conflicts.
2190
+ doctor Check required installed files.
2191
+
2192
+ 中文速讀:
2193
+ ✅ 第一次用:先在項目資料夾執行 init。
2194
+ 🔄 已裝過:先用 upgrade --dry-run 預演,再決定是否正式升級。
2195
+ 🩺 不確定狀態:用 doctor 檢查;doctor 只檢查,不會改檔。
2196
+
2197
+ 安裝之後:
2198
+ 不要把顯示出來的 "Work in ..." 文字輸入終端機。
2199
+ 請打開 Claude Code / Claude Cowork / OpenAI Codex / Google Antigravity,
2200
+ 或任何能讀寫此資料夾的 AI 工具,新增對話後貼上那句起步句。
2201
+ 這句會啟動新手引導;AI 會先帶你選擇情境,
2202
+ 再一步一步整理第一個任務。
2203
+
2204
+ 終端機範例:
2205
+ npx --yes @adamchanadam/agent-handoff-kit@latest init
2206
+ npx --yes @adamchanadam/agent-handoff-kit@latest doctor
2207
+ npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run
2208
+
2209
+ 以上才是建議的 npx 用戶路徑。裸寫不帶 --yes / @latest 的 npx doctor
2210
+ 不是本工具的建議用戶路徑,容易先出現 npm 自己的安裝提示。
2211
+
2212
+ 即使資料夾已有 AGENTS.md 或 dev/,電腦也未必已經有可直接執行的工具;
2213
+ npx --yes 只是先取得工具,然後才執行你指定的 init / doctor / upgrade。
2214
+
2215
+ 放在 package 名稱前的 --yes 只讓 npm 先取得執行工具,避免額外出現
2216
+ "Need to install" 提示。真正會建立項目文件的是 init;doctor 只檢查。
2217
+ `);
2218
+ console.log(`📦 版本:v${version}`);
2219
+ console.log(`🛠️ 模式:help ready`);
2220
+ console.log(`🚀 下一步:新項目先執行 init;舊項目先執行 upgrade --dry-run;只想檢查才執行 doctor。`);
2221
+ }