@adamchanadam/agent-handoff-kit 0.3.45 → 0.3.47

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
@@ -2,7 +2,7 @@
2
2
 
3
3
  [繁體中文](README.md) · [Getting started](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.en.html) · [Practical guide](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.en.html) · [AI install page](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-ai-install.en.html)
4
4
 
5
- Current published release: `v0.3.45` (GitHub Release and npm `@latest`).
5
+ Current published release: `v0.3.47` (GitHub Release and npm `@latest`).
6
6
 
7
7
  <p align="center">
8
8
  <img src="https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-promo-30s.gif" alt="Agent Handoff Kit overview animation" width="720">
@@ -36,6 +36,14 @@ If the folder already contains older Kit files or AI memory files such as `AGENT
36
36
  For a non-technical introduction, open the [English introduction](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.en.html). For complete walkthroughs, open the [English practical guide](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.en.html).
37
37
  To see how Agent Handoff Kit sits in a local agentic AI workflow, open [`local-agentic-ai-workflow-case-study.en.html`](https://adamchanadam.github.io/agent-handoff-kit/local-agentic-ai-workflow-case-study.en.html).
38
38
 
39
+ ## 🐱 How to read the status card
40
+
41
+ | Status | Meaning |
42
+ |---|---|
43
+ | `( o.o ) continuity ready` | Ready to continue; the AI has loaded resumable state. |
44
+ | `( -.- ) handoff saved` | Closeout has been saved; next time you can say `Start Agent Handoff` or `開工`. |
45
+ | `( x.x ) handoff blocked` | Not broken; something still needs to be saved, committed, verified, or handled. Follow the Blocker line first and do not treat this session as handed off. |
46
+
39
47
  ## 🧭 How to read this repository
40
48
 
41
49
  If you only want to use the kit, start from these four pages:
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  English: [README.en.md](README.en.md) · [Getting started](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.en.html) · [Practical guide](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.en.html) · [AI install page](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-ai-install.en.html)
4
4
 
5
- 目前正式版本:`v0.3.45`(GitHub Release 與 npm `@latest`)。
5
+ 目前正式版本:`v0.3.47`(GitHub Release 與 npm `@latest`)。
6
6
 
7
7
  <p align="center">
8
8
  <img src="https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-promo-30s.gif" alt="Agent Handoff Kit 功能簡介動畫" width="720">
@@ -29,13 +29,21 @@ Agent Handoff Kit 是 **AI 對話之間的接力棒**。
29
29
  2. 安裝完成後,對 AI 說 `Start Agent Handoff` 或「開工」。
30
30
  3. 完成本輪工作後,對 AI 說「收工」。
31
31
 
32
- 🔎 你不用判斷安裝、升級、檢查或檔案結構。AI 會先說明它看到的資料夾、風險與下一步;需要你確認時才停下來。
33
-
34
- 已裝過舊版,或資料夾裡已有 `AGENTS.md`、`CLAUDE.md`、`GEMINI.md` 等 AI 記憶文件,也用同一句交給 AI 判斷。AI 會先檢查,不會靜默覆寫。
35
-
36
- 想先看非技術版介紹,可打開 GitHub Pages 上的 [`agent-handoff-kit-intro.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.html)。想看完整操作示範,可開 [`agent-handoff-kit-guide.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.html)。想了解它在本機 Agentic AI 工作系統中的位置,可看 [`local-agentic-ai-workflow-case-study.html`](https://adamchanadam.github.io/agent-handoff-kit/local-agentic-ai-workflow-case-study.html)。
37
-
38
- ## 🧭 這個 repo 怎樣讀
32
+ 🔎 你不用判斷安裝、升級、檢查或檔案結構。AI 會先說明它看到的資料夾、風險與下一步;需要你確認時才停下來。
33
+
34
+ 已裝過舊版,或資料夾裡已有 `AGENTS.md`、`CLAUDE.md`、`GEMINI.md` 等 AI 記憶文件,也用同一句交給 AI 判斷。AI 會先檢查,不會靜默覆寫。
35
+
36
+ 想先看非技術版介紹,可打開 GitHub Pages 上的 [`agent-handoff-kit-intro.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-intro.html)。想看完整操作示範,可開 [`agent-handoff-kit-guide.html`](https://adamchanadam.github.io/agent-handoff-kit/agent-handoff-kit-guide.html)。想了解它在本機 Agentic AI 工作系統中的位置,可看 [`local-agentic-ai-workflow-case-study.html`](https://adamchanadam.github.io/agent-handoff-kit/local-agentic-ai-workflow-case-study.html)。
37
+
38
+ ## 🐱 狀態卡怎樣讀
39
+
40
+ | 狀態 | 意思 |
41
+ |---|---|
42
+ | `( o.o ) continuity ready` | 可以接力,AI 已讀到可繼續的狀態。 |
43
+ | `( -.- ) handoff saved` | 已收工保存,下次可以再說「開工」。 |
44
+ | `( x.x ) handoff blocked` | 不是壞了;只是仍有未保存、未提交、未驗證或需要處理的事。先照 Blocker 行處理,不要把本輪當作已完成交接。 |
45
+
46
+ ## 🧭 這個 repo 怎樣讀
39
47
 
40
48
  如果你只是想使用 Agent Handoff Kit,只需要看四個入口:
41
49
 
@@ -39,6 +39,11 @@ const directStatefulTargets = new Set([
39
39
  "dev/PROJECT_INDEX.md",
40
40
  "dev/SESSION_LOG.md"
41
41
  ]);
42
+ const closeoutFinalizeTargets = new Set([
43
+ ...directStatefulTargets,
44
+ "dev/DOC_SYNC_REGISTRY.md",
45
+ "dev/PROJECT_DECISIONS.md"
46
+ ]);
42
47
  const credentialLeakPatterns = [
43
48
  { pattern: /sk-ant-[A-Za-z0-9_-]{20,}/, label: "Anthropic API key" },
44
49
  { pattern: /\bsk-[A-Za-z0-9_-]{20,}/, label: "sk-prefixed token" },
@@ -593,7 +598,12 @@ async function main() {
593
598
  await runCloseoutStatus(root, version);
594
599
  return;
595
600
  }
596
-
601
+
602
+ if (command === "finalize-closeout") {
603
+ await runFinalizeCloseout(root, version);
604
+ return;
605
+ }
606
+
597
607
  throw new Error(`unknown command "${command}"`);
598
608
  }
599
609
 
@@ -625,6 +635,34 @@ async function runCloseoutStatus(root, version) {
625
635
  if (!result.ok) process.exitCode = 1;
626
636
  }
627
637
 
638
+ async function runFinalizeCloseout(root, version) {
639
+ await validateTransactionRoot(root, [], { createMissingRoot: false });
640
+ const archiveCasing = await checkSessionLogArchiveCasing(root);
641
+ if (!archiveCasing.ok) throw new Error(archiveCasing.finding);
642
+ const prior = await findCloseoutFinalizeBase(root);
643
+ if (!prior) {
644
+ console.log("closeout finalized: no post-upgrade current-state witness needed");
645
+ return;
646
+ }
647
+ const illegal = prior.mismatches.filter((item) => !isCloseoutFinalizeTarget(item.path));
648
+ if (illegal.length > 0) {
649
+ throw new Error(`non-closeout drift blocks finalize-closeout: ${illegal.map((item) => item.path).join(", ")}`);
650
+ }
651
+ if (prior.mismatches.length === 0) {
652
+ console.log("closeout finalized: current-state witness already matches project bytes");
653
+ return;
654
+ }
655
+ const transaction = await writeCloseoutFinalizeJournal(root, version, prior);
656
+ const doctorStatus = await runDoctor(root, version, {
657
+ silentCard: true,
658
+ context: "post-closeout-finalize-health",
659
+ expectedCurrentStateWitness: transaction.journal.currentStateWitness
660
+ });
661
+ if (doctorStatus !== "passed") throw new Error("post-closeout finalize doctor failed; finalize journal retained for inspection");
662
+ console.log(`closeout finalized: bound ${prior.mismatches.length} legal closeout state update(s)`);
663
+ console.log(`current-state digest: ${transaction.journal.currentStateWitness.currentStateDigest}`);
664
+ }
665
+
628
666
  function closeoutOutcome(value) {
629
667
  return /^(complete|completed)\b/i.test((value ?? "").trim()) ? "complete" : "blocked";
630
668
  }
@@ -654,6 +692,7 @@ function printCloseoutStatusCard(version, result) {
654
692
  console.log("");
655
693
  console.log("status: blocked");
656
694
  console.log(`⚠️ Blocker: ${result.findings.join("; ")}`);
695
+ console.log("💬 說明:這不是失敗;只是還有事未保存、未提交、未驗證或需要處理。先照 Blocker 行處理,不要把本輪當作已完成交接。");
657
696
  console.log("📌 Handoff: keep the current state resumable; do not call this closeout complete");
658
697
  }
659
698
 
@@ -1185,7 +1224,8 @@ async function synchronizeFormalUserRulesTransactionState(command, root, byTarge
1185
1224
  if (agentOutput.after) {
1186
1225
  const renderedBytes = encodeLikeExisting(renderedAgentsText, agentOutput.before, "AGENTS.md");
1187
1226
  if (!agentOutput.after.equals(renderedBytes)) {
1188
- throw new Error("formal user-rules transition would alter preserved AGENTS.md bytes; upgrade stops instead of rewriting a non-exact source");
1227
+ agentOutput.after = renderedBytes;
1228
+ agentOutput.reason = "formal user-rules acceptance digest transition";
1189
1229
  }
1190
1230
  }
1191
1231
  agentOutput.afterText = renderedAgentsText;
@@ -1889,15 +1929,36 @@ async function readOptionalBuffer(filePath) {
1889
1929
  try { return await readFile(filePath); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
1890
1930
  }
1891
1931
 
1892
- async function readOptionalText(filePath) {
1893
- const buffer = await readOptionalBuffer(filePath);
1894
- return buffer ? decodeUtf8(buffer, filePath).text : null;
1895
- }
1896
-
1897
- async function writeSecureJson(filePath, value) {
1898
- await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
1899
- await tightenPermissions(filePath, 0o600);
1900
- }
1932
+ async function readOptionalText(filePath) {
1933
+ const buffer = await readOptionalBuffer(filePath);
1934
+ return buffer ? decodeUtf8(buffer, filePath).text : null;
1935
+ }
1936
+
1937
+ async function checkSessionLogArchiveCasing(root) {
1938
+ const devDir = path.join(root, "dev");
1939
+ let entries;
1940
+ try {
1941
+ entries = await readdir(devDir, { withFileTypes: true });
1942
+ } catch (error) {
1943
+ if (error?.code === "ENOENT") return { ok: true, finding: null };
1944
+ throw error;
1945
+ }
1946
+ const matches = entries
1947
+ .filter((entry) => entry.isDirectory() && entry.name.toLowerCase() === "session_log_archive")
1948
+ .map((entry) => entry.name)
1949
+ .sort((left, right) => left.localeCompare(right));
1950
+ if (matches.length === 0) return { ok: true, finding: null };
1951
+ if (matches.length === 1 && matches[0] === "SESSION_LOG_archive") return { ok: true, finding: null };
1952
+ if (matches.includes("SESSION_LOG_archive")) {
1953
+ return { ok: false, finding: `mixed archive casing detected: ${matches.map((name) => `dev/${name}`).join(", ")}` };
1954
+ }
1955
+ return { ok: false, finding: `legacy archive casing detected: dev/${matches[0]}; use dev/SESSION_LOG_archive` };
1956
+ }
1957
+
1958
+ async function writeSecureJson(filePath, value) {
1959
+ await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
1960
+ await tightenPermissions(filePath, 0o600);
1961
+ }
1901
1962
 
1902
1963
  async function tightenPermissions(filePath, mode) {
1903
1964
  try { await chmod(filePath, mode); } catch { /* best effort on platforms without POSIX modes */ }
@@ -1957,7 +2018,7 @@ async function runDoctor(root, version, options = {}) {
1957
2018
  console.log(`${row.ok ? "ok" : "missing"} ${row.target}`);
1958
2019
  }
1959
2020
 
1960
- if (missing.length > 0) {
2021
+ if (missing.length > 0) {
1961
2022
  const misplacedRulePacks = await findMisplacedRulePacks(root, missing);
1962
2023
  printMisplacedRulePackWarnings(misplacedRulePacks);
1963
2024
  printDoctorSummary(version, root, "needs-fix", {
@@ -1974,6 +2035,21 @@ async function runDoctor(root, version, options = {}) {
1974
2035
  return "failed";
1975
2036
  }
1976
2037
 
2038
+ const archiveCasing = await checkSessionLogArchiveCasing(root);
2039
+ console.log(`\nSESSION_LOG archive casing checks: 1`);
2040
+ console.log(`${archiveCasing.ok ? "ok" : "missing"} dev/SESSION_LOG_archive canonical path`);
2041
+ if (!archiveCasing.ok) {
2042
+ console.log(` missing: ${archiveCasing.finding}`);
2043
+ printDoctorSummary(version, root, "needs-fix", {
2044
+ checked: rows.length + 1,
2045
+ failedKind: "SESSION_LOG archive casing checks",
2046
+ failedCount: 1,
2047
+ nextStep: "保留內容,先合併到 canonical dev/SESSION_LOG_archive;不要同時保留大小寫兩套路徑。"
2048
+ });
2049
+ process.exitCode = 1;
2050
+ return "failed";
2051
+ }
2052
+
1977
2053
  const currentStateResult = await checkCurrentStateWitness(root, currentStateWitness);
1978
2054
  console.log(`\nshared current-state checks: ${currentStateResult.checked}`);
1979
2055
  const currentStateLabel = currentStateWitness?.sourceConservation
@@ -2401,7 +2477,7 @@ function validateCurrentStateWitnessValue(value) {
2401
2477
  || ![1, 2].includes(value.schemaVersion)
2402
2478
  || !value.transaction || typeof value.transaction !== "object" || Array.isArray(value.transaction)
2403
2479
  || typeof value.transaction.id !== "string" || !value.transaction.id
2404
- || (value.transaction.command !== "init" && value.transaction.command !== "upgrade")
2480
+ || !["init", "upgrade", "finalize-closeout"].includes(value.transaction.command)
2405
2481
  || typeof value.transaction.mode !== "string" || !value.transaction.mode
2406
2482
  || !isStableSemver(value.transaction.attemptedVersion ?? "")
2407
2483
  || !Array.isArray(value.entries) || value.entries.length === 0
@@ -2489,7 +2565,7 @@ function validateSourceConservation(value, { required = false } = {}) {
2489
2565
  || !Array.isArray(entry.sourceByteRanges) || entry.sourceByteRanges.length !== 1
2490
2566
  || entry.sourceByteRanges[0]?.start !== 0 || entry.sourceByteRanges[0]?.end !== entry.sourceWitness.bytes
2491
2567
  || entry.sourceByteRanges[0]?.sha256 !== entry.sourceWitness.sha256
2492
- || !["preserve", "transaction-output", "unchanged-source", "retained-historical-state", "outside-known-kit-reachability"].includes(entry.disposition)
2568
+ || !["preserve", "transaction-output", "unchanged-source", "retained-historical-state", "outside-known-kit-reachability", "closeout-state-finalize"].includes(entry.disposition)
2493
2569
  || !Array.isArray(entry.existingReaders)
2494
2570
  || entry.existingReaders.some((reader) => !reader || typeof reader !== "object" || Array.isArray(reader) || typeof reader.reader !== "string" || !reader.reader || typeof reader.via !== "string" || !reader.via)
2495
2571
  || typeof entry.priorityRelation !== "string" || !entry.priorityRelation
@@ -2572,23 +2648,29 @@ async function createRuntimeAcceptance(root, outputs) {
2572
2648
 
2573
2649
  const entries = [];
2574
2650
  for (const item of directAgents) {
2575
- if (!item.before || !item.after.equals(item.before)) {
2651
+ const digestTransition = item.reason === "formal user-rules acceptance digest transition";
2652
+ if (!item.before || (!item.after.equals(item.before) && !digestTransition)) {
2576
2653
  throw new Error("direct AGENTS preservation must retain identical whole-file bytes");
2577
2654
  }
2578
2655
  const sourceWitness = byteWitness(item.before);
2656
+ const accepted = digestTransition ? byteWitness(item.after) : sourceWitness;
2579
2657
  const originalReader = await directAgentsEntryWitness(root, item.before);
2580
2658
  const activeReader = await directAgentsEntryWitness(root, item.after, outputByTarget);
2581
2659
  entries.push(Object.freeze({
2582
2660
  targetRel: item.targetRel,
2583
- accepted: sourceWitness,
2661
+ accepted,
2584
2662
  sourceWitness,
2585
2663
  sourceByteRanges: Object.freeze([Object.freeze({ start: 0, end: item.before.length, sha256: sourceWitness.sha256 })]),
2586
2664
  originalReader,
2587
2665
  activeReader,
2588
- priorityRelation: "direct AGENTS.md formal-entry byte order unchanged (single complete source range 0..N)",
2666
+ priorityRelation: digestTransition
2667
+ ? "direct AGENTS.md formal-entry byte order retained except the acceptance digest line"
2668
+ : "direct AGENTS.md formal-entry byte order unchanged (single complete source range 0..N)",
2589
2669
  conflictDecision: item.preservedRuntimeItem.conflictDecision,
2590
- effectDecision: "preserve-unmodified-through-direct-formal-entry",
2591
- disposition: item.preservedRuntimeItem.disposition
2670
+ effectDecision: digestTransition
2671
+ ? "update-formal-user-rules-digest-through-direct-formal-entry"
2672
+ : "preserve-unmodified-through-direct-formal-entry",
2673
+ disposition: digestTransition ? "formal-user-rules-digest-transition" : item.preservedRuntimeItem.disposition
2592
2674
  }));
2593
2675
  }
2594
2676
 
@@ -2927,7 +3009,7 @@ function validDirectAgentsAcceptanceEntry(entry, { requireReferences = false } =
2927
3009
  || entry.activeReader.bytes !== entry.accepted.bytes
2928
3010
  || typeof entry.priorityRelation !== "string" || !entry.priorityRelation.trim()) return false;
2929
3011
  if (entry.managedSegment) return validArtifactBoundManagedAgentsEntry(entry);
2930
- if (!sameByteWitness(entry.accepted, entry.sourceWitness)) return false;
3012
+ if (!sameByteWitness(entry.accepted, entry.sourceWitness) && !validFormalUserRulesDigestTransitionEntry(entry)) return false;
2931
3013
  const ranges = entry.sourceByteRanges;
2932
3014
  return Array.isArray(ranges) && ranges.length === 1
2933
3015
  && ranges[0]?.start === 0
@@ -2935,6 +3017,15 @@ function validDirectAgentsAcceptanceEntry(entry, { requireReferences = false } =
2935
3017
  && ranges[0]?.sha256 === entry.sourceWitness.sha256;
2936
3018
  }
2937
3019
 
3020
+ function validFormalUserRulesDigestTransitionEntry(entry) {
3021
+ return entry.disposition === "formal-user-rules-digest-transition"
3022
+ && entry.conflictDecision === "non-exact-package-bytes"
3023
+ && entry.effectDecision === "update-formal-user-rules-digest-through-direct-formal-entry"
3024
+ && entry.accepted.bytes === entry.sourceWitness.bytes
3025
+ && typeof entry.priorityRelation === "string"
3026
+ && entry.priorityRelation.includes("acceptance digest line");
3027
+ }
3028
+
2938
3029
  function validArtifactBoundManagedAgentsEntry(entry) {
2939
3030
  const segment = entry.managedSegment;
2940
3031
  if (!segment || typeof segment !== "object" || Array.isArray(segment)
@@ -3013,6 +3104,9 @@ function validRuntimeAcceptanceDecision(entry) {
3013
3104
  return (entry.disposition === "preserve"
3014
3105
  && entry.conflictDecision === "non-exact-package-bytes"
3015
3106
  && entry.effectDecision === "preserve-unmodified-through-direct-formal-entry")
3107
+ || (entry.disposition === "formal-user-rules-digest-transition"
3108
+ && entry.conflictDecision === "non-exact-package-bytes"
3109
+ && entry.effectDecision === "update-formal-user-rules-digest-through-direct-formal-entry")
3016
3110
  || (entry.disposition === "replace-managed-segment"
3017
3111
  && entry.conflictDecision === "artifact-bound-exact-managed-core"
3018
3112
  && entry.effectDecision === "replace-artifact-bound-managed-core-through-direct-formal-entry");
@@ -3339,6 +3433,212 @@ async function journalMatchesCurrentState(root, journal) {
3339
3433
  return true;
3340
3434
  }
3341
3435
 
3436
+ async function findCloseoutFinalizeBase(root) {
3437
+ const migrationsRoot = path.join(root, "dev", "governance_migrations");
3438
+ let names;
3439
+ try { names = await readdir(migrationsRoot); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
3440
+ const inspected = [];
3441
+ const superseded = new Set();
3442
+ for (const name of names) {
3443
+ if (name === ".upgrade.lock") continue;
3444
+ const journalPath = path.join(migrationsRoot, name, "transaction.json");
3445
+ try {
3446
+ const stats = await lstat(journalPath);
3447
+ if (!stats.isFile() || stats.isSymbolicLink()) continue;
3448
+ const journal = JSON.parse(await readFile(journalPath, "utf8"));
3449
+ if (journal.state !== "committed" || !journal.currentStateWitness) continue;
3450
+ await validateRecoveryJournal(root, journal, journalPath);
3451
+ inspected.push({ journal, journalPath });
3452
+ for (const digest of journal.currentStateWitness.transaction.supersedesCurrentStateDigests ?? []) superseded.add(digest);
3453
+ } catch (error) {
3454
+ if (error?.code !== "ENOENT") throw error;
3455
+ }
3456
+ }
3457
+ const candidates = [];
3458
+ const illegal = [];
3459
+ for (const item of inspected) {
3460
+ if (superseded.has(item.journal.currentStateWitness.currentStateDigest)) continue;
3461
+ const mismatches = await currentStateMismatches(root, item.journal);
3462
+ if (mismatches.length > 0 && !item.journal.currentStateWitness.sourceConservation) continue;
3463
+ if (mismatches.some((mismatch) => !isCloseoutFinalizeTarget(mismatch.path))) illegal.push({ ...item, mismatches });
3464
+ else candidates.push({ ...item, mismatches });
3465
+ }
3466
+ if (illegal.length > 0) return illegal.sort((left, right) => right.mismatches.length - left.mismatches.length)[0];
3467
+ const stale = candidates.filter((item) => item.mismatches.length > 0);
3468
+ if (stale.length === 0) return candidates[0] ?? null;
3469
+ if (stale.length > 1) {
3470
+ const digests = stale.map(({ journal }) => journal.currentStateWitness.currentStateDigest).join(", ");
3471
+ throw new Error(`multiple closeout-finalize candidate witnesses are stale: ${digests}`);
3472
+ }
3473
+ return stale[0];
3474
+ }
3475
+
3476
+ async function currentStateMismatches(root, journal) {
3477
+ const witness = validateCurrentStateWitness(journal);
3478
+ const mismatches = new Map();
3479
+ for (const entry of journal.entries) {
3480
+ const bytes = await readOptionalBuffer(path.join(root, entry.targetRel));
3481
+ if (!bytes || sha256(bytes) !== entry.afterHash) mismatches.set(entry.targetRel, { path: entry.targetRel, kind: "transaction-entry" });
3482
+ }
3483
+ for (const entry of witness.sourceConservation?.entries ?? []) {
3484
+ const bytes = await readOptionalBuffer(path.join(root, entry.sourcePath));
3485
+ if (!bytes || sha256(bytes) !== entry.accepted.sha256 || bytes.length !== entry.accepted.bytes) {
3486
+ mismatches.set(entry.sourcePath, { path: entry.sourcePath, kind: "source-conservation" });
3487
+ }
3488
+ }
3489
+ if (witness.sourceConservation) {
3490
+ const conserved = new Set(witness.sourceConservation.entries.map((entry) => entry.sourcePath));
3491
+ const currentFrozen = await freezeGate5Set({ root });
3492
+ assertGate5FrozenSet(currentFrozen);
3493
+ for (const item of currentFrozen.items) {
3494
+ if (conserved.has(item.sourcePath) || isFinalizeJournalState(item.sourcePath)) continue;
3495
+ mismatches.set(item.sourcePath, { path: item.sourcePath, kind: "new-source" });
3496
+ }
3497
+ }
3498
+ return [...mismatches.values()].sort((left, right) => left.path.localeCompare(right.path));
3499
+ }
3500
+
3501
+ async function writeCloseoutFinalizeJournal(root, version, prior) {
3502
+ const oldWitness = validateCurrentStateWitness(prior.journal);
3503
+ const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${randomUUID()}`;
3504
+ const migrationsRoot = path.join(root, "dev", "governance_migrations");
3505
+ const migrationDir = path.join(migrationsRoot, id);
3506
+ const backupDir = path.join(migrationDir, "backup");
3507
+ const stageDir = path.join(migrationDir, "stage");
3508
+ const journalPath = path.join(migrationDir, "transaction.json");
3509
+ const lockPath = path.join(migrationsRoot, ".upgrade.lock");
3510
+ await mkdir(backupDir, { recursive: true });
3511
+ await mkdir(stageDir, { recursive: true });
3512
+ await tightenPermissions(migrationsRoot, 0o700);
3513
+ await tightenPermissions(migrationDir, 0o700);
3514
+ const lock = await open(lockPath, "wx", 0o600).catch((error) => {
3515
+ if (error?.code === "EEXIST") throw new Error("another upgrade transaction or unresolved recovery lock is present");
3516
+ throw error;
3517
+ });
3518
+ await lock.writeFile(JSON.stringify({ id, host: hostname(), pid: process.pid, journal: path.relative(root, journalPath), command: "finalize-closeout" }, null, 2));
3519
+ await lock.close();
3520
+
3521
+ try {
3522
+ const priorEntryByTarget = new Map(prior.journal.entries.map((entry) => [entry.targetRel, entry]));
3523
+ const entries = [];
3524
+ for (const oldEntry of oldWitness.entries) {
3525
+ const targetRel = oldEntry.targetRel;
3526
+ const current = await readOptionalBuffer(path.join(root, targetRel));
3527
+ if (!current) throw new Error(`${targetRel}: cannot finalize missing closeout target`);
3528
+ const previous = await readPriorAcceptedBytes(root, prior.journalPath, priorEntryByTarget.get(targetRel), oldEntry.afterHash);
3529
+ const backupRel = path.relative(root, path.join(backupDir, targetRel)).replaceAll("\\", "/");
3530
+ await writeJournalFile(backupDir, targetRel, previous);
3531
+ await writeJournalFile(stageDir, targetRel, current);
3532
+ entries.push({
3533
+ targetRel,
3534
+ existed: true,
3535
+ beforeHash: sha256(previous),
3536
+ afterHash: sha256(current),
3537
+ backupRel,
3538
+ committed: true
3539
+ });
3540
+ }
3541
+
3542
+ const currentFrozen = oldWitness.sourceConservation ? await freezeGate5Set({ root }) : null;
3543
+ if (currentFrozen) assertGate5FrozenSet(currentFrozen);
3544
+ const oldSourceByPath = new Map((oldWitness.sourceConservation?.entries ?? []).map((entry) => [entry.sourcePath, entry]));
3545
+ const sourceConservation = oldWitness.sourceConservation
3546
+ ? {
3547
+ schemaVersion: oldWitness.sourceConservation.schemaVersion,
3548
+ frozenSetSha256: currentFrozen.frozenSetSha256,
3549
+ entries: await Promise.all(currentFrozen.items
3550
+ .filter((item) => !isFinalizeJournalState(item.sourcePath))
3551
+ .map(async (item) => {
3552
+ const entry = oldSourceByPath.get(item.sourcePath) ?? null;
3553
+ const current = await readOptionalBuffer(path.join(root, item.sourcePath));
3554
+ if (!current) throw new Error(`${item.sourcePath}: cannot finalize missing source`);
3555
+ const currentWitness = { sha256: sha256(current), bytes: current.length };
3556
+ const sourceWitness = entry?.accepted ?? currentWitness;
3557
+ const changed = currentWitness.sha256 !== sourceWitness.sha256 || currentWitness.bytes !== sourceWitness.bytes;
3558
+ return {
3559
+ sourcePath: item.sourcePath,
3560
+ sourceWitness,
3561
+ accepted: currentWitness,
3562
+ sourceByteRanges: [{ start: 0, end: sourceWitness.bytes, sha256: sourceWitness.sha256 }],
3563
+ disposition: isCloseoutFinalizeTarget(item.sourcePath) && changed
3564
+ ? "closeout-state-finalize"
3565
+ : entry?.disposition ?? (item.classifications.includes("transaction-state") ? "retained-historical-state" : "unchanged-source"),
3566
+ existingReaders: entry?.existingReaders ?? item.existingReaders.map((reader) => ({ reader: reader.reader, via: reader.via })),
3567
+ priorityRelation: entry?.priorityRelation ?? item.priorityConflict.relation,
3568
+ effectDecision: entry?.effectDecision ?? item.effect.decision,
3569
+ classifications: entry?.classifications ?? [...item.classifications]
3570
+ };
3571
+ }))
3572
+ }
3573
+ : null;
3574
+
3575
+ const journal = {
3576
+ id,
3577
+ command: "finalize-closeout",
3578
+ mode: "stateful-closeout",
3579
+ attemptedVersion: version,
3580
+ committedVersion: version,
3581
+ plannedSkips: 0,
3582
+ host: hostname(),
3583
+ pid: process.pid,
3584
+ state: "committed",
3585
+ createdAt: new Date().toISOString(),
3586
+ committedAt: new Date().toISOString(),
3587
+ entries,
3588
+ formalUserRules: null,
3589
+ runtimeReadback: null,
3590
+ runtimeAcceptance: null,
3591
+ runtimeAcceptanceReadback: null,
3592
+ sourceConservation,
3593
+ supersedesCurrentStateDigests: [oldWitness.currentStateDigest],
3594
+ currentStateWitness: null,
3595
+ currentStateReadback: null
3596
+ };
3597
+ journal.currentStateWitness = createCurrentStateWitness(journal);
3598
+ journal.currentStateReadback = currentStateReadbackFromDoctorStates(journal.currentStateWitness, null, null);
3599
+ await writeSecureJson(journalPath, journal);
3600
+ await writeFile(path.join(migrationDir, "migration-report.md"), [
3601
+ "# Agent Handoff Kit Closeout Finalize Report",
3602
+ "",
3603
+ `- Command: finalize-closeout`,
3604
+ `- Attempted version: ${version}`,
3605
+ `- Supersedes current-state digest: ${oldWitness.currentStateDigest}`,
3606
+ `- Current-state digest: ${journal.currentStateWitness.currentStateDigest}`,
3607
+ `- Finalized paths: ${prior.mismatches.map((item) => item.path).join(", ") || "none"}`,
3608
+ ""
3609
+ ].join("\n"), { mode: 0o600 });
3610
+ await unlinkIfExists(lockPath);
3611
+ return { journalPath, journal };
3612
+ } catch (error) {
3613
+ await unlinkIfExists(lockPath).catch(() => {});
3614
+ throw error;
3615
+ }
3616
+ }
3617
+
3618
+ async function readPriorAcceptedBytes(root, priorJournalPath, priorEntry, expectedHash) {
3619
+ if (priorEntry) {
3620
+ const stageBytes = await readOptionalBuffer(path.join(path.dirname(priorJournalPath), "stage", priorEntry.targetRel));
3621
+ if (stageBytes && sha256(stageBytes) === expectedHash) return stageBytes;
3622
+ }
3623
+ const current = await readOptionalBuffer(path.join(root, priorEntry?.targetRel ?? ""));
3624
+ if (current && sha256(current) === expectedHash) return current;
3625
+ throw new Error(`cannot reconstruct prior accepted bytes for closeout finalize: ${priorEntry?.targetRel ?? "unknown"}`);
3626
+ }
3627
+
3628
+ async function writeJournalFile(base, targetRel, bytes) {
3629
+ const filePath = path.join(base, targetRel);
3630
+ await mkdir(path.dirname(filePath), { recursive: true });
3631
+ await writeFile(filePath, bytes, { mode: 0o600 });
3632
+ }
3633
+
3634
+ function isCloseoutFinalizeTarget(relative) {
3635
+ return closeoutFinalizeTargets.has(relative) || relative.startsWith("dev/SESSION_LOG_archive/");
3636
+ }
3637
+
3638
+ function isFinalizeJournalState(relative) {
3639
+ return relative.startsWith("dev/governance_migrations/");
3640
+ }
3641
+
3342
3642
  async function checkRuntimeAcceptance(root, options = {}) {
3343
3643
  const witness = options.expectedRuntimeAcceptance ?? null;
3344
3644
  if (!witness) return { ok: true, checked: 0, finding: null, state: null };
@@ -6961,12 +7261,14 @@ Usage:
6961
7261
  agent-handoff-kit upgrade [--dry-run] [--yes] [--root <path>]
6962
7262
  agent-handoff-kit doctor [--root <path>]
6963
7263
  agent-handoff-kit closeout-status [--root <path>]
7264
+ agent-handoff-kit finalize-closeout [--root <path>]
6964
7265
 
6965
7266
  Commands:
6966
7267
  init Plan or install missing core files and rule packs.
6967
7268
  upgrade Preserve existing files; merge safe core updates or report conflicts.
6968
7269
  doctor Check required installed files.
6969
7270
  closeout-status Render the state-bound closeout card after a full closeout.
7271
+ finalize-closeout Bind legal post-upgrade closeout state edits before doctor.
6970
7272
 
6971
7273
  中文速讀:
6972
7274
  ✅ 第一次用:先在項目資料夾執行 init。
@@ -15,10 +15,11 @@ const formalEntryTargets = Object.freeze([
15
15
  "START_NEXT_SESSION_PROMPT.txt"
16
16
  ]);
17
17
 
18
- const dynamicDirectories = Object.freeze([
19
- { relative: "dev/governance_migrations", classification: "transaction-state" },
20
- { relative: "dev/session_log_archive", classification: "legacy-session-log-archive" }
21
- ]);
18
+ const dynamicDirectories = Object.freeze([
19
+ { relative: "dev/governance_migrations", classification: "transaction-state" },
20
+ { relative: "dev/SESSION_LOG_archive", classification: "session-log-archive" },
21
+ { relative: "dev/session_log_archive", classification: "legacy-session-log-archive" }
22
+ ]);
22
23
 
23
24
  /**
24
25
  * Builds a read-only, hash-bound description of the Kit data that an upgrade
@@ -154,13 +155,14 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
154
155
  formalEntryTargets: formalEntryTargets.filter((target) => entries.has(target))
155
156
  });
156
157
 
157
- async function addTree(relativeDirectory, classification) {
158
- const normalized = normalizeProjectRelative(relativeDirectory);
159
- if (!normalized) {
160
- addBlocker(String(relativeDirectory), "dynamic directory escapes the selected project root");
161
- return;
162
- }
163
- const absolute = path.resolve(rootPath, normalized);
158
+ async function addTree(relativeDirectory, classification) {
159
+ const normalized = normalizeProjectRelative(relativeDirectory);
160
+ if (!normalized) {
161
+ addBlocker(String(relativeDirectory), "dynamic directory escapes the selected project root");
162
+ return;
163
+ }
164
+ if (!(await hasExactProjectPath(rootPath, normalized))) return;
165
+ const absolute = path.resolve(rootPath, normalized);
164
166
  const stats = await lstat(absolute).catch((error) => {
165
167
  if (error?.code === "ENOENT") return null;
166
168
  throw error;
@@ -181,10 +183,26 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
181
183
  else if (item.isFile()) await addFile(child, classification, { from: "dynamic-state", via: normalized }, false);
182
184
  else addBlocker(child, "dynamic inventory source is not a regular file or directory");
183
185
  }
184
- }
185
- }
186
-
187
- /**
186
+ }
187
+ }
188
+
189
+ async function hasExactProjectPath(rootPath, normalized) {
190
+ const parts = normalized.split("/");
191
+ let current = rootPath;
192
+ for (const part of parts) {
193
+ const entries = await readdir(current, { withFileTypes: true }).catch((error) => {
194
+ if (error?.code === "ENOENT") return null;
195
+ throw error;
196
+ });
197
+ if (!entries) return false;
198
+ const exact = entries.find((entry) => entry.name === part);
199
+ if (!exact) return false;
200
+ current = path.join(current, exact.name);
201
+ }
202
+ return true;
203
+ }
204
+
205
+ /**
188
206
  * Gate 5 needs a stronger closure than the shared semantic-candidate
189
207
  * inventory: every regular project source under the selected root receives a
190
208
  * raw-byte witness, even when no currently known Kit reader reaches it. The
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adamchanadam/agent-handoff-kit",
3
- "version": "0.3.45",
3
+ "version": "0.3.47",
4
4
  "description": "Lightweight agent harness for project memory, handoff, and multi-session continuity.",
5
5
  "type": "module",
6
6
  "bin": {
package/packs/closeout.md CHANGED
@@ -67,7 +67,7 @@ status: complete
67
67
  ⚠️ Boundary: <important boundary or none>
68
68
  ```
69
69
 
70
- For `status: blocked`, the command instead says `handoff blocked`; retain that status and reason, then give the short local-root entry `Start Agent Handoff` / `開工` and the path-bearing fallback for an agent not yet pointed at the root. Do not hand-compose a third stateful prompt in the final response.
70
+ For `status: blocked`, the command instead says `handoff blocked`; retain that status, blocker reason, and human explanation: `這不是失敗;只是還有事未保存、未提交、未驗證或需要處理。先照 Blocker 行處理,不要把本輪當作已完成交接。` Then give the short local-root entry `Start Agent Handoff` / `開工` and the path-bearing fallback for an agent not yet pointed at the root. Do not hand-compose a third stateful prompt in the final response.
71
71
 
72
72
  ## Stop Conditions
73
73
 
@@ -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.3.44 | current template version |
9
+ | Agent Handoff Kit template version | 0.3.47 | current template version |
10
10
  | Runtime | TBD | TBD |
11
11
  | Framework | TBD | TBD |
12
12
  | Package manager | TBD | TBD |