@adamchanadam/agent-handoff-kit 0.4.1 → 0.4.2

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.en.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  **Your session relay baton.** Help the next AI conversation pick up your work: keep progress, key decisions, file locations and unfinished tasks.
6
6
 
7
- Code version covered: `v0.4.1`. This guide includes updates that have not been released yet. Features available to download depend on the published version.
7
+ Code version covered: `v0.4.2`. This guide includes updates that have not been released yet. Features available to download depend on the published version.
8
8
 
9
9
  [![Agent Handoff Kit introduction video](https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-promo-30s.gif)](https://youtu.be/RopbfBiSw1I)
10
10
 
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  **Session 接力棒**。讓下一次 AI 對話接得上:保留進度、重要決定、文件位置和未完事項。
6
6
 
7
- 文件對應程式版本:`v0.4.1`。這份說明包含尚未發布的更新;正式下載可用的功能,以已發布版本為準。
7
+ 文件對應程式版本:`v0.4.2`。這份說明包含尚未發布的更新;正式下載可用的功能,以已發布版本為準。
8
8
 
9
9
  [![Agent Handoff Kit 宣傳動畫](https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-promo-30s.gif)](https://youtu.be/RopbfBiSw1I)
10
10
 
@@ -562,10 +562,14 @@ const schemaChecks = [
562
562
  }
563
563
  ];
564
564
 
565
- main().catch((error) => {
566
- console.error(`agent-handoff-kit: ${error.message}`);
567
- process.exitCode = 1;
568
- });
565
+ // Importers can reuse the maintenance assessment without starting the CLI.
566
+ // Resolve the entry path so npm's symlink remains supported.
567
+ if (process.argv[1] && await realpath(process.argv[1]).catch(() => null) === fileURLToPath(import.meta.url)) {
568
+ main().catch((error) => {
569
+ console.error(`agent-handoff-kit: ${error.message}`);
570
+ process.exitCode = 1;
571
+ });
572
+ }
569
573
 
570
574
  async function main() {
571
575
  const { command, options } = parseArgs(process.argv.slice(2));
@@ -676,6 +680,11 @@ async function runCloseoutStatus(root, version) {
676
680
  const persistence = projectRequiredPersistence(fieldValueAfterMarker(handoffText, "project-required-persistence"));
677
681
  if (outcome !== "complete") findings.push("closeout outcome is not complete");
678
682
  if (!new Set(["complete", "not_required"]).has(persistence)) findings.push("project-required persistence is not complete or not required");
683
+ const declarations = assessCloseoutDeclarations(handoffText);
684
+ if (declarations.length > 0) {
685
+ findings.push("handoff reconciliation read-back is incomplete");
686
+ details.push(...declarations);
687
+ }
679
688
  const sufficiency = assessHandoffSufficiency(handoffText);
680
689
  if (sufficiency.length > 0) {
681
690
  findings.push("handoff sufficiency read-back is incomplete");
@@ -697,7 +706,7 @@ async function runCloseoutStatus(root, version) {
697
706
 
698
707
  // A closeout card needs a fresh local health readback, not a version-notice
699
708
  // network request. The caller has already completed the closeout workflow.
700
- const doctor = await assessUpgradeNoopHealth(root, version, { skipVersionRegistryLookup: true });
709
+ const doctor = await assessUpgradeNoopHealth(root, version, { skipVersionRegistryLookup: true, requireSessionLogMaintenance: true });
701
710
  if (!doctor.ok) {
702
711
  findings.push("fresh doctor read-back did not pass");
703
712
  details.push(...closeoutDoctorFailureDetails(doctor));
@@ -708,10 +717,10 @@ async function runCloseoutStatus(root, version) {
708
717
  if (!result.ok) process.exitCode = 1;
709
718
  }
710
719
 
711
- function assessHandoffSufficiency(text) {
720
+ function visibleHandoffLines(text) {
712
721
  // Only visible prose is a declaration. Preserve text outside inline comments,
713
722
  // but exclude fenced/indented examples and markers inside comments. This is
714
- // local to the sufficiency fields; no project source is opened by the check.
723
+ // shared by closeout field checks; no project source is opened by the parser.
715
724
  const original = text.replace(/\r\n/g, "\n").split("\n");
716
725
  const markerPattern = /^\s{0,3}<!-- (ack:(?:section|field):[\w-]+) -->\s*$/u;
717
726
  const visible = [];
@@ -748,6 +757,60 @@ function assessHandoffSufficiency(text) {
748
757
  if (opening && (opening[1][0] !== "`" || !opening[2].includes("`"))) { fence = opening[1]; continue; }
749
758
  visible.push({ text: prose.trim(), marker: null });
750
759
  }
760
+ return visible;
761
+ }
762
+
763
+ function assessCloseoutDeclarations(text) {
764
+ const visible = visibleHandoffLines(text);
765
+ const field = (id) => {
766
+ const indices = visible.map((line, index) => line.marker === `ack:field:${id}` ? index : -1).filter((index) => index >= 0);
767
+ if (indices.length !== 1) return "";
768
+ for (const line of visible.slice(indices[0] + 1)) {
769
+ if (line.marker || /^##\s/u.test(line.text)) break;
770
+ if (line.text) return line.text.match(/^[*-]\s+[^:]+:\s*(.*)$/u)?.[1] ?? "";
771
+ }
772
+ return "";
773
+ };
774
+ const findings = [];
775
+ if (!/^no(?:$|[\s,.;:—–-])/iu.test(field("stale-snapshots-left"))) {
776
+ findings.push("Handoff: stale snapshots must be reconciled; stale-snapshots-left must explicitly say no.");
777
+ }
778
+ for (const [id, label] of [["recommended-next-step-explicit", "recommended next step"], ["opening-message-matches-current-state", "opening message"]]) {
779
+ const value = field(id);
780
+ if (!isAffirmativeLifecycleFieldValue(value) || isUnresolvedLifecycleFieldValue(value)) {
781
+ findings.push(`Handoff: ${label} declaration is missing, negative or unverified; reconcile it before closeout.`);
782
+ }
783
+ }
784
+ const priorityContent = (line) => {
785
+ let value = (line || "").trim();
786
+ if (!value || /^#{1,6}(?:\s|$)/u.test(value) || /^(?:[-*_]\s*){3,}$/u.test(value)) return "";
787
+ value = value.replace(/^(?:(?:[-+*])|\d+[.)])\s+/u, "").replace(/^\[(?: |x|X)\]\s*/u, "");
788
+ let previous;
789
+ do {
790
+ previous = value;
791
+ value = value.replace(/^(\*{1,3}|_{1,3}|`{1,3})([\s\S]*?)\1$/u, "$2").trim();
792
+ } while (value && value !== previous);
793
+ return value;
794
+ };
795
+ const priorities = visibleHandoffLines(extractSectionText(text, "next-priorities", "Next Priorities"))
796
+ .map((line) => priorityContent(line.text))
797
+ .filter(Boolean);
798
+ const placeholder = (value) => /^<[^>]*>$/u.test(value)
799
+ || /^(?:TBD|todo|pending|unverified|unconfirmed|unknown|needs-review|no|blocked|uncertain|still unresolved|not resolved|not confirmed|待核對|待確認|待定|否|阻擋|不確定|(?:仍|尚)?未(?:解決|確認|核對|完成))[.!。]?$/iu.test(value);
800
+ // `Next Priorities` must be visible and usable, but its action/reason,
801
+ // decision, and blocker meaning are semantic closeout-pack review—not a
802
+ // machine-enforced English narrative grammar.
803
+ const knownUnfilledPriorityTemplate = /^Recommended next step:\s*TBD\s*—\s*reason:\s*TBD[.!。]?$/iu;
804
+ if (priorities.some((value) => knownUnfilledPriorityTemplate.test(value))) {
805
+ findings.push("Handoff: recommended next step is still an unfilled template; reconcile it before closeout.");
806
+ } else if (!priorities.some((value) => !placeholder(value))) {
807
+ findings.push("Handoff: Next Priorities must contain a visible, non-empty, non-placeholder statement; review its semantic adequacy under the closeout pack.");
808
+ }
809
+ return findings;
810
+ }
811
+
812
+ function assessHandoffSufficiency(text) {
813
+ const visible = visibleHandoffLines(text);
751
814
  const marked = (id) => visible.map((line, index) => line.marker === id ? index : -1).filter((index) => index >= 0);
752
815
  const indices = marked("ack:section:handoff-sufficiency-check");
753
816
  if (indices.length !== 1) return ["Handoff: require one active handoff-sufficiency-check section."];
@@ -808,6 +871,9 @@ function closeoutDoctorFailureDetails(doctor) {
808
871
  };
809
872
 
810
873
  add("Doctor: ", lines.find((line) => /^status:\s*failed\b/iu.test(line)));
874
+ for (const line of lines.filter((line) => /^\s*warn: (?:SESSION_LOG|dev\/SESSION_LOG\.md)/u.test(line))) {
875
+ add("Doctor maintenance: ", line.trim());
876
+ }
811
877
  const firstProblemIndex = lines.findIndex((line) => /^(missing|warn|failed)\s{2,}\S/iu.test(line.trim()));
812
878
  if (firstProblemIndex >= 0) {
813
879
  add("Doctor first problem: ", lines[firstProblemIndex].trim());
@@ -1176,7 +1242,13 @@ function workspaceValueMeansNoGit(value) {
1176
1242
 
1177
1243
  function workspaceRootMeansNoGit(value) {
1178
1244
  // Absence labels apply to the repository root, never to a branch/commit name.
1179
- return /^\s*(?:none|not_applicable|n\/a)(?:$|\s*[;(—–])/iu.test(value ?? "") || workspaceValueMeansNoGit(value);
1245
+ return /^\s*(?:none|not[ _]applicable|n\/a)(?:$|\s*[;(—–])/iu.test(value ?? "") || workspaceValueMeansNoGit(value);
1246
+ }
1247
+
1248
+ function workspaceValueIsNaturalNotApplicable(value) {
1249
+ // Git branch names cannot contain spaces. This spelling is therefore an
1250
+ // absence label in a known non-Git workspace, not Git identity.
1251
+ return /^\s*not[ _]applicable(?:$|\s*[;(—–])/iu.test(value ?? "");
1180
1252
  }
1181
1253
 
1182
1254
  function workspaceSectionClaimsNoGit(section) {
@@ -1191,7 +1263,9 @@ function workspaceSectionClaimsGitRepository(section) {
1191
1263
  workspaceFieldValue(section, "Commit")
1192
1264
  ];
1193
1265
  return (hasSubstantiveWorkspaceValue(gitRoot) && !workspaceRootMeansNoGit(gitRoot))
1194
- || values.some((value) => hasSubstantiveWorkspaceValue(value) && !workspaceValueMeansNoGit(value));
1266
+ || values.some((value) => hasSubstantiveWorkspaceValue(value)
1267
+ && !workspaceValueMeansNoGit(value)
1268
+ && !workspaceValueIsNaturalNotApplicable(value));
1195
1269
  }
1196
1270
 
1197
1271
  function workspaceSectionClaimsVerifiedState(section) {
@@ -3338,13 +3412,24 @@ async function runDoctor(root, version, options = {}) {
3338
3412
  return "failed";
3339
3413
  }
3340
3414
 
3341
- // R-010 SESSION_LOG handoff-role discipline check (warn-only; does not change mode or exit).
3415
+ // R-010 SESSION_LOG handoff-role discipline is advisory during ordinary
3416
+ // doctor use, but its existing maintenance triggers must be cleared at closeout.
3342
3417
  const disciplineResult = await assessSessionLogDiscipline(root);
3343
3418
  console.log(`\nSESSION_LOG 接力角色紀律: ${disciplineResult.ok ? "ok" : "warn"}`);
3344
3419
  if (!disciplineResult.ok) {
3345
3420
  for (const warning of disciplineResult.warnings) {
3346
3421
  console.log(` warn: ${warning}`);
3347
3422
  }
3423
+ if (options.requireSessionLogMaintenance) {
3424
+ printDoctorSummary(version, root, "needs-fix", {
3425
+ checked: rows.length + historicalReceiptChecks + anchorRows.length + schemaRows.length + userRulesResult.checked + researchTraceResult.checked + temperatureResult.checked + mirrorRows.length + 1,
3426
+ failedKind: "SESSION_LOG maintenance checks",
3427
+ failedCount: disciplineResult.warnings.length,
3428
+ nextStep: "先依 closeout pack 完成 SESSION_LOG 維護及歸檔讀回,再重跑 closeout-status;未完成維護不能宣告收工完成。"
3429
+ });
3430
+ process.exitCode = 1;
3431
+ return "failed";
3432
+ }
3348
3433
  }
3349
3434
 
3350
3435
  // R-030 v0.3.0+: credential leak prevention sweep over governance files.
@@ -3777,7 +3862,7 @@ function printDoctorSummary(version, root, mode, details) {
3777
3862
  }
3778
3863
  } else {
3779
3864
  console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
3780
- console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "formal user-rules checks" ? "AGENTS.md 與 dev/USER_RULES.md 的接受見證不一致。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : details.failedKind === "research decision trace checks" ? "研究導向決策缺少可追溯來源鏈。" : details.failedKind === "handoff temperature boundary checks" ? "當前交接內容混入一次性或歷史證據。" : "下次開工提示副本與 handoff 真源不同。"}`);
3865
+ console.log(`⚠️ 檢查未通過:${doctorFailureExplanation(details.failedKind)}`);
3781
3866
  }
3782
3867
  console.log("");
3783
3868
  console.log(`📦 版本:v${version}`);
@@ -3786,6 +3871,24 @@ function printDoctorSummary(version, root, mode, details) {
3786
3871
  console.log(`🚀 下一步:${details.nextStep}`);
3787
3872
  }
3788
3873
 
3874
+ export function doctorFailureExplanation(kind) {
3875
+ const explanations = {
3876
+ "missing files": "有必要檔案不存在。",
3877
+ "project shortcuts": "專案快捷入口缺少或內容不一致。",
3878
+ "SESSION_LOG archive casing checks": "SESSION_LOG 歸檔目錄的大小寫或位置不符合規定。",
3879
+ "formal user-rules checks": "AGENTS.md 與 dev/USER_RULES.md 的接受見證不一致。",
3880
+ "anchor checks": "有檔案存在,但內容缺少必要段落。",
3881
+ "schema checks": "交接或索引文件結構不完整。",
3882
+ "bridge checks": "CLAUDE.md / GEMINI.md 未正確連到 AGENTS.md。",
3883
+ "research decision trace checks": "研究導向決策缺少可追溯來源鏈。",
3884
+ "handoff temperature boundary checks": "當前交接內容混入一次性或歷史證據。",
3885
+ "prompt mirror checks": "下次開工提示副本與 handoff 真源不同。",
3886
+ "SESSION_LOG maintenance checks": "SESSION_LOG 維護尚未完成。",
3887
+ "credential leak": "治理檔案出現疑似機密值;請依上列位置處理。"
3888
+ };
3889
+ return Object.hasOwn(explanations, kind) ? explanations[kind] : "檢查未通過;請依上列失敗種類、明細與下一步處理。";
3890
+ }
3891
+
3789
3892
  function formalUserRulesRepairNextStep(finding) {
3790
3893
  const reason = String(finding ?? "");
3791
3894
  if (reason.includes("AGENTS.md managed core does not match")) {
@@ -4036,19 +4139,19 @@ function compactLifecycleDiagnosticLine(line) {
4036
4139
 
4037
4140
  function isAffirmativeLifecycleFieldValue(value) {
4038
4141
  const trimmed = (value || "").trim();
4039
- return /^(yes|resolved|confirmed|complete|completed|ok|passed|all clear)\b|^(是|已|完成|已完成|已解決|已核對|已確認|通過)\b/i.test(trimmed);
4142
+ return /^(yes|resolved|confirmed|complete|completed|ok|passed|all clear)\b|^(?:是|完成|已完成|已解決|已核對|已確認|通過)(?=$|[\s,。;:、,.!:;—–-])/iu.test(trimmed);
4040
4143
  }
4041
4144
 
4042
4145
  function isUnresolvedLifecycleFieldValue(value) {
4043
4146
  const trimmed = normalizeLifecycleFieldValue(value);
4044
- return /^(no|blocked|uncertain)\b|^(否|阻擋|不確定)\b/i.test(trimmed)
4045
- || /\b(still unresolved|not resolved)\b|仍未解決|尚未解決/i.test(trimmed);
4147
+ return /^(no|blocked|uncertain)\b|^(?:否|阻擋|不確定|未確認|未核對|未完成)/iu.test(trimmed)
4148
+ || /\b(still unresolved|not resolved|not confirmed|unverified)\b|(?:仍|尚)?未(?:解決|確認|核對|完成)/iu.test(trimmed);
4046
4149
  }
4047
4150
 
4048
4151
  function isPlaceholderLifecycleFieldValue(value) {
4049
4152
  const trimmed = normalizeLifecycleFieldValue(value);
4050
4153
  return !trimmed
4051
- || /^(TBD|todo|pending|unverified|unknown|needs-review)\b|^(待核對|待確認|未核對|未確認)\b/i.test(trimmed);
4154
+ || /^(TBD|todo|pending|unverified|unknown|needs-review)\b|^(?:待核對|待確認|待定|未核對|未確認)/iu.test(trimmed);
4052
4155
  }
4053
4156
 
4054
4157
  function normalizeLifecycleFieldValue(value) {
@@ -4605,7 +4708,7 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
4605
4708
  return { ...base, action: "skip", reason: "SESSION_HANDOFF.md lifecycle and startup contracts current" };
4606
4709
  }
4607
4710
  if (targetRel === "dev/SESSION_LOG.md" && command === "upgrade") {
4608
- const migratedLog = migrateSessionLog(targetText, sourceText);
4711
+ const migratedLog = migrateSessionLog(targetText, sourceText, context);
4609
4712
  if (!migratedLog) {
4610
4713
  return { ...base, action: "conflict", reason: "SESSION_LOG.md lacks a unique trusted entry-template boundary; migration stopped without replacing trace history" };
4611
4714
  }
@@ -5763,9 +5866,11 @@ function restoreMissingCurrentOpeningLines(targetPrompt, sourcePrompt) {
5763
5866
  return targetLines.join("\n");
5764
5867
  }
5765
5868
 
5766
- function migrateSessionLog(targetText, sourceText) {
5869
+ function migrateSessionLog(targetText, sourceText, context = {}) {
5767
5870
  let merged = mergeSessionLogTemplateContract(targetText, sourceText);
5768
5871
  if (!merged) return null;
5872
+ merged = replaceVerifiedOfficialSessionLogPreamble(merged, sourceText, context, targetText);
5873
+ if (!merged) return null;
5769
5874
  merged = mergeSessionLogEvidenceDispositionField(merged);
5770
5875
  if (!merged) return null;
5771
5876
 
@@ -5776,6 +5881,60 @@ function migrateSessionLog(targetText, sourceText) {
5776
5881
  return merged;
5777
5882
  }
5778
5883
 
5884
+ function sessionLogPreambleBounds(text) {
5885
+ const startMarker = "<!-- ack:section:session-log-preamble -->";
5886
+ const endMarker = "<!-- ack:section:session-log-entry-template -->";
5887
+ const start = text.indexOf(startMarker);
5888
+ if (start < 0 || text.indexOf(startMarker, start + startMarker.length) >= 0) return null;
5889
+ const templateStart = text.indexOf(endMarker, start + startMarker.length);
5890
+ if (templateStart < 0 || text.indexOf(endMarker, templateStart + endMarker.length) >= 0) return null;
5891
+ // Historical entries are allowed immediately before the template marker.
5892
+ // They are trace data, never part of the replaceable official preamble.
5893
+ const firstEntry = text.indexOf("<!-- ack:log-entry:start -->", start + startMarker.length);
5894
+ const end = firstEntry >= 0 && firstEntry < templateStart ? firstEntry : templateStart;
5895
+ return { start, end };
5896
+ }
5897
+
5898
+ function officialSessionLogPreambleBounds(text) {
5899
+ const currentBounds = sessionLogPreambleBounds(text);
5900
+ if (currentBounds) return { ...currentBounds, format: "marked" };
5901
+
5902
+ // The verified v0.1.0 catalog predates both SESSION_LOG boundary markers.
5903
+ // Its single legacy title/template boundary is only a candidate boundary;
5904
+ // callers still require exact equality with the trusted catalog baseline
5905
+ // before replacing project-owned content.
5906
+ const titles = [...text.matchAll(/^# Session Log\s*$/gm)];
5907
+ const templates = [...text.matchAll(/^## Entry Template\s*$/gm)];
5908
+ if (titles.length !== 1 || templates.length !== 1 || titles[0].index !== 0 || templates[0].index <= titles[0].index) return null;
5909
+ return { start: titles[0].index + titles[0][0].length, end: templates[0].index, format: "legacy" };
5910
+ }
5911
+
5912
+ function replaceVerifiedOfficialSessionLogPreamble(targetText, sourceText, context, originalTargetText = targetText) {
5913
+ const baselineVersion = context.trustedBaselineVersion;
5914
+ if (!baselineVersion || !context.officialCatalog) return targetText;
5915
+ const baseline = getOfficialBaseline({
5916
+ version: baselineVersion,
5917
+ targetRel: "dev/SESSION_LOG.md",
5918
+ catalog: context.officialCatalog
5919
+ });
5920
+ if (baseline?.state !== "present") return targetText;
5921
+
5922
+ const targetBounds = sessionLogPreambleBounds(targetText);
5923
+ const sourceBounds = sessionLogPreambleBounds(sourceText);
5924
+ const baselineBounds = officialSessionLogPreambleBounds(baseline.text);
5925
+ if (!targetBounds || !sourceBounds || !baselineBounds) return null;
5926
+
5927
+ const originalBounds = officialSessionLogPreambleBounds(originalTargetText);
5928
+ if (!originalBounds || originalBounds.format !== baselineBounds.format) return targetText;
5929
+
5930
+ const targetPreamble = originalTargetText.slice(originalBounds.start, originalBounds.end).replace(/\r\n?/g, "\n").trimEnd();
5931
+ const officialPreamble = baseline.text.slice(baselineBounds.start, baselineBounds.end).replace(/\r\n?/g, "\n").trimEnd();
5932
+ // Only the catalog's complete, verified historical preamble may be replaced.
5933
+ // A local line (even beside an otherwise old preamble) remains user content.
5934
+ if (targetPreamble !== officialPreamble) return targetText;
5935
+ return `${targetText.slice(0, targetBounds.start)}${sourceText.slice(sourceBounds.start, sourceBounds.end).trimEnd()}\n\n${targetText.slice(targetBounds.end)}`;
5936
+ }
5937
+
5779
5938
  function mergeHandoffLifecycleField(targetText) {
5780
5939
  const openingMarker = "<!-- ack:field:opening-message-matches-current-state -->";
5781
5940
  if (!targetText.includes(openingMarker)) return null;
@@ -6242,8 +6401,8 @@ function printProjectAge(result) {
6242
6401
  // Thresholds (all warn-only; doctor exit unaffected):
6243
6402
  // - H2 entry count ≥ 11 → warn (archive boundary; AI closeout flow should auto-advance)
6244
6403
  // - H2 entry count ≥ 25 → warn (severe drift; suggest AI re-do closeout)
6245
- // - line count ≥ 1500 → warn (anomalous entry size; safety net)
6246
- async function assessSessionLogDiscipline(root) {
6404
+ // - line count > 1500 → warn (anomalous entry size; safety net)
6405
+ export async function assessSessionLogDiscipline(root) {
6247
6406
  const logPath = path.join(root, "dev/SESSION_LOG.md");
6248
6407
  let text = "";
6249
6408
  try {
@@ -6263,7 +6422,7 @@ async function assessSessionLogDiscipline(root) {
6263
6422
  warnings.push(`SESSION_LOG entry count = ${entryCount}(達 N=11+ archive 邊界;下次 closeout 時 AI 應自動執行 N 規則推進,如未動請提醒)`);
6264
6423
  }
6265
6424
 
6266
- if (lineCount >= 1500) {
6425
+ if (lineCount > 1500) {
6267
6426
  warnings.push(`SESSION_LOG line count = ${lineCount}(超過 1500 安全網閾值;可能 entry 異常長)`);
6268
6427
  }
6269
6428
 
@@ -6748,7 +6907,8 @@ async function assessUpgradeNoopHealth(root, version, options = {}) {
6748
6907
  const status = await runDoctor(root, version, {
6749
6908
  silentCard: true,
6750
6909
  context: "upgrade-noop-health-check",
6751
- skipVersionRegistryLookup: options.skipVersionRegistryLookup === true
6910
+ skipVersionRegistryLookup: options.skipVersionRegistryLookup === true,
6911
+ requireSessionLogMaintenance: options.requireSessionLogMaintenance === true
6752
6912
  });
6753
6913
  const doctorExitCode = process.exitCode;
6754
6914
  return {
package/bin/commands.mjs CHANGED
@@ -12,13 +12,13 @@ export const commands = Object.freeze([
12
12
  {name:'handoff-kit-progress',label:'進度頁 / Progress',description:'Open the existing Agent Handoff Kit project overview without generating a report.',intent:'Open the project progress page',body:'In the verified project root, run node dev/handoff-kit/launch.mjs --root <project-root>, quoting the root as one argument in the active shell. The normal installer supplies this local program and its assets; opening progress does not use npm, download tools or require registry access. For an integrated browser, add --no-open and open the returned loopback URL there. Verify the returned page is reachable before reporting success. If the local program is missing or damaged, identify incomplete installation rather than silently acquiring @latest or overwriting files. A platform permission failure requires the runtime’s supported approval mechanism; do not change global caches, credentials, ACLs or sandbox settings or ask the user to repair npm. Give one short result. Do not read or summarize the log for the model, generate HTML, write progress data, or change the normal record-saving schedule.'},
13
13
  {name:'handoff-kit-align',label:'對齊治理 / Align',description:'Check a named document or scan for important documents not connected to Agent Handoff Kit.',intent:'Bridge governance / scan for unbridged governance documents',body:'Use the governance-bridge route in dev/RULE_PACKS.md and its existing owner. With a named target, review that target and its source/index/sync relationships. Without a target, perform the bounded candidate scan described by that workflow. Report gaps and proposed changes; a scan alone never authorizes edits, renames, deletes or authority merges. Apply a concrete fix only when the user has authorized its scope. This is not a Kit upgrade or a blanket rule rewrite.'},
14
14
  {name:'handoff-kit-onboard',label:'新手引導 / Onboard',description:'Guide a user who explicitly asks to learn or start using Agent Handoff Kit.',intent:'Teach me to use Agent Handoff Kit',body:'Use the onboarding route in dev/RULE_PACKS.md. Explain in the user’s language, use their existing goal when provided, and ask only for missing information that matters. Do not reset first-use state, reinstall the Kit, or mark project work complete. Follow the existing onboarding procedure rather than inventing another questionnaire.'},
15
- {name:'handoff-kit-remember',label:'保存工作規則 / Remember',description:'Route an explicitly requested future working rule into Agent Handoff Kit governance.',intent:'Connect this future working rule to Agent Handoff Kit',body:'Use the long-term governance route in dev/RULE_PACKS.md. If no rule or identifiable preceding instruction was provided, ask one short question. Locate the existing owner and writable project supplement, then merge only the authorized rule and verify its consumer route. Preserve official core/pack bodies. Do not save secrets or treat a session-log note as the durable rule owner.'},
15
+ {name:'handoff-kit-remember',label:'保存工作規則 / Remember',description:'Route an explicitly requested future working rule into Agent Handoff Kit governance.',intent:'Connect this future working rule to Agent Handoff Kit',body:'Use the long-term governance route in dev/RULE_PACKS.md. If no rule or identifiable preceding instruction was provided, ask one short question. Locate the existing owner and writable project supplement, then merge only the authorized rule and verify its consumer route. Keep each durable rule in one authoritative location; resolve conflicts there using the project\'s existing authority order, without duplicating the rule or creating a compromise rule. Preserve official core/pack bodies. Do not save secrets or treat a session-log note as the durable rule owner.'},
16
16
  {name:'handoff-kit-check',label:'檢查安裝 / Check',description:'Check the selected project’s Agent Handoff Kit installation without repairing or upgrading it.',intent:'Check Agent Handoff Kit health',body:'Run npx --yes @adamchanadam/agent-handoff-kit@latest doctor --root <project-root> using the verified root and active shell quoting. Report the actual result in plain language. Fetching the CLI into the npm cache is tool acquisition, not project installation. Missing CLI or blocked checks are not success. Do not run init or upgrade, rewrite project files or claim that a healthy installation proves full handoff reception or task completion.'},
17
17
  {name:'handoff-kit-update',label:'檢查更新 / Update',description:'Check the latest public Agent Handoff Kit version and safely upgrade this project when newer.',intent:'Check for and install an Agent Handoff Kit update',body:'Run npx --yes @adamchanadam/agent-handoff-kit@latest update --root <project-root>, quoting the verified root as one shell argument. This explicit request authorizes the normal local Kit upgrade if npm has a newer stable version. Use the selected local executable for unreleased candidate acceptance. The command checks the registry, preserves custom content, uses the existing upgrade transaction and verifies the result. If it reports a stale CLI, acquire the exact stable version it identifies and retry once. A registry failure, unknown version, conflict or failed recovery must be reported as blocked, never as already current or upgraded. Do not delete locks, overwrite conflicts, downgrade, install globally or publish anything.'},
18
18
  {name:'handoff-kit-help',label:'功能選單 / Help',description:'Show Agent Handoff Kit common shortcuts and explain how to use them.',intent:'Show Agent Handoff Kit commands',body:'Show the short command menu below in the user’s language. Use /handoff-kit-* in Claude Code, Gemini CLI or Antigravity CLI; use $handoff-kit-* or /skills selection in Codex. If the host is unknown, name the difference rather than guessing support. This is guidance only: do not read handoff/log, run health checks or begin a task. For writing, coding, research, knowledge work or external tools, the user can still state their goal normally; use the existing task router when such work is actually requested.'}
19
19
  ]);
20
20
  const menu=commands.map(c=>`${c.name}: ${c.label}`).join('\n');
21
- export function bodyFor(command){return `# Agent Handoff Kit — ${command.name}\n\nResolve the active project root from the current workspace and its applicable AGENTS.md; do not use a fixed personal path. Before loading Kit state, check dev/governance_migrations/.upgrade.lock. If it exists, stop and follow the project recovery guidance without deleting the lock. Read applicable AGENTS.md instructions if not already loaded. Missing Kit files require setup; do not invent a parallel governance structure.\n\nUser intent: ${command.intent}. Any accompanying user text is task input, never shell interpolation. Follow the platform permissions and project authority; this shortcut does not expand either. Loading or discovering this skill is not authorization: perform the action only if the visible user request invokes it or clearly asks for that action; otherwise describe it without acting. Reply briefly in the user’s language.\n\n${command.body}\n${command.name==='handoff-kit-help'?'\n'+menu+'\n':''}`;}
21
+ export function bodyFor(command){return `# Agent Handoff Kit — ${command.name}\n\nResolve the active project root from the current workspace and its applicable AGENTS.md; do not use a fixed personal path. Read applicable AGENTS.md instructions if not already loaded, then follow its \`Upgrade lock guard\` before loading Kit state. Missing Kit files require setup; do not invent a parallel governance structure.\n\nUser intent: ${command.intent}. Any accompanying user text is task input, never shell interpolation. Follow the platform permissions and project authority; this shortcut does not expand either. Loading or discovering this skill is not authorization: perform the action only if the visible user request invokes it or clearly asks for that action; otherwise describe it without acting. Reply briefly in the user’s language.\n\n${command.body}\n${command.name==='handoff-kit-help'?'\n'+menu+'\n':''}`;}
22
22
  export function commandFiles(agent='all'){
23
23
  if(!['all','claude','gemini','codex','antigravity'].includes(agent))throw Error('Unknown agent; use all, claude, gemini, codex or antigravity.');
24
24
  const files=[];
@@ -3,13 +3,13 @@
3
3
  // path cannot silently become current lifecycle authority before that route is
4
4
  // explicitly present.
5
5
 
6
- import { commandFiles } from './commands.mjs';
6
+ import { commands, commandFiles } from './commands.mjs';
7
7
 
8
8
  // Source-to-delivery routing. Unknown new shipped modules must receive an owner.
9
9
  // QA stages/evidence are defined by the existing assurance gate, not runtime doctor.
10
10
  export const deliveredFeatureContracts = Object.freeze([
11
11
  {id:'installer',sources:['package.json','bin/agent-handoff-kit.mjs','bin/installed-file-contract.mjs','bin/official-origin-catalog.mjs','bin/migration-baselines/','bin/upgrade-inventory.mjs','bin/user-rules-router.mjs']},
12
- {id:'shortcuts',sources:['bin/commands.mjs'],hosts:['claude','gemini','codex','antigravity'],nativeAcceptanceHosts:['codex'],nativeInvocationEntries:['handoff-kit-progress']},
12
+ {id:'shortcuts',sources:['bin/commands.mjs'],requiredForFull:true,hosts:['claude','gemini','codex','antigravity'],nativeAcceptanceHosts:['codex'],nativeInvocationEntries:commands.map(({name})=>name)},
13
13
  {id:'dashboard',sources:['bin/progress/']},
14
14
  {id:'continuity',sources:['runtime-core/','bin/handoff-read.mjs','bin/prompt-mirror-core.mjs']},
15
15
  {id:'task-packs',sources:['packs/']}