@adamchanadam/agent-handoff-kit 0.3.22 → 0.3.24

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Agent Handoff Kit
2
2
 
3
- 狀態:目前版本為 `v0.3.22`。這是早期可用版本,仍在持續完善中。
3
+ 狀態:目前版本為 `v0.3.24`。這是早期可用版本,仍在持續完善中。
4
4
 
5
5
  ![Agent Handoff Kit 主視覺](https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-main-visual2.png)
6
6
 
@@ -283,7 +283,7 @@ Agent Handoff Kit 可與 [Adam-AI-Instructions](https://github.com/prompt-templa
283
283
 
284
284
  ## 目前限制
285
285
 
286
- - 目前版本為 `v0.3.22`;正式安裝請以 npm registry `latest` 顯示為準。
286
+ - 目前版本為 `v0.3.24`;正式安裝請以 npm registry `latest` 顯示為準。
287
287
  - 這是早期可用版本,仍在持續完善中。
288
288
  - 升級合併屬窄範圍策略,不是完整的複雜合併工具。
289
289
  - `doctor` 能檢查結構,不能代替 AI 對專案內容的理解。
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { createInterface } from "node:readline/promises";
4
- import { stdin as input, stdout as output } from "node:process";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { stdin as input, stdout as output } from "node:process";
5
5
  import { copyFile, mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
6
6
  import path from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
- import { assessPromptMirrorTexts } from "./prompt-mirror-core.mjs";
9
-
10
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
8
+ import { assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
9
+
10
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
11
  const packageRoot = path.resolve(__dirname, "..");
12
12
 
13
13
  const mappings = [
@@ -46,8 +46,10 @@ const requiredAnchors = [
46
46
  "dev/SESSION_HANDOFF.md",
47
47
  "dev/SESSION_LOG.md",
48
48
  "dev/PROJECT_INDEX.md",
49
- "dev/RULE_PACKS.md",
49
+ "dev/RULE_PACKS.md",
50
50
  "Agent Handoff Kit v<version>",
51
+ "Display version rule",
52
+ "Agent Handoff Kit template version",
51
53
  "continuity ready",
52
54
  "Start Agent Handoff",
53
55
  "Ambiguous startup phrases",
@@ -69,12 +71,16 @@ const requiredAnchors = [
69
71
  "Wrap up Agent Handoff",
70
72
  "Ambiguous closeout phrases",
71
73
  "wrap up",
72
- "handoff",
73
- "Reconcile `dev/SESSION_HANDOFF.md`",
74
+ "handoff",
75
+ "Reconcile `dev/SESSION_HANDOFF.md`",
74
76
  "Add a concise entry to `dev/SESSION_LOG.md`",
77
+ "Closeout Write Contract",
78
+ "ack:log-entry:start/end",
75
79
  "next-session opening message",
76
80
  "fenced `text` code block",
77
81
  "handoff saved",
82
+ "Use the same display version rule as startup",
83
+ "Never print the literal placeholder `v<version>`",
78
84
  "next-session startup entry",
79
85
  "State Reconciliation Check",
80
86
  "handoff lifecycle consistency",
@@ -97,9 +103,10 @@ const requiredAnchors = [
97
103
  "ack:section:workspace-identity",
98
104
  "ack:section:sync-status",
99
105
  "ack:section:next-task-required-reading",
100
- "ack:section:state-reconciliation-check",
106
+ "ack:section:state-reconciliation-check",
101
107
  "ack:section:next-session-opening-message",
102
108
  "ack:field:lifecycle-conflicts-resolved",
109
+ "ack:field:persistence-routing-checked",
103
110
  "📋 Next session:",
104
111
  "```text",
105
112
  "Read in order:",
@@ -111,9 +118,13 @@ const requiredAnchors = [
111
118
  label: "session log event and opening message schema",
112
119
  placement: sessionLogAnchorPlacement,
113
120
  snippets: [
121
+ "ack:section:session-log-preamble",
122
+ "ack:section:session-log-entry-template",
123
+ "ack:log-entry:start",
124
+ "ack:log-entry:end",
114
125
  "Record what actually happened in the session",
115
126
  "## Entry Template",
116
- "- **QC:**",
127
+ "- **QC:**",
117
128
  "- **Sync:**",
118
129
  "- **Log maintenance:**",
119
130
  "### Next Session Opening Message",
@@ -176,12 +187,14 @@ const requiredAnchors = [
176
187
  snippets: [
177
188
  "Project Decisions Log",
178
189
  "warm 資料層",
179
- "AI 開工",
180
- "不需要讀",
181
- "AI 在收工時自動 update",
182
- "Evolution Timeline",
183
- "Decisions Archive",
184
- "Architecture Choices",
190
+ "AI 開工",
191
+ "不需要讀",
192
+ "AI 在收工時自動 update",
193
+ "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
194
+ "This file does not store raw build / upload / QC evidence",
195
+ "Evolution Timeline",
196
+ "Decisions Archive",
197
+ "Architecture Choices",
185
198
  "Insights & Learnings"
186
199
  ]
187
200
  },
@@ -252,10 +265,11 @@ const schemaChecks = [
252
265
  section("state-reconciliation-check", "State Reconciliation Check"),
253
266
  section("handoff-sufficiency-check", "Handoff Sufficiency Check"),
254
267
  section("next-session-opening-message", "Next Session Opening Message"),
255
- marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
256
- marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
257
- marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
258
- marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
268
+ marker("field", "stale-snapshots-left", "Stale snapshots left in this handoff"),
269
+ marker("field", "lifecycle-conflicts-resolved", "Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified"),
270
+ marker("field", "persistence-routing-checked", "Persistence routing checked"),
271
+ marker("field", "opening-message-matches-current-state", "Opening message matches current state"),
272
+ marker("field", "state-sections-rewritten-or-confirmed", "State sections rewritten or confirmed current"),
259
273
  marker("field", "user-intent", "User intent:"),
260
274
  marker("field", "task-essence", "Task essence:"),
261
275
  marker("field", "success-criteria", "Success criteria:")
@@ -286,13 +300,18 @@ const schemaChecks = [
286
300
  target: "dev/SESSION_LOG.md",
287
301
  label: "session log entry fields",
288
302
  checks: [
289
- heading("Entry Template"),
290
- includes("- **ID:**"),
303
+ heading("Entry Template"),
304
+ marker("section", "session-log-preamble", "Handoff role"),
305
+ marker("section", "session-log-entry-template", "Entry Template"),
306
+ includes("ack:log-entry:start"),
307
+ includes("ack:log-entry:end"),
308
+ includes("- **ID:**"),
291
309
  includes("- **Summary:**"),
292
310
  includes("- **Changed:**"),
293
- includes("- **Done:**"),
294
- includes("- **QC:**"),
295
- includes("- **Sync:**"),
311
+ includes("- **Done:**"),
312
+ includes("- **QC:**"),
313
+ includes("- **Evidence disposition:**"),
314
+ includes("- **Sync:**"),
296
315
  includes("- **Pending:**"),
297
316
  includes("- **Risks:**"),
298
317
  includes("- **Log maintenance:**")
@@ -361,17 +380,18 @@ const schemaChecks = [
361
380
  includes("dev/rules/integrations.md")
362
381
  ]
363
382
  },
364
- {
365
- target: "dev/PROJECT_DECISIONS.md",
366
- label: "project decisions log structure",
367
- checks: [
368
- heading("Evolution Timeline"),
369
- heading("Decisions Archive"),
370
- heading("Architecture Choices"),
371
- heading("Insights & Learnings"),
372
- includes("(empty)")
373
- ]
374
- },
383
+ {
384
+ target: "dev/PROJECT_DECISIONS.md",
385
+ label: "project decisions log structure",
386
+ checks: [
387
+ heading("Evolution Timeline"),
388
+ heading("Decisions Archive"),
389
+ heading("Architecture Choices"),
390
+ heading("Insights & Learnings"),
391
+ includes("Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>."),
392
+ includes("(empty)")
393
+ ]
394
+ },
375
395
  {
376
396
  target: "dev/rules/onboarding.md",
377
397
  label: "onboarding pack structure (新手引導包)",
@@ -487,28 +507,29 @@ async function runInstall(command, root, options, version) {
487
507
  // this guard, plan-time short-circuit returns before inject can fire, leaving
488
508
  // root on stale version forever.
489
509
  const projectIndexVersionNeedsInject = await needsProjectIndexVersionInject(root, command, version);
490
- const isUpgradeNoopAtPlanTime = command === "upgrade"
491
- && planCreateCount === 0
492
- && planMergeCount === 0
493
- && planConflictCount === 0
494
- && !projectIndexVersionNeedsInject;
495
-
496
- if (isUpgradeNoopAtPlanTime) {
497
- const noOpHealth = await assessUpgradeNoopHealth(root);
498
- printCard(version, "continuity ready", "o.o");
499
- console.log(`command: ${command}`);
500
- console.log(`current directory: ${process.cwd()}`);
510
+ const isUpgradeNoopAtPlanTime = command === "upgrade"
511
+ && planCreateCount === 0
512
+ && planMergeCount === 0
513
+ && planConflictCount === 0
514
+ && !projectIndexVersionNeedsInject;
515
+
516
+ if (isUpgradeNoopAtPlanTime) {
517
+ const noOpHealth = await assessUpgradeNoopHealth(root, version);
518
+ printCard(version, "continuity ready", "o.o");
519
+ console.log(`command: ${command}`);
520
+ console.log(`current directory: ${process.cwd()}`);
501
521
  console.log(`selected root: ${root}`);
502
522
  console.log(`mode: ${mode}`);
503
523
  console.log("");
504
524
  console.log(`📋 計劃預覽:create 0 / merge 0 / skip ${planSkipCount} / conflict 0 — 沒有檔案需要建立或合併。`);
505
525
  if (options.dryRun) {
506
- console.log("");
507
- console.log("dry-run: no files written");
508
- }
509
- printUpgradeNoopShortCircuit(version, noOpHealth);
510
- return;
511
- }
526
+ console.log("");
527
+ console.log("dry-run: no files written");
528
+ }
529
+ printUpgradeNoopShortCircuit(version, noOpHealth);
530
+ if (!noOpHealth.ok) process.exitCode = 1;
531
+ return;
532
+ }
512
533
 
513
534
  printPlan(command, root, mode, plan, version, options.dryRun);
514
535
 
@@ -543,14 +564,19 @@ async function runInstall(command, root, options, version) {
543
564
 
544
565
  await hydrateInitialOpeningPrompt(root, created);
545
566
 
546
- for (const item of plan) {
547
- if (item.action !== "merge") continue;
548
- const backupPath = path.join(backupDir, item.targetRel);
549
- await mkdir(path.dirname(backupPath), { recursive: true });
550
- await copyFile(item.targetAbs, backupPath);
551
- await writeFile(item.targetAbs, item.mergedText, "utf8");
552
- merged.push(item.targetRel);
553
- }
567
+ for (const item of plan) {
568
+ if (item.action !== "merge") continue;
569
+ const backupPath = path.join(backupDir, item.targetRel);
570
+ await mkdir(path.dirname(backupPath), { recursive: true });
571
+ await copyFile(item.targetAbs, backupPath);
572
+ await writeFile(item.targetAbs, item.mergedText, "utf8");
573
+ merged.push(item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
574
+ }
575
+
576
+ const promptRegenerated = await regeneratePromptFromHandoffIfHotEvidence(root, backupDir, merged);
577
+ if (promptRegenerated) {
578
+ console.log("auto-repair: START_NEXT_SESSION_PROMPT.txt - regenerate prompt from repaired handoff opening message");
579
+ }
554
580
 
555
581
  // R-031.3 v0.3.4+: Inject current CLI version into PROJECT_INDEX template version
556
582
  // metadata row — placed AFTER the merge loop to avoid the ordering bug where merge
@@ -593,16 +619,18 @@ async function runInstall(command, root, options, version) {
593
619
  // metadata row was stale (counts 0/0/0 but metadataUpdated truthy), user just
594
620
  // received a substantive upgrade — proceed through full ceremony so doctor
595
621
  // self-check confirms the inject result.
596
- const isUpgradeNoop = command === "upgrade"
597
- && created.length === 0
598
- && merged.length === 0
599
- && conflicts.length === 0
600
- && !metadataUpdated;
601
-
602
- if (isUpgradeNoop) {
603
- printUpgradeNoopShortCircuit(version);
604
- return;
605
- }
622
+ const isUpgradeNoop = command === "upgrade"
623
+ && created.length === 0
624
+ && merged.length === 0
625
+ && conflicts.length === 0
626
+ && !metadataUpdated;
627
+
628
+ if (isUpgradeNoop) {
629
+ const noOpHealth = await assessUpgradeNoopHealth(root, version);
630
+ printUpgradeNoopShortCircuit(version, noOpHealth);
631
+ if (!noOpHealth.ok) process.exitCode = 1;
632
+ return;
633
+ }
606
634
 
607
635
  const report = await writeMigrationReport(root, command, mode, plan, created, merged, conflicts, migrationDir, backupDir, metadataUpdated);
608
636
  printInstallSummary(version, command, mode, root, {
@@ -702,18 +730,52 @@ async function runDoctor(root, version, options = {}) {
702
730
  }
703
731
  }
704
732
 
705
- if (schemaFailures.length > 0) {
706
- printDoctorSummary(version, root, "needs-fix", {
707
- checked: rows.length + anchorRows.length + schemaRows.length,
708
- failedKind: "schema checks",
733
+ if (schemaFailures.length > 0) {
734
+ printDoctorSummary(version, root, "needs-fix", {
735
+ checked: rows.length + anchorRows.length + schemaRows.length,
736
+ failedKind: "schema checks",
709
737
  failedCount: schemaFailures.length,
710
738
  nextStep: "把這段 doctor 輸出貼給 AI,請它先修交接結構,不要直接重裝覆蓋。"
711
739
  });
712
740
  process.exitCode = 1;
713
- return "failed";
714
- }
715
-
716
- const mirrorRows = await checkPromptMirror(root);
741
+ return "failed";
742
+ }
743
+
744
+ const researchTraceResult = await checkResearchDecisionTrace(root);
745
+ console.log(`\nresearch decision trace checks: ${researchTraceResult.checked}`);
746
+ console.log(`${researchTraceResult.ok ? "ok" : "missing"} dev/PROJECT_DECISIONS.md (research-derived decision evidence chains)`);
747
+ if (!researchTraceResult.ok) {
748
+ for (const finding of researchTraceResult.findings) {
749
+ console.log(` missing: ${finding}`);
750
+ }
751
+ printDoctorSummary(version, root, "needs-fix", {
752
+ checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked,
753
+ failedKind: "research decision trace checks",
754
+ failedCount: researchTraceResult.findings.length,
755
+ nextStep: "把 research-derived decision 的 Evidence chain 補齊,並確認 Source=source:<id> token 已登記在 dev/PROJECT_INDEX.md 的 Fact Base 或 External Sources。"
756
+ });
757
+ process.exitCode = 1;
758
+ return "failed";
759
+ }
760
+
761
+ const temperatureResult = await checkHandoffTemperatureBoundary(root);
762
+ console.log(`\nhandoff temperature boundary checks: ${temperatureResult.checked}`);
763
+ console.log(`${temperatureResult.ok ? "ok" : "missing"} dev/SESSION_HANDOFF.md / START_NEXT_SESSION_PROMPT.txt (current-state evidence boundary)`);
764
+ if (!temperatureResult.ok) {
765
+ for (const finding of temperatureResult.findings) {
766
+ console.log(` missing: ${finding}`);
767
+ }
768
+ printDoctorSummary(version, root, "needs-fix", {
769
+ checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked,
770
+ failedKind: "handoff temperature boundary checks",
771
+ failedCount: temperatureResult.findings.length,
772
+ nextStep: "把一次性驗收證據、舊版本狀態、source token 或 Evidence chain 從 Durable Anchors / Next Priorities / opening message 移回 SESSION_LOG、PROJECT_INDEX 或 PROJECT_DECISIONS。"
773
+ });
774
+ process.exitCode = 1;
775
+ return "failed";
776
+ }
777
+
778
+ const mirrorRows = await checkPromptMirror(root);
717
779
  const mirrorBlockingFailures = mirrorRows.filter((row) => !row.ok && row.reason !== "convenience copy differs from dev/SESSION_HANDOFF.md");
718
780
  const mirrorWarnings = mirrorRows.filter((row) => !row.ok && row.reason === "convenience copy differs from dev/SESSION_HANDOFF.md");
719
781
  console.log(`\nprompt mirror checks: ${mirrorRows.length}`);
@@ -769,9 +831,9 @@ async function runDoctor(root, version, options = {}) {
769
831
  ? "檢查已通過。START_NEXT_SESSION_PROMPT.txt 只是下次開工便利副本;session 進行中不用手動重生,收工 closeout 時 AI 會從 dev/SESSION_HANDOFF.md 重生。"
770
832
  : null;
771
833
 
772
- const overallHealthy = credentialResult.ok;
773
- printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
774
- checked: rows.length + anchorRows.length + schemaRows.length + mirrorRows.length + 2,
834
+ const overallHealthy = credentialResult.ok;
835
+ printDoctorSummary(version, root, overallHealthy ? "healthy" : "needs-attention", {
836
+ checked: rows.length + anchorRows.length + schemaRows.length + researchTraceResult.checked + temperatureResult.checked + mirrorRows.length + 2,
775
837
  failedKind: !credentialResult.ok ? "credential leak" : null,
776
838
  failedCount: !credentialResult.ok ? credentialResult.findings.length : 0,
777
839
  warningKind: mirrorWarnings.length > 0 ? "prompt mirror warning" : null,
@@ -782,9 +844,245 @@ async function runDoctor(root, version, options = {}) {
782
844
  ? versionNextStep ?? promptMirrorNextStep ?? onboardingNextStep ?? "檢查已通過。繼續使用你原本的 AI 開工方式;如剛完成一個任務,記得在 AI 對話輸入「收工」保存交接。"
783
845
  : "繼續使用;下次 closeout 時 AI 應自動執行 SESSION_LOG N 規則推進(見上面 warn 行)。如未動請要求 AI 重做 closeout。"
784
846
  });
785
- return overallHealthy ? "passed" : "failed";
786
- }
787
-
847
+ return overallHealthy ? "passed" : "failed";
848
+ }
849
+
850
+ async function checkResearchDecisionTrace(root) {
851
+ const decisionsPath = path.join(root, "dev/PROJECT_DECISIONS.md");
852
+ const indexPath = path.join(root, "dev/PROJECT_INDEX.md");
853
+ let decisionsText = "";
854
+ let indexText = "";
855
+ try {
856
+ decisionsText = await readFile(decisionsPath, "utf8");
857
+ indexText = await readFile(indexPath, "utf8");
858
+ } catch {
859
+ return { ok: false, checked: 1, findings: ["dev/PROJECT_DECISIONS.md or dev/PROJECT_INDEX.md unreadable"] };
860
+ }
861
+
862
+ const findings = [];
863
+ const sourceTokenPattern = /\bsource:[A-Za-z0-9._-]+\b/g;
864
+ const blocks = markdownListBlocks(stripFencedCodeBlocks(decisionsText));
865
+ const researchBlocks = blocks.filter((block) => /\bresearch-derived\b/i.test(block) || /Evidence chain:/i.test(block));
866
+
867
+ researchBlocks.forEach((block, index) => {
868
+ const label = `research-derived decision #${index + 1}`;
869
+ if (!/Evidence chain:/i.test(block)) {
870
+ findings.push(`${label} missing Evidence chain`);
871
+ }
872
+ const tokens = [...block.matchAll(sourceTokenPattern)].map((match) => match[0]);
873
+ if (tokens.length === 0) {
874
+ findings.push(`${label} missing source:<id> token`);
875
+ }
876
+ for (const token of tokens) {
877
+ if (!indexText.includes(token)) {
878
+ findings.push(`${label} references ${token}, but dev/PROJECT_INDEX.md does not contain that token`);
879
+ }
880
+ }
881
+ });
882
+
883
+ return { ok: findings.length === 0, checked: 1, findings };
884
+ }
885
+
886
+ function stripFencedCodeBlocks(text) {
887
+ return text.replace(/```[\s\S]*?```/g, "");
888
+ }
889
+
890
+ function markdownListBlocks(text) {
891
+ const blocks = [];
892
+ let current = [];
893
+ for (const line of text.split(/\r?\n/)) {
894
+ if (/^\s*[-*]\s+/.test(line)) {
895
+ if (current.length > 0) blocks.push(current.join("\n"));
896
+ current = [line];
897
+ } else if (current.length > 0 && (/^\s{2,}\S/.test(line) || /^\s*$/.test(line))) {
898
+ current.push(line);
899
+ } else if (current.length > 0) {
900
+ blocks.push(current.join("\n"));
901
+ current = [];
902
+ }
903
+ }
904
+ if (current.length > 0) blocks.push(current.join("\n"));
905
+ return blocks;
906
+ }
907
+
908
+ async function checkHandoffTemperatureBoundary(root) {
909
+ const findings = [];
910
+ const sections = [];
911
+ let handoffText = "";
912
+
913
+ try {
914
+ handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
915
+ } catch {
916
+ return { ok: false, checked: 1, findings: ["dev/SESSION_HANDOFF.md unreadable"] };
917
+ }
918
+
919
+ sections.push(
920
+ { label: "Durable Anchors", text: extractHandoffSectionText(handoffText, "durable-anchors", "Durable Anchors") },
921
+ { label: "Next Priorities", text: extractHandoffSectionText(handoffText, "next-priorities", "Next Priorities") },
922
+ { label: "Next Session Opening Message", text: extractHandoffSectionText(handoffText, "next-session-opening-message", "Next Session Opening Message") }
923
+ );
924
+
925
+ const requiredReading = extractHandoffSectionText(handoffText, "next-task-required-reading", "Next Task Required Reading");
926
+ sections.push({ label: "Next Task Required Reading", text: requiredReading, allowSourceTokens: true });
927
+
928
+ try {
929
+ const promptText = await readFile(path.join(root, "START_NEXT_SESSION_PROMPT.txt"), "utf8");
930
+ sections.push({ label: "START_NEXT_SESSION_PROMPT.txt", text: promptText });
931
+ } catch {
932
+ // Missing prompt mirror is handled by prompt mirror checks; do not duplicate the failure here.
933
+ }
934
+
935
+ for (const section of sections) {
936
+ if (!section.text) continue;
937
+ findings.push(...currentStateEvidenceFindings(section.label, section.text, { allowSourceTokens: section.allowSourceTokens }));
938
+ }
939
+
940
+ return { ok: findings.length === 0, checked: 1, findings };
941
+ }
942
+
943
+ const rootMismatchGuard = "If this root does not match the expected project root";
944
+
945
+ function currentStateEvidenceRules() {
946
+ return [
947
+ { pattern: /post-publish artifact smoke/i, label: "post-publish artifact smoke evidence" },
948
+ { pattern: /PASS\s+7\/7/i, label: "historical PASS count" },
949
+ { pattern: /\bfileCount\b/i, label: "published artifact fileCount evidence" },
950
+ { pattern: /\brelease source\b/i, label: "release source evidence" },
951
+ { pattern: /Cross-mind evidence/i, label: "cross-agent review evidence" },
952
+ { pattern: /Evidence chain:/i, label: "research evidence chain" },
953
+ { pattern: /\bnpm latest\s+(?:is|=|v?\d)/i, label: "historical npm latest state" },
954
+ { pattern: /GitHub Release\s+(?:metadata|published|view|`?v?\d)/i, label: "historical GitHub Release state" }
955
+ ];
956
+ }
957
+
958
+ function currentStateEvidenceFindings(sectionLabel, text, options = {}) {
959
+ const findings = [];
960
+ for (const rule of currentStateEvidenceRules()) {
961
+ if (rule.pattern.test(text)) {
962
+ findings.push(`${sectionLabel} contains ${rule.label}; keep it in trace evidence unless it still affects the next action`);
963
+ }
964
+ }
965
+ if (!options.allowSourceTokens && /\bsource:[A-Za-z0-9._-]+\b/.test(text)) {
966
+ findings.push(`${sectionLabel} contains source:<id>; keep source tokens in PROJECT_INDEX / PROJECT_DECISIONS, not hot startup state`);
967
+ }
968
+ return findings;
969
+ }
970
+
971
+ function lineHasCurrentStateEvidence(line, options = {}) {
972
+ return currentStateEvidenceFindings("line", line, options).length > 0;
973
+ }
974
+
975
+ function repairHandoffOpeningRootGuard(text) {
976
+ if (text.includes(rootMismatchGuard)) return { changed: false, text };
977
+ const bounds = handoffSectionContentBounds(text, "next-session-opening-message", "Next Session Opening Message");
978
+ if (!bounds) return { changed: false, text };
979
+ const section = text.slice(bounds.start, bounds.end);
980
+ if (!section.includes("```text")) return { changed: false, text };
981
+
982
+ let repairedSection = section;
983
+ if (/^Before changing anything,/m.test(repairedSection)) {
984
+ repairedSection = repairedSection.replace(/^Before changing anything,/m, `${rootMismatchGuard}, stop and ask for confirmation.\n\nBefore changing anything,`);
985
+ } else if (/\n```/.test(repairedSection)) {
986
+ repairedSection = repairedSection.replace(/\n```/, `\n${rootMismatchGuard}, stop and ask for confirmation.\n\n\`\`\``);
987
+ } else {
988
+ return { changed: false, text };
989
+ }
990
+
991
+ return {
992
+ changed: repairedSection !== section,
993
+ text: `${text.slice(0, bounds.start)}${repairedSection}${text.slice(bounds.end)}`
994
+ };
995
+ }
996
+
997
+ function repairHandoffCurrentStateEvidenceBoundary(text) {
998
+ let repaired = text;
999
+ let changed = false;
1000
+ for (const section of [
1001
+ { id: "durable-anchors", heading: "Durable Anchors" },
1002
+ { id: "next-priorities", heading: "Next Priorities" },
1003
+ { id: "next-session-opening-message", heading: "Next Session Opening Message" }
1004
+ ]) {
1005
+ const bounds = handoffSectionContentBounds(repaired, section.id, section.heading);
1006
+ if (!bounds) continue;
1007
+ const originalSection = repaired.slice(bounds.start, bounds.end);
1008
+ const lines = originalSection.split(/\r?\n/);
1009
+ const cleanedLines = lines.filter((line) => !lineHasCurrentStateEvidence(line));
1010
+ if (cleanedLines.length !== lines.length) {
1011
+ const cleanedSection = cleanedLines.join("\n");
1012
+ repaired = `${repaired.slice(0, bounds.start)}${cleanedSection}${repaired.slice(bounds.end)}`;
1013
+ changed = true;
1014
+ }
1015
+ }
1016
+ return { changed, text: repaired };
1017
+ }
1018
+
1019
+ function handoffSectionContentBounds(text, id, headingText) {
1020
+ const marker = `<!-- ack:section:${id} -->`;
1021
+ const markerStart = text.indexOf(marker);
1022
+ if (markerStart >= 0) {
1023
+ const start = markerStart + marker.length;
1024
+ const nextMarker = text.indexOf("<!-- ack:section:", start);
1025
+ return { start, end: nextMarker >= 0 ? nextMarker : text.length };
1026
+ }
1027
+
1028
+ const headingPattern = new RegExp(`^##\\s+${escapeRegExp(headingText)}\\s*$`, "m");
1029
+ const headingMatch = headingPattern.exec(text);
1030
+ if (!headingMatch) return null;
1031
+ const start = headingMatch.index + headingMatch[0].length;
1032
+ const nextHeading = /\n##\s+/g;
1033
+ nextHeading.lastIndex = start;
1034
+ const nextMatch = nextHeading.exec(text);
1035
+ return { start, end: nextMatch ? nextMatch.index : text.length };
1036
+ }
1037
+
1038
+ function extractHandoffSectionText(text, id, headingText) {
1039
+ const marker = `<!-- ack:section:${id} -->`;
1040
+ const markerStart = text.indexOf(marker);
1041
+ if (markerStart >= 0) {
1042
+ const afterMarker = markerStart + marker.length;
1043
+ const nextMarker = text.indexOf("<!-- ack:section:", afterMarker);
1044
+ return text.slice(afterMarker, nextMarker >= 0 ? nextMarker : text.length);
1045
+ }
1046
+
1047
+ const headingPattern = new RegExp(`^##\\s+${escapeRegExp(headingText)}\\s*$`, "m");
1048
+ const headingMatch = headingPattern.exec(text);
1049
+ if (!headingMatch) return "";
1050
+ const start = headingMatch.index + headingMatch[0].length;
1051
+ const nextHeading = /\n##\s+/g;
1052
+ nextHeading.lastIndex = start;
1053
+ const nextMatch = nextHeading.exec(text);
1054
+ return text.slice(start, nextMatch ? nextMatch.index : text.length);
1055
+ }
1056
+
1057
+ async function regeneratePromptFromHandoffIfHotEvidence(root, backupDir, merged) {
1058
+ const handoffPath = path.join(root, "dev/SESSION_HANDOFF.md");
1059
+ const promptPath = path.join(root, "START_NEXT_SESSION_PROMPT.txt");
1060
+ let handoffText = "";
1061
+ let promptText = "";
1062
+ try {
1063
+ handoffText = await readFile(handoffPath, "utf8");
1064
+ promptText = await readFile(promptPath, "utf8");
1065
+ } catch {
1066
+ return false;
1067
+ }
1068
+
1069
+ const opening = extractOpeningMessage(handoffText);
1070
+ if (opening == null) return false;
1071
+
1072
+ const promptNeedsRepair = lineHasCurrentStateEvidence(promptText)
1073
+ || (!promptText.includes(rootMismatchGuard) && opening.includes(rootMismatchGuard));
1074
+ if (!promptNeedsRepair) return false;
1075
+
1076
+ const backupPath = path.join(backupDir, "START_NEXT_SESSION_PROMPT.txt");
1077
+ await mkdir(path.dirname(backupPath), { recursive: true });
1078
+ await copyFile(promptPath, backupPath);
1079
+ await writeFile(promptPath, `${opening}\n`, "utf8");
1080
+ if (!merged.some((item) => item.startsWith("START_NEXT_SESSION_PROMPT.txt"))) {
1081
+ merged.push("START_NEXT_SESSION_PROMPT.txt - regenerate prompt from repaired handoff opening message");
1082
+ }
1083
+ return true;
1084
+ }
1085
+
788
1086
  function getFirstUseNextStep(root, lastCloseout) {
789
1087
  if (lastCloseout.date) return null;
790
1088
  return `檢查已通過。下一步不要再留在終端機;打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,輸入 Start Agent Handoff 或「開工」;若 AI 還未指向此資料夾,才貼:${startupPathBootstrapPrompt(root)}`;
@@ -846,10 +1144,10 @@ function printDoctorSummary(version, root, mode, details) {
846
1144
  } else {
847
1145
  console.log("✅ 檢查通過:必要文件存在,基本結構完整,下次開工提示副本已與 handoff 一致。");
848
1146
  }
849
- } else {
850
- console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
851
- console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : "下次開工提示副本與 handoff 真源不同。"}`);
852
- }
1147
+ } else {
1148
+ console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
1149
+ 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" ? "當前交接內容混入一次性或歷史證據。" : "下次開工提示副本與 handoff 真源不同。"}`);
1150
+ }
853
1151
  console.log("");
854
1152
  console.log(`📦 版本:v${version}`);
855
1153
  console.log(`🩺 模式:${mode}`);
@@ -1256,9 +1554,9 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1256
1554
  // v0.3.6+: SESSION_HANDOFF.md gains a non-destructive lifecycle consistency
1257
1555
  // field. Existing handoff content stays intact; only the missing field and
1258
1556
  // rule note are inserted around stable ack markers.
1259
- if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
1260
- const mergedHandoff = mergeHandoffLifecycleField(targetText);
1261
- if (!mergedHandoff) {
1557
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:lifecycle-conflicts-resolved")) {
1558
+ const mergedHandoff = mergeHandoffLifecycleField(targetText);
1559
+ if (!mergedHandoff) {
1262
1560
  return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add lifecycle consistency field" };
1263
1561
  }
1264
1562
  return {
@@ -1268,6 +1566,18 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1268
1566
  mergedText: mergedHandoff
1269
1567
  };
1270
1568
  }
1569
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && !targetText.includes("ack:field:persistence-routing-checked")) {
1570
+ const mergedHandoff = mergeHandoffPersistenceRoutingField(targetText);
1571
+ if (!mergedHandoff) {
1572
+ return { ...base, action: "conflict", reason: "SESSION_HANDOFF.md state reconciliation markers were changed; manual merge required to add persistence routing field" };
1573
+ }
1574
+ return {
1575
+ ...base,
1576
+ action: "merge",
1577
+ reason: "insert persistence routing field into State Reconciliation Check (one-time evidence must not drive next-session state)",
1578
+ mergedText: mergedHandoff
1579
+ };
1580
+ }
1271
1581
  if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && isUpgradeFromOlderTemplate(context)) {
1272
1582
  const lifecycleValue = fieldValueAfterMarker(targetText, "lifecycle-conflicts-resolved");
1273
1583
  if (isPlaceholderLifecycleFieldValue(lifecycleValue) && hasSubstantiveHandoffState(targetText)) {
@@ -1283,6 +1593,9 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1283
1593
  };
1284
1594
  }
1285
1595
  }
1596
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMisplacedRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1597
+ 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" };
1598
+ }
1286
1599
  if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1287
1600
  const mergedHandoff = mergeHandoffArchiveContinuityRule(targetText, sourceText);
1288
1601
  if (!mergedHandoff) {
@@ -1295,6 +1608,40 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1295
1608
  mergedText: mergedHandoff
1296
1609
  };
1297
1610
  }
1611
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
1612
+ const repairedOpening = repairHandoffOpeningRootGuard(targetText);
1613
+ if (repairedOpening.changed) {
1614
+ return {
1615
+ ...base,
1616
+ action: "merge",
1617
+ reason: "restore root mismatch guard in Next Session Opening Message",
1618
+ mergedText: repairedOpening.text
1619
+ };
1620
+ }
1621
+ }
1622
+ if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade") {
1623
+ const repairedTemperature = repairHandoffCurrentStateEvidenceBoundary(targetText);
1624
+ if (repairedTemperature.changed) {
1625
+ return {
1626
+ ...base,
1627
+ action: "merge",
1628
+ reason: "move historical evidence out of hot handoff state",
1629
+ mergedText: repairedTemperature.text
1630
+ };
1631
+ }
1632
+ }
1633
+ if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade" && !targetText.includes("- **Evidence disposition:**")) {
1634
+ const mergedLog = mergeSessionLogEvidenceDispositionField(targetText);
1635
+ if (!mergedLog) {
1636
+ return { ...base, action: "conflict", reason: "SESSION_LOG.md entry template markers were changed; manual merge required to add evidence disposition field" };
1637
+ }
1638
+ return {
1639
+ ...base,
1640
+ action: "merge",
1641
+ reason: "insert SESSION_LOG evidence disposition field into Entry Template",
1642
+ mergedText: mergedLog
1643
+ };
1644
+ }
1298
1645
  if (command === "upgrade" && hasAnchorRepairMarkerDrift(targetText)) {
1299
1646
  return { ...base, action: "conflict", reason: "legacy anchor repair block markers are incomplete or obsolete; manual semantic cleanup required before upgrade can safely continue" };
1300
1647
  }
@@ -1421,7 +1768,12 @@ function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
1421
1768
  }
1422
1769
 
1423
1770
  function sessionLogAnchorPlacement(snippet, text) {
1771
+ if (snippet === "ack:section:session-log-preamble") return text.includes("ack:section:session-log-preamble");
1772
+ if (snippet === "ack:section:session-log-entry-template") return text.includes("ack:section:session-log-entry-template");
1424
1773
  if (snippet === "## Entry Template") return /^## Entry Template\s*$/m.test(text);
1774
+ if (snippet === "ack:log-entry:start" || snippet === "ack:log-entry:end") {
1775
+ return sessionLogEntryTemplateContains(text, snippet);
1776
+ }
1425
1777
  const preamble = [
1426
1778
  "Record what actually happened in the session",
1427
1779
  "kept, summarized, or archived",
@@ -1429,7 +1781,19 @@ function sessionLogAnchorPlacement(snippet, text) {
1429
1781
  "latest opening message",
1430
1782
  "not current state"
1431
1783
  ];
1432
- if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
1784
+ if (preamble.includes(snippet)) return sessionLogPreambleContains(text, snippet);
1785
+ return sessionLogEntryTemplateContains(text, snippet);
1786
+ }
1787
+
1788
+ function sessionLogPreambleContains(text, snippet) {
1789
+ const markerBounds = textSectionBounds(text, "<!-- ack:section:session-log-preamble -->", "<!-- ack:section:session-log-entry-template -->");
1790
+ if (markerBounds) return text.slice(markerBounds.start, markerBounds.end).includes(snippet);
1791
+ return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
1792
+ }
1793
+
1794
+ function sessionLogEntryTemplateContains(text, snippet) {
1795
+ const markerIndex = text.indexOf("<!-- ack:section:session-log-entry-template -->");
1796
+ if (markerIndex >= 0) return text.slice(markerIndex).includes(snippet);
1433
1797
  return snippetAppearsAfterHeading(text, snippet, "## Entry Template");
1434
1798
  }
1435
1799
 
@@ -1460,7 +1824,9 @@ function projectDecisionsAnchorPlacement(snippet, text) {
1460
1824
  "warm 資料層",
1461
1825
  "AI 開工",
1462
1826
  "不需要讀",
1463
- "AI 在收工時自動 update"
1827
+ "AI 在收工時自動 update",
1828
+ "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.",
1829
+ "This file does not store raw build / upload / QC evidence"
1464
1830
  ];
1465
1831
  if (preamble.includes(snippet)) return snippetAppearsBeforeHeading(text, snippet, "## Evolution Timeline");
1466
1832
  return true;
@@ -1527,15 +1893,15 @@ const semanticAnchorRepairStrategies = {
1527
1893
  } : null;
1528
1894
  },
1529
1895
  "dev/SESSION_LOG.md": (targetText, sourceText) => {
1530
- const mergedLog = insertSourcePreambleBeforeHeading(targetText, sourceText, "## Entry Template");
1896
+ const mergedLog = mergeSessionLogTemplateContract(targetText, sourceText);
1531
1897
  return mergedLog ? {
1532
1898
  action: "merge",
1533
- reason: "restore SESSION_LOG Kit preamble before ## Entry Template",
1899
+ reason: "restore SESSION_LOG machine boundaries and entry template contract",
1534
1900
  mergedText: mergedLog
1535
1901
  } : null;
1536
1902
  },
1537
- "dev/PROJECT_DECISIONS.md": (targetText, sourceText) => {
1538
- const mergedDecisions = insertSourcePreambleBeforeHeading(targetText, sourceText, "## Evolution Timeline");
1903
+ "dev/PROJECT_DECISIONS.md": (targetText, sourceText, missing) => {
1904
+ const mergedDecisions = mergeProjectDecisionsPreamble(targetText, sourceText, missing);
1539
1905
  return mergedDecisions ? {
1540
1906
  action: "merge",
1541
1907
  reason: "restore PROJECT_DECISIONS onboarding preamble before ## Evolution Timeline",
@@ -1578,6 +1944,33 @@ function insertSourcePreambleBeforeHeading(targetText, sourceText, headingText)
1578
1944
  return `${targetBefore}\n\n${sourcePreamble}\n\n${targetAfter}`;
1579
1945
  }
1580
1946
 
1947
+ function mergeProjectDecisionsPreamble(targetText, sourceText, missing) {
1948
+ const evidenceSnippet = "Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.";
1949
+ const boundarySnippet = "This file does not store raw build / upload / QC evidence";
1950
+ const targetIndex = targetText.indexOf("## Evolution Timeline");
1951
+ const sourceIndex = sourceText.indexOf("## Evolution Timeline");
1952
+ if (targetIndex < 0 || sourceIndex < 0) return null;
1953
+ if (targetText.includes("Project Decisions Log")) {
1954
+ const sourcePreamble = sourceText.slice(0, sourceIndex).trim();
1955
+ const blocks = [];
1956
+ if (missing.includes(evidenceSnippet)) {
1957
+ const researchBlock = sourcePreamble.match(/Research-derived decisions use[\s\S]*?source map\./)?.[0];
1958
+ if (!researchBlock) return null;
1959
+ if (!targetText.includes(researchBlock)) blocks.push(researchBlock);
1960
+ }
1961
+ if (missing.includes(boundarySnippet)) {
1962
+ const boundaryBlock = sourcePreamble.match(/This file does not store raw build \/ upload \/ QC evidence[^\r\n]*/)?.[0];
1963
+ if (!boundaryBlock) return null;
1964
+ if (!targetText.includes(boundaryBlock)) blocks.push(boundaryBlock);
1965
+ }
1966
+ if (blocks.length > 0) {
1967
+ return `${targetText.slice(0, targetIndex).trimEnd()}\n\n${blocks.join("\n\n")}\n\n${targetText.slice(targetIndex)}`;
1968
+ }
1969
+ if (missing.includes(evidenceSnippet) || missing.includes(boundarySnippet)) return targetText;
1970
+ }
1971
+ return insertSourcePreambleBeforeHeading(targetText, sourceText, "## Evolution Timeline");
1972
+ }
1973
+
1581
1974
  function mergeProjectIndexTemplateVersionRow(targetText, sourceText) {
1582
1975
  if (projectIndexTemplateVersion(targetText)) return targetText;
1583
1976
  const sourceRow = sourceText.match(/^\| Agent Handoff Kit template version \| [\d.]+ \| [^|\n]+ \|$/m)?.[0];
@@ -1752,21 +2145,10 @@ function projectIndexTemplateVersion(text) {
1752
2145
  function mergeHandoffLifecycleField(targetText) {
1753
2146
  const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
1754
2147
  if (!targetText.includes(openingMarker)) return null;
1755
-
1756
- const fieldBlock = "<!-- ack:field:lifecycle-conflicts-resolved -->\n- Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified: Reclassified at upgrade: field added by v0.3.6+ migration; pre-existing handoff state predates it; reconcile at next closeout.\n";
1757
- let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
1758
-
1759
- if (!merged.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
1760
- const ruleBlock = "Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.\n\n";
1761
- const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
1762
- if (merged.includes(sufficiencyMarker)) {
1763
- merged = merged.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
1764
- } else {
1765
- merged = `${merged.trimEnd()}\n\n${ruleBlock}`;
1766
- }
1767
- }
1768
2148
 
1769
- return merged;
2149
+ const fieldBlock = "<!-- ack:field:lifecycle-conflicts-resolved -->\n- Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified: Reclassified at upgrade: field added by v0.3.6+ migration; pre-existing handoff state predates it; reconcile at next closeout.\n";
2150
+ let merged = targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2151
+ return ensureHandoffStateReconciliationRules(ensureHandoffPersistenceRoutingField(merged));
1770
2152
  }
1771
2153
 
1772
2154
  function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
@@ -1784,18 +2166,131 @@ function reclassifyExistingHandoffLifecyclePlaceholder(targetText) {
1784
2166
  if (colonIndex < 0) return null;
1785
2167
  lines[fieldIndex] = `${lines[fieldIndex].slice(0, colonIndex + 1)} Reclassified at upgrade: existing lifecycle placeholder predates this version; pre-existing handoff state predates this check; reconcile at next closeout.`;
1786
2168
 
1787
- let merged = lines.join("\n");
1788
- if (!merged.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
1789
- const ruleBlock = "Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.\n\n";
1790
- const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
1791
- if (merged.includes(sufficiencyMarker)) {
1792
- merged = merged.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
1793
- } else {
1794
- merged = `${merged.trimEnd()}\n\n${ruleBlock}`;
2169
+ return ensureHandoffStateReconciliationRules(lines.join("\n"));
2170
+ }
2171
+
2172
+ function mergeHandoffPersistenceRoutingField(targetText) {
2173
+ const merged = ensureHandoffPersistenceRoutingField(targetText);
2174
+ if (!merged || merged === targetText) return null;
2175
+ return ensureHandoffStateReconciliationRules(merged);
2176
+ }
2177
+
2178
+ function ensureHandoffPersistenceRoutingField(targetText) {
2179
+ if (targetText.includes("ack:field:persistence-routing-checked")) return targetText;
2180
+ const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
2181
+ if (!targetText.includes(openingMarker)) return null;
2182
+ const fieldBlock = "<!-- ack:field:persistence-routing-checked -->\n- Persistence routing checked: Reclassified at upgrade: field added by template migration; pre-existing handoff state predates it; reconcile at next closeout.\n";
2183
+ return targetText.replace(openingMarker, `${fieldBlock}${openingMarker}`);
2184
+ }
2185
+
2186
+ function ensureHandoffStateReconciliationRules(targetText) {
2187
+ if (!targetText) return null;
2188
+ const rules = [];
2189
+ if (!targetText.includes("Lifecycle consistency rule: compare `Completed This Session`")) {
2190
+ rules.push("Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.");
2191
+ }
2192
+ if (!targetText.includes("Persistence routing rule: one-time delivery instructions")) {
2193
+ rules.push("Persistence routing rule: one-time delivery instructions, historical validation evidence, old hashes, old version facts, and incident notes must stay in trace evidence unless they still affect the next action.");
2194
+ }
2195
+ if (rules.length === 0) return targetText;
2196
+ const ruleBlock = `${rules.join("\n")}\n\n`;
2197
+ const sufficiencyMarker = "<!-- ack:section:handoff-sufficiency-check -->";
2198
+ if (targetText.includes(sufficiencyMarker)) {
2199
+ return targetText.replace(sufficiencyMarker, `${ruleBlock}${sufficiencyMarker}`);
2200
+ }
2201
+ return `${targetText.trimEnd()}\n\n${ruleBlock}`;
2202
+ }
2203
+
2204
+ function mergeSessionLogEvidenceDispositionField(targetText) {
2205
+ if (targetText.includes("- **Evidence disposition:**")) return mergeSessionLogTemplateContract(targetText, null) ?? targetText;
2206
+ const qcField = "- **QC:**";
2207
+ if (!targetText.includes(qcField)) return null;
2208
+ const withEvidence = targetText.replace(qcField, `${qcField}\n- **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>`);
2209
+ return mergeSessionLogTemplateContract(withEvidence, null) ?? withEvidence;
2210
+ }
2211
+
2212
+ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
2213
+ let merged = targetText;
2214
+ let changed = false;
2215
+
2216
+ if (!merged.includes("ack:section:session-log-preamble")) {
2217
+ const titleMatch = /^# Session Log\s*$/m.exec(merged);
2218
+ if (titleMatch) {
2219
+ const insertAt = titleMatch.index + titleMatch[0].length;
2220
+ merged = `${merged.slice(0, insertAt)}\n\n<!-- ack:section:session-log-preamble -->${merged.slice(insertAt)}`;
2221
+ changed = true;
2222
+ } else if (sourceText?.includes("ack:section:session-log-preamble")) {
2223
+ const sourcePreambleMarker = "<!-- ack:section:session-log-preamble -->";
2224
+ merged = `${sourcePreambleMarker}\n\n${merged}`;
2225
+ changed = true;
1795
2226
  }
1796
2227
  }
1797
2228
 
1798
- return merged;
2229
+ if (!merged.includes("ack:section:session-log-entry-template")) {
2230
+ const headingMatch = /^## Entry Template\s*$/m.exec(merged);
2231
+ if (headingMatch) {
2232
+ merged = `${merged.slice(0, headingMatch.index)}<!-- ack:section:session-log-entry-template -->\n\n${merged.slice(headingMatch.index)}`;
2233
+ changed = true;
2234
+ }
2235
+ }
2236
+
2237
+ if (sourceText) {
2238
+ const restored = restoreMissingSessionLogPreambleLines(merged, sourceText);
2239
+ if (restored !== merged) {
2240
+ merged = restored;
2241
+ changed = true;
2242
+ }
2243
+ }
2244
+
2245
+ const entryTemplateIndex = merged.search(/^## Entry Template\s*$/m);
2246
+ if (entryTemplateIndex >= 0) {
2247
+ const beforeTemplate = merged.slice(0, entryTemplateIndex);
2248
+ let templateAndAfter = merged.slice(entryTemplateIndex);
2249
+ if (!templateAndAfter.includes("ack:log-entry:start")) {
2250
+ const replaced = templateAndAfter.replace(/````markdown(\r?\n)/, "````markdown$1<!-- ack:log-entry:start -->$1");
2251
+ if (replaced !== templateAndAfter) {
2252
+ templateAndAfter = replaced;
2253
+ changed = true;
2254
+ }
2255
+ }
2256
+ if (!templateAndAfter.includes("ack:log-entry:end")) {
2257
+ const openingIndex = templateAndAfter.indexOf("````markdown");
2258
+ const closingIndex = openingIndex >= 0
2259
+ ? templateAndAfter.indexOf("\n````", openingIndex + "````markdown".length)
2260
+ : -1;
2261
+ if (closingIndex >= 0) {
2262
+ templateAndAfter = `${templateAndAfter.slice(0, closingIndex)}\n<!-- ack:log-entry:end -->${templateAndAfter.slice(closingIndex)}`;
2263
+ changed = true;
2264
+ }
2265
+ }
2266
+ merged = `${beforeTemplate}${templateAndAfter}`;
2267
+ }
2268
+
2269
+ return changed ? merged : targetText;
2270
+ }
2271
+
2272
+ function restoreMissingSessionLogPreambleLines(targetText, sourceText) {
2273
+ const sourceEntryIndex = sourceText.search(/^## Entry Template\s*$/m);
2274
+ const targetEntryMarkerIndex = targetText.indexOf("<!-- ack:section:session-log-entry-template -->");
2275
+ const targetEntryHeadingIndex = targetText.search(/^## Entry Template\s*$/m);
2276
+ const insertIndex = targetEntryMarkerIndex >= 0 ? targetEntryMarkerIndex : targetEntryHeadingIndex;
2277
+ if (sourceEntryIndex < 0 || insertIndex < 0) return targetText;
2278
+
2279
+ const sourcePreamble = sourceText.slice(0, sourceEntryIndex);
2280
+ const missingLines = [
2281
+ "Record what actually happened in the session",
2282
+ "kept, summarized, or archived",
2283
+ "Do not remove validation evidence",
2284
+ "latest opening message",
2285
+ "not current state"
2286
+ ].flatMap((snippet) => {
2287
+ if (targetText.includes(snippet)) return [];
2288
+ const line = sourcePreamble.split(/\r?\n/).find((candidate) => candidate.includes(snippet));
2289
+ return line ? [line] : [];
2290
+ });
2291
+
2292
+ if (missingLines.length === 0) return targetText;
2293
+ return `${targetText.slice(0, insertIndex).trimEnd()}\n\n${missingLines.join("\n\n")}\n\n${targetText.slice(insertIndex)}`;
1799
2294
  }
1800
2295
 
1801
2296
  function mergeHandoffArchiveContinuityRule(targetText, sourceText) {
@@ -2523,7 +3018,7 @@ function printUpgradeNextSteps(root, conflictCount) {
2523
3018
  console.log("============================================================");
2524
3019
  return;
2525
3020
  }
2526
- console.log("✅ 升級完成:Kit 檔案已更新到最新版本");
3021
+ console.log("🛠️ Kit 檔案已更新:等待下方 doctor 驗收");
2527
3022
  console.log("============================================================");
2528
3023
  console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
2529
3024
  console.log("");
@@ -2534,38 +3029,68 @@ function printUpgradeNextSteps(root, conflictCount) {
2534
3029
  console.log("============================================================");
2535
3030
  }
2536
3031
 
2537
- // R-031 v0.3.1+: Upgrade no-op short-circuit. When the user runs upgrade on a root
2538
- // already at latest version (skip all / create 0 / merge 0 / conflict 0), print a
2539
- // short factual message and return. Saves disk (no migration report) + reduces noise
2540
- // (no self-check doctor) + avoids misleading "安裝完成" framing for an idempotent
2541
- // operation where nothing changed.
2542
- async function assessUpgradeNoopHealth(root) {
2543
- try {
2544
- const handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
2545
- return { handoffLifecycle: assessHandoffLifecycleConsistency(handoffText) };
2546
- } catch {
2547
- return { handoffLifecycle: { ok: false, reason: "dev/SESSION_HANDOFF.md unreadable" } };
2548
- }
2549
- }
2550
-
2551
- function printUpgradeNoopShortCircuit(version, health = { handoffLifecycle: { ok: true } }) {
2552
- console.log("");
2553
- console.log(`📦 版本:v${version}`);
2554
- console.log("🛠️ 模式:upgrade-existing");
2555
- console.log("🔎 剛完成:檢查所有 Kit 檔案的狀態(含 AGENTS.md、dev/SESSION_HANDOFF.md、dev/PROJECT_INDEX.md 等)。");
2556
- if (health.handoffLifecycle?.ok) {
2557
- console.log("✅ 結果:你已經是最新版本,沒有檔案需要建立或合併;用戶填寫的內容全部保留現狀。");
2558
- console.log("");
2559
- console.log("🚀 下一步:回到原本的 AI 對話或開工句即可;如果剛完成任務,記得在 AI 對話輸入「收工」保存交接。");
2560
- console.log("");
2561
- return;
2562
- }
2563
- console.log("⚠️ 結果:Kit 檔案已是最新版本,沒有檔案需要建立或合併;但交接狀態仍需 AI closeout 核對。");
2564
- console.log("");
2565
- console.log("🚀 下一步:先執行 doctor 取得待修項,再把輸出貼給 AI;不要重裝或覆寫用戶內容。");
2566
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest doctor");
2567
- console.log("");
2568
- }
3032
+ // R-031 v0.3.24+: Upgrade no-op may skip file writes, but it must not skip the
3033
+ // single health authority. If the CLI says a latest root can continue, that claim
3034
+ // is backed by the same runDoctor() implementation users would invoke manually.
3035
+ async function assessUpgradeNoopHealth(root, version) {
3036
+ const originalLog = console.log;
3037
+ const originalError = console.error;
3038
+ const previousExitCode = process.exitCode;
3039
+ const stdout = [];
3040
+ const stderr = [];
3041
+
3042
+ try {
3043
+ console.log = (...args) => stdout.push(args.join(" "));
3044
+ console.error = (...args) => stderr.push(args.join(" "));
3045
+ process.exitCode = undefined;
3046
+ const status = await runDoctor(root, version, { silentCard: true, context: "upgrade-noop-health-check" });
3047
+ const doctorExitCode = process.exitCode;
3048
+ return {
3049
+ ok: status === "passed" && !doctorExitCode,
3050
+ status,
3051
+ stdout: stdout.join("\n"),
3052
+ stderr: stderr.join("\n"),
3053
+ error: null
3054
+ };
3055
+ } catch (error) {
3056
+ return {
3057
+ ok: false,
3058
+ status: "failed",
3059
+ stdout: stdout.join("\n"),
3060
+ stderr: stderr.join("\n"),
3061
+ error: error.message
3062
+ };
3063
+ } finally {
3064
+ console.log = originalLog;
3065
+ console.error = originalError;
3066
+ process.exitCode = previousExitCode;
3067
+ }
3068
+ }
3069
+
3070
+ function printUpgradeNoopShortCircuit(version, health = { ok: true }) {
3071
+ console.log("");
3072
+ console.log(`📦 版本:v${version}`);
3073
+ console.log("🛠️ 模式:upgrade-existing");
3074
+ console.log("🔎 剛完成:檢查所有 Kit 檔案的狀態(含 AGENTS.md、dev/SESSION_HANDOFF.md、dev/PROJECT_INDEX.md 等)。");
3075
+ if (health.ok) {
3076
+ console.log("✅ 結果:你已經是最新版本,沒有檔案需要建立或合併;用戶填寫的內容全部保留現狀。");
3077
+ console.log("");
3078
+ console.log("🚀 下一步:回到原本的 AI 對話或開工句即可;如果剛完成任務,記得在 AI 對話輸入「收工」保存交接。");
3079
+ console.log("");
3080
+ return;
3081
+ }
3082
+ console.log("⚠️ 結果:Kit 檔案已是最新版本,沒有檔案需要建立或合併;但完整 doctor 健康檢查未通過。");
3083
+ console.log("");
3084
+ console.log("🩺 doctor 輸出:");
3085
+ const doctorOutput = [health.stdout, health.stderr, health.error ? `error: ${health.error}` : ""]
3086
+ .filter(Boolean)
3087
+ .join("\n")
3088
+ .trim();
3089
+ console.log(doctorOutput || "doctor did not return readable output.");
3090
+ console.log("");
3091
+ console.log("🚀 下一步:把上方 doctor 輸出貼給能讀寫此資料夾的 AI,請它按失敗項修補;不要重裝或覆寫用戶內容。");
3092
+ console.log("");
3093
+ }
2569
3094
 
2570
3095
  function listOrNone(items) {
2571
3096
  if (items.length === 0) return ["- none"];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamchanadam/agent-handoff-kit",
3
- "version": "0.3.22",
3
+ "version": "0.3.24",
4
4
  "description": "Lightweight agent harness for project memory, handoff, and multi-session continuity.",
5
5
  "type": "module",
6
6
  "bin": {
package/packs/research.md CHANGED
@@ -26,3 +26,5 @@ Use for source gathering, evidence comparison, fact synthesis, recommendations,
26
26
  ## Closeout
27
27
 
28
28
  Record sources used, conclusions, uncertainty, and any facts that should be persisted into project files.
29
+
30
+ If research changes a long-term decision, public claim, strategy, governance rule, or material selection, persist a research-derived decision entry using the `dev/PROJECT_DECISIONS.md` evidence-chain format. One-time fact checks do not need this extra structure.
@@ -34,6 +34,8 @@ After reading `dev/PROJECT_INDEX.md`, if `## Installed Integrations` is non-empt
34
34
 
35
35
  After startup reads are complete, show one short startup card. If onboarding is loaded, combine this card and the onboarding choice list into one first response. Do not print any standalone startup card before the onboarding rule has been read. Do not print a partial card. Do not print the cat banner twice. If you started drafting a card and then discovered onboarding applies, discard the draft and output only the final combined response.
36
36
 
37
+ Display version rule: after reading `dev/PROJECT_INDEX.md`, take the card version from the `## Stack` row `Agent Handoff Kit template version`. Print it as `vX.Y.Z`. If that row is missing, unreadable, or not a version, print `version unverified`. Never print the literal placeholder `v<version>` in user-facing startup or closeout output.
38
+
37
39
  ```text
38
40
  /\_/\ Agent Handoff Kit v<version>
39
41
  ( o.o ) continuity ready
@@ -45,7 +47,7 @@ After startup reads are complete, show one short startup card. If onboarding is
45
47
  🚀 下一步:<next action>
46
48
  ```
47
49
 
48
- Keep the card short. Use plain Traditional Chinese labels in user-facing output. Use the full product name, not an abbreviation. If the installed template or CLI version is unknown, write `version unverified` instead of guessing.
50
+ Keep the card short. Use plain Traditional Chinese labels in user-facing output. Use the full product name, not an abbreviation.
49
51
 
50
52
  ## 2. Work Loop
51
53
 
@@ -55,7 +57,7 @@ Use this loop for every task:
55
57
  2. READ: inspect relevant files from `PROJECT_INDEX.md` and search for related definitions before editing.
56
58
  3. CHANGE: make focused changes only.
57
59
  4. QC: run available checks or state why they cannot run.
58
- 5. PERSIST: classify durable facts before writing them. Current state belongs in handoff, chronological evidence in log, file / command / reference maps in project index, sync obligations in doc sync registry, and reusable operating procedure in the relevant rule pack or registered reference. Do not store reusable procedure knowledge only in handoff or log.
60
+ 5. PERSIST: classify durable facts before writing them. Current state belongs in handoff, chronological evidence in log, file / command / reference maps in project index, sync obligations in doc sync registry, and reusable operating procedure in the relevant rule pack or registered reference. Do not persist one-time delivery instructions, historical validation evidence, old hashes, old version facts, or incident notes as current state, next priorities, durable anchors, or startup instructions. Do not store reusable procedure knowledge only in handoff or log.
59
61
 
60
62
  External skill flows, subagents, task plans, or another tool's "finish" step do not replace this loop. If you use any of them, the PLAN must include a final Agent Handoff Kit persistence step for the active project root, and completion cannot be claimed until that root's `dev/SESSION_HANDOFF.md`, `dev/SESSION_LOG.md`, `dev/PROJECT_INDEX.md`, and `dev/DOC_SYNC_REGISTRY.md` have been inspected and updated or explicitly marked not applicable.
61
63
 
@@ -87,14 +89,16 @@ Detect end-of-session or handoff intent in natural language, such as "收工", "
87
89
 
88
90
  Ambiguous closeout phrases need one concise confirmation question before full closeout. In particular, if the user says "<something> 收工", "<something> close", or similar wording that may refer to a real-world shift, event, project phase, or another context, ask whether they mean to wrap up Agent Handoff Kit and write the project handoff.
89
91
 
90
- At full closeout:
91
-
92
- 1. Reconcile `dev/SESSION_HANDOFF.md`. Do not append a new state snapshot under old state. Verify `Durable Anchors`, then rewrite or explicitly confirm every section under `Closeout-Reconciled State`.
92
+ At full closeout:
93
+
94
+ Closeout Write Contract: before writing `dev/SESSION_HANDOFF.md`, `dev/SESSION_LOG.md`, or `START_NEXT_SESSION_PROMPT.txt`, classify each fact by role and write it to the matching structured area. Use one Agent Handoff Kit marker standard as the machine boundary: `ack:section:*` for sections, `ack:field:*` for fields, `ack:log-entry:start/end` for log entries, and managed-core BEGIN/END for the installed AGENTS core. Do not remove or translate these markers. New closeout writes must use this marker standard; natural-language headings are only human labels, and legacy heading fallback is only for migration / repair of older installs. Current state and next action go only in `dev/SESSION_HANDOFF.md`. Trace evidence, one-time tasks, old build / release / hash facts, and completed delivery details go only in `dev/SESSION_LOG.md` unless promoted to `dev/PROJECT_INDEX.md`, `dev/PROJECT_DECISIONS.md`, `dev/DOC_SYNC_REGISTRY.md`, or a rule pack. `START_NEXT_SESSION_PROMPT.txt` is regenerated from the handoff opening-message block; do not hand-write separate startup state there.
95
+
96
+ 1. Reconcile `dev/SESSION_HANDOFF.md`. Do not append a new state snapshot under old state. Verify `Durable Anchors`, then rewrite or explicitly confirm every section under `Closeout-Reconciled State`.
93
97
  2. Add a concise entry to `dev/SESSION_LOG.md` with work actually completed this session and the exact next-session opening message.
94
98
  3. Update `dev/PROJECT_INDEX.md` if files, stack, commands, entry points, workspace identity, or durable document map changed.
95
99
  4. Check `dev/DOC_SYNC_REGISTRY.md` and record required sync status.
96
100
  5. Record unresolved drift risk, active worktree, parallel workspace, uncommitted changes, or blocked verification.
97
- 6. Complete the `State Reconciliation Check`: it must state when reconciliation happened, which state sections were rewritten or confirmed current, whether stale snapshots remain, whether completed / pending / risk / opening-message lifecycle conflicts were resolved, and whether the opening message matches current state. In the same step, run the handoff lifecycle consistency check before declaring handoff ready: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.
101
+ 6. Complete the `State Reconciliation Check`: it must state when reconciliation happened, which state sections were rewritten or confirmed current, whether stale snapshots remain, whether the `Persistence routing checked` field is complete, whether completed / pending / risk / opening-message lifecycle conflicts were resolved, and whether the opening message matches current state. In the same step, run the handoff lifecycle consistency check before declaring handoff ready: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.
98
102
  7. Run the handoff sufficiency check: the next AI should be able to continue from `AGENTS.md`, `dev/SESSION_HANDOFF.md`, `dev/PROJECT_INDEX.md`, and needed rule packs without searching old log history.
99
103
  8. If either check fails, fix `dev/SESSION_HANDOFF.md` first; do not push current-state responsibility into `dev/SESSION_LOG.md`.
100
104
  9. Regenerate `START_NEXT_SESSION_PROMPT.txt` from the fenced opening message in `dev/SESSION_HANDOFF.md`, then read it back or run the project's prompt mirror check before declaring closeout ready. `dev/SESSION_HANDOFF.md` is authoritative; `START_NEXT_SESSION_PROMPT.txt` is the stateful startup prompt that the next local agent must read. During an active session, do not regenerate it just to silence `doctor`; normal `doctor` may warn about drift, but closeout must make the copy match before handoff is declared ready.
@@ -103,11 +107,11 @@ At full closeout:
103
107
 
104
108
  Hard triggers:
105
109
 
106
- (a) Advance the SESSION_LOG N-rule (R-010 SESSION_LOG handoff-role discipline) when `dev/SESSION_LOG.md` reaches N ≥ 11 entries, or when the main log exceeds 1500 lines. If triggered, move N ≥ 11 entries into `dev/SESSION_LOG_archive/archive_<batch>_<low_date>_to_<high_date>.md` with raw content preserved, maintain `dev/SESSION_LOG_archive/INDEX.md`, collapse absorbed N=4–10 entries to short-index lines, and port any unique narrative into the relevant durable source before collapsing it. Handoff capability rests on `dev/SESSION_HANDOFF.md`; `dev/SESSION_LOG.md` is trace-back / audit trail and does not carry handoff responsibility.
110
+ (a) Advance the SESSION_LOG N-rule (R-010 SESSION_LOG handoff-role discipline) when `dev/SESSION_LOG.md` reaches N ≥ 11 entries, or when the main log exceeds 1500 lines. If triggered, move N ≥ 11 entries into `dev/SESSION_LOG_archive/archive_<batch>_<low_date>_to_<high_date>.md` with raw content preserved, maintain `dev/SESSION_LOG_archive/INDEX.md`, collapse absorbed N=4–10 entries to short-index lines, and port any unique narrative into the relevant durable source before collapsing it. If a research trail affected a long-term decision, public claim, strategy, governance rule, or material selection, port its evidence chain into `dev/PROJECT_DECISIONS.md` using that file's research-derived decision format before collapsing the log. Handoff capability rests on `dev/SESSION_HANDOFF.md`; `dev/SESSION_LOG.md` is trace-back / audit trail and does not carry handoff responsibility.
107
111
 
108
112
  (b) Maintain `dev/PROJECT_DECISIONS.md` per R-028 project narrative discipline when `dev/SESSION_HANDOFF.md` contains a decisions-like H2 section (e.g. `## Confirmed Decisions`, `## Decisions`, `## 已定案決策`) with a numbered list of ≥ 30 entries. If triggered, split the oldest entries, retaining the most recent 8–22 in the handoff hot tier, into `dev/PROJECT_DECISIONS.md` `## Decisions Archive`, newest first.
109
113
 
110
- (c) Append to `dev/PROJECT_DECISIONS.md` immediately, or at closeout, when the current session includes substantive task evolution, a multi-option architectural trade-off with recorded rationale, a cross-session accumulated pattern, or a user retrospective question. Use `## Evolution Timeline`, `## Architecture Choices`, or `## Insights & Learnings` as appropriate.
114
+ (c) Append to `dev/PROJECT_DECISIONS.md` immediately, or at closeout, when the current session includes substantive task evolution, a multi-option architectural trade-off with recorded rationale, a cross-session accumulated pattern, or a user retrospective question. Use `## Evolution Timeline`, `## Architecture Choices`, or `## Insights & Learnings` as appropriate. If the decision is research-derived, use that file's evidence-chain format so the source, summary, inference, decision impact, and uncertainty survive future compression.
111
115
 
112
116
  (d) Run a full long-term maintenance pass every 10 closeouts as a backstop, even if no trigger seems obvious. Count closeouts from the main `dev/SESSION_LOG.md` entries plus archive index entry counts when an archive exists; if the count cannot be determined confidently, treat the current N=10 boundary as the backstop trigger.
113
117
 
@@ -115,10 +119,12 @@ At full closeout:
115
119
 
116
120
  Installed handoff templates use English headings by default for cross-tool stability, but project teams may translate `dev/SESSION_HANDOFF.md` section headings and visible field labels into the project's working language. Keep the `ack:section:*` and `ack:field:*` semantic markers intact; `doctor` validates those markers so localized handoff notes remain supported.
117
121
 
118
- Use this closeout card:
119
-
120
- ```text
121
- /\_/\ Agent Handoff Kit v<version>
122
+ Use this closeout card:
123
+
124
+ Use the same display version rule as startup: take the version from `dev/PROJECT_INDEX.md` `## Stack` row `Agent Handoff Kit template version`, print it as `vX.Y.Z`, and fall back to `version unverified` only when it cannot be verified. Never print the literal placeholder `v<version>`.
125
+
126
+ ```text
127
+ /\_/\ Agent Handoff Kit v<version>
122
128
  ( -.- ) handoff saved
123
129
  > ^ <
124
130
 
@@ -146,7 +152,7 @@ A pack may add task-specific requirements. A pack cannot weaken core safety. If
146
152
 
147
153
  When a task references external tools (Notion / Google Drive / Slack / Linear / GitHub / Dropbox / HubSpot / Atlassian / etc.) or `dev/PROJECT_INDEX.md` `## Installed Integrations` is non-empty, load `dev/rules/integrations.md` together with the relevant domain pack. The integrations pack covers Connector-first defaults, credential separation, multi-layer source-of-truth architecture, and cross-session resilience for declared integrations.
148
154
 
149
- After the task, persist durable facts into the correct home: handoff for current state, log for trace evidence, project index for file / command / reference maps, doc sync registry for sync obligations, and rule packs or registered references for reusable operating procedures. Do not assume the next session remembers pack context unless it is recorded, and do not treat handoff/log persistence as sufficient for reusable procedure knowledge.
155
+ After the task, persist durable facts into the correct home: handoff for current state, log for trace evidence, project index for file / command / reference maps, doc sync registry for sync obligations, project decisions for long-term decisions or research-derived rationale, and rule packs or registered references for reusable operating procedures. Do not assume the next session remembers pack context unless it is recorded, and do not treat handoff/log persistence as sufficient for reusable procedure knowledge.
150
156
 
151
157
  If a pack, skill, subagent plan, demo workspace, or external workflow produces its own closeout, treat it as subordinate evidence. The active project root still needs Agent Handoff Kit persistence before the task is complete.
152
158
 
@@ -7,6 +7,16 @@
7
7
 
8
8
  不需要你手動寫 —— AI 在收工時自動 update;重大決策可在發生時即時記錄,不必等到最後才回想。
9
9
 
10
+ Research-derived decisions use this compact evidence-chain format inside the relevant section, without creating a new section:
11
+
12
+ ```text
13
+ - YYYY-MM-DD [research-derived] Decision summary. Evidence chain: Source=source:<id>; Summary=<source finding>; Inference=<reasoning>; Decision impact=<what changed>; Uncertainty=<limits or none>.
14
+ ```
15
+
16
+ The `source:<id>` token must also appear in `dev/PROJECT_INDEX.md` under `Fact Base` or `External Sources`, so later sessions can trace the decision back to its source map.
17
+
18
+ This file does not store raw build / upload / QC evidence, current next actions, one-time task results, or reusable operating procedures. Keep those in `dev/SESSION_LOG.md`, `dev/SESSION_HANDOFF.md`, or the relevant rule pack / registered reference.
19
+
10
20
  ---
11
21
 
12
22
  ## Evolution Timeline
@@ -111,6 +111,8 @@ At full closeout, complete this check after updating the state sections above.
111
111
  - Stale snapshots left in this handoff: TBD
112
112
  <!-- ack:field:lifecycle-conflicts-resolved -->
113
113
  - Completed / pending / risk / opening-message lifecycle conflicts resolved or explicitly reclassified: TBD
114
+ <!-- ack:field:persistence-routing-checked -->
115
+ - Persistence routing checked: TBD
114
116
  <!-- ack:field:opening-message-matches-current-state -->
115
117
  - Opening message matches current state: TBD
116
118
  <!-- ack:field:next-ai-can-continue -->
@@ -118,7 +120,7 @@ At full closeout, complete this check after updating the state sections above.
118
120
 
119
121
  If any answer is no, blocked, or uncertain, fix this handoff before declaring handoff ready.
120
122
 
121
- Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated.
123
+ Lifecycle consistency rule: compare `Completed This Session`, `Validation / QC`, `Next Priorities`, `Risks / Blockers`, and `Next Session Opening Message`. A completed or verified item must not remain as an unresolved next priority, active risk, or startup instruction unless it is explicitly reclassified as monitor-only, follow-up scope, blocked, or reopened with the missing evidence or trigger condition stated. Persistence routing rule: one-time delivery instructions, historical validation evidence, old hashes, old version facts, and incident notes must stay in trace evidence unless they still affect the next action.
122
124
 
123
125
  <!-- ack:section:handoff-sufficiency-check -->
124
126
  ## Handoff Sufficiency Check
@@ -1,5 +1,7 @@
1
1
  # Session Log
2
2
 
3
+ <!-- ack:section:session-log-preamble -->
4
+
3
5
  > **Handoff role**: This log is the trace-back / audit trail layer. Handoff capability rests on `dev/SESSION_HANDOFF.md`. The next AI session can continue by reading `AGENTS.md` + `dev/SESSION_HANDOFF.md` + `dev/PROJECT_INDEX.md` + needed rule packs; reading this log is not required for continuity. Each closeout must run the maintenance trigger check per `AGENTS.md` `## Closeout And Handoff` step 11 (R-010 SESSION_LOG handoff-role discipline): N=1–3 keep full, N=4–10 may short-index after absorbed-source check when triggered, N=11+ archive into `dev/SESSION_LOG_archive/`.
4
6
 
5
7
  Add new session entries at the top. Record what actually happened in the session; do not copy old completed work forward as new work.
@@ -10,9 +12,12 @@ Keep recent entries concise. If older entries no longer affect the next action a
10
12
 
11
13
  Before closeout, record whether older log detail was kept, summarized, or archived, and whether the maintenance trigger check was no-op, triggered, or backstop-driven. Do not remove validation evidence, unresolved risks, or the latest opening message.
12
14
 
15
+ <!-- ack:section:session-log-entry-template -->
16
+
13
17
  ## Entry Template
14
18
 
15
19
  ````markdown
20
+ <!-- ack:log-entry:start -->
16
21
  ## <YYYY-MM-DD> — <short session title>
17
22
 
18
23
  - **ID:** <agent_or_session_id>
@@ -20,6 +25,7 @@ Before closeout, record whether older log detail was kept, summarized, or archiv
20
25
  - **Changed:** <files changed, or none>
21
26
  - **Done:** <work completed this session>
22
27
  - **QC:** <checks run and results, or why not run>
28
+ - **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>
23
29
  - **Sync:** <doc/external sync status>
24
30
  - **Pending:** <next work>
25
31
  - **Risks:** <known risks or none>
@@ -47,4 +53,5 @@ This is the first startup after installing Agent Handoff Kit. Load the onboardin
47
53
 
48
54
  Before changing anything, tell me the current state and your recommended next step.
49
55
  ```
56
+ <!-- ack:log-entry:end -->
50
57
  ````