@adamchanadam/agent-handoff-kit 0.3.46 → 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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Prompt Templates
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Prompt Templates
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
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.46` (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">
@@ -33,18 +33,18 @@ You do not decide whether the folder needs an install, upgrade, health check, or
33
33
 
34
34
  If the folder already contains older Kit files or AI memory files such as `AGENTS.md`, `CLAUDE.md`, or `GEMINI.md`, use the same request. The AI inspects first; it must not silently overwrite them.
35
35
 
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
- 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
-
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
-
47
- ## 🧭 How to read this repository
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
+ 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
+
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
+
47
+ ## 🧭 How to read this repository
48
48
 
49
49
  If you only want to use the kit, start from these four pages:
50
50
 
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.46`(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">
@@ -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
  }
@@ -1186,7 +1224,8 @@ async function synchronizeFormalUserRulesTransactionState(command, root, byTarge
1186
1224
  if (agentOutput.after) {
1187
1225
  const renderedBytes = encodeLikeExisting(renderedAgentsText, agentOutput.before, "AGENTS.md");
1188
1226
  if (!agentOutput.after.equals(renderedBytes)) {
1189
- 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";
1190
1229
  }
1191
1230
  }
1192
1231
  agentOutput.afterText = renderedAgentsText;
@@ -1890,15 +1929,36 @@ async function readOptionalBuffer(filePath) {
1890
1929
  try { return await readFile(filePath); } catch (error) { if (error?.code === "ENOENT") return null; throw error; }
1891
1930
  }
1892
1931
 
1893
- async function readOptionalText(filePath) {
1894
- const buffer = await readOptionalBuffer(filePath);
1895
- return buffer ? decodeUtf8(buffer, filePath).text : null;
1896
- }
1897
-
1898
- async function writeSecureJson(filePath, value) {
1899
- await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
1900
- await tightenPermissions(filePath, 0o600);
1901
- }
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
+ }
1902
1962
 
1903
1963
  async function tightenPermissions(filePath, mode) {
1904
1964
  try { await chmod(filePath, mode); } catch { /* best effort on platforms without POSIX modes */ }
@@ -1958,7 +2018,7 @@ async function runDoctor(root, version, options = {}) {
1958
2018
  console.log(`${row.ok ? "ok" : "missing"} ${row.target}`);
1959
2019
  }
1960
2020
 
1961
- if (missing.length > 0) {
2021
+ if (missing.length > 0) {
1962
2022
  const misplacedRulePacks = await findMisplacedRulePacks(root, missing);
1963
2023
  printMisplacedRulePackWarnings(misplacedRulePacks);
1964
2024
  printDoctorSummary(version, root, "needs-fix", {
@@ -1975,6 +2035,21 @@ async function runDoctor(root, version, options = {}) {
1975
2035
  return "failed";
1976
2036
  }
1977
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
+
1978
2053
  const currentStateResult = await checkCurrentStateWitness(root, currentStateWitness);
1979
2054
  console.log(`\nshared current-state checks: ${currentStateResult.checked}`);
1980
2055
  const currentStateLabel = currentStateWitness?.sourceConservation
@@ -2402,7 +2477,7 @@ function validateCurrentStateWitnessValue(value) {
2402
2477
  || ![1, 2].includes(value.schemaVersion)
2403
2478
  || !value.transaction || typeof value.transaction !== "object" || Array.isArray(value.transaction)
2404
2479
  || typeof value.transaction.id !== "string" || !value.transaction.id
2405
- || (value.transaction.command !== "init" && value.transaction.command !== "upgrade")
2480
+ || !["init", "upgrade", "finalize-closeout"].includes(value.transaction.command)
2406
2481
  || typeof value.transaction.mode !== "string" || !value.transaction.mode
2407
2482
  || !isStableSemver(value.transaction.attemptedVersion ?? "")
2408
2483
  || !Array.isArray(value.entries) || value.entries.length === 0
@@ -2490,7 +2565,7 @@ function validateSourceConservation(value, { required = false } = {}) {
2490
2565
  || !Array.isArray(entry.sourceByteRanges) || entry.sourceByteRanges.length !== 1
2491
2566
  || entry.sourceByteRanges[0]?.start !== 0 || entry.sourceByteRanges[0]?.end !== entry.sourceWitness.bytes
2492
2567
  || entry.sourceByteRanges[0]?.sha256 !== entry.sourceWitness.sha256
2493
- || !["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)
2494
2569
  || !Array.isArray(entry.existingReaders)
2495
2570
  || entry.existingReaders.some((reader) => !reader || typeof reader !== "object" || Array.isArray(reader) || typeof reader.reader !== "string" || !reader.reader || typeof reader.via !== "string" || !reader.via)
2496
2571
  || typeof entry.priorityRelation !== "string" || !entry.priorityRelation
@@ -2573,23 +2648,29 @@ async function createRuntimeAcceptance(root, outputs) {
2573
2648
 
2574
2649
  const entries = [];
2575
2650
  for (const item of directAgents) {
2576
- 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)) {
2577
2653
  throw new Error("direct AGENTS preservation must retain identical whole-file bytes");
2578
2654
  }
2579
2655
  const sourceWitness = byteWitness(item.before);
2656
+ const accepted = digestTransition ? byteWitness(item.after) : sourceWitness;
2580
2657
  const originalReader = await directAgentsEntryWitness(root, item.before);
2581
2658
  const activeReader = await directAgentsEntryWitness(root, item.after, outputByTarget);
2582
2659
  entries.push(Object.freeze({
2583
2660
  targetRel: item.targetRel,
2584
- accepted: sourceWitness,
2661
+ accepted,
2585
2662
  sourceWitness,
2586
2663
  sourceByteRanges: Object.freeze([Object.freeze({ start: 0, end: item.before.length, sha256: sourceWitness.sha256 })]),
2587
2664
  originalReader,
2588
2665
  activeReader,
2589
- 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)",
2590
2669
  conflictDecision: item.preservedRuntimeItem.conflictDecision,
2591
- effectDecision: "preserve-unmodified-through-direct-formal-entry",
2592
- 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
2593
2674
  }));
2594
2675
  }
2595
2676
 
@@ -2928,7 +3009,7 @@ function validDirectAgentsAcceptanceEntry(entry, { requireReferences = false } =
2928
3009
  || entry.activeReader.bytes !== entry.accepted.bytes
2929
3010
  || typeof entry.priorityRelation !== "string" || !entry.priorityRelation.trim()) return false;
2930
3011
  if (entry.managedSegment) return validArtifactBoundManagedAgentsEntry(entry);
2931
- if (!sameByteWitness(entry.accepted, entry.sourceWitness)) return false;
3012
+ if (!sameByteWitness(entry.accepted, entry.sourceWitness) && !validFormalUserRulesDigestTransitionEntry(entry)) return false;
2932
3013
  const ranges = entry.sourceByteRanges;
2933
3014
  return Array.isArray(ranges) && ranges.length === 1
2934
3015
  && ranges[0]?.start === 0
@@ -2936,6 +3017,15 @@ function validDirectAgentsAcceptanceEntry(entry, { requireReferences = false } =
2936
3017
  && ranges[0]?.sha256 === entry.sourceWitness.sha256;
2937
3018
  }
2938
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
+
2939
3029
  function validArtifactBoundManagedAgentsEntry(entry) {
2940
3030
  const segment = entry.managedSegment;
2941
3031
  if (!segment || typeof segment !== "object" || Array.isArray(segment)
@@ -3014,6 +3104,9 @@ function validRuntimeAcceptanceDecision(entry) {
3014
3104
  return (entry.disposition === "preserve"
3015
3105
  && entry.conflictDecision === "non-exact-package-bytes"
3016
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")
3017
3110
  || (entry.disposition === "replace-managed-segment"
3018
3111
  && entry.conflictDecision === "artifact-bound-exact-managed-core"
3019
3112
  && entry.effectDecision === "replace-artifact-bound-managed-core-through-direct-formal-entry");
@@ -3340,6 +3433,212 @@ async function journalMatchesCurrentState(root, journal) {
3340
3433
  return true;
3341
3434
  }
3342
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
+
3343
3642
  async function checkRuntimeAcceptance(root, options = {}) {
3344
3643
  const witness = options.expectedRuntimeAcceptance ?? null;
3345
3644
  if (!witness) return { ok: true, checked: 0, finding: null, state: null };
@@ -6962,12 +7261,14 @@ Usage:
6962
7261
  agent-handoff-kit upgrade [--dry-run] [--yes] [--root <path>]
6963
7262
  agent-handoff-kit doctor [--root <path>]
6964
7263
  agent-handoff-kit closeout-status [--root <path>]
7264
+ agent-handoff-kit finalize-closeout [--root <path>]
6965
7265
 
6966
7266
  Commands:
6967
7267
  init Plan or install missing core files and rule packs.
6968
7268
  upgrade Preserve existing files; merge safe core updates or report conflicts.
6969
7269
  doctor Check required installed files.
6970
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.
6971
7272
 
6972
7273
  中文速讀:
6973
7274
  ✅ 第一次用:先在項目資料夾執行 init。