@adamchanadam/agent-handoff-kit 0.3.63 → 0.3.65

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
- Source package version: `v0.3.63`. npm `@latest` and GitHub Release are verified by post-publish readback.
5
+ Source package version: `v0.3.65`. npm `@latest` and GitHub Release are verified by post-publish readback.
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">
@@ -42,7 +42,9 @@ To see how Agent Handoff Kit sits in a local agentic AI workflow, open [`local-a
42
42
  |---|---|
43
43
  | `( o.o ) continuity ready` | Ready to continue; the AI has loaded resumable state. |
44
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. |
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
+ The closeout card checks saved handoff state, required fields, and recorded check results; it does not automatically prove that task conclusions are correct. Blocked work can still be handed off when its cause, impact, and conditions for resuming are clearly saved. “Saved” does not mean the overall task is complete.
46
48
 
47
49
  ## 🧭 How to read this repository
48
50
 
@@ -97,11 +99,11 @@ If the AI is not yet pointed at the project folder, use the path-bearing startup
97
99
  Work in <your project folder>. Read AGENTS.md first, then Start Agent Handoff. Before changing anything, tell me the current state and your recommended next step.
98
100
  ```
99
101
 
100
- A first installation marks onboarding as pending. If you only say `Start Agent Handoff` or `開工` after installing, and you do not provide a clear task in the same message, the AI should show the startup card and enter a short first-use welcome. Upgrades of existing projects do not reset that flow. When your goal and the available facts are clear, the AI may give a brief first-use frame and then begin the first safe task action.
102
+ A first installation marks onboarding as pending. The AI enters a short first-use welcome after the startup card only when that state is still `eligible`, the active objective is empty or `TBD`, and there is no concrete task in the same message. Upgrades of existing projects do not reset the state. When you clearly describe the goal and available facts, the AI may begin the first safe step without going through onboarding first.
101
103
 
102
104
  For ordinary daily startup, the AI reads `dev/SESSION_HANDOFF.md` first. Inside the same folder it does not reread `START_NEXT_SESSION_PROMPT.txt` or `dev/SESSION_LOG.md` during normal startup. The prompt copy is only for an AI that has not yet been pointed at the project folder.
103
105
 
104
- A bare `Start Agent Handoff` / `開工` restores the minimum current state, shows the startup card, status, and recommended next action, then waits. It does **not** authorize research, planning, QA, packaging, file writes, network use, or sub-agents. To work immediately, say so in the same message, for example: `Start Agent Handoff, continue <task>`.
106
+ `開工,繼續 <task>`, `<project> 開工`, and `Start Agent Handoff and continue <task>` are all continuity commands. The AI asks one short confirmation only when the phrase could genuinely refer to a real-world opening, shift, or unrelated event. A bare startup or one that adds only the project name restores the minimum state, shows the startup card and recommended next action, then waits; it does not authorize research, planning, QA, file writes, network use, or sub-agents. Only a concrete task or explicit long-run instruction in the same message authorizes work. The first-use guidance exception described above still applies.
105
107
 
106
108
  Then describe your task in ordinary language. The AI should explain the current state, next action, and risk before it starts the requested work.
107
109
 
@@ -117,7 +119,9 @@ You can also say `收工`, `Wrap up Agent Handoff`, or `handoff`.
117
119
 
118
120
  If the phrase could instead mean a real-world closing event, such as a restaurant closing, the AI should ask one short question rather than immediately changing the project handoff.
119
121
 
120
- At a real closeout, the AI updates the handoff and regenerates:
122
+ The AI should record the overall outcome, current subtask, exact resume point, and remaining acceptance checks, together with the necessary source versions, sections read, reading depth, and unresolved gaps. Simple tasks need only the relevant facts, not a multi-level task table. Before closeout, the AI reconstructs the next step using only the handoff, then compares it with your original request and actual results so a completed small step is not mistaken for the overall outcome. When resuming, the AI must still read the sources needed for the task; a predecessor's “read” record is not its own verification.
123
+
124
+ The AI should update only changed handoff state and compare the next-session prompt copy, regenerating it only when it differs:
121
125
 
122
126
  ```text
123
127
  START_NEXT_SESSION_PROMPT.txt
@@ -154,7 +158,7 @@ You do not need to remember rule file names. The Kit lets the AI classify what y
154
158
  | Write code or fix a bug | Reads the project index and relevant files, then changes and tests only what is needed. |
155
159
  | Write an article, README, or public copy | Clarifies audience, purpose, tone, and publication surface. |
156
160
  | Research or compare tools | Separates verified facts, source summaries, and the AI’s judgement. |
157
- | Delete files, use Git, publish, or use npm | Explains impact first and waits for your confirmation. |
161
+ | Delete files, use Git, publish, or use npm | For high-risk operations, explains impact first and waits for your confirmation. |
158
162
  | Use Notion, Google Drive, or another external tool | Checks the current tool guidance, handles resources by ownership, and keeps secrets out of project files. |
159
163
 
160
164
  You can simply say what you want, for example: “Help me revise the README”, “Research whether this tool is suitable”, or “Connect this document to Agent Handoff Kit.” The AI chooses the needed rules.
@@ -162,7 +166,7 @@ You can simply say what you want, for example: “Help me revise the README”,
162
166
  For a durable preference, tell the AI rather than editing rule files blindly:
163
167
 
164
168
  ```text
165
- For future public English documents, use clear professional English. Connect this rule to Agent Handoff Kit.
169
+ For future public Chinese documents, use written Traditional Chinese and avoid mixing Chinese and English fragments. Connect this rule to Agent Handoff Kit.
166
170
  ```
167
171
 
168
172
  The AI decides whether that belongs in a one-off note, the next handoff, the project index, or a durable work rule. It must not put everything into one file.
@@ -190,7 +194,7 @@ Rules that must persist across future sessions should be written into the approp
190
194
 
191
195
  Even if you do not write code, the Kit requires an AI to stop and explain high-risk actions.
192
196
 
193
- - **Destructive operations:** commands such as `rm -rf`, `git reset --hard`, and operations against system root paths are prohibited by default. Force-push, branch or tag deletion, and history rewriting need explicit scope, explicit approval, and readback of the affected refs.
197
+ - **Destructive operations:** commands such as `rm -rf`, `git reset --hard`, and operations against system root paths are prohibited. Force-push, branch or tag deletion, and history rewriting need explicit scope, explicit approval, and readback of the affected refs.
194
198
  - **Secrets:** do not print, commit, or upload `.env` values, API keys, or tokens.
195
199
  - **Verify; do not guess:** before using a third-party service, connector, MCP, CLI, API, or plugin, check current official or already verified local guidance. If it cannot be verified, say so.
196
200
  - **External-tool closeout:** an AI may close only resources it can show were created for the current task. Shared, user-owned, other-agent-owned, or unclear resources must be reported and left alone until you confirm.
@@ -204,4 +208,4 @@ Agent Handoff Kit can work alongside [Adam-AI-Instructions](https://github.com/p
204
208
  - **Adam-AI-Instructions** governs how an AI works within one conversation: tone, priorities, response structure, calculation discipline, and safety boundaries.
205
209
  - **Agent Handoff Kit** governs continuity between conversations: current state, next action, file routes, real closeout, and the next startup.
206
210
 
207
- This pairing is optional. It does not change installation or everyday use of Agent Handoff Kit.
211
+ This pairing is optional. It does not change installation or everyday use of Agent Handoff Kit. To use it, choose the version for your AI tool in that repository and paste it into the AI tool's settings.
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.63`。npm `@latest` 與 GitHub Release 以發佈後讀回為準。
5
+ 原始碼套件版本:`v0.3.65`。npm `@latest` 與 GitHub Release 以發佈後讀回為準。
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">
@@ -43,6 +43,8 @@ Agent Handoff Kit 是 **AI 對話之間的接力棒**。
43
43
  | `( -.- ) handoff saved` | 已收工保存,下次可以再說「開工」。 |
44
44
  | `( x.x ) handoff blocked` | 不是壞了;只是仍有未保存、未提交、未驗證或需要處理的事。先照 Blocker 行處理,不要把本輪當作已完成交接。 |
45
45
 
46
+ 收工卡核對交接是否保存、必要欄位與已記錄的檢查結果;它不會自動證明任務結論正確。工作仍受阻時,只要原因、影響與續接條件已清楚保存,也可以完成交接;「已保存」不等於整體任務完成。
47
+
46
48
  ## 🧭 這個 repo 怎樣讀
47
49
 
48
50
  如果你只是想使用 Agent Handoff Kit,只需要看四個入口:
@@ -97,9 +99,9 @@ Start Agent Handoff
97
99
  Work in <你的專案資料夾>. Read AGENTS.md first, then Start Agent Handoff. Before changing anything, tell me the current state and your recommended next step.
98
100
  ```
99
101
 
100
- 第一次安裝會把新手引導標記為待使用。若你安裝後只說 `Start Agent Handoff` 或「開工」,而沒有同句給出清楚任務,AI 應顯示開工卡並進入簡短新手歡迎引導;升級既有項目則不會重置這個流程。你已清楚描述目標和現有資料時,AI 可先用很短的新手框架說明工作節奏,再開始第一個安全步驟。日常「開工」先讀 `dev/SESSION_HANDOFF.md`;同一資料夾內不會再重讀 `START_NEXT_SESSION_PROMPT.txt` 或 `dev/SESSION_LOG.md`。提示副本只供尚未指向專案資料夾的 AI 接入。
102
+ 第一次安裝會把新手引導標記為待使用。只有該標記仍為 `eligible`、目前目標空白或 `TBD`,而且沒有同句明確任務時,AI 才在開工卡後進入簡短新手歡迎引導;升級既有項目不會重置這個標記。你已清楚描述目標和現有資料時,AI 可開始第一個安全步驟,不必先走新手流程。日常「開工」先讀 `dev/SESSION_HANDOFF.md`;同一資料夾內不會再重讀 `START_NEXT_SESSION_PROMPT.txt` 或 `dev/SESSION_LOG.md`。提示副本只供尚未指向專案資料夾的 AI 接入。
101
103
 
102
- 「開工,繼續 &lt;任務&gt;」、「&lt;項目&gt; 開工」或 `Start Agent Handoff and continue &lt;task&gt;` 會直接接力。只有語句明顯可能指現實世界的開業、輪班或其他無關事件時,AI 才作一次簡短確認。
104
+ 「開工,繼續 &lt;任務&gt;」、「&lt;項目&gt; 開工」或 `Start Agent Handoff and continue &lt;task&gt;` 都是接力指令。只有語句明顯可能指現實世界的開業、輪班或其他無關事件時,AI 才作一次簡短確認。單獨開工或只加項目名稱,會恢復最小狀態、顯示開工卡與建議下一步,然後等待;不會因此研究、計劃、驗收、改檔、連網或啟用子代理。只有同句明確任務或長程指令才授權開始工作;上面列明的新手引導例外仍適用。
103
105
 
104
106
  然後用日常話描述你要完成的任務。AI 應先讀交接文件,說明目前狀態、下一步與風險,再開始工作。
105
107
 
@@ -121,7 +123,9 @@ handoff
121
123
 
122
124
  若你說的是「某某收工」(例如餐廳收工、今天活動收工)這類帶其他上下文的話,AI 應先反問你是否要執行 Agent Handoff Kit 收工交接,而不是立即改寫交接文件。
123
125
 
124
- AI 應更新交接文件,並同步更新下一次開工提示副本:
126
+ AI 應把整體目標、目前子任務、準確續接點和剩餘驗收寫清楚,保留必要真源的版本、已讀段落、閱讀深度與未解缺口。簡單任務只記必要資訊,不必建立多層任務表。收工前,AI 要只憑交接內容重建下一步,再對照你的原始要求和實際成果,避免把小步完成當成整體完成;接續時仍須讀取任務所需真源,不能把上一位的「已讀」當作自己已核實。
127
+
128
+ AI 應只更新有變的交接狀態,並核對下一次開工提示副本;有差異時才重新產生:
125
129
 
126
130
  ```text
127
131
  START_NEXT_SESSION_PROMPT.txt
@@ -616,6 +616,11 @@ async function runCloseoutStatus(root, version) {
616
616
  const persistence = projectRequiredPersistence(fieldValueAfterMarker(handoffText, "project-required-persistence"));
617
617
  if (outcome !== "complete") findings.push("closeout outcome is not complete");
618
618
  if (!new Set(["complete", "not_required"]).has(persistence)) findings.push("project-required persistence is not complete or not required");
619
+ const sufficiency = assessHandoffSufficiency(handoffText);
620
+ if (sufficiency.length > 0) {
621
+ findings.push("handoff sufficiency read-back is incomplete");
622
+ details.push(...sufficiency);
623
+ }
619
624
  const lifecycle = assessHandoffLifecycleConsistency(handoffText);
620
625
  if (!lifecycle.ok) {
621
626
  findings.push("handoff lifecycle read-back is not healthy");
@@ -643,6 +648,89 @@ async function runCloseoutStatus(root, version) {
643
648
  if (!result.ok) process.exitCode = 1;
644
649
  }
645
650
 
651
+ function assessHandoffSufficiency(text) {
652
+ // Only visible prose is a declaration. Preserve text outside inline comments,
653
+ // but exclude fenced/indented examples and markers inside comments. This is
654
+ // local to the sufficiency fields; no project source is opened by the check.
655
+ const original = text.replace(/\r\n/g, "\n").split("\n");
656
+ const markerPattern = /^\s{0,3}<!-- (ack:(?:section|field):[\w-]+) -->\s*$/u;
657
+ const visible = [];
658
+ let fence = null;
659
+ let comment = false;
660
+ for (const raw of original) {
661
+ if (fence) {
662
+ const closing = /^ {0,3}(`{3,}|~{3,})\s*$/u.exec(raw);
663
+ if (closing && closing[1][0] === fence[0] && closing[1].length >= fence.length) fence = null;
664
+ continue;
665
+ }
666
+ if (!comment && /^(?: {4}| {0,3}\t)/u.test(raw)) continue;
667
+ const rawFence = !comment && /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(raw);
668
+ if (rawFence && (rawFence[1][0] !== "`" || !rawFence[2].includes("`"))) { fence = rawFence[1]; continue; }
669
+ const marker = !comment ? markerPattern.exec(raw)?.[1] : null;
670
+ if (marker) { visible.push({ text: marker, marker }); continue; }
671
+ let prose = "";
672
+ let offset = 0;
673
+ while (offset < raw.length) {
674
+ if (comment) {
675
+ const end = raw.indexOf("-->", offset);
676
+ if (end < 0) break;
677
+ comment = false;
678
+ offset = end + 3;
679
+ } else {
680
+ const start = raw.indexOf("<!--", offset);
681
+ if (start < 0) { prose += raw.slice(offset); break; }
682
+ prose += raw.slice(offset, start);
683
+ comment = true;
684
+ offset = start + 4;
685
+ }
686
+ }
687
+ const opening = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(prose);
688
+ if (opening && (opening[1][0] !== "`" || !opening[2].includes("`"))) { fence = opening[1]; continue; }
689
+ visible.push({ text: prose.trim(), marker: null });
690
+ }
691
+ const marked = (id) => visible.map((line, index) => line.marker === id ? index : -1).filter((index) => index >= 0);
692
+ const indices = marked("ack:section:handoff-sufficiency-check");
693
+ if (indices.length !== 1) return ["Handoff: require one active handoff-sufficiency-check section."];
694
+ const section = [];
695
+ let headingSeen = false;
696
+ for (const line of visible.slice(indices[0] + 1)) {
697
+ if (line.marker?.startsWith("ack:section:")) break;
698
+ if (/^##\s/u.test(line.text)) {
699
+ if (headingSeen || section.some((item) => item.trim())) break;
700
+ headingSeen = true;
701
+ continue;
702
+ }
703
+ section.push(line.text);
704
+ }
705
+ const fields = (label) => section.flatMap((line) => {
706
+ const match = new RegExp(`^(?:[-*]\\s+)?${escapeRegExp(label)}:\\s*(.*)$`, "iu").exec(line);
707
+ return match ? [match[1].trim()] : [];
708
+ });
709
+ const affirmative = (value) => /^yes(?:$|[\s.;:—–-])/iu.test(value);
710
+ const answers = fields("Answer");
711
+ const evidence = fields("Reconstruction evidence");
712
+ const findings = [];
713
+ if (answers.length !== 1 || !affirmative(answers[0])) {
714
+ findings.push("Handoff: Answer must occur once and start with yes after the packet-only reconstruction check; no/unknown/missing answers cannot complete closeout.");
715
+ }
716
+ const placeholder = /^(?:TBD|pending|unknown|not_started|not_assessed|待定|待補|未核實)(?:$|[\s.;:—–-])|^(?:yes|no|none|n\/?a|verified|complete|passed)[.!。]?$/iu;
717
+ if (evidence.length !== 1 || !evidence[0] || placeholder.test(evidence[0]) || /^<[^>]*>$/u.test(evidence[0])) {
718
+ findings.push("Handoff: add one non-placeholder Reconstruction evidence line citing the owning handoff sections; do not invent proof or copy a prior yes.");
719
+ }
720
+ const continuation = marked("ack:field:next-ai-can-continue");
721
+ if (continuation.length > 1) findings.push("Handoff: next-ai-can-continue is duplicated.");
722
+ if (continuation.length === 1) {
723
+ const following = [];
724
+ for (const line of visible.slice(continuation[0] + 1)) {
725
+ if (line.marker || /^##\s/u.test(line.text)) break;
726
+ if (line.text) following.push(line.text);
727
+ }
728
+ const value = following[0]?.match(/^[*-]\s+[^:]+:\s*(.*)$/u)?.[1] ?? "";
729
+ if (!affirmative(value)) findings.push("Handoff: next-ai-can-continue must agree with the affirmative sufficiency answer; repair negative, unknown or missing state.");
730
+ }
731
+ return findings;
732
+ }
733
+
646
734
  function closeoutDoctorFailureDetails(doctor) {
647
735
  const output = [doctor.stdout, doctor.stderr, doctor.error ? `error: ${doctor.error}` : ""]
648
736
  .filter(Boolean)
@@ -1023,7 +1111,7 @@ function hasSubstantiveWorkspaceValue(value) {
1023
1111
  }
1024
1112
 
1025
1113
  function workspaceValueMeansNoGit(value) {
1026
- return /\b(no git|non-git|not a git repository|not_git)\b|(?:沒有|無|不是).{0,12}\bGit\b/iu.test(value ?? "");
1114
+ return /\b(no git|non-git|not a git repository|not_git)\b|\bgit:\s*no(?=$|[\s,;.])|(?:沒有|無|不是).{0,12}\bGit\b/iu.test(value ?? "");
1027
1115
  }
1028
1116
 
1029
1117
  function workspaceSectionClaimsNoGit(section) {
@@ -1566,6 +1654,9 @@ async function buildTransactionOutputs(command, root, plan, version, options = {
1566
1654
  for (const item of plan) {
1567
1655
  if (item.action !== "create" && item.action !== "merge" && item.action !== "preserve") continue;
1568
1656
  const before = await readOptionalBuffer(item.targetAbs);
1657
+ if (item.plannedInputHash && (!before || sha256(before) !== item.plannedInputHash)) {
1658
+ throw new Error(`${item.targetRel}: input changed after official-region proof; restart the read-only plan`);
1659
+ }
1569
1660
  let afterText = null;
1570
1661
  let after = null;
1571
1662
  let projectIndexVersionMetadataMerge = false;
@@ -1739,13 +1830,11 @@ async function synchronizeFormalUserRulesTransactionState(command, root, byTarge
1739
1830
  routerOutput.afterText = renderUserRulesRouter(routerOutput.afterText, { state, entries });
1740
1831
  const acceptanceDigest = userRulesAcceptanceDigest(entries, state);
1741
1832
  const renderedAgentsText = renderUserRulesAcceptanceDigest(agentsText, acceptanceDigest);
1742
- if (agentOutput.after) {
1743
- const renderedBytes = encodeLikeExisting(renderedAgentsText, agentOutput.before, "AGENTS.md");
1744
- if (!agentOutput.after.equals(renderedBytes)) {
1745
- agentOutput.after = renderedBytes;
1746
- agentOutput.reason = "formal user-rules acceptance digest transition";
1747
- }
1748
- }
1833
+ const existingAgentsBytes = agentOutput.after ?? agentOutput.before;
1834
+ const renderedBody = Buffer.from(renderedAgentsText, "utf8");
1835
+ const renderedBytes = existingAgentsBytes && decodeUtf8(existingAgentsBytes, "AGENTS.md").bom
1836
+ ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), renderedBody]) : renderedBody;
1837
+ agentOutput.after = renderedBytes;
1749
1838
  agentOutput.afterText = renderedAgentsText;
1750
1839
  const witness = createFormalUserRulesWitness(entries, state, acceptanceDigest);
1751
1840
  routerOutput.formalUserRules = witness;
@@ -2178,6 +2267,20 @@ async function validateTransactionOverlay(root, outputs) {
2178
2267
  for (const check of rule.checks) if (!check.test(text)) failures.push(`${rule.target}: ${check.label}`);
2179
2268
  }
2180
2269
 
2270
+ // Structural anchors alone cannot certify that a newer runtime was installed.
2271
+ // Check the current required body before any transaction/version commit.
2272
+ for (const [sourceRel, targetRel] of mappings) {
2273
+ const strategy = installedFileContract(targetRel)?.strategy;
2274
+ if (strategy !== "managed-core" && strategy !== "rule-pack") continue;
2275
+ const text = await finalText(targetRel);
2276
+ if (text == null) continue;
2277
+ const expected = (await readFile(path.join(packageRoot, sourceRel), "utf8")).replace(/\r\n?/g, "\n");
2278
+ const actual = strategy === "managed-core" ? managedCoreTextRegion(text)?.text : text;
2279
+ const normalized = actual?.replace(/\r\n?/g, "\n");
2280
+ const current = strategy === "managed-core" ? normalized === expected.trim() : normalized?.startsWith(expected);
2281
+ if (!current) failures.push(`${targetRel}: current runtime requirements were not completely applied; preserve local content and resolve the merge`);
2282
+ }
2283
+
2181
2284
  const handoffText = await finalText("dev/SESSION_HANDOFF.md");
2182
2285
  const promptText = await finalText("START_NEXT_SESSION_PROMPT.txt");
2183
2286
  if (handoffText && promptText) {
@@ -4115,9 +4218,9 @@ function selectTrustedOfficialBaseline(context) {
4115
4218
  const version = context.rootTemplateVersion;
4116
4219
  if (!isStableSemver(version) || !context.officialCatalog?.releases?.[version]) return null;
4117
4220
  const dynamicTargets = new Set(["START_NEXT_SESSION_PROMPT.txt", "dev/SESSION_HANDOFF.md", "dev/PROJECT_INDEX.md"]);
4118
- // Normalized/canonical identity only selects a historical baseline for a
4119
- // preserve decision. It never reaches trustedOfficialOrigin(), which keeps
4120
- // raw byte equality as the sole authority to replace Kit-managed content.
4221
+ // Normalized/canonical identity selects a historical baseline, never direct
4222
+ // replacement authority. A non-raw update needs the separate complete-region
4223
+ // transport proof below; custom appendices also require a consistent baseline.
4121
4224
  let baselineSupport = 0;
4122
4225
  let contradiction = false;
4123
4226
  for (const [targetRel, origin] of context.officialOrigins) {
@@ -4136,6 +4239,93 @@ function trustedOfficialOrigin(targetRel, context) {
4136
4239
  return null;
4137
4240
  }
4138
4241
 
4242
+ // A transport proof is narrower than canonical identity: every non-newline
4243
+ // character in this entire official region must match an artifact-bound
4244
+ // catalog body. Never use headings, a version row, or fuzzy/canonical matches
4245
+ // to grant ownership of arbitrary local content. Bytes outside the proven
4246
+ // region (including BOM and local appendices) are reconstructed unchanged.
4247
+ function officialRuntimeBodies(targetRel, context) {
4248
+ const bodies = [];
4249
+ for (const [version, release] of Object.entries(context.officialCatalog?.releases ?? {})) {
4250
+ const npm = release.source?.npm;
4251
+ if (!npm?.integrity?.startsWith("sha512-") || !/^[a-f0-9]{40}$/.test(npm.shasum ?? "")) continue;
4252
+ if (!isStableSemver(version) || compareSemver(version, context.currentVersion) > 0) continue;
4253
+ const baseline = getOfficialBaseline({ version, targetRel, catalog: context.officialCatalog });
4254
+ if (baseline?.state !== "present") continue;
4255
+ const text = baseline.text.replace(/\r\n?/g, "\n");
4256
+ if (sha256(Buffer.from(text, "utf8")) !== baseline.normalizedSha256) continue;
4257
+ bodies.push({ version, text });
4258
+ }
4259
+ return bodies.sort((a, b) => compareSemver(b.version, a.version));
4260
+ }
4261
+
4262
+ function managedCoreTextRegion(text) {
4263
+ if (countText(text, managedCoreStart) !== 1 || countText(text, managedCoreEnd) !== 1) return null;
4264
+ const match = /^<!-- BEGIN Agent Handoff Kit managed core -->\r?\n([\s\S]*?)\r?\n<!-- END Agent Handoff Kit managed core -->/m.exec(text);
4265
+ if (!match) return null;
4266
+ const start = match.index + match[0].indexOf("\n") + 1;
4267
+ return { start, end: start + match[1].length, text: match[1] };
4268
+ }
4269
+
4270
+ function replaceProvenTextRegion(targetText, targetBytes, start, end, currentText) {
4271
+ const region = targetText.slice(start, end);
4272
+ const rendered = encodeLikeExisting(currentText, Buffer.from(region, "utf8"), "official runtime region");
4273
+ const bomBytes = decodeUtf8(targetBytes, "official runtime target").bom ? 3 : 0;
4274
+ const byteStart = bomBytes + Buffer.byteLength(targetText.slice(0, start), "utf8");
4275
+ const byteEnd = bomBytes + Buffer.byteLength(targetText.slice(0, end), "utf8");
4276
+ return Buffer.concat([targetBytes.subarray(0, byteStart), rendered, targetBytes.subarray(byteEnd)]);
4277
+ }
4278
+
4279
+ function planProvenRuntimeRegion(targetRel, targetText, targetBytes, sourceText, context) {
4280
+ const normalize = (text) => text.replace(/\r\n?/g, "\n");
4281
+ const bodies = officialRuntimeBodies(targetRel, context);
4282
+ if (targetRel === "AGENTS.md") {
4283
+ const region = managedCoreTextRegion(targetText);
4284
+ if (!region) return null;
4285
+ const current = sourceText.trim();
4286
+ if (normalize(region.text) === normalize(current)) return { action: "skip", reason: "managed core matches current content; local surrounding bytes preserved" };
4287
+ const official = bodies.find((body) => {
4288
+ const oldCore = managedCoreTextRegion(body.text);
4289
+ return oldCore && normalize(region.text) === normalize(oldCore.text);
4290
+ });
4291
+ if (!official) return null;
4292
+ return {
4293
+ action: "merge",
4294
+ mergedBytes: replaceProvenTextRegion(targetText, targetBytes, region.start, region.end, current),
4295
+ reason: `update artifact-bound official v${official.version} managed core with an explicit newline transform; preserve every surrounding byte`
4296
+ };
4297
+ }
4298
+ if (installedFileContract(targetRel)?.strategy !== "rule-pack") return null;
4299
+ const normalized = normalize(targetText);
4300
+ const candidates = [{ version: context.currentVersion, text: normalize(sourceText), current: true }, ...bodies]
4301
+ .sort((a, b) => b.text.length - a.text.length);
4302
+ for (const candidate of candidates) {
4303
+ if (!normalized.startsWith(candidate.text)) continue;
4304
+ const suffix = normalized.slice(candidate.text.length);
4305
+ if (suffix && !candidate.text.endsWith("\n")) continue;
4306
+ // A custom appendix is not evidence for a forged/missing baseline. Exact
4307
+ // whole official bodies can repair mixed roots from their own provenance.
4308
+ if (suffix && !candidate.current && (
4309
+ !isStableSemver(context.rootTemplateVersion)
4310
+ || compareSemver(candidate.version, context.rootTemplateVersion) > 0
4311
+ || (context.rootTemplateVersion !== context.currentVersion && context.trustedBaselineVersion !== candidate.version)
4312
+ )) continue;
4313
+ if (candidate.current) return { action: "skip", reason: "current official rule content and local appendix preserved" };
4314
+ let localEnd = 0;
4315
+ for (let offset = 0; offset < candidate.text.length; offset += 1) {
4316
+ if (targetText[localEnd] === "\r" && targetText[localEnd + 1] === "\n") localEnd += 2;
4317
+ else localEnd += 1;
4318
+ }
4319
+ if (normalize(targetText.slice(0, localEnd)) !== candidate.text) continue;
4320
+ return {
4321
+ action: "merge",
4322
+ mergedBytes: replaceProvenTextRegion(targetText, targetBytes, 0, localEnd, sourceText),
4323
+ reason: `update artifact-bound official v${candidate.version} ${targetRel} rule body with an explicit newline transform; preserve local appendix bytes`
4324
+ };
4325
+ }
4326
+ return null;
4327
+ }
4328
+
4139
4329
  function requiresHistoricalBaselineProof(context) {
4140
4330
  if (!isStableSemver(context.currentVersion)) return false;
4141
4331
  if (!context.rootTemplateVersion) return context.historicalOfficialEvidence;
@@ -4173,6 +4363,10 @@ function findUniqueManagedCoreBoundary(bytes, transform) {
4173
4363
  function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAbs, sourceText, targetText, context = {}, targetBytes = null) {
4174
4364
  const base = { sourceRel, targetRel, sourceAbs, targetAbs };
4175
4365
  if (targetText.replace(/\r\n/g, "\n") === sourceText.replace(/\r\n/g, "\n") && targetRel !== "AGENTS.md") return { ...base, action: "skip", reason: "already current" };
4366
+ if (command === "upgrade" && targetBytes && (targetRel === "AGENTS.md" || installedFileContract(targetRel)?.strategy === "rule-pack")) {
4367
+ const proven = planProvenRuntimeRegion(targetRel, targetText, targetBytes, sourceText, context);
4368
+ if (proven) return { ...base, ...proven, plannedInputHash: sha256(targetBytes) };
4369
+ }
4176
4370
  if (targetRel === "AGENTS.md") {
4177
4371
  // Marker shape, titles, and pathname are never ownership evidence. Exact
4178
4372
  // official bytes may be replaced; otherwise current managed-core structure
@@ -4233,26 +4427,21 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
4233
4427
  reason: `AGENTS.md managed-core markers are unpaired or duplicated (starts=${health.evidence.managedStart}, ends=${health.evidence.managedEnd})`
4234
4428
  };
4235
4429
  }
4236
- if (health.state === "needs-merge") {
4430
+ if (health.state === "needs-merge" && health.evidence.reason === "no Kit core present") {
4237
4431
  return {
4238
4432
  ...base,
4239
4433
  action: "merge",
4240
- reason: health.evidence.reason === "sandwich: managed marker + unmarked stale core"
4241
- ? "replace sandwich dup core (managed marker + unmarked stale core present)"
4242
- : health.evidence.reason === "legacy duplicate cores"
4243
- ? "replace duplicated legacy Agent Handoff Kit cores"
4244
- : "add managed core while preserving existing AGENTS.md content",
4434
+ reason: "add managed core while preserving existing AGENTS.md content",
4245
4435
  mergedText: mergeManagedBlock(targetText, sourceText)
4246
4436
  };
4247
4437
  }
4248
- // state === "clean": may still need legacy-core replacement or anchor catch-up
4249
- if (health.evidence?.upgradeable === "legacy-core") {
4250
- return {
4251
- ...base,
4252
- action: "merge",
4253
- reason: "replace unmarked legacy Agent Handoff Kit core with managed-marker block",
4254
- mergedText: mergeManagedBlock(targetText, sourceText)
4255
- };
4438
+ // Titles, marker shape and missing anchors cannot authorize deleting an
4439
+ // unknown rule. Proven official/current bodies returned above; preserve all
4440
+ // other existing cores for explicit reconciliation, including legacy forms.
4441
+ const existingCore = managedCoreTextRegion(targetText);
4442
+ if (health.state === "needs-merge" || health.evidence?.upgradeable === "legacy-core"
4443
+ || !existingCore || existingCore.text.replace(/\r\n?/g, "\n") !== sourceText.trim().replace(/\r\n?/g, "\n")) {
4444
+ return { ...base, action: "conflict", reason: "existing core is not current and no artifact-bound official region proves a safe update; preserve local content for an explicit merge" };
4256
4445
  }
4257
4446
  if (hasRequiredAnchor(targetRel, targetText)) {
4258
4447
  return { ...base, action: "skip", reason: "managed core clean and required anchors present" };
@@ -4324,9 +4513,13 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
4324
4513
  reason: `${targetRel} has local content but the version row and official file fingerprints do not identify one consistent historical baseline; upgrade stopped instead of guessing`
4325
4514
  };
4326
4515
  }
4327
- // R-029/R-030: RULE_PACKS.md is a routing table, but upgrade still preserves
4328
- // user-added rows. Missing maintainer rows are merged into the existing table
4329
- // instead of replacing the whole file.
4516
+ // All proven official/current rule bodies returned above. Do not let older
4517
+ // shape/anchor repair helpers replace unknown rules, even with intact headings.
4518
+ if (command === "upgrade" && installedFileContract(targetRel)?.strategy === "rule-pack") {
4519
+ return { ...base, action: "conflict", reason: `${targetRel} is not current and no artifact-bound official body proves a safe update; preserve local content for an explicit merge` };
4520
+ }
4521
+ // RULE_PACKS.md is a routing table: preserve user-added rows while updating
4522
+ // marker-identified maintainer rows through its separate current contract.
4330
4523
  if (targetRel === "dev/RULE_PACKS.md" && command === "upgrade") {
4331
4524
  const mergedRulePacks = mergeRulePacksRows(targetText, sourceText);
4332
4525
  if (!mergedRulePacks) {
@@ -4954,10 +5147,8 @@ function sessionLogEntryTemplateContract(text) {
4954
5147
 
4955
5148
  const fence = sessionLogTemplateFence(text, section);
4956
5149
  if (!fence) return null;
4957
- const sectionText = text.slice(section.start, section.end);
4958
5150
  const startMarker = "<!-- ack:log-entry:start -->";
4959
5151
  const endMarker = "<!-- ack:log-entry:end -->";
4960
- if (countText(sectionText, startMarker) !== 1 || countText(sectionText, endMarker) !== 1) return null;
4961
5152
  if (countText(fence.templateText, startMarker) !== 1 || countText(fence.templateText, endMarker) !== 1) return null;
4962
5153
  const relativeStart = fence.templateText.indexOf(startMarker);
4963
5154
  const relativeEnd = fence.templateText.indexOf(endMarker);
@@ -5555,8 +5746,7 @@ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
5555
5746
  if (!section || !fence) return null;
5556
5747
  const startMarker = "<!-- ack:log-entry:start -->";
5557
5748
  const endMarker = "<!-- ack:log-entry:end -->";
5558
- const sectionText = merged.slice(section.start, section.end);
5559
- if (countText(sectionText, startMarker) > 1 || countText(sectionText, endMarker) > 1) return null;
5749
+ if (countText(fence.templateText, startMarker) > 1 || countText(fence.templateText, endMarker) > 1) return null;
5560
5750
  let templateText = fence.templateText;
5561
5751
  if (!templateText.includes(startMarker)) {
5562
5752
  templateText = `${startMarker}\n${templateText}`;