@adamchanadam/agent-handoff-kit 0.3.23 → 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.23`。這是早期可用版本,仍在持續完善中。
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.23`;正式安裝請以 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 = [
@@ -71,9 +71,11 @@ const requiredAnchors = [
71
71
  "Wrap up Agent Handoff",
72
72
  "Ambiguous closeout phrases",
73
73
  "wrap up",
74
- "handoff",
75
- "Reconcile `dev/SESSION_HANDOFF.md`",
74
+ "handoff",
75
+ "Reconcile `dev/SESSION_HANDOFF.md`",
76
76
  "Add a concise entry to `dev/SESSION_LOG.md`",
77
+ "Closeout Write Contract",
78
+ "ack:log-entry:start/end",
77
79
  "next-session opening message",
78
80
  "fenced `text` code block",
79
81
  "handoff saved",
@@ -116,9 +118,13 @@ const requiredAnchors = [
116
118
  label: "session log event and opening message schema",
117
119
  placement: sessionLogAnchorPlacement,
118
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",
119
125
  "Record what actually happened in the session",
120
126
  "## Entry Template",
121
- "- **QC:**",
127
+ "- **QC:**",
122
128
  "- **Sync:**",
123
129
  "- **Log maintenance:**",
124
130
  "### Next Session Opening Message",
@@ -294,8 +300,12 @@ const schemaChecks = [
294
300
  target: "dev/SESSION_LOG.md",
295
301
  label: "session log entry fields",
296
302
  checks: [
297
- heading("Entry Template"),
298
- 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:**"),
299
309
  includes("- **Summary:**"),
300
310
  includes("- **Changed:**"),
301
311
  includes("- **Done:**"),
@@ -497,28 +507,29 @@ async function runInstall(command, root, options, version) {
497
507
  // this guard, plan-time short-circuit returns before inject can fire, leaving
498
508
  // root on stale version forever.
499
509
  const projectIndexVersionNeedsInject = await needsProjectIndexVersionInject(root, command, version);
500
- const isUpgradeNoopAtPlanTime = command === "upgrade"
501
- && planCreateCount === 0
502
- && planMergeCount === 0
503
- && planConflictCount === 0
504
- && !projectIndexVersionNeedsInject;
505
-
506
- if (isUpgradeNoopAtPlanTime) {
507
- const noOpHealth = await assessUpgradeNoopHealth(root);
508
- printCard(version, "continuity ready", "o.o");
509
- console.log(`command: ${command}`);
510
- 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()}`);
511
521
  console.log(`selected root: ${root}`);
512
522
  console.log(`mode: ${mode}`);
513
523
  console.log("");
514
524
  console.log(`📋 計劃預覽:create 0 / merge 0 / skip ${planSkipCount} / conflict 0 — 沒有檔案需要建立或合併。`);
515
525
  if (options.dryRun) {
516
- console.log("");
517
- console.log("dry-run: no files written");
518
- }
519
- printUpgradeNoopShortCircuit(version, noOpHealth);
520
- return;
521
- }
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
+ }
522
533
 
523
534
  printPlan(command, root, mode, plan, version, options.dryRun);
524
535
 
@@ -553,14 +564,19 @@ async function runInstall(command, root, options, version) {
553
564
 
554
565
  await hydrateInitialOpeningPrompt(root, created);
555
566
 
556
- for (const item of plan) {
557
- if (item.action !== "merge") continue;
558
- const backupPath = path.join(backupDir, item.targetRel);
559
- await mkdir(path.dirname(backupPath), { recursive: true });
560
- await copyFile(item.targetAbs, backupPath);
561
- await writeFile(item.targetAbs, item.mergedText, "utf8");
562
- merged.push(item.targetRel);
563
- }
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
+ }
564
580
 
565
581
  // R-031.3 v0.3.4+: Inject current CLI version into PROJECT_INDEX template version
566
582
  // metadata row — placed AFTER the merge loop to avoid the ordering bug where merge
@@ -603,16 +619,18 @@ async function runInstall(command, root, options, version) {
603
619
  // metadata row was stale (counts 0/0/0 but metadataUpdated truthy), user just
604
620
  // received a substantive upgrade — proceed through full ceremony so doctor
605
621
  // self-check confirms the inject result.
606
- const isUpgradeNoop = command === "upgrade"
607
- && created.length === 0
608
- && merged.length === 0
609
- && conflicts.length === 0
610
- && !metadataUpdated;
611
-
612
- if (isUpgradeNoop) {
613
- printUpgradeNoopShortCircuit(version);
614
- return;
615
- }
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
+ }
616
634
 
617
635
  const report = await writeMigrationReport(root, command, mode, plan, created, merged, conflicts, migrationDir, backupDir, metadataUpdated);
618
636
  printInstallSummary(version, command, mode, root, {
@@ -914,7 +932,18 @@ async function checkHandoffTemperatureBoundary(root) {
914
932
  // Missing prompt mirror is handled by prompt mirror checks; do not duplicate the failure here.
915
933
  }
916
934
 
917
- const evidencePatterns = [
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 [
918
947
  { pattern: /post-publish artifact smoke/i, label: "post-publish artifact smoke evidence" },
919
948
  { pattern: /PASS\s+7\/7/i, label: "historical PASS count" },
920
949
  { pattern: /\bfileCount\b/i, label: "published artifact fileCount evidence" },
@@ -924,21 +953,86 @@ async function checkHandoffTemperatureBoundary(root) {
924
953
  { pattern: /\bnpm latest\s+(?:is|=|v?\d)/i, label: "historical npm latest state" },
925
954
  { pattern: /GitHub Release\s+(?:metadata|published|view|`?v?\d)/i, label: "historical GitHub Release state" }
926
955
  ];
927
- const sourceTokenPattern = /\bsource:[A-Za-z0-9._-]+\b/;
956
+ }
928
957
 
929
- for (const section of sections) {
930
- if (!section.text) continue;
931
- for (const rule of evidencePatterns) {
932
- if (rule.pattern.test(section.text)) {
933
- findings.push(`${section.label} contains ${rule.label}; keep it in trace evidence unless it still affects the next action`);
934
- }
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`);
935
963
  }
936
- if (!section.allowSourceTokens && sourceTokenPattern.test(section.text)) {
937
- findings.push(`${section.label} contains source:<id>; keep source tokens in PROJECT_INDEX / PROJECT_DECISIONS, not hot startup state`);
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;
938
1014
  }
939
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
+ }
940
1027
 
941
- return { ok: findings.length === 0, checked: 1, findings };
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 };
942
1036
  }
943
1037
 
944
1038
  function extractHandoffSectionText(text, id, headingText) {
@@ -960,6 +1054,35 @@ function extractHandoffSectionText(text, id, headingText) {
960
1054
  return text.slice(start, nextMatch ? nextMatch.index : text.length);
961
1055
  }
962
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
+
963
1086
  function getFirstUseNextStep(root, lastCloseout) {
964
1087
  if (lastCloseout.date) return null;
965
1088
  return `檢查已通過。下一步不要再留在終端機;打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,輸入 Start Agent Handoff 或「開工」;若 AI 還未指向此資料夾,才貼:${startupPathBootstrapPrompt(root)}`;
@@ -1470,6 +1593,9 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1470
1593
  };
1471
1594
  }
1472
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
+ }
1473
1599
  if (targetRel === "dev/SESSION_HANDOFF.md" && command === "upgrade" && hasMissingRequiredAnchor(targetRel, targetText, "handoff log archive continuity")) {
1474
1600
  const mergedHandoff = mergeHandoffArchiveContinuityRule(targetText, sourceText);
1475
1601
  if (!mergedHandoff) {
@@ -1482,6 +1608,28 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
1482
1608
  mergedText: mergedHandoff
1483
1609
  };
1484
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
+ }
1485
1633
  if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade" && !targetText.includes("- **Evidence disposition:**")) {
1486
1634
  const mergedLog = mergeSessionLogEvidenceDispositionField(targetText);
1487
1635
  if (!mergedLog) {
@@ -1620,7 +1768,12 @@ function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
1620
1768
  }
1621
1769
 
1622
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");
1623
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
+ }
1624
1777
  const preamble = [
1625
1778
  "Record what actually happened in the session",
1626
1779
  "kept, summarized, or archived",
@@ -1628,7 +1781,19 @@ function sessionLogAnchorPlacement(snippet, text) {
1628
1781
  "latest opening message",
1629
1782
  "not current state"
1630
1783
  ];
1631
- 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);
1632
1797
  return snippetAppearsAfterHeading(text, snippet, "## Entry Template");
1633
1798
  }
1634
1799
 
@@ -1728,10 +1893,10 @@ const semanticAnchorRepairStrategies = {
1728
1893
  } : null;
1729
1894
  },
1730
1895
  "dev/SESSION_LOG.md": (targetText, sourceText) => {
1731
- const mergedLog = insertSourcePreambleBeforeHeading(targetText, sourceText, "## Entry Template");
1896
+ const mergedLog = mergeSessionLogTemplateContract(targetText, sourceText);
1732
1897
  return mergedLog ? {
1733
1898
  action: "merge",
1734
- reason: "restore SESSION_LOG Kit preamble before ## Entry Template",
1899
+ reason: "restore SESSION_LOG machine boundaries and entry template contract",
1735
1900
  mergedText: mergedLog
1736
1901
  } : null;
1737
1902
  },
@@ -2037,10 +2202,95 @@ function ensureHandoffStateReconciliationRules(targetText) {
2037
2202
  }
2038
2203
 
2039
2204
  function mergeSessionLogEvidenceDispositionField(targetText) {
2040
- if (targetText.includes("- **Evidence disposition:**")) return targetText;
2205
+ if (targetText.includes("- **Evidence disposition:**")) return mergeSessionLogTemplateContract(targetText, null) ?? targetText;
2041
2206
  const qcField = "- **QC:**";
2042
2207
  if (!targetText.includes(qcField)) return null;
2043
- return 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>`);
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;
2226
+ }
2227
+ }
2228
+
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)}`;
2044
2294
  }
2045
2295
 
2046
2296
  function mergeHandoffArchiveContinuityRule(targetText, sourceText) {
@@ -2768,7 +3018,7 @@ function printUpgradeNextSteps(root, conflictCount) {
2768
3018
  console.log("============================================================");
2769
3019
  return;
2770
3020
  }
2771
- console.log("✅ 升級完成:Kit 檔案已更新到最新版本");
3021
+ console.log("🛠️ Kit 檔案已更新:等待下方 doctor 驗收");
2772
3022
  console.log("============================================================");
2773
3023
  console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
2774
3024
  console.log("");
@@ -2779,38 +3029,68 @@ function printUpgradeNextSteps(root, conflictCount) {
2779
3029
  console.log("============================================================");
2780
3030
  }
2781
3031
 
2782
- // R-031 v0.3.1+: Upgrade no-op short-circuit. When the user runs upgrade on a root
2783
- // already at latest version (skip all / create 0 / merge 0 / conflict 0), print a
2784
- // short factual message and return. Saves disk (no migration report) + reduces noise
2785
- // (no self-check doctor) + avoids misleading "安裝完成" framing for an idempotent
2786
- // operation where nothing changed.
2787
- async function assessUpgradeNoopHealth(root) {
2788
- try {
2789
- const handoffText = await readFile(path.join(root, "dev/SESSION_HANDOFF.md"), "utf8");
2790
- return { handoffLifecycle: assessHandoffLifecycleConsistency(handoffText) };
2791
- } catch {
2792
- return { handoffLifecycle: { ok: false, reason: "dev/SESSION_HANDOFF.md unreadable" } };
2793
- }
2794
- }
2795
-
2796
- function printUpgradeNoopShortCircuit(version, health = { handoffLifecycle: { ok: true } }) {
2797
- console.log("");
2798
- console.log(`📦 版本:v${version}`);
2799
- console.log("🛠️ 模式:upgrade-existing");
2800
- console.log("🔎 剛完成:檢查所有 Kit 檔案的狀態(含 AGENTS.md、dev/SESSION_HANDOFF.md、dev/PROJECT_INDEX.md 等)。");
2801
- if (health.handoffLifecycle?.ok) {
2802
- console.log("✅ 結果:你已經是最新版本,沒有檔案需要建立或合併;用戶填寫的內容全部保留現狀。");
2803
- console.log("");
2804
- console.log("🚀 下一步:回到原本的 AI 對話或開工句即可;如果剛完成任務,記得在 AI 對話輸入「收工」保存交接。");
2805
- console.log("");
2806
- return;
2807
- }
2808
- console.log("⚠️ 結果:Kit 檔案已是最新版本,沒有檔案需要建立或合併;但交接狀態仍需 AI closeout 核對。");
2809
- console.log("");
2810
- console.log("🚀 下一步:先執行 doctor 取得待修項,再把輸出貼給 AI;不要重裝或覆寫用戶內容。");
2811
- console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest doctor");
2812
- console.log("");
2813
- }
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
+ }
2814
3094
 
2815
3095
  function listOrNone(items) {
2816
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.23",
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": {
@@ -89,9 +89,11 @@ Detect end-of-session or handoff intent in natural language, such as "收工", "
89
89
 
90
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.
91
91
 
92
- At full closeout:
93
-
94
- 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`.
95
97
  2. Add a concise entry to `dev/SESSION_LOG.md` with work actually completed this session and the exact next-session opening message.
96
98
  3. Update `dev/PROJECT_INDEX.md` if files, stack, commands, entry points, workspace identity, or durable document map changed.
97
99
  4. Check `dev/DOC_SYNC_REGISTRY.md` and record required sync status.
@@ -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>
@@ -48,4 +53,5 @@ This is the first startup after installing Agent Handoff Kit. Load the onboardin
48
53
 
49
54
  Before changing anything, tell me the current state and your recommended next step.
50
55
  ```
56
+ <!-- ack:log-entry:end -->
51
57
  ````