@adamchanadam/agent-handoff-kit 0.3.37 → 0.3.39

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,10 +2,12 @@
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";
5
+ import { chmod, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { hostname } from "node:os";
6
8
  import path from "node:path";
7
9
  import { fileURLToPath } from "node:url";
8
- import { assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
10
+ import { assessPromptMirrorRoot, assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
9
11
 
10
12
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
13
  const packageRoot = path.resolve(__dirname, "..");
@@ -28,8 +30,9 @@ const mappings = [
28
30
  ["packs/agent-governance.md", "dev/rules/agent-governance.md"],
29
31
  ["packs/release.md", "dev/rules/release.md"],
30
32
  ["packs/knowledge.md", "dev/rules/knowledge.md"],
31
- ["packs/communication.md", "dev/rules/communication.md"],
32
- ["packs/onboarding.md", "dev/rules/onboarding.md"],
33
+ ["packs/communication.md", "dev/rules/communication.md"],
34
+ ["packs/closeout.md", "dev/rules/closeout.md"],
35
+ ["packs/onboarding.md", "dev/rules/onboarding.md"],
33
36
  ["packs/integrations.md", "dev/rules/integrations.md"]
34
37
  ];
35
38
 
@@ -37,66 +40,78 @@ const requiredTargets = mappings.map(([, target]) => target);
37
40
  const rulePackTargets = mappings
38
41
  .map(([, target]) => target)
39
42
  .filter((target) => target.startsWith("dev/rules/"));
40
- const managedCoreStart = "<!-- BEGIN Agent Handoff Kit managed core -->";
41
- const managedCoreEnd = "<!-- END Agent Handoff Kit managed core -->";
43
+ const managedCoreStart = "<!-- BEGIN Agent Handoff Kit managed core -->";
44
+ const managedCoreEnd = "<!-- END Agent Handoff Kit managed core -->";
45
+ const credentialLeakPatterns = [
46
+ { pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key" },
47
+ { pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "sk-prefixed token" },
48
+ { pattern: /\bntn_[A-Za-z0-9_-]{40,}/, label: "Notion token" },
49
+ { pattern: /\bsecret_[A-Za-z0-9_-]{40,}/, label: "secret-prefixed token" },
50
+ { pattern: /\bya29\.[A-Za-z0-9_-]{20,}/, label: "Google OAuth token" },
51
+ { pattern: /\b1\/\/[A-Za-z0-9_-]{30,}/, label: "Google refresh token" },
52
+ { pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}/, label: "Slack token" },
53
+ { pattern: /\b(?:ghp|gho|ghs)_[A-Za-z0-9]{36}/, label: "GitHub token" },
54
+ { pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/, label: "GitHub fine-grained token" },
55
+ { pattern: /\bsl\.[A-Za-z0-9_-]{50,}/, label: "Dropbox token" },
56
+ { pattern: /\bAKIA[A-Z0-9]{16}/, label: "AWS access key" },
57
+ { pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key" }
58
+ ];
42
59
 
43
60
  const requiredAnchors = [
44
- {
45
- target: "AGENTS.md",
46
- label: "startup read order",
47
- snippets: [
48
- "## 1. Startup Reads",
49
- "dev/SESSION_HANDOFF.md",
50
- "dev/SESSION_LOG.md",
51
- "dev/PROJECT_INDEX.md",
52
- "dev/RULE_PACKS.md",
53
- "Agent Handoff Kit v<version>",
54
- "Display version rule",
55
- "Agent Handoff Kit template version",
61
+ {
62
+ target: "AGENTS.md",
63
+ label: "continuity-first startup and proportional work",
64
+ snippets: [
65
+ "## 1. Intent And Startup",
66
+ "dev/SESSION_HANDOFF.md",
67
+ "Do not read `dev/SESSION_LOG.md` during ordinary startup",
68
+ "dev/PROJECT_INDEX.md",
69
+ "dev/RULE_PACKS.md",
70
+ "Agent Handoff Kit v<version>",
56
71
  "continuity ready",
57
72
  "推薦下一步",
58
- "recommended action",
59
73
  "Start Agent Handoff",
60
- "Ambiguous startup phrases",
61
- "Reachable is not the same as ingested",
62
- "Do not treat unread sources as absent",
63
- "Task contract changes are durable facts",
64
- "External Impact Note",
65
- "ARTIFACT GOVERNANCE GATE",
66
- // R-030 v0.3.0+: forces managed-core merge on v0.2.x → v0.3.0 upgrade to propagate
67
- // startup availability probe + integrations pack reference + credential separation discipline.
68
- "startup availability probe",
69
- "dev/rules/integrations.md",
70
- "Credential separation"
71
- ]
72
- },
73
- {
74
- target: "AGENTS.md",
75
- label: "closeout intent and full handoff",
76
- snippets: [
77
- "Detect end-of-session or handoff intent",
78
- "收工",
79
- "Wrap up Agent Handoff",
80
- "Ambiguous closeout phrases",
81
- "wrap up",
82
- "handoff",
83
- "Reconcile `dev/SESSION_HANDOFF.md`",
84
- "Add a concise entry to `dev/SESSION_LOG.md`",
85
- "Closeout Write Contract",
86
- "ack:log-entry:start/end",
87
- "next-session opening message",
88
- "fenced `text` code block",
89
- "handoff saved",
90
- "Use the same display version rule as startup",
91
- "Never print the literal placeholder `v<version>`",
92
- "next-session startup entry",
93
- "State Reconciliation Check",
94
- "handoff lifecycle consistency",
95
- "A final chat summary without updated handoff/log/prompt evidence is not closeout",
96
- "Do not append a new state snapshot",
97
- "START_NEXT_SESSION_PROMPT.txt"
98
- ]
99
- },
74
+ "A fresh install or short message only makes guidance available",
75
+ "Direct ordinary tasks do not show the card",
76
+ "Reachable is not the same as ingested",
77
+ "Proportionate Work Loop",
78
+ "Pack loading is normally silent",
79
+ "dev/rules/integrations.md",
80
+ "Probe an integration only immediately before a task uses it"
81
+ ]
82
+ },
83
+ {
84
+ target: "AGENTS.md",
85
+ label: "closeout trigger and invariants",
86
+ snippets: [
87
+ "## 4. Closeout Trigger",
88
+ "收工",
89
+ "Wrap up Agent Handoff",
90
+ "wrap up",
91
+ "handoff",
92
+ "dev/rules/closeout.md",
93
+ "Current state lives in `dev/SESSION_HANDOFF.md`",
94
+ "no third full copy is retained",
95
+ "START_NEXT_SESSION_PROMPT.txt"
96
+ ]
97
+ },
98
+ {
99
+ target: "dev/rules/closeout.md",
100
+ label: "closeout pack complete contract",
101
+ snippets: [
102
+ "Closeout Pack",
103
+ "single detailed contract",
104
+ "Reconcile lifecycle state",
105
+ "Completed This Session",
106
+ "prompt-mirror verification result",
107
+ "Mark first-use guidance",
108
+ "Maintenance Trigger Check",
109
+ "START_NEXT_SESSION_PROMPT.txt",
110
+ "omit the full opening message by design",
111
+ "handoff saved",
112
+ "Stop Conditions"
113
+ ]
114
+ },
100
115
  {
101
116
  target: "dev/SESSION_HANDOFF.md",
102
117
  label: "handoff workspace and opening message schema",
@@ -116,11 +131,11 @@ const requiredAnchors = [
116
131
  "ack:section:next-session-opening-message",
117
132
  "ack:field:recommended-next-step-explicit",
118
133
  "ack:field:lifecycle-conflicts-resolved",
119
- "ack:field:persistence-routing-checked",
120
- "📋 Next session:",
121
- "```text",
122
- "Read in order:",
123
- "dev/DOC_SYNC_REGISTRY.md"
134
+ "ack:field:persistence-routing-checked",
135
+ "ack:field:first-use-guidance-state",
136
+ "📋 Next session:",
137
+ "```text",
138
+ "Do not read dev/SESSION_LOG.md during ordinary startup"
124
139
  ]
125
140
  },
126
141
  {
@@ -136,7 +151,7 @@ const requiredAnchors = [
136
151
  },
137
152
  {
138
153
  target: "dev/SESSION_LOG.md",
139
- label: "session log event and opening message schema",
154
+ label: "session log event schema without prompt copy",
140
155
  placement: sessionLogAnchorPlacement,
141
156
  snippets: [
142
157
  "ack:section:session-log-preamble",
@@ -146,13 +161,10 @@ const requiredAnchors = [
146
161
  "Record what actually happened in the session",
147
162
  "## Entry Template",
148
163
  "- **QC:**",
149
- "- **Sync:**",
150
- "- **Log maintenance:**",
151
- "### Next Session Opening Message",
152
- "📋 Next session:",
153
- "```text",
154
- "Read in order:",
155
- "dev/DOC_SYNC_REGISTRY.md"
164
+ "- **Sync:**",
165
+ "- **Log maintenance:**",
166
+ "- **Opening-message mirror:**",
167
+ "full text omitted by design"
156
168
  ]
157
169
  },
158
170
  {
@@ -174,10 +186,10 @@ const requiredAnchors = [
174
186
  label: "log retention and evidence schema",
175
187
  placement: sessionLogAnchorPlacement,
176
188
  snippets: [
177
- "kept, summarized, or archived",
178
- "Do not remove validation evidence",
179
- "latest opening message",
180
- "not current state"
189
+ "kept, summarized, or archived",
190
+ "Do not remove validation evidence",
191
+ "full opening message never belongs in this log",
192
+ "not current state"
181
193
  ]
182
194
  },
183
195
  {
@@ -215,7 +227,8 @@ const requiredAnchors = [
215
227
  "browser profiles",
216
228
  "desktop app sessions",
217
229
  "shared tool servers",
218
- "notebook kernels"
230
+ "notebook kernels",
231
+ "Short-lived localhost validation services"
219
232
  ]
220
233
  },
221
234
  {
@@ -243,7 +256,9 @@ const requiredAnchors = [
243
256
  "Onboarding Pack",
244
257
  "transient pack",
245
258
  "Explicit onboarding signal keywords",
246
- "5-step walk-through pattern",
259
+ "Continuity startup boundary",
260
+ "starts continuity and reads the current handoff state; it is not an onboarding signal",
261
+ "Infer when sufficient; ask only when unresolved",
247
262
  "Application Scenario Library",
248
263
  "Scenario A. Build systems, tools, platforms, websites, or apps",
249
264
  "Scenario B. Organize research or write a report",
@@ -277,6 +292,8 @@ const requiredAnchors = [
277
292
  "Runtime-Controlled Tool Operation Variants",
278
293
  "Tool Operation References",
279
294
  "Do not guess Chrome, Playwright, or DevTools commands",
295
+ "Local HTML / app validation fallback",
296
+ "`file://` rejection alone is not enough evidence to stop",
280
297
  "Anti-pattern"
281
298
  ]
282
299
  }
@@ -319,27 +336,29 @@ const schemaChecks = [
319
336
  marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
320
337
  marker("field", "user-intent", "User intent:"),
321
338
  marker("field", "task-essence", "Task essence:"),
322
- marker("field", "success-criteria", "Success criteria:")
339
+ marker("field", "success-criteria", "Success criteria:")
340
+ ,marker("field", "first-use-guidance-state", "First-use guidance state:")
323
341
  ]
324
342
  },
325
343
  {
326
344
  target: "dev/SESSION_HANDOFF.md",
327
345
  label: "handoff opening message structure",
328
346
  checks: [
329
- includes("📋 Next session:"),
330
- includes("```text"),
331
- includes("Work in "),
332
- includes("Read in order:"),
333
- includes("If this root does not match the expected project root")
347
+ includes("📋 Next session:"),
348
+ includes("```text"),
349
+ includes("Work in "),
350
+ includes("Read AGENTS.md, then dev/SESSION_HANDOFF.md"),
351
+ includes("Do not read dev/SESSION_LOG.md during ordinary startup")
334
352
  ]
335
353
  },
336
354
  {
337
355
  target: "dev/SESSION_HANDOFF.md",
338
- label: "handoff lifecycle consistency",
356
+ label: "handoff lifecycle mechanical checks",
339
357
  checks: [
340
- {
341
- label: "completed work is not carried forward as unresolved next work",
342
- test: (text) => assessHandoffLifecycleConsistency(text).ok
358
+ {
359
+ label: "completed work is not carried forward as unresolved next work",
360
+ test: (text) => assessHandoffLifecycleConsistency(text).ok,
361
+ explain: (text) => assessHandoffLifecycleConsistency(text).reason
343
362
  }
344
363
  ]
345
364
  },
@@ -360,8 +379,13 @@ const schemaChecks = [
360
379
  includes("- **Evidence disposition:**"),
361
380
  includes("- **Sync:**"),
362
381
  includes("- **Pending:**"),
363
- includes("- **Risks:**"),
364
- includes("- **Log maintenance:**")
382
+ includes("- **Risks:**"),
383
+ includes("- **Log maintenance:**"),
384
+ includes("- **Opening-message mirror:**"),
385
+ {
386
+ label: "SESSION_LOG does not contain a full opening-message copy",
387
+ test: (text) => !text.includes("Read AGENTS.md, then dev/SESSION_HANDOFF.md. Trust the handoff over this generated mirror.")
388
+ }
365
389
  ]
366
390
  },
367
391
  {
@@ -376,6 +400,10 @@ const schemaChecks = [
376
400
  heading("Installed Integrations"),
377
401
  heading("Tool Operation References"),
378
402
  heading("Local QC Commands"),
403
+ {
404
+ label: "Installed Integrations and Tool Operation References are unique real H2 sections before Local QC Commands",
405
+ test: (text) => projectIndexGovernanceSectionsAreValid(text)
406
+ },
379
407
  heading("Workspace Identity"),
380
408
  heading("Change Hotspots"),
381
409
  heading("Maintenance Rule"),
@@ -423,20 +451,40 @@ const schemaChecks = [
423
451
  // R-029 v0.2.1+: routing table must include onboarding pack first-time signal row.
424
452
  // Without this anchor, the upgrade flow may silently leave v0.1.X users with a
425
453
  // stale routing table that does not route onboarding signals.
426
- includes("First-time user signals"),
427
- includes("dev/rules/onboarding.md"),
454
+ includes("Explicit onboarding requests"),
455
+ includes("dev/rules/onboarding.md"),
456
+ includes("fresh install"),
457
+ includes("dev/rules/closeout.md"),
428
458
  // R-030 v0.3.0+: routing table must include integrations pack row.
429
459
  includes("dev/rules/integrations.md"),
430
460
  includes("External tool resource pressure"),
431
461
  includes("ownership-based external-tool resource closeout"),
462
+ includes("local HTML validation"),
463
+ includes("localhost fallback"),
432
464
  includes("Governance bridge / bridge governance"),
433
465
  includes("equivalent Chinese user phrases"),
434
466
  includes("scan for unbridged governance documents"),
435
467
  includes("scan for unbridged governance documents")
436
468
  ]
437
469
  },
438
- {
439
- target: "dev/rules/agent-governance.md",
470
+ {
471
+ target: "dev/rules/closeout.md",
472
+ label: "closeout pack structure",
473
+ checks: [
474
+ heading("Scope"),
475
+ heading("Required Reads"),
476
+ heading("Write Contract"),
477
+ heading("Full Closeout"),
478
+ heading("Maintenance Trigger Check"),
479
+ heading("Opening Message And Card"),
480
+ heading("Stop Conditions"),
481
+ includes("full opening message"),
482
+ includes("first-use guidance"),
483
+ includes("START_NEXT_SESSION_PROMPT.txt")
484
+ ]
485
+ },
486
+ {
487
+ target: "dev/rules/agent-governance.md",
440
488
  label: "agent governance pack structure",
441
489
  checks: [
442
490
  heading("Scope"),
@@ -563,9 +611,25 @@ async function needsProjectIndexVersionInject(root, command, version) {
563
611
  return false;
564
612
  }
565
613
 
566
- async function runInstall(command, root, options, version) {
567
- const mode = await detectMode(root);
568
- const plan = await buildPlan(root, command, version);
614
+ async function runInstall(command, root, options, version) {
615
+ if (options.dryRun) await assertDryRunHasNoPendingTransaction(root);
616
+ else await recoverInterruptedTransaction(root);
617
+ const installedVersion = await readInstalledTemplateVersion(root);
618
+ if (command === "upgrade" && installedVersion && compareSemver(installedVersion, version) > 0) {
619
+ printCard(version, "upgrade blocked", "x.x");
620
+ console.log(`selected root: ${root}`);
621
+ console.log(`status: blocked`);
622
+ console.log(`reason: project template v${installedVersion} is newer than this CLI v${version}`);
623
+ console.log("no files written: use an equal or newer Agent Handoff Kit CLI; downgrade requires a separately designed command");
624
+ process.exitCode = 1;
625
+ return;
626
+ }
627
+ const mode = await detectMode(root);
628
+ const plan = await buildPlan(root, command, version);
629
+ // Validate the operator-selected path before every exit path, including
630
+ // dry-run, conflicts, and already-current no-op upgrades. Otherwise a
631
+ // junction can be silently accepted whenever there is nothing to write.
632
+ await validateTransactionRoot(root, plan, { createMissingRoot: !options.dryRun });
569
633
 
570
634
  // R-031 v0.3.1+: plan-time upgrade no-op detection. When upgrade has zero
571
635
  // create/merge/conflict actions (skip-only), skip the full plan listing +
@@ -607,150 +671,566 @@ async function runInstall(command, root, options, version) {
607
671
 
608
672
  printPlan(command, root, mode, plan, version, options.dryRun);
609
673
 
610
- if (options.dryRun) {
674
+ if (options.dryRun) {
611
675
  console.log("\ndry-run: no files written");
612
676
  printDryRunExplanation(command, mode, plan);
613
677
  if (plan.some((item) => item.action === "conflict")) process.exitCode = 1;
614
- return;
615
- }
616
-
617
- if (!options.yes) {
678
+ return;
679
+ }
680
+
681
+ if (plan.some((item) => item.action === "conflict")) {
682
+ console.log("");
683
+ console.log("⛔ 升級預檢發現 conflict;治理目標檔、版本與 migration artifact 均沒有寫入。");
684
+ console.log("📋 下一步:根據上方 conflict 資料作非破壞性合併;不要以舊版本資料列當作已完成。");
685
+ process.exitCode = 1;
686
+ return;
687
+ }
688
+
689
+ if (!options.yes) {
618
690
  const ok = await confirmWrite();
619
691
  if (!ok) {
620
692
  console.log("cancelled: no files written");
621
- return;
622
- }
623
- }
624
-
625
- const created = [];
626
- const merged = [];
627
- const conflicts = plan.filter((item) => item.action === "conflict");
628
- const stamp = migrationStamp();
629
- const migrationDir = path.join(root, "dev/governance_migrations", stamp);
630
- const backupDir = path.join(migrationDir, "backup");
631
-
632
- for (const item of plan) {
633
- if (item.action !== "create") continue;
634
- await mkdir(path.dirname(item.targetAbs), { recursive: true });
635
- if (item.targetRel === "AGENTS.md") {
636
- const sourceText = await readFile(item.sourceAbs, "utf8");
637
- await writeFile(item.targetAbs, mergeManagedBlock("", sourceText), "utf8");
638
- } else {
639
- await copyFile(item.sourceAbs, item.targetAbs);
640
- }
641
- created.push(item.targetRel);
642
- }
643
-
644
- await hydrateInitialOpeningPrompt(root, created);
645
-
646
- for (const item of plan) {
647
- if (item.action !== "merge") continue;
648
- const backupPath = path.join(backupDir, item.targetRel);
649
- await mkdir(path.dirname(backupPath), { recursive: true });
650
- await copyFile(item.targetAbs, backupPath);
651
- await writeFile(item.targetAbs, item.mergedText, "utf8");
652
- merged.push(item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
653
- }
654
-
655
- const promptRegenerated = await regeneratePromptFromHandoffIfHotEvidence(root, backupDir, merged);
656
- if (promptRegenerated) {
657
- console.log("auto-repair: START_NEXT_SESSION_PROMPT.txt - regenerate prompt from repaired handoff opening message");
658
- }
659
-
660
- // R-031.3 v0.3.4+: Inject current CLI version into PROJECT_INDEX template version
661
- // metadata row — placed AFTER the merge loop to avoid the ordering bug where merge
662
- // overwrites inject. Merge writes item.mergedText computed at plan-build phase
663
- // (which contains the pre-inject stale version row); if inject ran before merge,
664
- // merge would silently revert it. R-016 still protected: only the metadata row
665
- // mutates, user content rows (External Sources / Fact Base etc.) preserved.
666
- // The captured metadataUpdated object is passed to writeMigrationReport so the
667
- // audit trail records this mutation alongside file create/merge operations.
668
- let metadataUpdated = null;
669
- if (command === "upgrade" || created.includes("dev/PROJECT_INDEX.md")) {
670
- const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
671
- try {
672
- const text = await readFile(indexPath, "utf8");
673
- const m = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
674
- if (m && isStableSemver(m[1]) && compareSemver(m[1], version) < 0) {
675
- const updated = text.replace(
676
- /\| Agent Handoff Kit template version \| [\d.]+ \|/,
677
- `| Agent Handoff Kit template version | ${version} |`
678
- );
679
- await writeFile(indexPath, updated, "utf8");
680
- metadataUpdated = {
681
- file: "dev/PROJECT_INDEX.md",
682
- field: "Agent Handoff Kit template version",
683
- from: m[1],
684
- to: version
685
- };
686
- }
687
- } catch {
688
- // ignore — doctor anchor (R-016) only checks row existence, not specific value.
689
- }
690
- }
691
-
692
- const skippedCount = plan.filter((item) => item.action === "skip").length;
693
-
694
- // R-031 v0.3.1+: scenario branching. Upgrade no-op (零改動) short-circuits — skip
695
- // migration report, self-check doctor, install banner, onboarding canonical phrase.
696
- // Prevents misleading "安裝完成" framing when user is just verifying they are latest.
697
- // R-031.3 v0.3.4+: also short-circuit only when metadata is current. If only the
698
- // metadata row was stale (counts 0/0/0 but metadataUpdated truthy), user just
699
- // received a substantive upgrade — proceed through full ceremony so doctor
700
- // self-check confirms the inject result.
701
- const isUpgradeNoop = command === "upgrade"
702
- && created.length === 0
703
- && merged.length === 0
704
- && conflicts.length === 0
705
- && !metadataUpdated;
706
-
707
- if (isUpgradeNoop) {
708
- const noOpHealth = await assessUpgradeNoopHealth(root, version);
709
- printUpgradeNoopShortCircuit(version, noOpHealth);
710
- if (!noOpHealth.ok) process.exitCode = 1;
711
- return;
712
- }
713
-
714
- const report = await writeMigrationReport(root, command, mode, plan, created, merged, conflicts, migrationDir, backupDir, metadataUpdated);
715
- printInstallSummary(version, command, mode, root, {
716
- created: created.length,
717
- merged: merged.length,
718
- skipped: skippedCount,
719
- conflicts: conflicts.length,
720
- backupRel: merged.length > 0 ? path.relative(root, backupDir) : null,
721
- reportRel: path.relative(root, report)
722
- });
723
-
724
- // R-031 v0.3.1+: install vs upgrade narrative split.
725
- if (command === "upgrade") {
726
- printUpgradeNextSteps(root, conflicts.length);
727
- } else {
728
- printInstallNextSteps(root, conflicts.length, mode, skippedCount);
729
- }
730
-
731
- // R-024 upgrade.done self-check: after substantive upgrade writes, run doctor automatically.
732
- // The user must see whether the merged state actually reaches a clean health state.
733
- if (command === "upgrade" && conflicts.length === 0) {
734
- console.log("");
735
- console.log("------------------------------------------------------------");
736
- console.log("🩺 升級後自動檢查:正在檢查升級後的資料夾");
737
- console.log("------------------------------------------------------------");
738
- const doctorStatus = await runDoctor(root, version, { silentCard: true, context: "upgrade-self-check" });
739
- if (doctorStatus !== "passed") {
740
- console.log("");
741
- console.log("⚠️ 升級後自動檢查未通過;請看上方檢查輸出。");
742
- console.log("📋 下一步:把上面 doctor 輸出貼給 AI,請它先按提示修補後再宣稱 upgrade 完成。");
743
- process.exitCode = 1;
744
- } else {
745
- console.log("");
746
- console.log("✅ 升級驗收完成:doctor 已通過;可以繼續使用這個項目。");
747
- }
748
- }
749
-
750
- if (conflicts.length > 0) process.exitCode = 1;
751
- }
693
+ return;
694
+ }
695
+ }
696
+
697
+ await executeInstallTransaction(command, root, mode, plan, version);
698
+ }
752
699
 
753
- async function runDoctor(root, version, options = {}) {
700
+ async function readInstalledTemplateVersion(root) {
701
+ try {
702
+ const text = await readFile(path.join(root, "dev/PROJECT_INDEX.md"), "utf8");
703
+ const match = text.match(/\| Agent Handoff Kit template version \| ([\d.]+) \|/);
704
+ return match && isStableSemver(match[1]) ? match[1] : null;
705
+ } catch {
706
+ return null;
707
+ }
708
+ }
709
+
710
+ async function executeInstallTransaction(command, root, mode, plan, version) {
711
+ const outputs = await buildTransactionOutputs(command, root, plan, version);
712
+ if (outputs.length === 0) {
713
+ const health = await assessUpgradeNoopHealth(root, version);
714
+ printUpgradeNoopShortCircuit(version, health);
715
+ if (!health.ok) process.exitCode = 1;
716
+ return;
717
+ }
718
+
719
+ const credentialInputs = [];
720
+ for (const relative of requiredTargets) {
721
+ const buffer = await readOptionalBuffer(path.join(root, relative));
722
+ if (buffer) credentialInputs.push({ relative, text: decodeUtf8(buffer, relative).text });
723
+ }
724
+ const credentialFindings = detectCredentialValues(credentialInputs);
725
+ if (credentialFindings.length > 0) {
726
+ console.log("⛔ 升級已停止:待備份的治理檔疑似含有 credential value。");
727
+ console.log("機密值不會顯示或複製;請先移除並輪換機密,再重跑 upgrade。");
728
+ for (const finding of credentialFindings) console.log(`blocked ${finding.relative}:${finding.line} (${finding.label})`);
729
+ process.exitCode = 1;
730
+ return;
731
+ }
732
+
733
+ const transaction = await prepareTransaction(root, command, version, outputs, mode, plan);
734
+ try {
735
+ await validateTransactionOverlay(root, outputs);
736
+ transaction.journal.state = "committing";
737
+ await writeSecureJson(transaction.journalPath, transaction.journal);
738
+
739
+ let committedCount = 0;
740
+ const qaFailAfterCommit = Number.parseInt(process.env.AGENT_HANDOFF_KIT_QA_FAIL_AFTER_COMMIT ?? "", 10);
741
+ for (const entry of transaction.journal.entries) {
742
+ const output = outputs.find((item) => item.targetRel === entry.targetRel);
743
+ await atomicReplaceFromBuffer(root, output.targetAbs, output.after, transaction.id);
744
+ entry.committed = true;
745
+ committedCount += 1;
746
+ await writeSecureJson(transaction.journalPath, transaction.journal);
747
+ if (Number.isInteger(qaFailAfterCommit) && qaFailAfterCommit === committedCount) {
748
+ throw new Error(`QA fault injection after committed target ${committedCount}`);
749
+ }
750
+ }
751
+
752
+ transaction.journal.committedVersion = version;
753
+ transaction.journal.state = "committed";
754
+ transaction.journal.committedAt = new Date().toISOString();
755
+ await writeSecureJson(transaction.journalPath, transaction.journal);
756
+ if (process.env.AGENT_HANDOFF_KIT_QA_INTERRUPT_AFTER_JOURNAL_COMMIT === "1") {
757
+ const interruption = new Error("QA interruption after committed journal before migration report");
758
+ interruption.code = "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT";
759
+ throw interruption;
760
+ }
761
+ const reportPath = await writeTransactionReport(transaction);
762
+ await unlinkIfExists(transaction.lockPath);
763
+
764
+ const created = outputs.filter((item) => !item.before).map((item) => item.targetRel);
765
+ const merged = outputs.filter((item) => item.before).map((item) => item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
766
+ printInstallSummary(version, command, mode, root, {
767
+ created: created.length,
768
+ merged: merged.length,
769
+ skipped: plan.filter((item) => item.action === "skip").length,
770
+ conflicts: 0,
771
+ backupRel: path.relative(root, transaction.backupDir),
772
+ reportRel: path.relative(root, reportPath)
773
+ });
774
+ if (command === "upgrade") printUpgradeNextSteps(root, 0);
775
+ else printInstallNextSteps(root, 0, mode, plan.filter((item) => item.action === "skip").length);
776
+
777
+ if (command === "upgrade") {
778
+ console.log("");
779
+ console.log("✅ migration committed:離線遷移驗收已通過,版本代表本次成功提交。");
780
+ console.log("🩺 project health:現在執行完整 doctor;它的結果與 migration committed 分開。");
781
+ const doctorStatus = await runDoctor(root, version, { silentCard: true, context: "post-transaction-project-health" });
782
+ if (doctorStatus === "passed") console.log("✅ project health: passed");
783
+ else console.log("⚠️ project health: needs attention; migration remains committed because the deterministic migration gate passed");
784
+ }
785
+ } catch (error) {
786
+ if (error?.code === "ACK_QA_INTERRUPT_AFTER_JOURNAL_COMMIT") throw error;
787
+ transaction.journal.state = "rollback-needed";
788
+ transaction.journal.error = safeErrorLabel(error);
789
+ await writeSecureJson(transaction.journalPath, transaction.journal).catch(() => {});
790
+ const rollback = await rollbackTransaction(root, transaction.journal, transaction.journalPath);
791
+ if (rollback.ok) {
792
+ await unlinkIfExists(transaction.lockPath);
793
+ console.log("⚠️ migration rolled back:遷移驗收或寫入失敗,已復原本次交易所改動的目標。");
794
+ } else {
795
+ console.log("⛔ migration incomplete:現存檔案已出現第三種內容,工具沒有強制回滾以免覆寫後續修改。");
796
+ for (const conflict of rollback.conflicts) console.log(`blocked ${conflict}`);
797
+ }
798
+ throw error;
799
+ }
800
+ }
801
+
802
+ async function buildTransactionOutputs(command, root, plan, version) {
803
+ const byTarget = new Map();
804
+ for (const item of plan) {
805
+ if (item.action !== "create" && item.action !== "merge") continue;
806
+ const before = await readOptionalBuffer(item.targetAbs);
807
+ let afterText;
808
+ if (item.action === "create") {
809
+ const sourceText = await readFile(item.sourceAbs, "utf8");
810
+ afterText = item.targetRel === "AGENTS.md" ? mergeManagedBlock("", sourceText) : sourceText;
811
+ } else {
812
+ afterText = item.mergedText;
813
+ }
814
+ afterText = afterText.replaceAll("<absolute project root>", root);
815
+ byTarget.set(item.targetRel, {
816
+ targetRel: item.targetRel,
817
+ targetAbs: item.targetAbs,
818
+ before,
819
+ afterText,
820
+ reason: item.reason ?? item.action
821
+ });
822
+ }
823
+
824
+ const indexRel = "dev/PROJECT_INDEX.md";
825
+ const indexAbs = path.join(root, indexRel);
826
+ let indexOutput = byTarget.get(indexRel);
827
+ if (!indexOutput && (command === "upgrade" || await exists(indexAbs))) {
828
+ const before = await readOptionalBuffer(indexAbs);
829
+ if (before) indexOutput = { targetRel: indexRel, targetAbs: indexAbs, before, afterText: decodeUtf8(before, indexRel).text, reason: "template version metadata" };
830
+ }
831
+ if (indexOutput) {
832
+ const updated = indexOutput.afterText.replace(/\| Agent Handoff Kit template version \| [\d.]+ \|/, `| Agent Handoff Kit template version | ${version} |`);
833
+ indexOutput.afterText = updated;
834
+ byTarget.set(indexRel, indexOutput);
835
+ }
836
+
837
+ const handoffRel = "dev/SESSION_HANDOFF.md";
838
+ const promptRel = "START_NEXT_SESSION_PROMPT.txt";
839
+ const handoffOutput = byTarget.get(handoffRel);
840
+ const finalHandoffText = handoffOutput?.afterText ?? await readOptionalText(path.join(root, handoffRel));
841
+ if (finalHandoffText) {
842
+ const opening = extractOpeningMessage(finalHandoffText);
843
+ if (opening != null) {
844
+ const promptAbs = path.join(root, promptRel);
845
+ const promptBefore = await readOptionalBuffer(promptAbs);
846
+ const existing = byTarget.get(promptRel);
847
+ byTarget.set(promptRel, {
848
+ targetRel: promptRel,
849
+ targetAbs: promptAbs,
850
+ before: existing?.before ?? promptBefore,
851
+ afterText: opening.replaceAll("<absolute project root>", root),
852
+ reason: "regenerated from authoritative handoff opening message"
853
+ });
854
+ }
855
+ }
856
+
857
+ const outputs = [];
858
+ for (const item of byTarget.values()) {
859
+ const after = encodeLikeExisting(item.afterText, item.before, item.targetRel);
860
+ if (item.before && item.before.equals(after)) continue;
861
+ outputs.push({ ...item, after, beforeHash: item.before ? sha256(item.before) : null, afterHash: sha256(after) });
862
+ }
863
+ return outputs;
864
+ }
865
+
866
+ async function prepareTransaction(root, command, version, outputs, mode, plan) {
867
+ const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
868
+ const migrationsRoot = path.join(root, "dev", "governance_migrations");
869
+ const migrationDir = path.join(migrationsRoot, id);
870
+ const backupDir = path.join(migrationDir, "backup");
871
+ const stageDir = path.join(migrationDir, "stage");
872
+ const journalPath = path.join(migrationDir, "transaction.json");
873
+ const lockPath = path.join(migrationsRoot, ".upgrade.lock");
874
+ await mkdir(backupDir, { recursive: true });
875
+ await mkdir(stageDir, { recursive: true });
876
+ await tightenPermissions(migrationsRoot, 0o700);
877
+ await tightenPermissions(migrationDir, 0o700);
878
+ const lock = await open(lockPath, "wx", 0o600).catch((error) => {
879
+ if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
880
+ throw error;
881
+ });
882
+ await lock.writeFile(JSON.stringify({ id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath) }, null, 2));
883
+ await lock.close();
884
+
885
+ const entries = [];
886
+ for (const output of outputs) {
887
+ const stagePath = path.join(stageDir, output.targetRel);
888
+ await mkdir(path.dirname(stagePath), { recursive: true });
889
+ await writeFile(stagePath, output.after, { mode: 0o600 });
890
+ let backupRel = null;
891
+ if (output.before) {
892
+ const backupPath = path.join(backupDir, output.targetRel);
893
+ await mkdir(path.dirname(backupPath), { recursive: true });
894
+ await writeFile(backupPath, output.before, { mode: 0o600 });
895
+ backupRel = path.relative(root, backupPath);
896
+ }
897
+ entries.push({ targetRel: output.targetRel, existed: Boolean(output.before), beforeHash: output.beforeHash, afterHash: output.afterHash, backupRel, committed: false });
898
+ }
899
+ const journal = {
900
+ id,
901
+ command,
902
+ mode,
903
+ attemptedVersion: version,
904
+ committedVersion: null,
905
+ plannedSkips: plan.filter((item) => item.action === "skip").length,
906
+ host: hostname(),
907
+ pid: process.pid,
908
+ state: "prepared",
909
+ createdAt: new Date().toISOString(),
910
+ entries
911
+ };
912
+ await writeSecureJson(journalPath, journal);
913
+ return { id, migrationDir, backupDir, stageDir, journalPath, lockPath, journal };
914
+ }
915
+
916
+ async function validateTransactionRoot(root, plan, { createMissingRoot = true } = {}) {
917
+ let rootStats;
918
+ try {
919
+ rootStats = await lstat(root);
920
+ } catch (error) {
921
+ if (error?.code !== "ENOENT") throw error;
922
+ if (path.parse(path.resolve(root)).root === path.resolve(root)) throw new Error("selected root cannot be a filesystem root");
923
+ const parent = await nearestExistingParent(path.dirname(root));
924
+ if (!samePath(parent.lexical, parent.real)) throw new Error("selected root resolves through a symbolic link or junction; use the resolved project root");
925
+ if (!createMissingRoot) {
926
+ for (const item of plan) {
927
+ if (item.action !== "create" && item.action !== "merge") continue;
928
+ const relative = path.relative(path.resolve(root), path.resolve(item.targetAbs));
929
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`target escapes selected root: ${item.targetRel}`);
930
+ }
931
+ return;
932
+ }
933
+ await mkdir(root, { recursive: true });
934
+ rootStats = await lstat(root);
935
+ if (!isInside(parent.real, await realpath(root))) throw new Error("created root escaped its verified parent");
936
+ }
937
+ if (rootStats.isSymbolicLink()) throw new Error("selected root is a symbolic link or junction; use the resolved project root");
938
+ const realRoot = await realpath(root);
939
+ for (const item of plan) {
940
+ if (item.action !== "create" && item.action !== "merge") continue;
941
+ const relative = path.relative(root, item.targetAbs);
942
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) throw new Error(`target escapes selected root: ${item.targetRel}`);
943
+ const parent = await nearestExistingRealParent(path.dirname(item.targetAbs));
944
+ if (!isInside(realRoot, parent)) throw new Error(`target parent resolves outside selected root: ${item.targetRel}`);
945
+ try {
946
+ if ((await lstat(item.targetAbs)).isSymbolicLink()) throw new Error(`target is a symbolic link or junction: ${item.targetRel}`);
947
+ const buffer = await readFile(item.targetAbs);
948
+ decodeUtf8(buffer, item.targetRel);
949
+ } catch (error) {
950
+ if (error?.code !== "ENOENT") throw error;
951
+ }
952
+ }
953
+ }
954
+
955
+ async function validateTransactionOverlay(root, outputs) {
956
+ const outputMap = new Map(outputs.map((item) => [item.targetRel, decodeUtf8(item.after, item.targetRel).text]));
957
+ const finalText = async (relative) => outputMap.get(relative) ?? await readOptionalText(path.join(root, relative));
958
+ const failures = [];
959
+ for (const target of requiredTargets) if ((await finalText(target)) == null) failures.push(`${target}: missing after transaction`);
960
+ for (const rule of requiredAnchors) {
961
+ const text = await finalText(rule.target);
962
+ if (text == null) continue;
963
+ for (const failure of requiredAnchorFailures(rule, text)) failures.push(`${rule.target}: ${failure.kind} ${failure.snippet}`);
964
+ }
965
+ for (const rule of schemaChecks) {
966
+ const text = await finalText(rule.target);
967
+ if (text == null) continue;
968
+ for (const check of rule.checks) if (!check.test(text)) failures.push(`${rule.target}: ${check.label}`);
969
+ }
970
+
971
+ const handoffText = await finalText("dev/SESSION_HANDOFF.md");
972
+ const promptText = await finalText("START_NEXT_SESSION_PROMPT.txt");
973
+ if (handoffText && promptText) {
974
+ const otherTexts = [];
975
+ for (const target of requiredTargets) {
976
+ if (target === "dev/SESSION_HANDOFF.md" || target === "START_NEXT_SESSION_PROMPT.txt") continue;
977
+ const text = await finalText(target);
978
+ if (text) otherTexts.push({ relative: target, text });
979
+ }
980
+ const mirror = assessPromptMirrorTexts(handoffText, promptText, otherTexts);
981
+ if (!mirror.ok) failures.push(`prompt mirror: ${mirror.reason}`);
982
+ }
983
+ const bridgeFailures = await validateBridgeTexts(finalText);
984
+ failures.push(...bridgeFailures);
985
+ if (failures.length > 0) throw new Error(`migration acceptance gate failed: ${failures.slice(0, 12).join("; ")}${failures.length > 12 ? `; +${failures.length - 12} more` : ""}`);
986
+ }
987
+
988
+ async function validateBridgeTexts(finalText) {
989
+ const failures = [];
990
+ for (const target of ["CLAUDE.md", "GEMINI.md"]) {
991
+ const failure = bridgeTextFailure(target, await finalText(target) ?? "");
992
+ if (failure) failures.push(`${target}: ${failure}`);
993
+ }
994
+ return failures;
995
+ }
996
+
997
+ function bridgeTextFailure(targetRel, text) {
998
+ const active = stripMarkdownCommentsAndFences(text);
999
+ if (targetRel === "CLAUDE.md") {
1000
+ const imports = active.split(/\r?\n/).filter((line) => line.trim() === "@AGENTS.md");
1001
+ return imports.length === 1 ? null : `expected one active @AGENTS.md import, found ${imports.length}`;
1002
+ }
1003
+ if (targetRel === "GEMINI.md") {
1004
+ return /^Authoritative operating rules remain in `AGENTS\.md`\.\s*$/m.test(active)
1005
+ && /^2\. Read `AGENTS\.md`\.\s*$/m.test(active)
1006
+ ? null
1007
+ : "active AGENTS.md bridge instructions missing or misplaced";
1008
+ }
1009
+ return "unknown bridge target";
1010
+ }
1011
+
1012
+ async function atomicReplaceFromBuffer(root, targetAbs, buffer, id) {
1013
+ const relative = path.relative(root, targetAbs);
1014
+ if (relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("atomic target escaped root");
1015
+ await mkdir(path.dirname(targetAbs), { recursive: true });
1016
+ const tempPath = path.join(path.dirname(targetAbs), `.${path.basename(targetAbs)}.ack-${id}.tmp`);
1017
+ await writeFile(tempPath, buffer, { mode: 0o600 });
1018
+ await rename(tempPath, targetAbs);
1019
+ }
1020
+
1021
+ async function rollbackTransaction(root, journal, journalPath) {
1022
+ const conflicts = [];
1023
+ for (const entry of [...journal.entries].reverse()) {
1024
+ if (!entry.committed) continue;
1025
+ const targetAbs = path.join(root, entry.targetRel);
1026
+ const current = await readOptionalBuffer(targetAbs);
1027
+ const currentHash = current ? sha256(current) : null;
1028
+ if (currentHash === entry.beforeHash) continue;
1029
+ if (currentHash !== entry.afterHash) {
1030
+ conflicts.push(`${entry.targetRel}: current content differs from both transaction input and candidate`);
1031
+ continue;
1032
+ }
1033
+ if (entry.existed) {
1034
+ const backup = await readFile(path.join(root, entry.backupRel));
1035
+ await atomicReplaceFromBuffer(root, targetAbs, backup, `${journal.id}-rollback`);
1036
+ } else {
1037
+ await unlink(targetAbs);
1038
+ }
1039
+ }
1040
+ journal.state = conflicts.length === 0 ? "rolled-back" : "manual-recovery-required";
1041
+ journal.committedVersion = null;
1042
+ journal.rollbackAt = new Date().toISOString();
1043
+ journal.recoveryConflicts = conflicts;
1044
+ await writeSecureJson(journalPath, journal).catch(() => {});
1045
+ return { ok: conflicts.length === 0, conflicts };
1046
+ }
1047
+
1048
+ async function recoverInterruptedTransaction(root) {
1049
+ const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
1050
+ let lock;
1051
+ try {
1052
+ lock = JSON.parse(await readFile(lockPath, "utf8"));
1053
+ } catch (error) {
1054
+ if (error?.code === "ENOENT") return;
1055
+ throw new Error("upgrade lock exists but is unreadable; no writes attempted");
1056
+ }
1057
+ if (lock.host === hostname() && processIsAlive(lock.pid)) throw new Error(`another upgrade process is active (pid ${lock.pid})`);
1058
+ if (lock.host && lock.host !== hostname()) throw new Error(`upgrade lock belongs to another host (${lock.host}); no automatic recovery attempted`);
1059
+ const journalPath = path.resolve(root, lock.journal ?? "");
1060
+ if (!isInside(root, journalPath)) throw new Error("upgrade lock journal path escapes selected root");
1061
+ let journal;
1062
+ try {
1063
+ journal = JSON.parse(await readFile(journalPath, "utf8"));
1064
+ } catch {
1065
+ throw new Error("incomplete upgrade lock has no readable journal; no automatic recovery attempted");
1066
+ }
1067
+ if (journal.state === "committed") {
1068
+ if (!journal.committedVersion) journal.committedVersion = journal.attemptedVersion;
1069
+ const migrationDir = path.dirname(journalPath);
1070
+ await writeSecureJson(journalPath, journal);
1071
+ await writeTransactionReport({ id: journal.id, migrationDir, journal });
1072
+ await unlinkIfExists(lockPath);
1073
+ console.log("⚠️ recovered committed upgrade: migration report was verified or rebuilt before planning this run");
1074
+ return;
1075
+ }
1076
+ if (journal.state === "rolled-back") {
1077
+ await unlinkIfExists(lockPath);
1078
+ return;
1079
+ }
1080
+ const rollback = await rollbackTransaction(root, journal, journalPath);
1081
+ if (!rollback.ok) throw new Error(`interrupted upgrade has third-state edits: ${rollback.conflicts.join("; ")}`);
1082
+ await unlinkIfExists(lockPath);
1083
+ console.log("⚠️ recovered interrupted upgrade: transaction-owned changes were safely rolled back before planning this run");
1084
+ }
1085
+
1086
+ async function writeTransactionReport(transaction) {
1087
+ const reportPath = path.join(transaction.migrationDir, "migration-report.md");
1088
+ const lines = [
1089
+ "# Agent Handoff Kit Migration Report",
1090
+ "",
1091
+ `- Transaction: ${transaction.id}`,
1092
+ `- Mode: ${transaction.journal.mode ?? "unknown"}`,
1093
+ `- Attempted version: ${transaction.journal.attemptedVersion}`,
1094
+ `- Committed version: ${transaction.journal.committedVersion ?? "none"}`,
1095
+ `- Transaction state: ${transaction.journal.state}`,
1096
+ `- Created at: ${transaction.journal.createdAt}`,
1097
+ `- Committed at: ${transaction.journal.committedAt}`,
1098
+ "- Credential values: not recorded",
1099
+ "",
1100
+ "## Actions",
1101
+ "",
1102
+ ...transaction.journal.entries.map((entry) => `- ${entry.existed ? "merge" : "create"}: ${entry.targetRel}; backup=${entry.backupRel ?? "none"}; committed=${entry.committed}`),
1103
+ "",
1104
+ `- Planned skips: ${transaction.journal.plannedSkips ?? "unknown"}`,
1105
+ "- Conflicts: 0"
1106
+ ];
1107
+ await writeFile(reportPath, `${lines.join("\n")}\n`, { mode: 0o600 });
1108
+ await tightenPermissions(reportPath, 0o600);
1109
+ return reportPath;
1110
+ }
1111
+
1112
+ function decodeUtf8(buffer, relative) {
1113
+ const bom = buffer.length >= 3 && buffer[0] === 0xef && buffer[1] === 0xbb && buffer[2] === 0xbf;
1114
+ const body = bom ? buffer.subarray(3) : buffer;
1115
+ let text;
1116
+ try {
1117
+ text = new TextDecoder("utf-8", { fatal: true }).decode(body);
1118
+ } catch {
1119
+ throw new Error(`${relative}: invalid UTF-8; conflict required`);
1120
+ }
1121
+ const crlfCount = (text.match(/\r\n/g) ?? []).length;
1122
+ const loneLfCount = (text.match(/(^|[^\r])\n/g) ?? []).length;
1123
+ return {
1124
+ text,
1125
+ bom,
1126
+ newline: crlfCount > loneLfCount ? "\r\n" : "\n",
1127
+ mixed: crlfCount > 0 && loneLfCount > 0
1128
+ };
1129
+ }
1130
+
1131
+ function encodeLikeExisting(text, before, relative) {
1132
+ if (!before) return Buffer.from(text.replace(/\r\n?/g, "\n"), "utf8");
1133
+ const style = decodeUtf8(before, relative);
1134
+ const normalized = text.replace(/\r\n?/g, "\n").replace(/\n/g, style.newline);
1135
+ return style.bom ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(normalized, "utf8")]) : Buffer.from(normalized, "utf8");
1136
+ }
1137
+
1138
+ function detectCredentialValues(items) {
1139
+ const findings = [];
1140
+ for (const item of items) {
1141
+ for (const { pattern, label } of credentialLeakPatterns) {
1142
+ const match = item.text.match(pattern);
1143
+ if (match) findings.push({ relative: item.relative, line: item.text.slice(0, match.index).split("\n").length, label });
1144
+ }
1145
+ }
1146
+ return findings;
1147
+ }
1148
+
1149
+ async function nearestExistingRealParent(start) {
1150
+ let current = path.resolve(start);
1151
+ while (true) {
1152
+ try { return await realpath(current); } catch (error) {
1153
+ if (error?.code !== "ENOENT") throw error;
1154
+ const parent = path.dirname(current);
1155
+ if (parent === current) throw error;
1156
+ current = parent;
1157
+ }
1158
+ }
1159
+ }
1160
+
1161
+ async function nearestExistingParent(start) {
1162
+ let current = path.resolve(start);
1163
+ while (true) {
1164
+ try { return { lexical: current, real: await realpath(current) }; } catch (error) {
1165
+ if (error?.code !== "ENOENT") throw error;
1166
+ const parent = path.dirname(current);
1167
+ if (parent === current) throw error;
1168
+ current = parent;
1169
+ }
1170
+ }
1171
+ }
1172
+
1173
+ function samePath(left, right) {
1174
+ const normalize = (value) => process.platform === "win32" ? path.resolve(value).toLowerCase() : path.resolve(value);
1175
+ return normalize(left) === normalize(right);
1176
+ }
1177
+
1178
+ function isInside(root, candidate) {
1179
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
1180
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
1181
+ }
1182
+
1183
+ function sha256(buffer) {
1184
+ return createHash("sha256").update(buffer).digest("hex");
1185
+ }
1186
+
1187
+ async function readOptionalBuffer(filePath) {
1188
+ try { return await readFile(filePath); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
1189
+ }
1190
+
1191
+ async function readOptionalText(filePath) {
1192
+ const buffer = await readOptionalBuffer(filePath);
1193
+ return buffer ? decodeUtf8(buffer, filePath).text : null;
1194
+ }
1195
+
1196
+ async function writeSecureJson(filePath, value) {
1197
+ await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
1198
+ await tightenPermissions(filePath, 0o600);
1199
+ }
1200
+
1201
+ async function tightenPermissions(filePath, mode) {
1202
+ try { await chmod(filePath, mode); } catch { /* best effort on platforms without POSIX modes */ }
1203
+ }
1204
+
1205
+ async function unlinkIfExists(filePath) {
1206
+ try { await unlink(filePath); } catch (error) { if (error?.code !== "ENOENT") throw error; }
1207
+ }
1208
+
1209
+ function processIsAlive(pid) {
1210
+ if (!Number.isInteger(pid) || pid <= 0) return false;
1211
+ try { process.kill(pid, 0); return true; } catch { return false; }
1212
+ }
1213
+
1214
+ async function assertDryRunHasNoPendingTransaction(root) {
1215
+ const lockPath = path.join(root, "dev", "governance_migrations", ".upgrade.lock");
1216
+ try {
1217
+ await lstat(lockPath);
1218
+ } catch (error) {
1219
+ if (error?.code === "ENOENT") return;
1220
+ throw error;
1221
+ }
1222
+ throw new Error("dry-run blocked: an unresolved transaction requires a non-dry-run recovery; no files written");
1223
+ }
1224
+
1225
+ function stripMarkdownCommentsAndFences(text) {
1226
+ return text.replace(/<!--[\s\S]*?-->/g, "").replace(/```[\s\S]*?```/g, "");
1227
+ }
1228
+
1229
+ function safeErrorLabel(error) {
1230
+ return String(error?.message ?? error).slice(0, 500);
1231
+ }
1232
+
1233
+ async function runDoctor(root, version, options = {}) {
754
1234
  if (!options.silentCard) printCard(version, "doctor ready", "o.o");
755
1235
  const rows = [];
756
1236
  for (const target of requiredTargets) {
@@ -813,7 +1293,7 @@ async function runDoctor(root, version, options = {}) {
813
1293
  }
814
1294
  }
815
1295
 
816
- if (schemaFailures.length > 0) {
1296
+ if (schemaFailures.length > 0) {
817
1297
  printDoctorSummary(version, root, "needs-fix", {
818
1298
  checked: rows.length + anchorRows.length + schemaRows.length,
819
1299
  failedKind: "schema checks",
@@ -821,10 +1301,25 @@ async function runDoctor(root, version, options = {}) {
821
1301
  nextStep: "把這段 doctor 輸出貼給 AI,請它先修交接結構,不要直接重裝覆蓋。"
822
1302
  });
823
1303
  process.exitCode = 1;
824
- return "failed";
825
- }
826
-
827
- const researchTraceResult = await checkResearchDecisionTrace(root);
1304
+ return "failed";
1305
+ }
1306
+
1307
+ const bridgeFailures = await validateBridgeTexts(async (relative) => readOptionalText(path.join(root, relative)));
1308
+ console.log(`\nbridge checks: 2`);
1309
+ console.log(`${bridgeFailures.length === 0 ? "ok" : "missing"} CLAUDE.md / GEMINI.md (active one-hop AGENTS.md bridges)`);
1310
+ for (const finding of bridgeFailures) console.log(` missing: ${finding}`);
1311
+ if (bridgeFailures.length > 0) {
1312
+ printDoctorSummary(version, root, "needs-fix", {
1313
+ checked: rows.length + anchorRows.length + schemaRows.length + 2,
1314
+ failedKind: "bridge checks",
1315
+ failedCount: bridgeFailures.length,
1316
+ nextStep: "修正 CLAUDE.md / GEMINI.md 的有效橋接指令;註解、程式碼區塊或重複字樣不能代替真實路由。"
1317
+ });
1318
+ process.exitCode = 1;
1319
+ return "failed";
1320
+ }
1321
+
1322
+ const researchTraceResult = await checkResearchDecisionTrace(root);
828
1323
  console.log(`\nresearch decision trace checks: ${researchTraceResult.checked}`);
829
1324
  console.log(`${researchTraceResult.ok ? "ok" : "missing"} dev/PROJECT_DECISIONS.md (research-derived decision evidence chains)`);
830
1325
  if (!researchTraceResult.ok) {
@@ -860,7 +1355,7 @@ async function runDoctor(root, version, options = {}) {
860
1355
 
861
1356
  const artifactResult = await checkGeneratedMarkdownGovernance(root);
862
1357
  console.log(`\ngenerated markdown governance checks: ${artifactResult.checked}`);
863
- console.log(`${artifactResult.ok ? "ok" : "missing"} dev/PROJECT_INDEX.md (generated Markdown / durable artifact registration)`);
1358
+ console.log(`${artifactResult.ok ? "ok" : "missing"} dev/PROJECT_INDEX.md (generated Markdown registration; other formats require human review)`);
864
1359
  if (!artifactResult.ok) {
865
1360
  for (const finding of artifactResult.findings) {
866
1361
  console.log(` missing: ${finding}`);
@@ -869,7 +1364,7 @@ async function runDoctor(root, version, options = {}) {
869
1364
  checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked + artifactResult.checked,
870
1365
  failedKind: "generated markdown governance checks",
871
1366
  failedCount: artifactResult.findings.length,
872
- nextStep: "把新生成或新修改的 Markdown / durable artifact 登記到 dev/PROJECT_INDEX.md,或在 SESSION_LOG / task summary 明確標成 draft、temporary 或 one-time evidence;如內容重複,先合併到單一真源。"
1367
+ nextStep: "把新生成或新修改的 Markdown 登記到 dev/PROJECT_INDEX.md,或在 SESSION_LOG / task summary 以同一紀錄精確標成 draft、temporary 或 one-time evidence;如內容重複,先合併到單一真源。其他持久格式須由 AI 另作人工治理核對。"
873
1368
  });
874
1369
  process.exitCode = 1;
875
1370
  return "failed";
@@ -1071,15 +1566,38 @@ function isGeneratedArtifactCandidate(rel) {
1071
1566
 
1072
1567
  function isArtifactGoverned(rel, { indexText, logText, handoffText }) {
1073
1568
  const normalized = rel.replaceAll("\\", "/");
1074
- if (indexText.includes(normalized)) return true;
1569
+ if (projectIndexRegistersExactPath(indexText, normalized)) return true;
1570
+ return textExplicitlyClassifiesExactArtifact(logText, normalized)
1571
+ || textExplicitlyClassifiesExactArtifact(handoffText, normalized);
1572
+ }
1573
+
1574
+ function projectIndexRegistersExactPath(indexText, normalized) {
1575
+ const active = stripMarkdownCommentsAndFences(indexText);
1576
+ for (const line of active.split(/\r?\n/)) {
1577
+ if (!line.trim().startsWith("|")) continue;
1578
+ const cells = line.split("|").slice(1, -1);
1579
+ for (const rawCell of cells) {
1580
+ const cell = rawCell.trim().replace(/^`([^`]+)`$/, "$1");
1581
+ if (cell === normalized) return true;
1582
+ const link = /^\[[^\]]*\]\(([^)]+)\)$/.exec(cell);
1583
+ if (link && link[1].replace(/^<|>$/g, "") === normalized) return true;
1584
+ }
1585
+ }
1586
+ return false;
1587
+ }
1588
+
1589
+ function textExplicitlyClassifiesExactArtifact(text, normalized) {
1590
+ const active = stripMarkdownCommentsAndFences(text);
1075
1591
  const escaped = normalized.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1076
- const labels = "(draft|temporary|one-time evidence|non-authoritative|not source of truth|草稿|臨時|暫存|一次性|非真源|非權威)";
1077
- const afterPath = new RegExp(`${escaped}[\\s\\S]{0,240}${labels}`, "i");
1078
- const beforePath = new RegExp(`${labels}[\\s\\S]{0,240}${escaped}`, "i");
1079
- return afterPath.test(logText)
1080
- || beforePath.test(logText)
1081
- || afterPath.test(handoffText)
1082
- || beforePath.test(handoffText);
1592
+ const exactPath = new RegExp(`(?:^|[\\s\`|([<])${escaped}(?=$|[\\s\`|)\\]>.,;:])`, "i");
1593
+ const label = /(draft|temporary|one-time evidence|non-authoritative|not source of truth|草稿|臨時|暫存|一次性|非真源|非權威)/i;
1594
+ const markdownPath = /(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.md\b/gi;
1595
+ for (const line of active.split(/\r?\n/)) {
1596
+ if (!exactPath.test(line) || !label.test(line)) continue;
1597
+ const paths = new Set((line.match(markdownPath) ?? []).map((item) => item.replaceAll("\\", "/").toLowerCase()));
1598
+ if (paths.size === 1 && paths.has(normalized.toLowerCase())) return true;
1599
+ }
1600
+ return false;
1083
1601
  }
1084
1602
 
1085
1603
  function stripFencedCodeBlocks(text) {
@@ -1171,29 +1689,7 @@ function lineHasCurrentStateEvidence(line, options = {}) {
1171
1689
  return currentStateEvidenceFindings("line", line, options).length > 0;
1172
1690
  }
1173
1691
 
1174
- function repairHandoffOpeningRootGuard(text) {
1175
- if (text.includes(rootMismatchGuard)) return { changed: false, text };
1176
- const bounds = handoffSectionContentBounds(text, "next-session-opening-message", "Next Session Opening Message");
1177
- if (!bounds) return { changed: false, text };
1178
- const section = text.slice(bounds.start, bounds.end);
1179
- if (!section.includes("```text")) return { changed: false, text };
1180
-
1181
- let repairedSection = section;
1182
- if (/^Before changing anything,/m.test(repairedSection)) {
1183
- repairedSection = repairedSection.replace(/^Before changing anything,/m, `${rootMismatchGuard}, stop and ask for confirmation.\n\nBefore changing anything,`);
1184
- } else if (/\n```/.test(repairedSection)) {
1185
- repairedSection = repairedSection.replace(/\n```/, `\n${rootMismatchGuard}, stop and ask for confirmation.\n\n\`\`\``);
1186
- } else {
1187
- return { changed: false, text };
1188
- }
1189
-
1190
- return {
1191
- changed: repairedSection !== section,
1192
- text: `${text.slice(0, bounds.start)}${repairedSection}${text.slice(bounds.end)}`
1193
- };
1194
- }
1195
-
1196
- function repairHandoffCurrentStateEvidenceBoundary(text) {
1692
+ function repairHandoffCurrentStateEvidenceBoundary(text) {
1197
1693
  let repaired = text;
1198
1694
  let changed = false;
1199
1695
  for (const section of [
@@ -1290,23 +1786,7 @@ function getFirstUseNextStep(root, lastCloseout) {
1290
1786
  // R-030 v0.3.0+: Credential leak prevention sweep. Scans dev/PROJECT_INDEX.md,
1291
1787
  // dev/SESSION_HANDOFF.md, dev/SESSION_LOG.md for common credential prefix patterns.
1292
1788
  // Credentials must live in OS-level secure storage or AI-tool config, never in dev/*.
1293
- async function checkInstalledIntegrationsCredentialLeak(root) {
1294
- const credentialPatterns = [
1295
- { pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key (sk-ant-)" },
1296
- { pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "OpenAI / generic sk- prefix" },
1297
- { pattern: /\bntn_[A-Za-z0-9_-]{40,}/, label: "Notion Integration Token (ntn_)" },
1298
- { pattern: /\bsecret_[A-Za-z0-9_-]{40,}/, label: "Notion legacy secret_ token" },
1299
- { pattern: /\bya29\.[A-Za-z0-9_-]{20,}/, label: "Google OAuth access token (ya29.)" },
1300
- { pattern: /\b1\/\/[A-Za-z0-9_-]{30,}/, label: "Google refresh token (1//)" },
1301
- { pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}/, label: "Slack token (xoxp-/xoxb-/etc)" },
1302
- { pattern: /\bghp_[A-Za-z0-9]{36}/, label: "GitHub Personal Access Token (ghp_)" },
1303
- { pattern: /\bgho_[A-Za-z0-9]{36}/, label: "GitHub OAuth token (gho_)" },
1304
- { pattern: /\bghs_[A-Za-z0-9]{36}/, label: "GitHub server token (ghs_)" },
1305
- { pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}/, label: "GitHub fine-grained PAT (github_pat_)" },
1306
- { pattern: /\bsl\.[A-Za-z0-9_-]{50,}/, label: "Dropbox token (sl.)" },
1307
- { pattern: /\bAKIA[A-Z0-9]{16}/, label: "AWS access key (AKIA)" },
1308
- { pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key (AIza)" }
1309
- ];
1789
+ async function checkInstalledIntegrationsCredentialLeak(root) {
1310
1790
  const targetFiles = [
1311
1791
  "dev/PROJECT_INDEX.md",
1312
1792
  "dev/SESSION_HANDOFF.md",
@@ -1321,7 +1801,7 @@ async function checkInstalledIntegrationsCredentialLeak(root) {
1321
1801
  } catch {
1322
1802
  continue;
1323
1803
  }
1324
- for (const { pattern, label } of credentialPatterns) {
1804
+ for (const { pattern, label } of credentialLeakPatterns) {
1325
1805
  const match = text.match(pattern);
1326
1806
  if (match) {
1327
1807
  const line = text.slice(0, match.index).split("\n").length;
@@ -1345,7 +1825,7 @@ function printDoctorSummary(version, root, mode, details) {
1345
1825
  }
1346
1826
  } else {
1347
1827
  console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
1348
- console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : details.failedKind === "generated markdown governance checks" ? "有 Markdown 或 durable artifact 未完成入庫、同步或臨時分類。" : "下次開工提示副本與 handoff 真源不同。"}`);
1828
+ console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : details.failedKind === "generated markdown governance checks" ? "有 Markdown 未完成登記、同步或精確臨時分類;其他持久格式須另作人工治理核對。" : "下次開工提示副本與 handoff 真源不同。"}`);
1349
1829
  }
1350
1830
  console.log("");
1351
1831
  console.log(`📦 版本:v${version}`);
@@ -1408,22 +1888,8 @@ async function hydrateInitialOpeningPrompt(root, created) {
1408
1888
  }
1409
1889
  }
1410
1890
 
1411
- async function checkPromptMirror(root) {
1412
- const handoffPath = path.join(root, "dev/SESSION_HANDOFF.md");
1413
- const promptPath = path.join(root, "START_NEXT_SESSION_PROMPT.txt");
1414
- let handoffText = "";
1415
- let promptText = "";
1416
- try {
1417
- handoffText = await readFile(handoffPath, "utf8");
1418
- } catch {
1419
- return [{ target: "START_NEXT_SESSION_PROMPT.txt", label: "matches handoff opening message", ok: false, reason: "handoff unreadable" }];
1420
- }
1421
- try {
1422
- promptText = await readFile(promptPath, "utf8");
1423
- } catch {
1424
- return [{ target: "START_NEXT_SESSION_PROMPT.txt", label: "matches handoff opening message", ok: false, reason: "prompt copy unreadable" }];
1425
- }
1426
- const mirror = assessPromptMirrorTexts(handoffText, promptText);
1891
+ async function checkPromptMirror(root) {
1892
+ const mirror = assessPromptMirrorRoot(root);
1427
1893
  return [{
1428
1894
  target: "START_NEXT_SESSION_PROMPT.txt",
1429
1895
  label: "matches handoff opening message",
@@ -1432,19 +1898,71 @@ async function checkPromptMirror(root) {
1432
1898
  }];
1433
1899
  }
1434
1900
 
1435
- function assessHandoffLifecycleConsistency(text) {
1436
- const fieldValue = fieldValueAfterMarker(text, "lifecycle-conflicts-resolved");
1437
- if (isAffirmativeLifecycleFieldValue(fieldValue)) {
1438
- return { ok: true, reason: "" };
1439
- }
1440
- if (isUnresolvedLifecycleFieldValue(fieldValue)) {
1441
- return { ok: false, reason: "lifecycle field is explicitly unresolved" };
1442
- }
1443
- if (isPlaceholderLifecycleFieldValue(fieldValue) && hasSubstantiveHandoffState(text)) {
1444
- return { ok: false, reason: "lifecycle field is still placeholder after handoff content changed" };
1445
- }
1446
- return { ok: true, reason: "" };
1447
- }
1901
+ function assessHandoffLifecycleConsistency(text) {
1902
+ const fieldValue = fieldValueAfterMarker(text, "lifecycle-conflicts-resolved");
1903
+ if (isUnresolvedLifecycleFieldValue(fieldValue)) {
1904
+ return { ok: false, reason: "lifecycle field is explicitly unresolved" };
1905
+ }
1906
+ if (isPlaceholderLifecycleFieldValue(fieldValue) && hasSubstantiveHandoffState(text)) {
1907
+ return { ok: false, reason: "lifecycle field is still placeholder after handoff content changed" };
1908
+ }
1909
+ const contradictions = findHandoffLifecycleContradictions(text);
1910
+ if (contradictions.length > 0) {
1911
+ return { ok: false, reason: `resolved work overlaps unresolved carry-forward state: ${contradictions[0]}` };
1912
+ }
1913
+ return { ok: true, reason: "" };
1914
+ }
1915
+
1916
+ function handoffStateLines(text, markerId, headingTitle) {
1917
+ return extractSectionText(text, markerId, headingTitle)
1918
+ .replace(/```[\s\S]*?```/g, "")
1919
+ .split(/\r?\n/)
1920
+ .map((line) => line.replace(/^[-*\d.)\s]+/, "").trim())
1921
+ .filter((line) => line.length > 3 && !line.startsWith("##") && !line.startsWith("<!--") && !/^(TBD|none|n\/a|未適用|無)$/i.test(line));
1922
+ }
1923
+
1924
+ function lifecycleTopicTokens(line) {
1925
+ const latin = (line.toLowerCase().match(/[a-z0-9][a-z0-9_-]{3,}/g) ?? [])
1926
+ .filter((token) => !new Set(["completed", "complete", "passed", "verified", "pending", "blocked", "follow-up", "monitor-only", "reopened", "session", "current", "next", "work", "task", "with", "from", "that", "this", "handoff", "lifecycle", "migration", "regression", "agent"]).has(token));
1927
+ const chineseRuns = line.match(/[\u3400-\u9fff]{2,}/g) ?? [];
1928
+ const chinese = chineseRuns.flatMap((run) => Array.from({ length: Math.max(0, run.length - 1) }, (_, index) => run.slice(index, index + 2)));
1929
+ return new Set([...latin, ...chinese]);
1930
+ }
1931
+
1932
+ function lifecycleTopicsOverlap(left, right) {
1933
+ const leftCompact = left.toLowerCase().replace(/[^a-z0-9\u3400-\u9fff]+/g, "");
1934
+ const rightCompact = right.toLowerCase().replace(/[^a-z0-9\u3400-\u9fff]+/g, "");
1935
+ if (leftCompact.length >= 8 && rightCompact.length >= 8 && (leftCompact.includes(rightCompact) || rightCompact.includes(leftCompact))) return true;
1936
+ const leftTokens = lifecycleTopicTokens(left);
1937
+ const common = [...lifecycleTopicTokens(right)].filter((token) => leftTokens.has(token));
1938
+ return common.length >= 2;
1939
+ }
1940
+
1941
+ function isExplicitLifecycleReclassification(line) {
1942
+ const category = /(monitor-only|follow-up scope|blocked|reopened|只監察|後續追蹤|受阻|重開)/i.test(line);
1943
+ const condition = /(trigger|until|when|missing evidence|reason|條件|證據|原因|待.+(?:時|後))/i.test(line);
1944
+ return category && condition;
1945
+ }
1946
+
1947
+ function findHandoffLifecycleContradictions(text) {
1948
+ const resolved = [
1949
+ ...handoffStateLines(text, "completed-this-session", "Completed This Session"),
1950
+ ...handoffStateLines(text, "validation-qc", "Validation / QC").filter((line) => /(pass|passed|verified|complete|success|通過|完成|已驗證|已核對)/i.test(line))
1951
+ ];
1952
+ const carryForward = [
1953
+ ...handoffStateLines(text, "next-priorities", "Next Priorities"),
1954
+ ...handoffStateLines(text, "risks-blockers", "Risks / Blockers"),
1955
+ ...handoffStateLines(text, "next-session-opening-message", "Next Session Opening Message")
1956
+ ];
1957
+ const findings = [];
1958
+ for (const pending of carryForward) {
1959
+ if (isExplicitLifecycleReclassification(pending)) continue;
1960
+ for (const done of resolved) {
1961
+ if (lifecycleTopicsOverlap(done, pending)) findings.push(`${done} <> ${pending}`);
1962
+ }
1963
+ }
1964
+ return findings;
1965
+ }
1448
1966
 
1449
1967
  function isAffirmativeLifecycleFieldValue(value) {
1450
1968
  const trimmed = (value || "").trim();
@@ -1577,9 +2095,9 @@ async function checkSchema(root) {
1577
2095
  rows.push({ target: rule.target, label: rule.label, ok: false, missing: ["file unreadable"] });
1578
2096
  continue;
1579
2097
  }
1580
- const missing = rule.checks
1581
- .filter((check) => !check.test(text))
1582
- .map((check) => check.label);
2098
+ const missing = rule.checks
2099
+ .filter((check) => !check.test(text))
2100
+ .map((check) => check.explain?.(text) ? `${check.label}: ${check.explain(text)}` : check.label);
1583
2101
  rows.push({
1584
2102
  target: rule.target,
1585
2103
  label: rule.label,
@@ -1630,10 +2148,17 @@ function tableHeader(...cells) {
1630
2148
 
1631
2149
  async function buildPlan(root, command, version = null) {
1632
2150
  const plan = [];
1633
- const context = {
1634
- currentVersion: version,
1635
- rootTemplateVersion: command === "upgrade" ? await readRootTemplateVersion(root) : null
1636
- };
2151
+ const context = {
2152
+ currentVersion: version,
2153
+ rootTemplateVersion: command === "upgrade" ? await readRootTemplateVersion(root) : null,
2154
+ migrationBaselines: new Map()
2155
+ };
2156
+ if (command === "upgrade" && context.rootTemplateVersion === "0.3.38") {
2157
+ for (const relative of ["packs/integrations.md", "packs/onboarding.md", "packs/safety.md"]) {
2158
+ const baseline = await readOptionalText(path.join(packageRoot, "bin", "migration-baselines", "v0.3.38", path.basename(relative)));
2159
+ if (baseline != null) context.migrationBaselines.set(relative, baseline);
2160
+ }
2161
+ }
1637
2162
  for (const [sourceRel, targetRel] of mappings) {
1638
2163
  const sourceAbs = path.join(packageRoot, sourceRel);
1639
2164
  const targetAbs = path.join(root, targetRel);
@@ -1672,11 +2197,10 @@ async function readRootTemplateVersion(root) {
1672
2197
  }
1673
2198
  }
1674
2199
 
1675
- function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context = {}) {
1676
- const base = { sourceRel, targetRel, sourceAbs, targetAbs };
1677
- if (targetText === sourceText && targetRel !== "AGENTS.md") return { ...base, action: "skip", reason: "already current" };
1678
- if (command !== "upgrade") return { ...base, action: "skip", reason: "init preserves existing files" };
1679
- if (targetRel === "AGENTS.md") {
2200
+ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context = {}) {
2201
+ const base = { sourceRel, targetRel, sourceAbs, targetAbs };
2202
+ if (targetText.replace(/\r\n/g, "\n") === sourceText.replace(/\r\n/g, "\n") && targetRel !== "AGENTS.md") return { ...base, action: "skip", reason: "already current" };
2203
+ if (targetRel === "AGENTS.md") {
1680
2204
  const health = assessAgentsMdHealth(targetText);
1681
2205
  if (health.state === "conflict") {
1682
2206
  return {
@@ -1707,87 +2231,84 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1707
2231
  };
1708
2232
  }
1709
2233
  if (hasRequiredAnchor(targetRel, targetText)) {
1710
- return { ...base, action: "skip", reason: "managed core clean and required anchors present" };
1711
- }
1712
- return {
1713
- ...base,
1714
- action: "merge",
1715
- reason: "add managed core while preserving existing AGENTS.md content",
1716
- mergedText: mergeManagedBlock(targetText, sourceText)
1717
- };
1718
- }
1719
- // R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
1720
- // user-added rows. Missing maintainer rows are merged into the existing table
1721
- // instead of replacing the whole file.
1722
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("First-time user signals")) {
1723
- const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1724
- if (!mergedRulePacks) {
1725
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
2234
+ return { ...base, action: "skip", reason: "managed core clean and required anchors present" };
1726
2235
  }
1727
2236
  return {
1728
2237
  ...base,
1729
2238
  action: "merge",
1730
- reason: "merge missing v0.2.0+ routing rows while preserving existing custom rows (新手引導 signal routing)",
1731
- mergedText: mergedRulePacks
2239
+ reason: "add managed core while preserving existing AGENTS.md content",
2240
+ mergedText: mergeManagedBlock(targetText, sourceText)
1732
2241
  };
1733
2242
  }
1734
- // R-030 v0.3.0+: dev/RULE_PACKS.md must also include integrations pack routing row.
1735
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool integrations")) {
2243
+ // R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
2244
+ // user-added rows. Missing maintainer rows are merged into the existing table
2245
+ // instead of replacing the whole file.
2246
+ if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade") {
1736
2247
  const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1737
2248
  if (!mergedRulePacks) {
1738
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1739
- }
1740
- return {
1741
- ...base,
1742
- action: "merge",
1743
- reason: "merge missing v0.3.0+ routing rows while preserving existing custom rows (Integration governance routing)",
1744
- mergedText: mergedRulePacks
1745
- };
2249
+ return { ...base, action: "conflict", reason: "RULE_PACKS.md must contain one valid routing table; marked official rows and local rows could not be separated safely" };
2250
+ }
2251
+ if (mergedRulePacks !== targetText) {
2252
+ return {
2253
+ ...base,
2254
+ action: "merge",
2255
+ reason: "update marker-identified official routing rows while preserving every unmarked local row",
2256
+ mergedText: mergedRulePacks
2257
+ };
2258
+ }
2259
+ return { ...base, action: "skip", reason: "official marked routes current; local rows preserved" };
1746
2260
  }
1747
- // External-tool resource lifecycle extension: old v0.3.x installs may already
1748
- // have the integrations row, but still lack the resource-pressure routing row.
1749
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && !targetText.includes("External tool resource pressure")) {
1750
- const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1751
- if (!mergedRulePacks) {
1752
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
2261
+ if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade") {
2262
+ const mergedProjectIndex = mergeProjectIndexGovernanceSections(targetText, sourceText);
2263
+ if (!mergedProjectIndex) {
2264
+ return {
2265
+ ...base,
2266
+ action: "conflict",
2267
+ reason: "PROJECT_INDEX.md must contain unique real H2 governance sections in the expected order; inline or fenced lookalikes are not sections"
2268
+ };
1753
2269
  }
1754
- return {
1755
- ...base,
1756
- action: "merge",
1757
- reason: "merge missing external-tool resource lifecycle routing row while preserving existing custom rows",
1758
- mergedText: mergedRulePacks
1759
- };
2270
+ if (mergedProjectIndex !== targetText) {
2271
+ return {
2272
+ ...base,
2273
+ action: "merge",
2274
+ reason: "insert or normalize the unique Installed Integrations and Tool Operation References H2 sections while preserving all existing project content",
2275
+ mergedText: mergedProjectIndex
2276
+ };
2277
+ }
2278
+ return { ...base, action: "skip", reason: "PROJECT_INDEX.md governance sections current and structurally unique" };
1760
2279
  }
1761
- // Governance bridge v0.3.27+: route durable document bridging requests to
1762
- // agent-governance without replacing user-added routing rows.
1763
- if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade" && (
1764
- !targetText.includes("Governance bridge / bridge governance")
1765
- || !targetText.includes("equivalent Chinese user phrases")
1766
- || !targetText.includes("scan for unbridged governance documents")
1767
- )) {
1768
- const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
1769
- if (!mergedRulePacks) {
1770
- return { ...base, action: "conflict", reason: "RULE_PACKS.md routing table header was changed; manual merge required to preserve custom rows" };
1771
- }
1772
- return {
1773
- ...base,
1774
- action: "merge",
1775
- reason: "merge missing governance bridge routing row while preserving existing custom rows",
1776
- mergedText: mergedRulePacks
1777
- };
2280
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
2281
+ const migratedHandoff = migrateSessionHandoff(targetText, sourceText, context);
2282
+ if (!migratedHandoff) {
2283
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md lacks unique trusted state/opening boundaries; migration stopped without replacing project state" };
2284
+ }
2285
+ if (migratedHandoff !== targetText) {
2286
+ return { ...base, action: "merge", reason: "update handoff lifecycle/startup contracts while preserving current project state", mergedText: migratedHandoff };
2287
+ }
2288
+ return { ...base, action: "skip", reason: "SESSION_HANDOFF.md lifecycle and startup contracts current" };
1778
2289
  }
1779
- // Language migration: older integrations packs were AI-facing rules written
1780
- // partly in Chinese/Cantonese. If the file still has the trusted legacy Kit
1781
- // shape, replace it with the current English maintainer pack. If the shape is
1782
- // ambiguous or locally restructured, stop as a conflict instead of doing a
1783
- // partial merge that could create a half-English, half-legacy pack.
1784
- if (targetRel === "dev/rules/integrations.md" && command === "upgrade" && isLegacyChineseIntegrationsPack(targetText)) {
1785
- return {
1786
- ...base,
1787
- action: "merge",
1788
- reason: "replace legacy Chinese integrations pack with current English maintainer pack",
1789
- mergedText: sourceText
1790
- };
2290
+ if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade") {
2291
+ const migratedLog = migrateSessionLog(targetText, sourceText);
2292
+ if (!migratedLog) {
2293
+ return { ...base, action: "conflict", reason: "SESSION_LOG.md lacks a unique trusted entry-template boundary; migration stopped without replacing trace history" };
2294
+ }
2295
+ if (migratedLog !== targetText) {
2296
+ return { ...base, action: "merge", reason: "update only the log preamble/template and remove Kit-shaped full prompt copies while preserving trace entries", mergedText: migratedLog };
2297
+ }
2298
+ return { ...base, action: "skip", reason: "SESSION_LOG.md trace/template boundary current" };
2299
+ }
2300
+ if (command === "upgrade" && ["dev/rules/integrations.md", "dev/rules/onboarding.md", "dev/rules/safety.md"].includes(targetRel)) {
2301
+ const baseline = context.migrationBaselines?.get(sourceRel);
2302
+ if (baseline != null) {
2303
+ const mergedPack = threeWayPreserveLocalChanges(baseline, targetText, sourceText);
2304
+ if (!mergedPack) {
2305
+ return { ...base, action: "conflict", reason: `${targetRel} has local edits that overlap changed Kit rules; upgrade stopped without replacing custom content` };
2306
+ }
2307
+ if (mergedPack !== targetText) {
2308
+ return { ...base, action: "merge", reason: `three-way merge v0.3.38 official rules while preserving non-overlapping local ${path.basename(targetRel)} changes`, mergedText: mergedPack };
2309
+ }
2310
+ return { ...base, action: "skip", reason: `${targetRel} current after three-way preservation check` };
2311
+ }
1791
2312
  }
1792
2313
  // Governance bridge v0.3.27+: add the triggered review workflow to the
1793
2314
  // agent-governance pack only when the pack still has a trusted Checks section.
@@ -1807,69 +2328,9 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1807
2328
  mergedText: mergedGovernancePack
1808
2329
  };
1809
2330
  }
1810
- // R-030 v0.3.0+: dev/PROJECT_INDEX.md gets ## Installed Integrations section auto-inserted before
1811
- // ## Local QC Commands on upgrade if missing. NON-DESTRUCTIVE: existing ## External Sources content
1812
- // is fully preserved (including any user-filled rows). User can later manually add the `via` column
1813
- // to External Sources rows (or AI can guide that incremental migration during a later session).
1814
- if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade" && !targetText.includes("## Installed Integrations")) {
1815
- // Extract just the ## Installed Integrations block from source (not touching External Sources).
1816
- const sourceInstalledMatch = sourceText.match(/(## Installed Integrations[\s\S]*?)(?=## Local QC Commands)/);
1817
- if (sourceInstalledMatch && targetText.includes("## Local QC Commands")) {
1818
- const installedBlock = sourceInstalledMatch[1];
1819
- return {
1820
- ...base,
1821
- action: "merge",
1822
- reason: "insert ## Installed Integrations section template before ## Local QC Commands (R-030 Integration governance migration; existing External Sources content preserved non-destructively)",
1823
- mergedText: targetText.replace("## Local QC Commands", installedBlock + "## Local QC Commands")
1824
- };
1825
- }
1826
- }
1827
- if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade" && !targetText.includes("## Tool Operation References")) {
1828
- const sourceToolRefsMatch = sourceText.match(/(## Tool Operation References[\s\S]*?)(?=## Local QC Commands)/);
1829
- if (sourceToolRefsMatch && targetText.includes("## Local QC Commands")) {
1830
- const toolRefsBlock = sourceToolRefsMatch[1];
1831
- const normalizedTarget = mergeProjectIndexCredentialReferences(targetText);
1832
- return {
1833
- ...base,
1834
- action: "merge",
1835
- reason: "insert ## Tool Operation References section template before ## Local QC Commands and normalize integration reference wording (runtime-controlled tool operation governance)",
1836
- mergedText: normalizedTarget.replace("## Local QC Commands", toolRefsBlock + "## Local QC Commands")
1837
- };
1838
- }
1839
- }
1840
- if (targetRel === "dev/PROJECT_INDEX.md" && command === "upgrade" && (
1841
- targetText.includes("Credential Location")
1842
- || targetText.includes("Credential Reference(no value)")
1843
- || targetText.includes("Claude Code MCP config + env var")
1844
- || targetText.includes("Credential 應由 AI 工具自身 secure storage 管理(譬如 Claude Desktop Extensions")
1845
- || targetText.includes("機密分離原則")
1846
- )) {
1847
- const mergedProjectIndex = mergeProjectIndexCredentialReferences(targetText);
1848
- if (mergedProjectIndex !== targetText) {
1849
- return {
1850
- ...base,
1851
- action: "merge",
1852
- reason: "update PROJECT_INDEX credential reference wording without changing user integration rows",
1853
- mergedText: mergedProjectIndex
1854
- };
1855
- }
1856
- }
1857
- // Language migration: older onboarding packs were AI-facing rules written
1858
- // mostly in Chinese. If the file still has the trusted legacy Kit shape,
1859
- // replace it with the current concise English maintainer pack. If the shape
1860
- // is ambiguous or locally restructured, stop as a conflict instead of
1861
- // producing a half-English, half-legacy pack.
1862
- if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && isLegacyChineseOnboardingPack(targetText)) {
1863
- return {
1864
- ...base,
1865
- action: "merge",
1866
- reason: "replace legacy Chinese onboarding pack with current English maintainer pack",
1867
- mergedText: sourceText
1868
- };
1869
- }
1870
2331
  // R-030 v0.3.0+: dev/rules/onboarding.md gets Scenario F auto-inserted before
1871
2332
  // ## Cross-reference to guide.html on upgrade if missing and the pack is not
1872
- // a legacy Chinese pack that should be replaced wholesale.
2333
+ // a legacy pack whose structure cannot accept this bounded insertion safely.
1873
2334
  if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Scenario F. External-tool governance")) {
1874
2335
  const sourceScenarioFMatch = sourceText.match(/(### Scenario F\. External-tool governance[\s\S]*?)(?=## Cross-reference to guide\.html)/);
1875
2336
  if (sourceScenarioFMatch && hasTrustedOnboardingScenarioLibrary(targetText)) {
@@ -1890,112 +2351,33 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1890
2351
  action: "merge",
1891
2352
  reason: "update onboarding Scenario A wording from narrow coding label to broader system/tool/platform/app label",
1892
2353
  mergedText: mergedOnboarding
1893
- };
1894
- }
1895
- }
1896
- // v0.3.6+: SESSION_HANDOFF.md gains a non-destructive lifecycle consistency
1897
- // field. Existing handoff content stays intact; only the missing field and
1898
- // rule note are inserted around stable ack markers.
1899
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
1900
- const mergedHandoff = mergeHandoffLifecycleField(targetText);
1901
- if (!mergedHandoff) {
1902
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add lifecycle consistency field" };
1903
- }
1904
- return {
1905
- ...base,
1906
- action: "merge",
1907
- reason: "insert lifecycle consistency field into State Reconciliation Check (completed work must not carry forward as unresolved next work)",
1908
- mergedText: mergedHandoff
1909
- };
1910
- }
1911
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:persistence-routing-checked")) {
1912
- const mergedHandoff = mergeHandoffPersistenceRoutingField(targetText);
1913
- if (!mergedHandoff) {
1914
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add persistence routing field" };
2354
+ };
1915
2355
  }
1916
- return {
1917
- ...base,
1918
- action: "merge",
1919
- reason: "insert persistence routing field into State Reconciliation Check (one-time evidence must not drive next-session state)",
1920
- mergedText: mergedHandoff
1921
- };
1922
2356
  }
1923
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:recommended-next-step-explicit")) {
1924
- const mergedHandoff = mergeHandoffRecommendedNextStepDiscipline(targetText);
1925
- if (!mergedHandoff) {
1926
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add recommended next-step field" };
2357
+ if (targetRel === "dev/rules/onboarding.md" && command === "upgrade" && !targetText.includes("Infer when sufficient; ask only when unresolved")) {
2358
+ const mergedOnboarding = mergeOnboardingDecisionFirstPolicy(targetText, sourceText);
2359
+ if (!mergedOnboarding) {
2360
+ return { ...base, action: "conflict", reason: "onboarding decision flow was customized or structurally changed; manual merge required rather than forcing the chooser-policy migration" };
1927
2361
  }
1928
2362
  return {
1929
2363
  ...base,
1930
2364
  action: "merge",
1931
- reason: "insert recommended next-step field and preserve existing next-priority items",
1932
- mergedText: mergedHandoff
2365
+ reason: "replace the trusted mandatory chooser flow with decision-first onboarding while preserving scenario content and local sections",
2366
+ mergedText: mergedOnboarding
1933
2367
  };
1934
2368
  }
1935
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && isUpgradeFromOlderTemplate(context)) {
1936
- const lifecycleValue = fieldValueAfterMarker(targetText, "lifecycle-conflicts-resolved");
1937
- if (isPlaceholderLifecycleFieldValue(lifecycleValue) && hasSubstantiveHandoffState(targetText)) {
1938
- const mergedHandoff = reclassifyExistingHandoffLifecyclePlaceholder(targetText);
1939
- if (!mergedHandoff) {
1940
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md lifecycle field exists but could not be safely reclassified; manual closeout required" };
1941
- }
1942
- return {
1943
- ...base,
1944
- action: "merge",
1945
- reason: "reclassify stale lifecycle placeholder from earlier template version so upgrade self-check can validate pre-existing handoff content",
1946
- mergedText: mergedHandoff
1947
- };
1948
- }
1949
- }
1950
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1951
- return { ...base, action: "conflict", reason: "required Kit anchors are present outside trusted semantic sections; upgrade stopped to avoid accepting naked anchor text as valid state" };
1952
- }
1953
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1954
- const mergedHandoff = mergeHandoffArchiveContinuityRule(targetText, sourceText);
1955
- if (!mergedHandoff) {
1956
- return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md handoff sufficiency markers were changed; manual merge required to add archive continuity rule" };
1957
- }
1958
- return {
1959
- ...base,
1960
- action: "merge",
1961
- reason: "insert handoff archive continuity rule so upgrade self-check can pass without requiring manual anchor repair",
1962
- mergedText: mergedHandoff
1963
- };
1964
- }
1965
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
1966
- const repairedOpening = repairHandoffOpeningRootGuard(targetText);
1967
- if (repairedOpening.changed) {
1968
- return {
1969
- ...base,
1970
- action: "merge",
1971
- reason: "restore root mismatch guard in Next Session Opening Message",
1972
- mergedText: repairedOpening.text
1973
- };
1974
- }
1975
- }
1976
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
1977
- const repairedTemperature = repairHandoffCurrentStateEvidenceBoundary(targetText);
1978
- if (repairedTemperature.changed) {
1979
- return {
1980
- ...base,
1981
- action: "merge",
1982
- reason: "move historical evidence out of hot handoff state",
1983
- mergedText: repairedTemperature.text
1984
- };
1985
- }
1986
- }
1987
- if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade" && !targetText.includes("- **Evidence disposition:**")) {
1988
- const mergedLog = mergeSessionLogEvidenceDispositionField(targetText);
1989
- if (!mergedLog) {
1990
- return { ...base, action: "conflict", reason: "SESSION_LOG.md entry template markers were changed; manual merge required to add evidence disposition field" };
1991
- }
1992
- return {
1993
- ...base,
1994
- action: "merge",
1995
- reason: "insert SESSION_LOG evidence disposition field into Entry Template",
1996
- mergedText: mergedLog
1997
- };
1998
- }
2369
+ if (command !== "upgrade") return { ...base, action: "skip", reason: "init preserves existing files" };
2370
+ if (targetRel === "START_NEXT_SESSION_PROMPT.txt" && command === "upgrade") {
2371
+ const mergedStartupGuidance = mergeLegacyFirstStartupGuidance(targetText, sourceText);
2372
+ if (mergedStartupGuidance && mergedStartupGuidance !== targetText) {
2373
+ return {
2374
+ ...base,
2375
+ action: "merge",
2376
+ reason: "replace the exact legacy first-start chooser sentence without changing surrounding project state",
2377
+ mergedText: mergedStartupGuidance
2378
+ };
2379
+ }
2380
+ }
1999
2381
  if (command === "upgrade" && hasAnchorRepairMarkerDrift(targetText)) {
2000
2382
  return { ...base, action: "conflict", reason: "legacy anchor repair block markers are incomplete or obsolete; manual semantic cleanup required before upgrade can safely continue" };
2001
2383
  }
@@ -2008,20 +2390,21 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2008
2390
  return { ...base, ...semanticRepair };
2009
2391
  }
2010
2392
  return { ...base, action: "conflict", reason: "required Kit anchors are missing but no safe semantic repair path exists; upgrade stopped without appending naked anchor text" };
2011
- }
2012
- if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
2013
- if (!targetText.includes("AGENTS.md")) {
2014
- return { ...base, action: "conflict", reason: "existing bridge does not route to AGENTS.md" };
2015
- }
2016
- if (looksLikeExpandedKitBridge(targetRel, targetText)) {
2017
- return {
2393
+ }
2394
+ if (targetRel === "CLAUDE.md" || targetRel === "GEMINI.md") {
2395
+ if (looksLikeExpandedKitBridge(targetRel, targetText)) {
2396
+ return {
2018
2397
  ...base,
2019
2398
  action: "merge",
2020
2399
  reason: `${targetRel} appears to be an expanded Kit bridge; restore short bridge so AGENTS.md remains the single source of truth`,
2021
- mergedText: sourceText
2022
- };
2023
- }
2024
- }
2400
+ mergedText: sourceText
2401
+ };
2402
+ }
2403
+ const bridgeFailure = bridgeTextFailure(targetRel, targetText);
2404
+ if (bridgeFailure) {
2405
+ return { ...base, action: "conflict", reason: `existing bridge is not an active one-hop route (${bridgeFailure})` };
2406
+ }
2407
+ }
2025
2408
  return { ...base, action: "skip", reason: "preserve existing file" };
2026
2409
  }
2027
2410
 
@@ -2064,7 +2447,90 @@ function mergeOnboardingScenarioALabel(targetText) {
2064
2447
  );
2065
2448
  return merged;
2066
2449
  }
2067
-
2450
+
2451
+ function mergeOnboardingDecisionFirstPolicy(targetText, sourceText) {
2452
+ const legacySignalLine = "- equivalent Chinese user phrases such as \"新手\", \"教我用\", \"我剛安裝\", \"點開始\", \"開工\", \"能力\", or \"能做甚麼\"";
2453
+ const currentSignalBoundary = "- equivalent Chinese user phrases such as \"新手\", \"教我用\", \"我剛安裝\", \"點開始\", \"能力\", or \"能做甚麼\"\n\n### Continuity startup boundary\n\n`Start Agent Handoff` / \"開工\" starts continuity and reads the current handoff state; it is not an onboarding signal. If the same message or loaded state contains a concrete objective, infer the working scenario and begin the first safe action. Only when no executable objective remains after state reading should the AI ask one concise question or offer the guided onboarding path. Explicit requests such as \"新手,教我用\" enter onboarding directly.";
2454
+ let working = targetText;
2455
+ let startupBoundaryChanged = false;
2456
+ if (working.includes(legacySignalLine) && !working.includes("### Continuity startup boundary")) {
2457
+ working = working.replace(legacySignalLine, currentSignalBoundary);
2458
+ startupBoundaryChanged = true;
2459
+ }
2460
+
2461
+ const legacyStart = "### 2. Offer scenario choice before task execution";
2462
+ const legacyEnd = "### 5. Keep the first task small";
2463
+ const sourceStart = "### 2. Infer first; offer scenario choice only when needed";
2464
+ const sourceEnd = "### 5. Keep the first task small";
2465
+ const targetStartIndex = working.indexOf(legacyStart);
2466
+ const targetEndIndex = working.indexOf(legacyEnd);
2467
+ const sourceStartIndex = sourceText.indexOf(sourceStart);
2468
+ const sourceEndIndex = sourceText.indexOf(sourceEnd);
2469
+ if (targetStartIndex < 0 || targetEndIndex <= targetStartIndex) {
2470
+ return startupBoundaryChanged && working.includes("Infer when sufficient; ask only when unresolved") ? working : null;
2471
+ }
2472
+ if (sourceStartIndex < 0 || sourceEndIndex <= sourceStartIndex) return null;
2473
+
2474
+ const legacyDecisionBlock = working.slice(targetStartIndex, targetEndIndex);
2475
+ const trustedLegacyPhrases = [
2476
+ "When onboarding applies, the first visible response must combine the startup card and scenario chooser",
2477
+ "After the user picks a scenario, guide one small first task through five steps",
2478
+ "Do not run all five steps in one message"
2479
+ ];
2480
+ if (!trustedLegacyPhrases.every((phrase) => legacyDecisionBlock.includes(phrase))) return null;
2481
+
2482
+ const replacements = [
2483
+ [
2484
+ "Use this transient pack for first-time Agent Handoff Kit users, vague first messages, or fresh-install sessions where the user has not yet chosen a working scenario.",
2485
+ "Use this transient pack for first-time Agent Handoff Kit users who request guidance, or when the user's first-task intent remains genuinely unresolved after reading the available project state."
2486
+ ],
2487
+ [
2488
+ "- The first user message is short and vague.",
2489
+ "- The first user message is short and still genuinely vague after available project state is read."
2490
+ ],
2491
+ [
2492
+ "- `SESSION_HANDOFF` Active Objective is empty and Session count is 1.",
2493
+ "- `SESSION_HANDOFF` Active Objective is empty and Session count is 1, and the user has not already supplied a concrete objective with enough material facts."
2494
+ ],
2495
+ [
2496
+ "Each scenario keeps the same five-step rhythm. The model may adapt wording, but must preserve the intent, tone, and safety boundaries.",
2497
+ "Each scenario is a fallback guidance template, not a mandatory questionnaire. The model may skip answered steps, infer the route when evidence is sufficient, and adapt wording while preserving intent, tone, and safety boundaries."
2498
+ ],
2499
+ [
2500
+ "Step E.1: ask for four facts: objective, existing material or tools, technical comfort level, and the first small result the user wants.",
2501
+ "Step E.1: use any facts already provided, then ask only for missing information that materially affects the first safe action. Do not ask about technical comfort unless it changes the delivery approach."
2502
+ ],
2503
+ [
2504
+ "| Treating a vague first message as a specific task | The user may be trying to learn the workflow or choose a scenario. | Offer the A-F scenario chooser first. |",
2505
+ "| Treating a genuinely vague first message as a specific task | The user may be trying to learn the workflow or choose a scenario. | Offer the A-F scenario chooser only when the intent remains unresolved. |"
2506
+ ],
2507
+ [
2508
+ "| Running all five steps without waiting | The user loses control of the walk-through. | Pause for confirmation at each step. |",
2509
+ "| Forcing the chooser or all five guided steps after the objective is already concrete | The user must repeat known information and the AI shifts technical work back to the user. | Infer the scenario, state the assumption, and begin the first safe action; ask only for missing facts or required risk approval. |"
2510
+ ]
2511
+ ];
2512
+ if (!replacements.every(([before]) => working.includes(before))) return null;
2513
+
2514
+ let merged = `${working.slice(0, targetStartIndex)}${sourceText.slice(sourceStartIndex, sourceEndIndex)}${working.slice(targetEndIndex)}`;
2515
+ for (const [before, after] of replacements) merged = merged.replace(before, after);
2516
+ return merged.includes("Infer when sufficient; ask only when unresolved")
2517
+ && !merged.includes("Offer scenario choice before task execution")
2518
+ && !merged.includes("Each scenario keeps the same five-step rhythm")
2519
+ ? merged
2520
+ : null;
2521
+ }
2522
+
2523
+ function mergeLegacyFirstStartupGuidance(targetText, sourceText) {
2524
+ const legacySentence = "This is the first startup after installing Agent Handoff Kit. Load the onboarding guidance from dev/RULE_PACKS.md when appropriate. Help me choose the right working scenario, then guide me through the first task step by step.";
2525
+ if (!targetText.includes(legacySentence)) return targetText;
2526
+ const sourceSentence = sourceText.split(/\r?\n/).find((line) => (
2527
+ line.startsWith("This is the first startup after installing Agent Handoff Kit.")
2528
+ && line.includes("If my objective and the available project facts are already concrete")
2529
+ && line.includes("Offer the chooser only if my intent is genuinely unresolved")
2530
+ ));
2531
+ return sourceSentence ? targetText.replace(legacySentence, sourceSentence) : null;
2532
+ }
2533
+
2068
2534
  function mergeAgentGovernanceBridgeWorkflow(targetText, sourceText) {
2069
2535
  const sourceRuleLine = sourceText.split(/\r?\n/).find((line) => line.startsWith("9. Governance bridge"));
2070
2536
  const workflowMatch = sourceText.match(/\n## Governance Bridge Workflow[\s\S]*?(?=\n## Generated Artifact Governance Workflow|\n## Checks)/);
@@ -2181,9 +2647,10 @@ function sessionLogAnchorPlacement(snippet, text) {
2181
2647
  }
2182
2648
  const preamble = [
2183
2649
  "Record what actually happened in the session",
2184
- "kept, summarized, or archived",
2185
- "Do not remove validation evidence",
2186
- "latest opening message",
2650
+ "kept, summarized, or archived",
2651
+ "Do not remove validation evidence",
2652
+ "full opening message never belongs in this log",
2653
+ "latest opening message",
2187
2654
  "not current state"
2188
2655
  ];
2189
2656
  if (preamble.includes(snippet)) return sessionLogPreambleContains(text, snippet);
@@ -2236,8 +2703,14 @@ function projectDecisionsAnchorPlacement(snippet, text) {
2236
2703
  return true;
2237
2704
  }
2238
2705
 
2239
- function onboardingAnchorPlacement(snippet, text) {
2240
- if (snippet === "Application Scenario Library") {
2706
+ function onboardingAnchorPlacement(snippet, text) {
2707
+ if (snippet === "Continuity startup boundary" || snippet === "starts continuity and reads the current handoff state; it is not an onboarding signal") {
2708
+ return snippetAppearsBetweenHeadings(text, snippet, "## Load When", "## Discipline");
2709
+ }
2710
+ if (snippet === "Infer when sufficient; ask only when unresolved") {
2711
+ return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Application Scenario Library");
2712
+ }
2713
+ if (snippet === "Application Scenario Library") {
2241
2714
  return Boolean(textSectionBounds(text, "## Application Scenario Library", "## Cross-reference to guide.html"));
2242
2715
  }
2243
2716
  if (/^Scenario [A-F]\./.test(snippet)) {
@@ -2247,7 +2720,7 @@ function onboardingAnchorPlacement(snippet, text) {
2247
2720
  }
2248
2721
 
2249
2722
  function integrationsAnchorPlacement(snippet, text) {
2250
- if (snippet === "Credential Separation Principle" || snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands") {
2723
+ if (snippet === "Credential Separation Principle" || snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Source-of-truth Architecture" || snippet === "Cross-session Lifecycle" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands" || snippet === "Local HTML / app validation fallback" || snippet === "`file://` rejection alone is not enough evidence to stop") {
2251
2724
  return snippetAppearsBetweenHeadings(text, snippet, "## Discipline", "## Rules");
2252
2725
  }
2253
2726
  if (snippet === "Connector-first default") {
@@ -2328,6 +2801,14 @@ const semanticAnchorRepairStrategies = {
2328
2801
  mergedText: mergedCommunication
2329
2802
  } : null;
2330
2803
  },
2804
+ "dev/rules/onboarding.md": (targetText, sourceText) => {
2805
+ const mergedOnboarding = mergeOnboardingDecisionFirstPolicy(targetText, sourceText);
2806
+ return mergedOnboarding ? {
2807
+ action: "merge",
2808
+ reason: "restore decision-first onboarding in its trusted semantic sections",
2809
+ mergedText: mergedOnboarding
2810
+ } : null;
2811
+ },
2331
2812
  "dev/rules/integrations.md": (targetText, sourceText, missing) => {
2332
2813
  const mergedIntegrations = mergeIntegrationsSectionsByMissingAnchors(targetText, sourceText, missing);
2333
2814
  return mergedIntegrations ? {
@@ -2425,6 +2906,169 @@ function mergeCommunicationNextStepDiscipline(targetText, sourceText, missing) {
2425
2906
  return merged === targetText ? null : merged;
2426
2907
  }
2427
2908
 
2909
+ function parseMarkdownH2Sections(text) {
2910
+ const sections = [];
2911
+ const linePattern = /.*(?:\r?\n|$)/g;
2912
+ let fenced = false;
2913
+ let fenceDelimiter = null;
2914
+ let inComment = false;
2915
+ let match;
2916
+ while ((match = linePattern.exec(text)) && match[0] !== "") {
2917
+ const raw = match[0];
2918
+ const line = raw.replace(/\r?\n$/, "");
2919
+ const trimmed = line.trim();
2920
+ if (inComment) {
2921
+ if (trimmed.includes("-->")) inComment = false;
2922
+ continue;
2923
+ }
2924
+ if (trimmed.startsWith("<!--")) {
2925
+ if (!trimmed.includes("-->")) inComment = true;
2926
+ continue;
2927
+ }
2928
+ const fence = trimmed.match(/^(`{3,}|~{3,})/);
2929
+ if (fence) {
2930
+ if (!fenced) {
2931
+ fenced = true;
2932
+ fenceDelimiter = fence[1][0];
2933
+ } else if (fence[1][0] === fenceDelimiter) {
2934
+ fenced = false;
2935
+ fenceDelimiter = null;
2936
+ }
2937
+ continue;
2938
+ }
2939
+ if (fenced) continue;
2940
+ const headingMatch = line.match(/^## ([^#].*?)\s*$/);
2941
+ if (headingMatch) sections.push({ title: headingMatch[1], start: match.index, end: text.length });
2942
+ }
2943
+ for (let index = 0; index < sections.length - 1; index += 1) {
2944
+ sections[index].end = sections[index + 1].start;
2945
+ }
2946
+ return sections;
2947
+ }
2948
+
2949
+ function lcsLinePairs(left, right) {
2950
+ const rows = left.length + 1;
2951
+ const cols = right.length + 1;
2952
+ const table = Array.from({ length: rows }, () => new Uint16Array(cols));
2953
+ for (let i = left.length - 1; i >= 0; i -= 1) {
2954
+ for (let j = right.length - 1; j >= 0; j -= 1) {
2955
+ table[i][j] = left[i] === right[j]
2956
+ ? table[i + 1][j + 1] + 1
2957
+ : Math.max(table[i + 1][j], table[i][j + 1]);
2958
+ }
2959
+ }
2960
+ const pairs = [];
2961
+ let i = 0;
2962
+ let j = 0;
2963
+ while (i < left.length && j < right.length) {
2964
+ if (left[i] === right[j]) {
2965
+ pairs.push([i, j]);
2966
+ i += 1;
2967
+ j += 1;
2968
+ } else if (table[i + 1][j] >= table[i][j + 1]) i += 1;
2969
+ else j += 1;
2970
+ }
2971
+ return pairs;
2972
+ }
2973
+
2974
+ function lineDiffHunks(base, changed) {
2975
+ const pairs = [...lcsLinePairs(base, changed), [base.length, changed.length]];
2976
+ const hunks = [];
2977
+ let baseCursor = 0;
2978
+ let changedCursor = 0;
2979
+ for (const [baseMatch, changedMatch] of pairs) {
2980
+ if (baseMatch > baseCursor || changedMatch > changedCursor) {
2981
+ hunks.push({ baseStart: baseCursor, baseEnd: baseMatch, added: changed.slice(changedCursor, changedMatch) });
2982
+ }
2983
+ baseCursor = baseMatch + 1;
2984
+ changedCursor = changedMatch + 1;
2985
+ }
2986
+ return hunks;
2987
+ }
2988
+
2989
+ function hunksOverlap(left, right) {
2990
+ const leftInsertion = left.baseStart === left.baseEnd;
2991
+ const rightInsertion = right.baseStart === right.baseEnd;
2992
+ if (leftInsertion && rightInsertion) return false;
2993
+ if (leftInsertion) return left.baseStart > right.baseStart && left.baseStart < right.baseEnd;
2994
+ if (rightInsertion) return right.baseStart > left.baseStart && right.baseStart < left.baseEnd;
2995
+ return left.baseStart < right.baseEnd && right.baseStart < left.baseEnd;
2996
+ }
2997
+
2998
+ function mapBaseBoundaryToChanged(base, changed, boundary) {
2999
+ if (boundary === 0) return 0;
3000
+ if (boundary === base.length) return changed.length;
3001
+ const pairs = lcsLinePairs(base, changed);
3002
+ const next = pairs.find(([baseIndex]) => baseIndex >= boundary);
3003
+ if (next) return next[1];
3004
+ const previous = [...pairs].reverse().find(([baseIndex]) => baseIndex < boundary);
3005
+ return previous ? previous[1] + 1 : null;
3006
+ }
3007
+
3008
+ function threeWayPreserveLocalChanges(baseText, localText, currentText) {
3009
+ if (localText.replace(/\r\n/g, "\n") === currentText.replace(/\r\n/g, "\n")) return localText;
3010
+ const baseHadFinalNewline = /\r?\n$/.test(baseText);
3011
+ const localHadFinalNewline = /\r?\n$/.test(localText);
3012
+ const base = baseText.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
3013
+ const local = localText.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
3014
+ const current = currentText.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
3015
+ const localHunks = lineDiffHunks(base, local);
3016
+ const upstreamHunks = lineDiffHunks(base, current);
3017
+ if (localHunks.some((localHunk) => upstreamHunks.some((upstreamHunk) => hunksOverlap(localHunk, upstreamHunk)))) return null;
3018
+
3019
+ const merged = [...current];
3020
+ const mapped = [];
3021
+ for (const hunk of localHunks) {
3022
+ const start = mapBaseBoundaryToChanged(base, current, hunk.baseStart);
3023
+ const end = mapBaseBoundaryToChanged(base, current, hunk.baseEnd);
3024
+ if (start == null || end == null || end < start) return null;
3025
+ mapped.push({ start, end, added: hunk.added });
3026
+ }
3027
+ for (const hunk of mapped.sort((a, b) => b.start - a.start)) merged.splice(hunk.start, hunk.end - hunk.start, ...hunk.added);
3028
+ const newline = localText.includes("\r\n") ? "\r\n" : "\n";
3029
+ return `${merged.join(newline)}${localHadFinalNewline || baseHadFinalNewline ? newline : ""}`;
3030
+ }
3031
+
3032
+ function uniqueH2Section(text, title) {
3033
+ const matches = parseMarkdownH2Sections(text).filter((section) => section.title === title);
3034
+ return matches.length === 1 ? matches[0] : null;
3035
+ }
3036
+
3037
+ function projectIndexGovernanceSectionsAreValid(text) {
3038
+ const installed = uniqueH2Section(text, "Installed Integrations");
3039
+ const toolRefs = uniqueH2Section(text, "Tool Operation References");
3040
+ const localQc = uniqueH2Section(text, "Local QC Commands");
3041
+ return Boolean(installed && toolRefs && localQc && installed.start < toolRefs.start && toolRefs.start < localQc.start);
3042
+ }
3043
+
3044
+ function mergeProjectIndexGovernanceSections(targetText, sourceText) {
3045
+ const targetSections = parseMarkdownH2Sections(targetText);
3046
+ const sourceSections = parseMarkdownH2Sections(sourceText);
3047
+ const requiredTitles = ["Installed Integrations", "Tool Operation References", "Local QC Commands"];
3048
+ const targetByTitle = new Map(requiredTitles.map((title) => [title, targetSections.filter((section) => section.title === title)]));
3049
+ const sourceByTitle = new Map(requiredTitles.map((title) => [title, sourceSections.filter((section) => section.title === title)]));
3050
+ if (requiredTitles.some((title) => sourceByTitle.get(title).length !== 1)) return null;
3051
+ if (targetByTitle.get("Local QC Commands").length !== 1) return null;
3052
+ if (targetByTitle.get("Installed Integrations").length > 1 || targetByTitle.get("Tool Operation References").length > 1) return null;
3053
+
3054
+ const installed = targetByTitle.get("Installed Integrations")[0];
3055
+ const toolRefs = targetByTitle.get("Tool Operation References")[0];
3056
+ const localQc = targetByTitle.get("Local QC Commands")[0];
3057
+ if ((installed && installed.start > localQc.start) || (toolRefs && toolRefs.start > localQc.start)) return null;
3058
+ if (installed && toolRefs && installed.start > toolRefs.start) return null;
3059
+
3060
+ const missing = requiredTitles.slice(0, 2).filter((title) => targetByTitle.get(title).length === 0);
3061
+ let merged = targetText;
3062
+ if (missing.length > 0) {
3063
+ const insertion = missing
3064
+ .map((title) => sourceText.slice(sourceByTitle.get(title)[0].start, sourceByTitle.get(title)[0].end).trimEnd())
3065
+ .join("\n\n");
3066
+ merged = `${targetText.slice(0, localQc.start).trimEnd()}\n\n${insertion}\n\n${targetText.slice(localQc.start)}`;
3067
+ }
3068
+ merged = mergeProjectIndexCredentialReferences(merged);
3069
+ return projectIndexGovernanceSectionsAreValid(merged) ? merged : null;
3070
+ }
3071
+
2428
3072
  function mergeProjectIndexCredentialReferences(targetText) {
2429
3073
  return targetText
2430
3074
  .replace(
@@ -2523,7 +3167,8 @@ function mergeSafetyRulesByMissingAnchors(targetText, sourceText, missing) {
2523
3167
  { snippet: "parser failure", number: "13" },
2524
3168
  { snippet: "Process termination and cache cleanup boundary", number: "14" },
2525
3169
  { snippet: "task-owned or agent-managed", number: "14" },
2526
- { snippet: "other-agent-owned", number: "14" }
3170
+ { snippet: "other-agent-owned", number: "14" },
3171
+ { snippet: "Short-lived localhost validation services", number: "15" }
2527
3172
  ];
2528
3173
  for (const { snippet, number } of appendableRules) {
2529
3174
  if (!remainingMissing.includes(snippet) || targetText.includes(snippet)) continue;
@@ -2592,7 +3237,7 @@ function mergeIntegrationsSectionsByMissingAnchors(targetText, sourceText, missi
2592
3237
  changed = true;
2593
3238
  }
2594
3239
 
2595
- if (missing.some((snippet) => snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "other-agent-owned" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands")) {
3240
+ if (missing.some((snippet) => snippet === "External Tool Usage Verification Gate" || snippet === "External Tool Resource Lifecycle" || snippet === "other-agent-owned" || snippet === "do not invent" || snippet === "input schema" || snippet === "official documentation" || snippet === "Runtime-Controlled Tool Operation Variants" || snippet === "Tool Operation References" || snippet === "Do not guess Chrome, Playwright, or DevTools commands" || snippet === "Local HTML / app validation fallback" || snippet === "`file://` rejection alone is not enough evidence to stop")) {
2596
3241
  const withVerificationGate = mergeIntegrationsVerificationGateSection(merged, sourceText);
2597
3242
  if (!withVerificationGate) return null;
2598
3243
  merged = withVerificationGate;
@@ -2636,38 +3281,6 @@ function mergeIntegrationsVerificationGateSection(targetText, sourceText) {
2636
3281
  return null;
2637
3282
  }
2638
3283
 
2639
- function isLegacyChineseIntegrationsPack(text) {
2640
- return text.includes("# Integrations Pack")
2641
- && countText(text, "## Scope") === 1
2642
- && countText(text, "## Load When") === 1
2643
- && countText(text, "## Discipline") === 1
2644
- && countText(text, "## Rules") === 1
2645
- && countText(text, "## Checks") === 1
2646
- && countText(text, "## Closeout") === 1
2647
- && countText(text, "## Cross-reference") === 1
2648
- && (text.includes("機密分離原則") || text.includes("四類整合"))
2649
- && !text.includes("## Local Discipline")
2650
- && !text.includes("Duplicate ambiguous local heading")
2651
- && countText(text, "四類整合") <= 2;
2652
- }
2653
-
2654
- function isLegacyChineseOnboardingPack(text) {
2655
- return text.includes("# Onboarding Pack")
2656
- && countText(text, "## Scope") === 1
2657
- && countText(text, "## Load When") === 1
2658
- && countText(text, "## Discipline") === 1
2659
- && countText(text, "## Application Scenario Library") === 1
2660
- && countText(text, "## Cross-reference to guide.html") === 1
2661
- && countText(text, "## Tone Discipline") === 1
2662
- && countText(text, "## Closeout") === 1
2663
- && text.includes("### Scenario A.")
2664
- && text.includes("### Scenario E.")
2665
- && (text.includes("明確 onboarding signal keywords") || text.includes("Scenario F. 審視已裝外部工具") || text.includes("Anti-pattern(不要做的事)"))
2666
- && !text.includes("### Local Scenario A")
2667
- && !text.includes("structurally ambiguous onboarding")
2668
- && !text.includes("## Local Discipline");
2669
- }
2670
-
2671
3284
  function hasTrustedSafetyPackShape(text) {
2672
3285
  return text.includes("# Safety Pack")
2673
3286
  && text.includes("## Scope")
@@ -2699,10 +3312,10 @@ function safetyAnchorHasTrustedRuleShape(text, snippet) {
2699
3312
  && line.includes("Prefer native PowerShell cmdlets")
2700
3313
  && line.includes("do not compose filesystem modification commands across shells");
2701
3314
  }
2702
- if (snippet === "git reset --hard") {
2703
- return line.includes("branch deletion")
2704
- && line.includes("force push")
2705
- && line.includes("history rewrite");
3315
+ if (snippet === "git reset --hard") {
3316
+ return line.includes("Never run")
3317
+ && line.includes("User request does not make these named commands permissible")
3318
+ && line.includes("git clean -fdx");
2706
3319
  }
2707
3320
  if (snippet === "secret values") {
2708
3321
  return line.includes("Do not print")
@@ -2782,15 +3395,84 @@ function textSectionBounds(text, startHeading, endHeading) {
2782
3395
  return { start: startIndex, end: endIndex };
2783
3396
  }
2784
3397
 
2785
- function projectIndexTemplateVersion(text) {
3398
+ function projectIndexTemplateVersion(text) {
2786
3399
  const bounds = textSectionBounds(text, "## Stack", "## Directory Map");
2787
3400
  if (!bounds) return null;
2788
3401
  const stack = text.slice(bounds.start, bounds.end);
2789
3402
  const row = stack.match(/^\| Agent Handoff Kit template version \| ([\d.]+) \| [^|\n]+ \|$/m);
2790
- return row ? row[1] : null;
2791
- }
2792
-
2793
- function mergeHandoffLifecycleField(targetText) {
3403
+ return row ? row[1] : null;
3404
+ }
3405
+
3406
+ function migrateSessionHandoff(targetText, sourceText, context = {}) {
3407
+ if (countText(targetText, "## Next Session Opening Message") !== 1) return null;
3408
+ let merged = mergeLegacyFirstStartupGuidance(targetText, sourceText) ?? targetText;
3409
+
3410
+ if (!merged.includes("ack:field:lifecycle-conflicts-resolved")) {
3411
+ merged = mergeHandoffLifecycleField(merged);
3412
+ if (!merged) return null;
3413
+ }
3414
+ merged = ensureCurrentHandoffMigrationFields(merged);
3415
+ if (!merged) return null;
3416
+ if (isUpgradeFromOlderTemplate(context)
3417
+ && isPlaceholderLifecycleFieldValue(fieldValueAfterMarker(merged, "lifecycle-conflicts-resolved"))
3418
+ && hasSubstantiveHandoffState(merged)) {
3419
+ merged = reclassifyExistingHandoffLifecyclePlaceholder(merged);
3420
+ if (!merged) return null;
3421
+ }
3422
+
3423
+ if (!merged.includes("ack:field:first-use-guidance-state")) {
3424
+ const nextMarker = "<!-- ack:section:task-understanding-summary -->";
3425
+ if (!merged.includes(nextMarker)) return null;
3426
+ const field = "<!-- ack:field:first-use-guidance-state -->\n5. First-use guidance state: not_applicable — added by upgrade; prior use state is preserved and onboarding is not reactivated.\n\n";
3427
+ merged = merged.replace(nextMarker, `${field}${nextMarker}`);
3428
+ }
3429
+
3430
+ const archiveRule = mergeHandoffArchiveContinuityRule(merged, sourceText);
3431
+ if (!archiveRule) return null;
3432
+ merged = archiveRule;
3433
+
3434
+ const targetBounds = handoffSectionContentBounds(merged, "next-session-opening-message", "Next Session Opening Message");
3435
+ const sourceBounds = handoffSectionContentBounds(sourceText, "next-session-opening-message", "Next Session Opening Message");
3436
+ if (!targetBounds || !sourceBounds) return null;
3437
+ const targetSection = merged.slice(targetBounds.start, targetBounds.end);
3438
+ const sourceSection = sourceText.slice(sourceBounds.start, sourceBounds.end);
3439
+ const targetPrompt = targetSection.match(/```text\s*\r?\n([\s\S]*?)\r?\n```/);
3440
+ const sourcePrompt = sourceSection.match(/```text\s*\r?\n([\s\S]*?)\r?\n```/);
3441
+ if (!targetPrompt || !sourcePrompt) return null;
3442
+ const existingRoot = targetPrompt[1].match(/^Work in (.+?)\. Read AGENTS\.md,/m)?.[1] ?? "<absolute project root>";
3443
+ const currentPrompt = sourcePrompt[1].replace("<absolute project root>", existingRoot);
3444
+ const updatedSection = targetSection.replace(targetPrompt[0], `\`\`\`text\n${currentPrompt}\n\`\`\``);
3445
+ merged = `${merged.slice(0, targetBounds.start)}${updatedSection}${merged.slice(targetBounds.end)}`;
3446
+
3447
+ const temperatureRepair = repairHandoffCurrentStateEvidenceBoundary(merged);
3448
+ return temperatureRepair.text;
3449
+ }
3450
+
3451
+ function migrateSessionLog(targetText, sourceText) {
3452
+ let merged = mergeSessionLogTemplateContract(targetText, sourceText);
3453
+ if (!merged) return null;
3454
+ merged = mergeSessionLogEvidenceDispositionField(merged) ?? merged;
3455
+
3456
+ const startMarker = "<!-- ack:log-entry:start -->";
3457
+ const endMarker = "<!-- ack:log-entry:end -->";
3458
+ if (countText(merged, startMarker) !== 1 || countText(merged, endMarker) !== 1
3459
+ || countText(sourceText, startMarker) !== 1 || countText(sourceText, endMarker) !== 1) return null;
3460
+ const targetStart = merged.indexOf(startMarker);
3461
+ const targetEnd = merged.indexOf(endMarker, targetStart) + endMarker.length;
3462
+ const sourceStart = sourceText.indexOf(startMarker);
3463
+ const sourceEnd = sourceText.indexOf(endMarker, sourceStart) + endMarker.length;
3464
+ merged = `${merged.slice(0, targetStart)}${sourceText.slice(sourceStart, sourceEnd)}${merged.slice(targetEnd)}`;
3465
+
3466
+ merged = merged.replace(/```(?:text)?\s*\r?\n([\s\S]*?)\r?\n```/g, (block, content) => {
3467
+ const signatures = ["Work in ", "Read AGENTS.md", "SESSION_HANDOFF.md", "PROJECT_INDEX.md"];
3468
+ return signatures.every((signature) => content.includes(signature))
3469
+ ? "Opening-message mirror: migrated; full text omitted by design."
3470
+ : block;
3471
+ });
3472
+ return merged;
3473
+ }
3474
+
3475
+ function mergeHandoffLifecycleField(targetText) {
2794
3476
  const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2795
3477
  if (!targetText.includes(openingMarker)) return null;
2796
3478
 
@@ -2969,8 +3651,9 @@ function restoreMissingSessionLogPreambleLines(targetText, sourceText) {
2969
3651
  const missingLines = [
2970
3652
  "Record what actually happened in the session",
2971
3653
  "kept, summarized, or archived",
2972
- "Do not remove validation evidence",
2973
- "latest opening message",
3654
+ "Do not remove validation evidence",
3655
+ "full opening message never belongs",
3656
+ "latest opening message",
2974
3657
  "not current state"
2975
3658
  ].flatMap((snippet) => {
2976
3659
  if (targetText.includes(snippet)) return [];
@@ -3006,50 +3689,58 @@ function mergeHandoffArchiveContinuityRule(targetText, sourceText) {
3006
3689
  return null;
3007
3690
  }
3008
3691
 
3009
- function mergeRulePacksRows(targetText, sourceText) {
3010
- const requiredPacks = [
3011
- "dev/rules/onboarding.md",
3012
- "dev/rules/integrations.md",
3013
- "dev/rules/agent-governance.md"
3014
- ];
3015
- const sourceRows = sourceText
3016
- .split(/\r?\n/)
3017
- .filter((line) => line.startsWith("|") && requiredPacks.some((pack) => line.includes(pack)));
3018
- if (sourceRows.length === 0) return targetText;
3019
-
3020
- const lines = targetText.split(/\r?\n/);
3021
- const tableStart = lines.findIndex((line) => line.trim() === "| Task signal | Pack | Purpose |");
3022
- if (tableStart < 0) return null;
3023
-
3024
- let tableEnd = tableStart;
3025
- while (tableEnd < lines.length && lines[tableEnd].startsWith("|")) tableEnd++;
3026
-
3027
- const before = lines.slice(0, tableStart);
3028
- const governanceBridgeSourceRow = sourceRows.find((row) => row.includes("Governance bridge / bridge governance"));
3029
- const hasAnyGovernanceRow = targetText.includes("Governance bridge / 治理打通") || targetText.includes("Governance bridge / bridge governance");
3030
- const table = lines.slice(tableStart, tableEnd).map((line) => (
3031
- governanceBridgeSourceRow && (line.includes("Governance bridge / 治理打通") || line.includes("Governance bridge / bridge governance"))
3032
- ? governanceBridgeSourceRow
3033
- : line
3034
- ));
3035
- const after = lines.slice(tableEnd);
3036
- const sourceRowsToApply = sourceRows.filter((row) => {
3037
- if (row.includes("dev/rules/onboarding.md")) return !targetText.includes("First-time user signals");
3038
- if (row.includes("External tool resource pressure")) return !targetText.includes("External tool resource pressure");
3039
- if (row.includes("dev/rules/integrations.md")) return !targetText.includes("External tool integrations");
3040
- if (row.includes("Governance bridge / bridge governance")) return !hasAnyGovernanceRow;
3041
- return false;
3042
- });
3043
- if (sourceRowsToApply.length === 0 && table.join("\n") === lines.slice(tableStart, tableEnd).join("\n")) return targetText;
3044
-
3045
- const merged = [
3046
- ...before,
3047
- ...table,
3048
- ...sourceRowsToApply,
3049
- ...after
3050
- ];
3051
- return merged.join("\n");
3052
- }
3692
+ function mergeRulePacksRows(targetText, sourceText) {
3693
+ const sourceRows = sourceText.split(/\r?\n/).filter((line) => /^\|.*<!-- ack:route:[a-z0-9-]+ -->/.test(line));
3694
+ const sourceById = new Map(sourceRows.map((row) => [routeMarkerId(row), row]));
3695
+ if (sourceById.size === 0 || sourceById.size !== sourceRows.length) return null;
3696
+
3697
+ const lines = targetText.split(/\r?\n/);
3698
+ const headerIndexes = lines.map((line, index) => line.trim() === "| Task signal | Pack | Purpose |" ? index : -1).filter((index) => index >= 0);
3699
+ if (headerIndexes.length !== 1) return null;
3700
+ const tableStart = headerIndexes[0];
3701
+ if (!/^\|[-\s|]+\|$/.test(lines[tableStart + 1]?.trim() ?? "")) return null;
3702
+ let tableEnd = tableStart + 2;
3703
+ while (tableEnd < lines.length && lines[tableEnd].startsWith("|")) tableEnd += 1;
3704
+
3705
+ const seen = new Set();
3706
+ const localRows = [];
3707
+ const replacedRows = [];
3708
+ for (const row of lines.slice(tableStart + 2, tableEnd)) {
3709
+ const markedId = routeMarkerId(row);
3710
+ const legacyId = markedId ? null : knownOfficialLegacyRouteId(row);
3711
+ const id = markedId ?? legacyId;
3712
+ if (id && sourceById.has(id)) {
3713
+ if (seen.has(id)) return null;
3714
+ seen.add(id);
3715
+ replacedRows.push(sourceById.get(id));
3716
+ continue;
3717
+ }
3718
+ localRows.push(row);
3719
+ }
3720
+
3721
+ const missingOfficialRows = sourceRows.filter((row) => !seen.has(routeMarkerId(row)));
3722
+ const mergedTable = [lines[tableStart], lines[tableStart + 1], ...missingOfficialRows, ...replacedRows, ...localRows];
3723
+ const originalTable = lines.slice(tableStart, tableEnd);
3724
+ if (mergedTable.join("\n") === originalTable.join("\n")) return targetText;
3725
+ return [...lines.slice(0, tableStart), ...mergedTable, ...lines.slice(tableEnd)].join("\n");
3726
+ }
3727
+
3728
+ const knownOfficialLegacyRouteHashes = new Map([
3729
+ ["f2c36ac687929b03891b37fe79aace2c806d9d5027c43b7d280c386574e44c14", "onboarding"],
3730
+ ["3153da07fb53483eeb4a35cfff013f44c5a75d14b1a44ee536bcd85cbc3219c6", "governance-bridge"],
3731
+ ["d3379dc2984fb0f2a8f122c4efbf131b2da320e66845d4c5f1945300431879f3", "long-term-governance"],
3732
+ ["2011d8309aaa5d6cc76f7036e990355c472a5ed6ba81fcf8e0078b9a6c5f6ef1", "integration-use"],
3733
+ ["3fc0717cc408dbe96e8925a07f6315448abb0f38106dbe844a098d7ab84d37cc", "runtime-tool"],
3734
+ ["7cd99dbd30bbf7be9641f6a5fc7bf4c7cbe3efb3ab114fe1f19c254cd110612d", "resource-closeout"]
3735
+ ]);
3736
+
3737
+ function routeMarkerId(row) {
3738
+ return row.match(/<!-- ack:route:([a-z0-9-]+) -->/)?.[1] ?? null;
3739
+ }
3740
+
3741
+ function knownOfficialLegacyRouteId(row) {
3742
+ return knownOfficialLegacyRouteHashes.get(sha256(Buffer.from(row.trim(), "utf8"))) ?? null;
3743
+ }
3053
3744
 
3054
3745
  // R-031.2 v0.3.2+: Version alignment assessment for doctor "項目狀態速覽".
3055
3746
  // Compares CLI version (running), root template metadata version (in dev/PROJECT_INDEX.md),
@@ -3165,22 +3856,23 @@ function printLastCloseout(result) {
3165
3856
  // R-031.2 v0.3.2+: Project age assessment. Reads the oldest folder timestamp in
3166
3857
  // dev/governance_migrations/ which records the first install date. Read-only; doctor
3167
3858
  // remains side-effect-free (no new write logic).
3168
- async function assessProjectAge(root) {
3169
- const migrationsDir = path.join(root, "dev/governance_migrations");
3170
- try {
3171
- const entries = await readdir(migrationsDir);
3172
- const timestamps = entries.filter((name) => /^\d{8}T\d{6}Z$/.test(name)).sort();
3173
- if (timestamps.length === 0) return { firstInstall: null };
3174
- const oldest = timestamps[0];
3175
- // Format: 20260423T112233Z → 2026-04-23
3176
- const year = oldest.slice(0, 4);
3177
- const month = oldest.slice(4, 6);
3178
- const day = oldest.slice(6, 8);
3179
- return { firstInstall: `${year}-${month}-${day}` };
3180
- } catch {
3181
- return { firstInstall: null };
3182
- }
3183
- }
3859
+ async function assessProjectAge(root) {
3860
+ const migrationsDir = path.join(root, "dev/governance_migrations");
3861
+ try {
3862
+ const entries = await readdir(migrationsDir);
3863
+ const dates = entries.map(parseMigrationDirectoryDate).filter(Boolean).sort();
3864
+ return { firstInstall: dates[0] ?? null };
3865
+ } catch {
3866
+ return { firstInstall: null };
3867
+ }
3868
+ }
3869
+
3870
+ function parseMigrationDirectoryDate(name) {
3871
+ const legacy = /^(\d{4})(\d{2})(\d{2})T\d{6}Z$/.exec(name);
3872
+ if (legacy) return `${legacy[1]}-${legacy[2]}-${legacy[3]}`;
3873
+ const transaction = /^(\d{4})-(\d{2})-(\d{2})T\d{2}-\d{2}-\d{2}-\d{3}Z-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.exec(name);
3874
+ return transaction ? `${transaction[1]}-${transaction[2]}-${transaction[3]}` : null;
3875
+ }
3184
3876
 
3185
3877
  function printProjectAge(result) {
3186
3878
  if (!result.firstInstall) {
@@ -3469,8 +4161,8 @@ function printInstallSummary(version, command, mode, root, counts) {
3469
4161
  if (counts.conflicts > 0) {
3470
4162
  console.log("🚀 下一步:把 migration report 或這段輸出貼給 AI,請它判斷衝突檔案怎樣處理;工具已停手,沒有覆寫 conflict 檔案。");
3471
4163
  } else if (command === "upgrade") {
3472
- console.log("🚀 下一步:留意下方升級後自動檢查;若全綠即升級完成。");
3473
- } else if (mode === "partial" || counts.skipped > 0) {
4164
+ console.log("🚀 下一步:留意下方 migration committed 與 project health 的分開結果。");
4165
+ } else if (counts.skipped > 0) {
3474
4166
  console.log("🚀 下一步:先看下方提示。若你原本已有 AGENTS.md 或其他 AI 規則,請先執行 upgrade --dry-run 補入口連接,再執行 doctor。");
3475
4167
  } else {
3476
4168
  console.log("🚀 下一步:不用再留在終端機。打開 AI 工具,啟動 Agent Handoff。");
@@ -3661,7 +4353,7 @@ function printCard(version, status, eyes) {
3661
4353
  function printInstallNextSteps(root, conflictCount, mode = "first-install", skippedCount = 0) {
3662
4354
  console.log("");
3663
4355
  console.log("============================================================");
3664
- if (mode === "partial" || skippedCount > 0) {
4356
+ if (skippedCount > 0) {
3665
4357
  console.log("⚠️ 已補齊缺少檔案,但仍要檢查入口連接");
3666
4358
  } else {
3667
4359
  console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
@@ -3673,7 +4365,7 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
3673
4365
  console.log("📋 下一步:把 migration report 或這段輸出貼給 AI,請它幫你判斷怎樣合併。");
3674
4366
  console.log("");
3675
4367
  }
3676
- if (mode === "partial" || skippedCount > 0) {
4368
+ if (skippedCount > 0) {
3677
4369
  console.log("你原本已有部分 AI 記憶檔,工具已保留它們,沒有覆寫。");
3678
4370
  console.log("下一步先不要開始新任務;請在終端機執行以下預演,讓工具檢查能否安全補入口連接:");
3679
4371
  console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run");
@@ -3696,8 +4388,9 @@ function printInstallNextSteps(root, conflictCount, mode = "first-install", skip
3696
4388
  console.log(startupPathBootstrapPrompt(root));
3697
4389
  console.log("------------------------------------------------------------");
3698
4390
  console.log("");
3699
- console.log("🚀 AI 會依 AGENTS.md 讀取 START_NEXT_SESSION_PROMPT.txt。第一次安裝後,該檔案會觸發新手引導;收工後,該檔案會承載下一次接力狀態。");
3700
- console.log(" 收工可說「Wrap up Agent Handoff」/「收工」;「某某開工 / 某某收工」會先確認是否指本工具交接。");
4391
+ console.log("🚀 AI 會依 AGENTS.md 先讀取權威交接狀態。START_NEXT_SESSION_PROMPT.txt 只是給尚未指向此資料夾的 AI 使用的生成鏡像。");
4392
+ console.log(" 已給出明確任務時,AI 直接開始第一個安全步驟;只有你要求教學或仍無可執行目標時才進入新手引導。");
4393
+ console.log(" 收工可說「Wrap up Agent Handoff」/「收工」;「開工,繼續 <任務>」會直接接力。");
3701
4394
  console.log("============================================================");
3702
4395
  }
3703
4396
 
@@ -3716,14 +4409,14 @@ function printUpgradeNextSteps(root, conflictCount) {
3716
4409
  console.log("============================================================");
3717
4410
  return;
3718
4411
  }
3719
- console.log("🛠️ Kit 檔案已更新:等待下方 doctor 驗收");
4412
+ console.log("🛠️ Kit migration 已通過離線遷移驗收;下方 doctor 另行回報整體項目健康");
3720
4413
  console.log("============================================================");
3721
4414
  console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
3722
4415
  console.log("");
3723
4416
  console.log("💡 版本詳情不在升級流程內展開;如需要,可稍後查看 GitHub Release:");
3724
4417
  console.log(" https://github.com/Adamchanadam/agent-handoff-kit/releases/latest");
3725
4418
  console.log("");
3726
- console.log("🩺 升級驗收會在下方自動執行 doctor;若全綠即升級完成。");
4419
+ console.log("🩺 下方會分開顯示 migration committed 與 project health;doctor 需要處理時,不會改寫已提交的遷移結果。");
3727
4420
  console.log("============================================================");
3728
4421
  }
3729
4422
 
@@ -3832,10 +4525,10 @@ Commands:
3832
4525
  Work in <project root>. Read AGENTS.md first, then Start Agent Handoff. Before changing anything, tell me the current state and your recommended next step.
3833
4526
  例如 Claude Code、OpenAI Codex、Gemini CLI、Google Antigravity。
3834
4527
  普通 web chat AI 若不能讀寫本機資料夾,並不適合使用本工具。
3835
- AI 會依 AGENTS.md 讀取 START_NEXT_SESSION_PROMPT.txt;第一次安裝後該檔案會啟動新手引導,
3836
- 收工後該檔案會承載下一次接力狀態。
3837
- 用「Wrap up Agent Handoff」/「收工」保存交接;「某某開工 / 某某收工」
3838
- 會先確認是否指本工具交接。
4528
+ AI 已在項目根目錄時,依 AGENTS.md 判斷意圖;只有接力、收工或依賴既有狀態的任務才讀交接狀態,
4529
+ 不會再重讀 START_NEXT_SESSION_PROMPT.txt。第一次安裝只令新手引導可用,不會強制進入教學。
4530
+ 用「Wrap up Agent Handoff」/「收工」保存交接;「<項目名> 開工」是明確接力。
4531
+ 只有語句確實可能指現實工作、活動或其他語境時,AI 才問一條精簡確認問題。
3839
4532
 
3840
4533
  終端機範例:
3841
4534
  npx --yes @adamchanadam/agent-handoff-kit@latest init