@adamchanadam/agent-handoff-kit 0.1.6 → 0.1.8

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.1.6` 已正式發佈到 GitHub 與 npm。這是早期可用版本,尚未宣稱所有需求已完成。
3
+ 狀態:`v0.1.8` 已正式發佈到 GitHub 與 npm。這是早期可用版本,尚未宣稱所有需求已完成。
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
 
@@ -8,7 +8,7 @@ Agent Handoff Kit 是 **AI Session 之間的接力棒**。
8
8
 
9
9
  它只處理一件狹窄但重要的事:AI 跨對話失憶。每次開新對話,AI 往往不記得你上次做到哪裡,也認不出中途新建的文件、你引入的參考資料、哪些檔案是真源。這套工具把進度、下一步、風險、檔案登記與下次開工提示寫進固定文件,讓下一個 AI 工具能接得上上一棒。
10
10
 
11
- 想先看非技術版介紹,可打開 GitHub Pages 上的 [`agent-handoff-kit-intro.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.html)。那一頁是新手 60 秒入門,README 則保留安裝、日常使用與限制。
11
+ 想先看非技術版介紹,可打開 GitHub Pages 上的 [`agent-handoff-kit-intro.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.html) —— 新手 60 秒入門。看完想睇實際操作示範,可開 [`agent-handoff-kit-guide.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.html) —— 兩個日常情景(整理電腦下載目錄、開咖啡店市場調查)嘅七步流程完整示範。README 則保留安裝、日常使用與限制。
12
12
 
13
13
  ## 它解決甚麼問題
14
14
 
@@ -106,7 +106,7 @@ dev/rules/*.md
106
106
  | `GEMINI.md` | 讓 Gemini CLI 找到同一套入口。 |
107
107
  | `START_NEXT_SESSION_PROMPT.txt` | 下次開工時可直接貼上的便利副本;由 handoff 產生。 |
108
108
  | `dev/SESSION_HANDOFF.md` | 保存目前狀態、下一步、風險、驗收結果與下一次開工文字。 |
109
- | `dev/SESSION_LOG.md` | 保存近期實際做過的事與檢查結果。 |
109
+ | `dev/SESSION_LOG.md` | 保存近期實際做過的事與檢查結果。主檔長期保持短小;N=11+ 嘅舊條目自動 archive 至 `dev/SESSION_LOG_archive/`,trace-back 用。接力靠 `SESSION_HANDOFF.md`,本檔屬冷資料層。 |
110
110
  | `dev/PROJECT_INDEX.md` | 記錄專案檔案、必讀資料、外部來源與常用檢查。 |
111
111
  | `dev/DOC_SYNC_REGISTRY.md` | 記錄哪些文件改動後需要同步。 |
112
112
  | `dev/RULE_PACKS.md` | 告訴 AI 不同任務應讀哪些工作規則。 |
@@ -197,11 +197,11 @@ npm package 只包含安裝所需內容:
197
197
  - `LICENSE`
198
198
  - `package.json`
199
199
 
200
- GitHub Pages 上的新手介紹頁 `agent-handoff-kit-intro.html` 由原始碼倉庫根目錄發佈;`agent-handoff-kit-intro.html` 與 `images/` 是原始碼倉庫資產,不會安裝到你的專案。
200
+ GitHub Pages 上的兩個 onboarding 頁 —— [`agent-handoff-kit-intro.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.html)(60 秒入門)與 [`agent-handoff-kit-guide.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.html)(實操指南)—— 由原始碼倉庫根目錄發佈;兩個 HTML 與 `images/` 是原始碼倉庫資產,不會安裝到你的專案。
201
201
 
202
202
  ## 目前限制
203
203
 
204
- - `v0.1.6` 是 GitHub 與 npm 同步發佈版本。
204
+ - `v0.1.8` 是 GitHub 與 npm 同步發佈版本。
205
205
  - 這是早期可用版本,尚未宣稱完整穩定。
206
206
  - 升級合併仍是窄範圍策略,不是完整的複雜合併工具。
207
207
  - `doctor` 能檢查結構,不能代替 AI 對專案內容的理解。
@@ -167,16 +167,8 @@ const schemaChecks = [
167
167
  label: "core runtime uniqueness",
168
168
  checks: [
169
169
  {
170
- label: "exactly one Agent Handoff Kit Core Runtime heading",
171
- test: (text) => countOccurrences(text, "# Agent Handoff Kit Core Runtime") === 1
172
- },
173
- {
174
- label: "managed core markers are paired and not duplicated",
175
- test: (text) => {
176
- const starts = countOccurrences(text, managedCoreStart);
177
- const ends = countOccurrences(text, managedCoreEnd);
178
- return starts === ends && starts <= 1;
179
- }
170
+ label: "AGENTS.md health state is clean (single managed core, no unmarked dup, paired markers)",
171
+ test: (text) => assessAgentsMdHealth(text).state === "clean"
180
172
  }
181
173
  ]
182
174
  },
@@ -374,18 +366,38 @@ async function runInstall(command, root, options, version) {
374
366
  }
375
367
 
376
368
  const report = await writeMigrationReport(root, command, mode, plan, created, merged, conflicts, migrationDir, backupDir);
377
- console.log(`\n✅ created: ${created.length}`);
378
- console.log(`🔀 merged: ${merged.length}`);
379
- console.log(`⏭️ skipped existing: ${plan.filter((item) => item.action === "skip").length}`);
380
- console.log(`${conflicts.length > 0 ? "⚠️ " : "✅ "}conflict: ${conflicts.length}`);
381
- if (merged.length > 0) console.log(`💾 backup: ${path.relative(root, backupDir)}`);
382
- console.log(`📄 migration report: ${path.relative(root, report)}`);
369
+ const skippedCount = plan.filter((item) => item.action === "skip").length;
370
+ printInstallSummary(version, command, mode, root, {
371
+ created: created.length,
372
+ merged: merged.length,
373
+ skipped: skippedCount,
374
+ conflicts: conflicts.length,
375
+ backupRel: merged.length > 0 ? path.relative(root, backupDir) : null,
376
+ reportRel: path.relative(root, report)
377
+ });
383
378
  printInstallNextSteps(root, conflicts.length);
379
+
380
+ // R-024 upgrade.done self-check: after upgrade writes, run doctor automatically.
381
+ // The user must see whether the merged state actually reaches a clean health state.
382
+ if (command === "upgrade" && conflicts.length === 0) {
383
+ console.log("");
384
+ console.log("------------------------------------------------------------");
385
+ console.log("🩺 upgrade self-check: running doctor against the upgraded root");
386
+ console.log("------------------------------------------------------------");
387
+ const doctorStatus = await runDoctor(root, version, { silentCard: true });
388
+ if (doctorStatus !== "passed") {
389
+ console.log("");
390
+ console.log("⚠️ upgrade self-check did not pass; see doctor output above.");
391
+ console.log("📋 下一步:把上面 doctor 輸出貼給 AI,請它先按提示修補後再宣稱 upgrade 完成。");
392
+ process.exitCode = 1;
393
+ }
394
+ }
395
+
384
396
  if (conflicts.length > 0) process.exitCode = 1;
385
397
  }
386
398
 
387
- async function runDoctor(root, version) {
388
- printCard(version, "doctor ready", "o.o");
399
+ async function runDoctor(root, version, options = {}) {
400
+ if (!options.silentCard) printCard(version, "doctor ready", "o.o");
389
401
  const rows = [];
390
402
  for (const target of requiredTargets) {
391
403
  rows.push({ target, ok: await exists(path.join(root, target)) });
@@ -399,11 +411,14 @@ async function runDoctor(root, version) {
399
411
  }
400
412
 
401
413
  if (missing.length > 0) {
402
- console.log(`\nstatus: failed (${missing.length} missing)`);
403
- console.log("⚠️ 檢查未通過:有必要檔案不存在。");
404
- console.log("下一步:先確認你是否在正確專案資料夾;如是,執行 init 或 upgrade 補回缺少檔案。");
414
+ printDoctorSummary(version, root, "needs-fix", {
415
+ checked: rows.length,
416
+ failedKind: "missing files",
417
+ failedCount: missing.length,
418
+ nextStep: "先確認你是否在正確專案資料夾;如是,執行 init 或 upgrade 補回缺少檔案。"
419
+ });
405
420
  process.exitCode = 1;
406
- return;
421
+ return "failed";
407
422
  }
408
423
 
409
424
  const anchorRows = await checkRequiredAnchors(root);
@@ -414,11 +429,14 @@ async function runDoctor(root, version) {
414
429
  }
415
430
 
416
431
  if (anchorFailures.length > 0) {
417
- console.log(`\nstatus: failed (${anchorFailures.length} anchor checks failed)`);
418
- console.log("⚠️ 檢查未通過:有檔案存在,但內容缺少必要段落。");
419
- console.log("下一步:執行 upgrade --dry-run 查看可否安全補齊;不要手動覆寫既有檔案。");
432
+ printDoctorSummary(version, root, "needs-fix", {
433
+ checked: rows.length + anchorRows.length,
434
+ failedKind: "anchor checks",
435
+ failedCount: anchorFailures.length,
436
+ nextStep: "執行 upgrade --dry-run 查看可否安全補齊;不要手動覆寫既有檔案。"
437
+ });
420
438
  process.exitCode = 1;
421
- return;
439
+ return "failed";
422
440
  }
423
441
 
424
442
  const schemaRows = await checkSchema(root);
@@ -432,11 +450,14 @@ async function runDoctor(root, version) {
432
450
  }
433
451
 
434
452
  if (schemaFailures.length > 0) {
435
- console.log(`\nstatus: failed (${schemaFailures.length} schema checks failed)`);
436
- console.log("⚠️ 檢查未通過:交接或索引文件結構不完整。");
437
- console.log("下一步:把這段 doctor 輸出貼給 AI,請它先修交接結構,不要直接重裝覆蓋。");
453
+ printDoctorSummary(version, root, "needs-fix", {
454
+ checked: rows.length + anchorRows.length + schemaRows.length,
455
+ failedKind: "schema checks",
456
+ failedCount: schemaFailures.length,
457
+ nextStep: "把這段 doctor 輸出貼給 AI,請它先修交接結構,不要直接重裝覆蓋。"
458
+ });
438
459
  process.exitCode = 1;
439
- return;
460
+ return "failed";
440
461
  }
441
462
 
442
463
  const mirrorRows = await checkPromptMirror(root);
@@ -448,15 +469,51 @@ async function runDoctor(root, version) {
448
469
  }
449
470
 
450
471
  if (mirrorFailures.length > 0) {
451
- console.log(`\nstatus: failed (${mirrorFailures.length} prompt mirror checks failed)`);
452
- console.log("⚠️ 檢查未通過:下次開工提示副本與 handoff 真源不同。");
453
- console.log("下一步:以 dev/SESSION_HANDOFF.md 的 Next Session Opening Message 為準,重生 START_NEXT_SESSION_PROMPT.txt。");
472
+ printDoctorSummary(version, root, "needs-fix", {
473
+ checked: rows.length + anchorRows.length + schemaRows.length + mirrorRows.length,
474
+ failedKind: "prompt mirror checks",
475
+ failedCount: mirrorFailures.length,
476
+ nextStep: "以 dev/SESSION_HANDOFF.md 的 Next Session Opening Message 為準,重生 START_NEXT_SESSION_PROMPT.txt。"
477
+ });
454
478
  process.exitCode = 1;
455
- return;
479
+ return "failed";
480
+ }
481
+
482
+ // R-010 SESSION_LOG handoff-role discipline check (warn-only; does not change mode or exit).
483
+ const disciplineResult = await assessSessionLogDiscipline(root);
484
+ console.log(`\nSESSION_LOG discipline (R-010): ${disciplineResult.ok ? "ok" : "warn"}`);
485
+ if (!disciplineResult.ok) {
486
+ for (const warning of disciplineResult.warnings) {
487
+ console.log(` warn: ${warning}`);
488
+ }
456
489
  }
457
490
 
458
- console.log("\nstatus: passed");
459
- console.log("✅ 檢查通過:必要文件存在,基本結構完整,下次開工提示副本也與 handoff 一致。");
491
+ printDoctorSummary(version, root, "healthy", {
492
+ checked: rows.length + anchorRows.length + schemaRows.length + mirrorRows.length + 1,
493
+ failedKind: null,
494
+ failedCount: 0,
495
+ nextStep: disciplineResult.ok
496
+ ? "繼續日常使用;如要升級到較新版,執行 npx @adamchanadam/agent-handoff-kit@latest upgrade。"
497
+ : "繼續使用;下次 closeout 時 AI 應自動執行 R-010 N 規則推進(見上面 warn 行)。如未動請要求 AI 重做 closeout。"
498
+ });
499
+ return "passed";
500
+ }
501
+
502
+ // R-026 CLI Output Contract: doctor 完成必含四項(版本/模式/剛做咗乜/下一步)。
503
+ function printDoctorSummary(version, root, mode, details) {
504
+ console.log("");
505
+ if (mode === "healthy") {
506
+ console.log("status: passed");
507
+ console.log("✅ 檢查通過:必要文件存在,基本結構完整,下次開工提示副本也與 handoff 一致。");
508
+ } else {
509
+ console.log(`status: failed (${details.failedCount} ${details.failedKind} failed)`);
510
+ console.log(`⚠️ 檢查未通過:${details.failedKind === "missing files" ? "有必要檔案不存在。" : details.failedKind === "anchor checks" ? "有檔案存在,但內容缺少必要段落。" : details.failedKind === "schema checks" ? "交接或索引文件結構不完整。" : "下次開工提示副本與 handoff 真源不同。"}`);
511
+ }
512
+ console.log("");
513
+ console.log(`📦 版本:v${version}`);
514
+ console.log(`🩺 模式:${mode}`);
515
+ console.log(`🔎 剛做咗:檢查 ${details.checked} 項;${mode === "healthy" ? "全部通過" : `${details.failedCount} 項未通過(${details.failedKind})`}。`);
516
+ console.log(`🚀 下一步:${details.nextStep}`);
460
517
  }
461
518
 
462
519
  async function checkPromptMirror(root) {
@@ -608,11 +665,42 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
608
665
  if (targetText === sourceText) return { ...base, action: "skip", reason: "already current" };
609
666
  if (command !== "upgrade") return { ...base, action: "skip", reason: "init preserves existing files" };
610
667
  if (targetRel === "AGENTS.md") {
611
- if (hasRequiredAnchor(targetRel, targetText)) return { ...base, action: "skip", reason: "required anchors already present" };
668
+ const health = assessAgentsMdHealth(targetText);
669
+ if (health.state === "conflict") {
670
+ return {
671
+ ...base,
672
+ action: "conflict",
673
+ reason: `AGENTS.md managed-core markers are unpaired or duplicated (starts=${health.evidence.managedStart}, ends=${health.evidence.managedEnd})`
674
+ };
675
+ }
676
+ if (health.state === "needs-merge") {
677
+ return {
678
+ ...base,
679
+ action: "merge",
680
+ reason: health.evidence.reason === "sandwich: managed marker + unmarked stale core"
681
+ ? "replace sandwich dup core (managed marker + unmarked stale core present)"
682
+ : health.evidence.reason === "legacy duplicate cores"
683
+ ? "replace duplicated legacy Agent Handoff Kit cores"
684
+ : "add managed core while preserving existing AGENTS.md content",
685
+ mergedText: mergeManagedBlock(targetText, sourceText)
686
+ };
687
+ }
688
+ // state === "clean": may still need legacy-core replacement or anchor catch-up
689
+ if (health.evidence?.upgradeable === "legacy-core") {
690
+ return {
691
+ ...base,
692
+ action: "merge",
693
+ reason: "replace unmarked legacy Agent Handoff Kit core with managed-marker block",
694
+ mergedText: mergeManagedBlock(targetText, sourceText)
695
+ };
696
+ }
697
+ if (hasRequiredAnchor(targetRel, targetText)) {
698
+ return { ...base, action: "skip", reason: "managed core clean and required anchors present" };
699
+ }
612
700
  return {
613
701
  ...base,
614
702
  action: "merge",
615
- reason: "replace stale Agent Handoff Kit core or add managed core while preserving existing AGENTS.md content",
703
+ reason: "add managed core while preserving existing AGENTS.md content",
616
704
  mergedText: mergeManagedBlock(targetText, sourceText)
617
705
  };
618
706
  }
@@ -622,27 +710,202 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
622
710
  return { ...base, action: "skip", reason: "preserve existing file" };
623
711
  }
624
712
 
625
- function mergeManagedBlock(targetText, sourceText) {
626
- const block = `${managedCoreStart}\n${sourceText.trim()}\n${managedCoreEnd}`;
627
- const existingBlock = new RegExp(`${escapeRegExp(managedCoreStart)}[\\s\\S]*?${escapeRegExp(managedCoreEnd)}`);
628
- if (existingBlock.test(targetText)) return `${targetText.replace(existingBlock, block).trimEnd()}\n`;
629
- const unmarkedCore = findUnmarkedCoreRange(targetText);
630
- if (unmarkedCore) {
631
- return `${targetText.slice(0, unmarkedCore.start).trimEnd()}${targetText.slice(0, unmarkedCore.start).trimEnd() ? "\n\n" : ""}${block}${targetText.slice(unmarkedCore.end).trimStart() ? `\n\n${targetText.slice(unmarkedCore.end).trimStart()}` : ""}\n`;
713
+ // R-010 SESSION_LOG handoff-role discipline (warn-only doctor check).
714
+ // Returns { ok, warnings } where:
715
+ // - ok: true if no warnings triggered
716
+ // - warnings: array of Chinese, actionable warning strings
717
+ // Thresholds (all warn-only; doctor exit unaffected):
718
+ // - H2 entry count ≥ 11 → warn (archive boundary; AI closeout flow should auto-advance)
719
+ // - H2 entry count ≥ 25 → warn (severe drift; suggest AI re-do closeout)
720
+ // - line count ≥ 1500 → warn (anomalous entry size; safety net)
721
+ async function assessSessionLogDiscipline(root) {
722
+ const logPath = path.join(root, "dev/SESSION_LOG.md");
723
+ let text = "";
724
+ try {
725
+ text = await readFile(logPath, "utf8");
726
+ } catch {
727
+ return { ok: false, warnings: ["dev/SESSION_LOG.md unreadable; discipline check skipped"] };
728
+ }
729
+
730
+ const warnings = [];
731
+ const entryMatches = text.match(/^## \d{4}-\d{2}-\d{2}/gm) || [];
732
+ const entryCount = entryMatches.length;
733
+ const lineCount = text.split("\n").length;
734
+
735
+ if (entryCount >= 25) {
736
+ warnings.push(`SESSION_LOG entry count = ${entryCount}(嚴重超過 N=11+ archive 邊界;R-010 嘅 AI closeout flow 應該已自動推進,如未動請要求 AI 跟 R-010 重做 closeout)`);
737
+ } else if (entryCount >= 11) {
738
+ warnings.push(`SESSION_LOG entry count = ${entryCount}(達 N=11+ archive 邊界;下次 closeout 時 AI 應自動執行 N 規則推進,如未動請提醒)`);
739
+ }
740
+
741
+ if (lineCount >= 1500) {
742
+ warnings.push(`SESSION_LOG line count = ${lineCount}(超過 1500 安全網閾值;可能 entry 異常長)`);
743
+ }
744
+
745
+ return { ok: warnings.length === 0, warnings };
746
+ }
747
+
748
+ // R-024 唯一真源:AGENTS.md 健康判斷合三為一函數。
749
+ // Returns { state, evidence } where state ∈ { clean, needs-merge, conflict }.
750
+ // - clean: structurally healthy
751
+ // * exactly one paired managed-core marker block with no unmarked title outside it, OR
752
+ // * no managed marker and exactly one core title (fresh-init legacy form)
753
+ // - needs-merge: stale state that upgrade must replace
754
+ // * managed marker pair plus unmarked title outside it (sandwich), or
755
+ // * no managed marker with two or more title duplicates, or
756
+ // * no managed marker and no title at all (file exists but Kit core absent)
757
+ // - conflict: structural breakage
758
+ // * managed-core markers unpaired or duplicated
759
+ function assessAgentsMdHealth(text) {
760
+ const managedStartCount = countOccurrences(text, managedCoreStart);
761
+ const managedEndCount = countOccurrences(text, managedCoreEnd);
762
+
763
+ if (managedStartCount !== managedEndCount || managedStartCount > 1) {
764
+ return {
765
+ state: "conflict",
766
+ evidence: {
767
+ managedStart: managedStartCount,
768
+ managedEnd: managedEndCount,
769
+ reason: "managed-core markers unpaired or duplicated"
770
+ }
771
+ };
772
+ }
773
+
774
+ let managedRange = null;
775
+ if (managedStartCount === 1) {
776
+ const start = text.indexOf(managedCoreStart);
777
+ const endStart = text.indexOf(managedCoreEnd, start);
778
+ if (endStart < 0 || endStart < start) {
779
+ return {
780
+ state: "conflict",
781
+ evidence: {
782
+ managedStart: managedStartCount,
783
+ managedEnd: managedEndCount,
784
+ reason: "managed-core end marker missing or before start"
785
+ }
786
+ };
787
+ }
788
+ managedRange = { start, end: endStart + managedCoreEnd.length };
789
+ }
790
+
791
+ // Only count real top-level headings (line-anchored), not inline mentions inside backticks.
792
+ const titlePositions = locateCoreTitlePositions(text);
793
+
794
+ const titlesOutsideManaged = titlePositions.filter((pos) =>
795
+ !managedRange || pos < managedRange.start || pos >= managedRange.end
796
+ );
797
+
798
+ // Case A: managed marker pair present
799
+ if (managedStartCount === 1) {
800
+ if (titlesOutsideManaged.length > 0) {
801
+ const unmarkedRange = computeUnmarkedRange(text, titlesOutsideManaged[0], managedRange);
802
+ return {
803
+ state: "needs-merge",
804
+ evidence: {
805
+ managedStart: 1,
806
+ titleCount: titlePositions.length,
807
+ unmarkedTitleCount: titlesOutsideManaged.length,
808
+ unmarkedRange,
809
+ reason: "sandwich: managed marker + unmarked stale core"
810
+ }
811
+ };
812
+ }
813
+ return {
814
+ state: "clean",
815
+ evidence: {
816
+ managedStart: 1,
817
+ titleCount: titlePositions.length,
818
+ reason: "single managed core, no unmarked dup"
819
+ }
820
+ };
821
+ }
822
+
823
+ // Case B: no managed marker
824
+ if (titlePositions.length === 1) {
825
+ // Structurally healthy (single heading, no dup), but upgrade should still replace
826
+ // this legacy core form with a managed-marker block. doctor passes; upgrade merges.
827
+ return {
828
+ state: "clean",
829
+ evidence: {
830
+ managedStart: 0,
831
+ titleCount: 1,
832
+ upgradeable: "legacy-core",
833
+ legacyRange: computeUnmarkedRange(text, titlePositions[0], null),
834
+ reason: "single legacy core, no managed marker"
835
+ }
836
+ };
837
+ }
838
+ if (titlePositions.length > 1) {
839
+ return {
840
+ state: "needs-merge",
841
+ evidence: {
842
+ managedStart: 0,
843
+ titleCount: titlePositions.length,
844
+ unmarkedTitleCount: titlePositions.length,
845
+ unmarkedRange: computeUnmarkedRange(text, titlePositions[0], null),
846
+ reason: "legacy duplicate cores"
847
+ }
848
+ };
632
849
  }
633
- return `${targetText.trimEnd()}\n\n${block}\n`;
850
+ return {
851
+ state: "needs-merge",
852
+ evidence: {
853
+ managedStart: 0,
854
+ titleCount: 0,
855
+ reason: "no Kit core present"
856
+ }
857
+ };
634
858
  }
635
859
 
636
- function findUnmarkedCoreRange(text) {
637
- const start = text.indexOf("# Agent Handoff Kit Core Runtime");
638
- if (start < 0) return null;
860
+ // Locate Kit core titles that are real top-level headings (line-anchored).
861
+ // This intentionally excludes inline mentions like `# Agent Handoff Kit Core Runtime`
862
+ // inside backticks or prose, so the assess function only reacts to real duplicate headings.
863
+ function locateCoreTitlePositions(text) {
864
+ const regex = /(^|\n)# Agent Handoff Kit Core Runtime(?=\r?\n|$)/g;
865
+ const positions = [];
866
+ let match;
867
+ while ((match = regex.exec(text)) !== null) {
868
+ const headingStart = match.index + (match[1] === "\n" ? 1 : 0);
869
+ positions.push(headingStart);
870
+ }
871
+ return positions;
872
+ }
873
+
874
+ function computeUnmarkedRange(text, titleStart, managedRange) {
875
+ const titleNeedle = "# Agent Handoff Kit Core Runtime";
639
876
  const terminal = "keep the core within budget.";
640
- const terminalIndex = text.indexOf(terminal, start);
641
- if (terminalIndex >= 0) return { start, end: terminalIndex + terminal.length };
642
- const afterTitle = start + "# Agent Handoff Kit Core Runtime".length;
643
- const nextTopLevel = text.slice(afterTitle).search(/\n# (?!Agent Handoff Kit Core Runtime\b)/);
644
- if (nextTopLevel < 0) return { start, end: text.length };
645
- return { start, end: afterTitle + nextTopLevel + 1 };
877
+ const terminalIndex = text.indexOf(terminal, titleStart);
878
+ if (terminalIndex >= 0 && (!managedRange || terminalIndex < managedRange.start || terminalIndex >= managedRange.end)) {
879
+ return { start: titleStart, end: terminalIndex + terminal.length };
880
+ }
881
+ const afterTitle = titleStart + titleNeedle.length;
882
+ const remainder = text.slice(afterTitle);
883
+ // Find next real top-level heading that is NOT another Kit core heading.
884
+ const nextTopLevel = remainder.search(/\n# (?!Agent Handoff Kit Core Runtime(?=\r?\n|$))/);
885
+ if (nextTopLevel < 0) return { start: titleStart, end: text.length };
886
+ return { start: titleStart, end: afterTitle + nextTopLevel + 1 };
887
+ }
888
+
889
+ function mergeManagedBlock(targetText, sourceText) {
890
+ const block = `${managedCoreStart}\n${sourceText.trim()}\n${managedCoreEnd}`;
891
+
892
+ // Strip every unmarked / legacy core range first; iterate to handle multiple legacy stacks.
893
+ let working = targetText;
894
+ for (let i = 0; i < 5; i += 1) {
895
+ const probe = assessAgentsMdHealth(working);
896
+ const range = probe.evidence?.unmarkedRange ?? probe.evidence?.legacyRange;
897
+ if (!range) break;
898
+ const before = working.slice(0, range.start).trimEnd();
899
+ const after = working.slice(range.end).trimStart();
900
+ working = before + (before && after ? "\n\n" : before ? "\n" : "") + after;
901
+ }
902
+
903
+ const existingBlock = new RegExp(`${escapeRegExp(managedCoreStart)}[\\s\\S]*?${escapeRegExp(managedCoreEnd)}`);
904
+ if (existingBlock.test(working)) {
905
+ return `${working.replace(existingBlock, block).trimEnd()}\n`;
906
+ }
907
+ if (working.trim().length === 0) return `${block}\n`;
908
+ return `${working.trimEnd()}\n\n${block}\n`;
646
909
  }
647
910
 
648
911
  function countOccurrences(text, needle) {
@@ -679,7 +942,7 @@ function printPlan(command, root, mode, plan, version) {
679
942
  console.log(`selected root: ${root}`);
680
943
  console.log(`mode: ${mode}`);
681
944
  console.log("");
682
- console.log("📋 人話解讀:下面只是計劃。create 會新增缺少檔案,merge 會在備份後安全合併,skip 會保留既有檔案,conflict 代表工具停手等你確認。");
945
+ console.log("📋 計劃預覽:以下未執行。create 新增缺少檔案;merge 在備份後合併;skip 保留既有檔案;conflict 代表工具停手等你確認。");
683
946
  console.log("");
684
947
  for (const action of ["create", "merge", "skip", "conflict"]) {
685
948
  const items = plan.filter((item) => item.action === action);
@@ -689,6 +952,27 @@ function printPlan(command, root, mode, plan, version) {
689
952
  console.log(`\nbackup: ${plan.filter((item) => item.action === "merge").length}`);
690
953
  }
691
954
 
955
+ // R-026 CLI Output Contract: install/upgrade 完成必含四項(版本/模式/剛做咗乜/下一步)。
956
+ function printInstallSummary(version, command, mode, root, counts) {
957
+ console.log(`\n✅ created: ${counts.created}`);
958
+ console.log(`🔀 merged: ${counts.merged}`);
959
+ console.log(`⏭️ skipped existing: ${counts.skipped}`);
960
+ console.log(`${counts.conflicts > 0 ? "⚠️ " : "✅ "}conflict: ${counts.conflicts}`);
961
+ if (counts.backupRel) console.log(`💾 backup: ${counts.backupRel}`);
962
+ if (counts.reportRel) console.log(`📄 migration report: ${counts.reportRel}`);
963
+ console.log("");
964
+ console.log(`📦 版本:v${version}`);
965
+ console.log(`🛠️ 模式:${mode}`);
966
+ console.log(`🔎 剛做咗:${command} 命令;create ${counts.created} / merge ${counts.merged} / skip ${counts.skipped} / conflict ${counts.conflicts}。`);
967
+ if (counts.conflicts > 0) {
968
+ console.log("🚀 下一步:把 migration report 或這段輸出貼給 AI,請它判斷 conflict 點處理;工具已停手,沒有覆寫 conflict 檔案。");
969
+ } else if (command === "upgrade") {
970
+ console.log("🚀 下一步:留意下方 upgrade self-check(自動跑 doctor);若全綠即升級完成。");
971
+ } else {
972
+ console.log("🚀 下一步:開新 AI 對話,按下方提示貼入 Work in <root> 一句後描述任務。");
973
+ }
974
+ }
975
+
692
976
  function printDryRunExplanation(plan) {
693
977
  const conflicts = plan.filter((item) => item.action === "conflict");
694
978
  console.log("✅ 這次沒有改動任何檔案。");
@@ -912,4 +1196,7 @@ After install:
912
1196
  Open your AI tool, start a new chat, paste the shown Work in ... message,
913
1197
  then describe your task in normal language.
914
1198
  `);
1199
+ console.log(`📦 版本:v${version}`);
1200
+ console.log(`🛠️ 模式:help ready`);
1201
+ console.log(`🚀 下一步:第一次使用先跑 init;既有專案升級用 upgrade --dry-run;要檢查現狀用 doctor。`);
915
1202
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamchanadam/agent-handoff-kit",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Lightweight agent harness for project memory, handoff, and multi-session continuity.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,10 +19,11 @@
19
19
  "qa:prototype": "node scripts/check-public-prototype.mjs",
20
20
  "qa:packs": "node scripts/check-pack-scenarios.mjs",
21
21
  "qa:upgrade": "node scripts/check-upgrade-safety.mjs",
22
- "qa:release": "node scripts/check-release-readiness.mjs"
22
+ "qa:release": "node scripts/check-release-readiness.mjs",
23
+ "qa:fixtures": "node scripts/generate-upgrade-fixtures.mjs"
23
24
  },
24
25
  "engines": {
25
26
  "node": ">=18"
26
27
  },
27
28
  "license": "MIT"
28
- }
29
+ }
@@ -48,6 +48,16 @@ External skill flows, subagents, task plans, or another tool's "finish" step do
48
48
 
49
49
  For high-risk work, pause after PLAN. High-risk means destructive operations, ambiguous target, external systems, release/publish, or broad multi-file change.
50
50
 
51
+ ## 2.1 Upgrade Done Contract
52
+
53
+ `agent-handoff-kit upgrade` is considered complete only when all of the following hold. The CLI enforces this contract; do not declare upgrade success without it.
54
+
55
+ 1. `AGENTS.md` health state is `clean`: exactly one `# Agent Handoff Kit Core Runtime` heading, exactly one paired managed-core marker block, and no unmarked stale core ranges. Sandwich states (managed marker plus an unmarked stale core) are not clean; the installer must replace the stale ranges, not skip.
56
+ 2. The CLI runs `doctor` automatically against the upgraded root after writes complete. `doctor` must report `status: passed` across required files, anchors, schema checks, and prompt mirror checks.
57
+ 3. The migration report records every action taken, with backup paths for merged files.
58
+
59
+ If any check fails, the upgrade did not finish; resolve the failure (or hand the failure output to the user) before reporting completion. This contract is the single source of truth for upgrade success; downstream QA scripts and release-grade QA derive their assertions from it.
60
+
51
61
  ## 3. Safety Boundaries
52
62
 
53
63
  Do not delete, reset, overwrite, bulk-move, or publish without explicit user approval.
@@ -74,6 +84,7 @@ At full closeout:
74
84
  8. If either check fails, fix `dev/SESSION_HANDOFF.md` first; do not push current-state responsibility into `dev/SESSION_LOG.md`.
75
85
  9. Show a short closeout card, then provide a copy-paste-ready next-session opening message inside a fenced `text` code block, so the user can clearly copy and paste it into the next session.
76
86
  10. Regenerate `START_NEXT_SESSION_PROMPT.txt` from the fenced opening message in `dev/SESSION_HANDOFF.md`. `dev/SESSION_HANDOFF.md` is authoritative; `START_NEXT_SESSION_PROMPT.txt` is only a convenience copy for the user to paste at the next startup.
87
+ 11. Advance the SESSION_LOG N-rule (R-010 SESSION_LOG handoff-role discipline). After prepending the new closeout entry, count `## YYYY-MM-DD` H2 entries in `dev/SESSION_LOG.md`. Any entry now at position N ≥ 11 (oldest end) must be moved into `dev/SESSION_LOG_archive/archive_<batch>_<low_date>_to_<high_date>.md` with raw content preserved. Maintain `dev/SESSION_LOG_archive/INDEX.md` (master index of all archive batches; create on first archive). Entries at N=4–10 whose core facts are already absorbed into HANDOFF / PROJECT_INDEX / requirements / decision records collapse to a short-index line using structural anchors, not line numbers. Entries with unique narrative not yet absorbed must first be ported into the relevant durable source, then collapsed. This is mandatory; do not skip. Handoff capability rests on `dev/SESSION_HANDOFF.md`; `dev/SESSION_LOG.md` is trace-back / audit trail and does not carry handoff responsibility.
77
88
 
78
89
  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.
79
90
 
@@ -112,4 +123,4 @@ If a pack, skill, subagent plan, demo workspace, or external workflow produces i
112
123
 
113
124
  ## Core Complexity Rule
114
125
 
115
- New default-core rules are allowed only when they apply to most sessions, protect safety or continuity, cannot live in a pack or registry, and keep the core within budget.
126
+ New default-core rules are allowed only when they apply to most sessions, protect safety or continuity, cannot live in a pack or registry, and keep the core within budget.
@@ -6,7 +6,7 @@ Purpose: give a stateless AI a compact map of the project before it reads or edi
6
6
 
7
7
  | Field | Value | Last verified |
8
8
  |---|---|---|
9
- | Agent Handoff Kit template version | 0.1.6 | package prototype |
9
+ | Agent Handoff Kit template version | 0.1.7 | package prototype |
10
10
  | Runtime | TBD | TBD |
11
11
  | Framework | TBD | TBD |
12
12
  | Package manager | TBD | TBD |
@@ -1,5 +1,7 @@
1
1
  # Session Log
2
2
 
3
+ > **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 advance the N-rule per `AGENTS.md` `## Closeout And Handoff` step 11 (R-010 SESSION_LOG handoff-role discipline): N=1–3 keep full, N=4–10 short-index after absorbed-source check, N=11+ archive into `dev/SESSION_LOG_archive/`.
4
+
3
5
  Add new session entries at the top. Record what actually happened in the session; do not copy old completed work forward as new work.
4
6
 
5
7
  This log carries recent evidence, not current state. Put the current objective, next action, risks, and workspace identity in `dev/SESSION_HANDOFF.md`.