@adamchanadam/agent-handoff-kit 0.3.11 → 0.3.13

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