@adamchanadam/agent-handoff-kit 0.3.39 → 0.3.40

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.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Agent Handoff Kit
2
2
 
3
- 目前版本:`v0.3.39`。
3
+ 目前版本:`v0.3.40`。
4
4
 
5
5
  <p align="center">
6
6
  <img src="https://raw.githubusercontent.com/Adamchanadam/agent-handoff-kit/main/images/agent-handoff-kit-promo-30s.gif" alt="Agent Handoff Kit 功能簡介動畫" width="720">
@@ -56,6 +56,15 @@ const credentialLeakPatterns = [
56
56
  { pattern: /\bAKIA[A-Z0-9]{16}/, label: "AWS access key" },
57
57
  { pattern: /\bAIza[A-Za-z0-9_-]{35}/, label: "Google API key" }
58
58
  ];
59
+
60
+ // Exact v0.3.38 continuity quick-fix packs observed in real projects before the
61
+ // product migration shipped. They contain no project-specific state. Matching
62
+ // is whole-file and newline-normalized so an extra local edit still takes the
63
+ // conservative three-way merge/conflict path instead of being overwritten.
64
+ const knownV038ContinuityQuickFixHashes = new Map([
65
+ ["packs/onboarding.md", "5dc32d9e164604379eb60f7ea0a731a2accb3da945ac5f28654ac253add187cf"],
66
+ ["packs/integrations.md", "8110bfb1e09fb503463072909c06027de0b39850c22a4f4c208c5752cf380826"]
67
+ ]);
59
68
 
60
69
  const requiredAnchors = [
61
70
  {
@@ -362,12 +371,16 @@ const schemaChecks = [
362
371
  }
363
372
  ]
364
373
  },
365
- {
366
- target: "dev/SESSION_LOG.md",
367
- label: "session log entry fields",
368
- checks: [
369
- heading("Entry Template"),
370
- marker("section", "session-log-preamble", "Handoff role"),
374
+ {
375
+ target: "dev/SESSION_LOG.md",
376
+ label: "session log entry fields",
377
+ checks: [
378
+ heading("Entry Template"),
379
+ {
380
+ label: "SESSION_LOG has one trusted current entry-template boundary",
381
+ test: (text) => Boolean(sessionLogEntryTemplateContract(text))
382
+ },
383
+ marker("section", "session-log-preamble", "Handoff role"),
371
384
  marker("section", "session-log-entry-template", "Entry Template"),
372
385
  includes("ack:log-entry:start"),
373
386
  includes("ack:log-entry:end"),
@@ -1914,34 +1927,91 @@ function assessHandoffLifecycleConsistency(text) {
1914
1927
  }
1915
1928
 
1916
1929
  function handoffStateLines(text, markerId, headingTitle) {
1917
- return extractSectionText(text, markerId, headingTitle)
1930
+ const sectionText = markerId === "next-session-opening-message"
1931
+ ? (extractOpeningMessage(text) ?? "")
1932
+ : extractSectionText(text, markerId, headingTitle);
1933
+ return sectionText
1918
1934
  .replace(/```[\s\S]*?```/g, "")
1919
1935
  .split(/\r?\n/)
1920
1936
  .map((line) => line.replace(/^[-*\d.)\s]+/, "").trim())
1921
- .filter((line) => line.length > 3 && !line.startsWith("##") && !line.startsWith("<!--") && !/^(TBD|none|n\/a|未適用|無)$/i.test(line));
1937
+ .filter((line) => line.length > 3 && !line.startsWith("##") && !line.startsWith("<!--") && !/^(TBD|none|n\/a|未適用|無)$/i.test(line))
1938
+ .filter((line) => markerId !== "next-session-opening-message" || !isOwnedOpeningLifecycleBoilerplate(line));
1939
+ }
1940
+
1941
+ function isOwnedOpeningLifecycleBoilerplate(line) {
1942
+ return /^Resume the current objective\. If my message or the handoff already gives an executable task, begin its first safe action in this response\./i.test(line)
1943
+ || /^A fresh install only makes guidance available; it does not force onboarding\./i.test(line)
1944
+ || /^Load onboarding only when I explicitly ask for guidance or no executable objective remains after state reading\./i.test(line);
1945
+ }
1946
+
1947
+ function stripResolvedNegatedActionClauses(line) {
1948
+ return line.split(/(?<=[.;;。])\s*/).filter((clause) => {
1949
+ const negated = /\b(?:no|not|never|without|did not|has not|have not)\b/i.test(clause);
1950
+ const action = /\b(?:commit|push|tag|release|publish|deploy|deployment|sync|write|upgrade)\b/i.test(clause);
1951
+ return !(negated && action);
1952
+ }).join(" ");
1953
+ }
1954
+
1955
+ const ignoredLifecycleEnglish = new Set([
1956
+ "completed", "complete", "finish", "finished", "continue", "incomplete", "passed", "verified", "pending", "blocked", "follow", "scope",
1957
+ "monitor", "only", "reopened", "recommended", "next", "step", "session", "current", "work", "task", "with",
1958
+ "from", "that", "this", "handoff", "lifecycle", "migration", "regression", "agent", "reason", "condition",
1959
+ "the", "and", "for", "into", "still", "remains"
1960
+ ]);
1961
+
1962
+ function lifecycleEnglishTokens(line, stripNegated = false) {
1963
+ const source = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
1964
+ return (source.toLowerCase().match(/[a-z0-9][a-z0-9_-]{2,}/g) ?? [])
1965
+ .filter((token) => !ignoredLifecycleEnglish.has(token));
1966
+ }
1967
+
1968
+ function lifecycleTopicWindows(line, stripNegated = false) {
1969
+ const source = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
1970
+ const englishTokens = lifecycleEnglishTokens(source);
1971
+ const english = Array.from({ length: Math.max(0, englishTokens.length - 2) }, (_, index) => englishTokens.slice(index, index + 3).join(" "));
1972
+ const chineseRuns = source.match(/[\u3400-\u9fff]{6,}/g) ?? [];
1973
+ const chinese = chineseRuns.flatMap((run) => Array.from({ length: Math.max(0, run.length - 5) }, (_, index) => run.slice(index, index + 6)));
1974
+ return new Set([...english, ...chinese]);
1922
1975
  }
1923
1976
 
1924
- function lifecycleTopicTokens(line) {
1925
- const latin = (line.toLowerCase().match(/[a-z0-9][a-z0-9_-]{3,}/g) ?? [])
1926
- .filter((token) => !new Set(["completed", "complete", "passed", "verified", "pending", "blocked", "follow-up", "monitor-only", "reopened", "session", "current", "next", "work", "task", "with", "from", "that", "this", "handoff", "lifecycle", "migration", "regression", "agent"]).has(token));
1927
- const chineseRuns = line.match(/[\u3400-\u9fff]{2,}/g) ?? [];
1928
- const chinese = chineseRuns.flatMap((run) => Array.from({ length: Math.max(0, run.length - 1) }, (_, index) => run.slice(index, index + 2)));
1929
- return new Set([...latin, ...chinese]);
1977
+ function lifecycleShortChineseCore(line, stripNegated = false) {
1978
+ const rawSource = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
1979
+ const source = rawSource.split(/(?:\s+[—–-]\s*)?(?:reason|condition)\s*[::]|(?:原因|條件)\s*[::]/i)[0];
1980
+ const ignored = /(後續追蹤|只監察|尚未完成|已經完成|重新開啟|完成|已驗證|繼續|下一步|待辦|尚未|未完成|通過|風險|受阻|重開|監察|追蹤|修復|修補|修正)/g;
1981
+ const core = (source.match(/[\u3400-\u9fff]+/g) ?? []).join("").replace(ignored, "");
1982
+ return core.length >= 2 && core.length <= 5 ? core : null;
1930
1983
  }
1931
1984
 
1932
1985
  function lifecycleTopicsOverlap(left, right) {
1933
- const leftCompact = left.toLowerCase().replace(/[^a-z0-9\u3400-\u9fff]+/g, "");
1934
- const rightCompact = right.toLowerCase().replace(/[^a-z0-9\u3400-\u9fff]+/g, "");
1935
- if (leftCompact.length >= 8 && rightCompact.length >= 8 && (leftCompact.includes(rightCompact) || rightCompact.includes(leftCompact))) return true;
1936
- const leftTokens = lifecycleTopicTokens(left);
1937
- const common = [...lifecycleTopicTokens(right)].filter((token) => leftTokens.has(token));
1938
- return common.length >= 2;
1986
+ const leftWindows = lifecycleTopicWindows(left, true);
1987
+ if ([...lifecycleTopicWindows(right)].some((window) => leftWindows.has(window))) return true;
1988
+ const leftEnglish = lifecycleEnglishTokens(left, true);
1989
+ const rightEnglish = lifecycleEnglishTokens(right);
1990
+ if (leftEnglish.length === 2 && rightEnglish.length === 2 && leftEnglish.join(" ") === rightEnglish.join(" ")) return true;
1991
+ const leftChinese = lifecycleShortChineseCore(left, true);
1992
+ return Boolean(leftChinese && leftChinese === lifecycleShortChineseCore(right));
1939
1993
  }
1940
1994
 
1941
1995
  function isExplicitLifecycleReclassification(line) {
1942
- const category = /(monitor-only|follow-up scope|blocked|reopened|只監察|後續追蹤|受阻|重開)/i.test(line);
1943
- const condition = /(trigger|until|when|missing evidence|reason|條件|證據|原因|待.+(?:時|後))/i.test(line);
1944
- return category && condition;
1996
+ const normalized = line
1997
+ .replace(/^recommended next step\s*:\s*/i, "")
1998
+ .replace(/^[\s—–:-]+/, "")
1999
+ .trim();
2000
+ if (!/^(?:(?:monitor-only|follow-up scope|blocked|reopened)\b|只監察|後續追蹤|受阻|重開)/i.test(normalized)) return false;
2001
+ if (/\b(no condition|without condition|unconditional)\b|無條件|沒有條件/i.test(normalized)) return false;
2002
+
2003
+ const labelled = normalized.match(/(?:\bcondition|\btrigger|\bmissing evidence|條件|觸發條件|缺少證據|證據|原因|\breason)\s*[::-]\s*([^;;\n]+)/i);
2004
+ if (labelled) return isSubstantiveLifecycleCondition(labelled[1]);
2005
+ const temporal = normalized.match(/(?:\bwhen|\buntil|待)(?:\s+|:|:)([^;;\n]+)/i);
2006
+ return temporal ? isSubstantiveLifecycleCondition(temporal[1]) : false;
2007
+ }
2008
+
2009
+ function isSubstantiveLifecycleCondition(value) {
2010
+ const normalized = (value ?? "").trim().replace(/[.。]+$/, "");
2011
+ if (normalized.length < 4) return false;
2012
+ if (/^(TBD|todo|pending|unknown|unverified|none|n\/a|待定|待確認|未知|無)$/i.test(normalized)) return false;
2013
+ if (/\b(no condition|without condition|unconditional)\b|無條件|沒有條件/i.test(normalized)) return false;
2014
+ return true;
1945
2015
  }
1946
2016
 
1947
2017
  function findHandoffLifecycleContradictions(text) {
@@ -2293,13 +2363,21 @@ function classifyExistingFile(command, sourceRel, targetRel, sourceAbs, targetAb
2293
2363
  return { ...base, action: "conflict", reason: "SESSION_LOG.md lacks a unique trusted entry-template boundary; migration stopped without replacing trace history" };
2294
2364
  }
2295
2365
  if (migratedLog !== targetText) {
2296
- return { ...base, action: "merge", reason: "update only the log preamble/template and remove Kit-shaped full prompt copies while preserving trace entries", mergedText: migratedLog };
2366
+ return { ...base, action: "merge", reason: "update only the trusted current log preamble/template while preserving every historical trace entry", mergedText: migratedLog };
2297
2367
  }
2298
2368
  return { ...base, action: "skip", reason: "SESSION_LOG.md trace/template boundary current" };
2299
2369
  }
2300
2370
  if (command === "upgrade" && ["dev/rules/integrations.md", "dev/rules/onboarding.md", "dev/rules/safety.md"].includes(targetRel)) {
2301
2371
  const baseline = context.migrationBaselines?.get(sourceRel);
2302
2372
  if (baseline != null) {
2373
+ if (isKnownV038ContinuityQuickFix(sourceRel, targetText)) {
2374
+ return {
2375
+ ...base,
2376
+ action: "merge",
2377
+ reason: `replace the exact known v0.3.38 continuity quick-fix ${path.basename(targetRel)} with the current official pack`,
2378
+ mergedText: sourceText
2379
+ };
2380
+ }
2303
2381
  const mergedPack = threeWayPreserveLocalChanges(baseline, targetText, sourceText);
2304
2382
  if (!mergedPack) {
2305
2383
  return { ...base, action: "conflict", reason: `${targetRel} has local edits that overlap changed Kit rules; upgrade stopped without replacing custom content` };
@@ -2638,12 +2716,11 @@ function isRequiredAnchorSemanticallyPlaced(rule, snippet, text) {
2638
2716
  return rule.placement ? rule.placement(snippet, text) : true;
2639
2717
  }
2640
2718
 
2641
- function sessionLogAnchorPlacement(snippet, text) {
2642
- if (snippet === "ack:section:session-log-preamble") return text.includes("ack:section:session-log-preamble");
2643
- if (snippet === "ack:section:session-log-entry-template") return text.includes("ack:section:session-log-entry-template");
2644
- if (snippet === "## Entry Template") return /^## Entry Template\s*$/m.test(text);
2645
- if (snippet === "ack:log-entry:start" || snippet === "ack:log-entry:end") {
2646
- return sessionLogEntryTemplateContains(text, snippet);
2719
+ function sessionLogAnchorPlacement(snippet, text) {
2720
+ if (snippet === "ack:section:session-log-preamble") return countText(text, "ack:section:session-log-preamble") === 1;
2721
+ if (snippet === "ack:section:session-log-entry-template" || snippet === "## Entry Template") return Boolean(sessionLogEntryTemplateContract(text));
2722
+ if (snippet === "ack:log-entry:start" || snippet === "ack:log-entry:end") {
2723
+ return sessionLogEntryTemplateContains(text, snippet);
2647
2724
  }
2648
2725
  const preamble = [
2649
2726
  "Record what actually happened in the session",
@@ -2663,11 +2740,10 @@ function sessionLogPreambleContains(text, snippet) {
2663
2740
  return snippetAppearsBeforeHeading(text, snippet, "## Entry Template");
2664
2741
  }
2665
2742
 
2666
- function sessionLogEntryTemplateContains(text, snippet) {
2667
- const markerIndex = text.indexOf("<!-- ack:section:session-log-entry-template -->");
2668
- if (markerIndex >= 0) return text.slice(markerIndex).includes(snippet);
2669
- return snippetAppearsAfterHeading(text, snippet, "## Entry Template");
2670
- }
2743
+ function sessionLogEntryTemplateContains(text, snippet) {
2744
+ const contract = sessionLogEntryTemplateContract(text);
2745
+ return Boolean(contract && contract.templateText.includes(snippet));
2746
+ }
2671
2747
 
2672
2748
  function handoffContinuityAnchorPlacement(snippet, text) {
2673
2749
  const suffixContinuityAnchors = [
@@ -2946,6 +3022,53 @@ function parseMarkdownH2Sections(text) {
2946
3022
  return sections;
2947
3023
  }
2948
3024
 
3025
+ function uniqueSessionLogEntryTemplateSection(text) {
3026
+ const matches = parseMarkdownH2Sections(text).filter((section) => section.title === "Entry Template");
3027
+ return matches.length === 1 ? matches[0] : null;
3028
+ }
3029
+
3030
+ function sessionLogTemplateFence(text, section) {
3031
+ if (!section) return null;
3032
+ const sectionText = text.slice(section.start, section.end);
3033
+ const matches = [...sectionText.matchAll(/^````markdown\s*\r?\n([\s\S]*?)\r?\n````\s*$/gm)];
3034
+ if (matches.length !== 1) return null;
3035
+ const match = matches[0];
3036
+ const templateOffset = match.index + match[0].indexOf(match[1]);
3037
+ return {
3038
+ start: section.start + match.index,
3039
+ end: section.start + match.index + match[0].length,
3040
+ templateStart: section.start + templateOffset,
3041
+ templateEnd: section.start + templateOffset + match[1].length,
3042
+ templateText: match[1]
3043
+ };
3044
+ }
3045
+
3046
+ function sessionLogEntryTemplateContract(text) {
3047
+ const section = uniqueSessionLogEntryTemplateSection(text);
3048
+ if (!section) return null;
3049
+ const sectionMarker = "<!-- ack:section:session-log-entry-template -->";
3050
+ if (countText(text, sectionMarker) !== 1) return null;
3051
+ const markerIndex = text.indexOf(sectionMarker);
3052
+ if (markerIndex >= section.start || text.slice(markerIndex + sectionMarker.length, section.start).trim() !== "") return null;
3053
+
3054
+ const fence = sessionLogTemplateFence(text, section);
3055
+ if (!fence) return null;
3056
+ const sectionText = text.slice(section.start, section.end);
3057
+ const startMarker = "<!-- ack:log-entry:start -->";
3058
+ const endMarker = "<!-- ack:log-entry:end -->";
3059
+ if (countText(sectionText, startMarker) !== 1 || countText(sectionText, endMarker) !== 1) return null;
3060
+ if (countText(fence.templateText, startMarker) !== 1 || countText(fence.templateText, endMarker) !== 1) return null;
3061
+ const relativeStart = fence.templateText.indexOf(startMarker);
3062
+ const relativeEnd = fence.templateText.indexOf(endMarker);
3063
+ if (relativeStart >= relativeEnd) return null;
3064
+ return {
3065
+ ...section,
3066
+ ...fence,
3067
+ entryStart: fence.templateStart + relativeStart,
3068
+ entryEnd: fence.templateStart + relativeEnd + endMarker.length
3069
+ };
3070
+ }
3071
+
2949
3072
  function lcsLinePairs(left, right) {
2950
3073
  const rows = left.length + 1;
2951
3074
  const cols = right.length + 1;
@@ -3029,6 +3152,12 @@ function threeWayPreserveLocalChanges(baseText, localText, currentText) {
3029
3152
  return `${merged.join(newline)}${localHadFinalNewline || baseHadFinalNewline ? newline : ""}`;
3030
3153
  }
3031
3154
 
3155
+ function isKnownV038ContinuityQuickFix(sourceRel, text) {
3156
+ const expected = knownV038ContinuityQuickFixHashes.get(sourceRel);
3157
+ if (!expected) return false;
3158
+ return sha256(Buffer.from(text.replace(/\r\n/g, "\n"), "utf8")) === expected;
3159
+ }
3160
+
3032
3161
  function uniqueH2Section(text, title) {
3033
3162
  const matches = parseMarkdownH2Sections(text).filter((section) => section.title === title);
3034
3163
  return matches.length === 1 ? matches[0] : null;
@@ -3451,24 +3580,13 @@ function migrateSessionHandoff(targetText, sourceText, context = {}) {
3451
3580
  function migrateSessionLog(targetText, sourceText) {
3452
3581
  let merged = mergeSessionLogTemplateContract(targetText, sourceText);
3453
3582
  if (!merged) return null;
3454
- merged = mergeSessionLogEvidenceDispositionField(merged) ?? merged;
3583
+ merged = mergeSessionLogEvidenceDispositionField(merged);
3584
+ if (!merged) return null;
3455
3585
 
3456
- const startMarker = "<!-- ack:log-entry:start -->";
3457
- const endMarker = "<!-- ack:log-entry:end -->";
3458
- if (countText(merged, startMarker) !== 1 || countText(merged, endMarker) !== 1
3459
- || countText(sourceText, startMarker) !== 1 || countText(sourceText, endMarker) !== 1) return null;
3460
- const targetStart = merged.indexOf(startMarker);
3461
- const targetEnd = merged.indexOf(endMarker, targetStart) + endMarker.length;
3462
- const sourceStart = sourceText.indexOf(startMarker);
3463
- const sourceEnd = sourceText.indexOf(endMarker, sourceStart) + endMarker.length;
3464
- merged = `${merged.slice(0, targetStart)}${sourceText.slice(sourceStart, sourceEnd)}${merged.slice(targetEnd)}`;
3465
-
3466
- merged = merged.replace(/```(?:text)?\s*\r?\n([\s\S]*?)\r?\n```/g, (block, content) => {
3467
- const signatures = ["Work in ", "Read AGENTS.md", "SESSION_HANDOFF.md", "PROJECT_INDEX.md"];
3468
- return signatures.every((signature) => content.includes(signature))
3469
- ? "Opening-message mirror: migrated; full text omitted by design."
3470
- : block;
3471
- });
3586
+ const targetContract = sessionLogEntryTemplateContract(merged);
3587
+ const sourceContract = sessionLogEntryTemplateContract(sourceText);
3588
+ if (!targetContract || !sourceContract) return null;
3589
+ merged = `${merged.slice(0, targetContract.entryStart)}${sourceText.slice(sourceContract.entryStart, sourceContract.entryEnd)}${merged.slice(targetContract.entryEnd)}`;
3472
3590
  return merged;
3473
3591
  }
3474
3592
 
@@ -3572,17 +3690,22 @@ function ensureHandoffStateReconciliationRules(targetText) {
3572
3690
  return `${targetText.trimEnd()}\n\n${ruleBlock}`;
3573
3691
  }
3574
3692
 
3575
- function mergeSessionLogEvidenceDispositionField(targetText) {
3576
- if (targetText.includes("- **Evidence disposition:**")) return mergeSessionLogTemplateContract(targetText, null) ?? targetText;
3577
- const qcField = "- **QC:**";
3578
- if (!targetText.includes(qcField)) return null;
3579
- const withEvidence = targetText.replace(qcField, `${qcField}\n- **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>`);
3580
- return mergeSessionLogTemplateContract(withEvidence, null) ?? withEvidence;
3581
- }
3582
-
3583
- function mergeSessionLogTemplateContract(targetText, sourceText = null) {
3584
- let merged = targetText;
3585
- let changed = false;
3693
+ function mergeSessionLogEvidenceDispositionField(targetText) {
3694
+ const contract = sessionLogEntryTemplateContract(targetText);
3695
+ if (!contract) return null;
3696
+ if (contract.templateText.includes("- **Evidence disposition:**")) return targetText;
3697
+ const qcField = "- **QC:**";
3698
+ if (countText(contract.templateText, qcField) !== 1) return null;
3699
+ const withEvidenceTemplate = contract.templateText.replace(qcField, `${qcField}\n- **Evidence disposition:** <one-time only / kept as recent trace evidence / absorbed into handoff / indexed in PROJECT_INDEX / promoted to PROJECT_DECISIONS / promoted to rule pack>`);
3700
+ return `${targetText.slice(0, contract.templateStart)}${withEvidenceTemplate}${targetText.slice(contract.templateEnd)}`;
3701
+ }
3702
+
3703
+ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
3704
+ let merged = targetText;
3705
+ let changed = false;
3706
+
3707
+ const initialSection = uniqueSessionLogEntryTemplateSection(merged);
3708
+ if (!initialSection) return null;
3586
3709
 
3587
3710
  if (!merged.includes("ack:section:session-log-preamble")) {
3588
3711
  const titleMatch = /^# Session Log\s*$/m.exec(merged);
@@ -3597,13 +3720,19 @@ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
3597
3720
  }
3598
3721
  }
3599
3722
 
3600
- if (!merged.includes("ack:section:session-log-entry-template")) {
3601
- const headingMatch = /^## Entry Template\s*$/m.exec(merged);
3602
- if (headingMatch) {
3603
- merged = `${merged.slice(0, headingMatch.index)}<!-- ack:section:session-log-entry-template -->\n\n${merged.slice(headingMatch.index)}`;
3604
- changed = true;
3605
- }
3606
- }
3723
+ const sectionMarker = "<!-- ack:section:session-log-entry-template -->";
3724
+ const sectionMarkerCount = countText(merged, sectionMarker);
3725
+ if (sectionMarkerCount > 1) return null;
3726
+ if (sectionMarkerCount === 0) {
3727
+ const currentSection = uniqueSessionLogEntryTemplateSection(merged);
3728
+ if (!currentSection) return null;
3729
+ merged = `${merged.slice(0, currentSection.start)}${sectionMarker}\n\n${merged.slice(currentSection.start)}`;
3730
+ changed = true;
3731
+ } else {
3732
+ const currentSection = uniqueSessionLogEntryTemplateSection(merged);
3733
+ const markerIndex = merged.indexOf(sectionMarker);
3734
+ if (!currentSection || markerIndex >= currentSection.start || merged.slice(markerIndex + sectionMarker.length, currentSection.start).trim() !== "") return null;
3735
+ }
3607
3736
 
3608
3737
  if (sourceText) {
3609
3738
  const restored = restoreMissingSessionLogPreambleLines(merged, sourceText);
@@ -3613,32 +3742,30 @@ function mergeSessionLogTemplateContract(targetText, sourceText = null) {
3613
3742
  }
3614
3743
  }
3615
3744
 
3616
- const entryTemplateIndex = merged.search(/^## Entry Template\s*$/m);
3617
- if (entryTemplateIndex >= 0) {
3618
- const beforeTemplate = merged.slice(0, entryTemplateIndex);
3619
- let templateAndAfter = merged.slice(entryTemplateIndex);
3620
- if (!templateAndAfter.includes("ack:log-entry:start")) {
3621
- const replaced = templateAndAfter.replace(/````markdown(\r?\n)/, "````markdown$1<!-- ack:log-entry:start -->$1");
3622
- if (replaced !== templateAndAfter) {
3623
- templateAndAfter = replaced;
3624
- changed = true;
3625
- }
3626
- }
3627
- if (!templateAndAfter.includes("ack:log-entry:end")) {
3628
- const openingIndex = templateAndAfter.indexOf("````markdown");
3629
- const closingIndex = openingIndex >= 0
3630
- ? templateAndAfter.indexOf("\n````", openingIndex + "````markdown".length)
3631
- : -1;
3632
- if (closingIndex >= 0) {
3633
- templateAndAfter = `${templateAndAfter.slice(0, closingIndex)}\n<!-- ack:log-entry:end -->${templateAndAfter.slice(closingIndex)}`;
3634
- changed = true;
3635
- }
3636
- }
3637
- merged = `${beforeTemplate}${templateAndAfter}`;
3638
- }
3639
-
3640
- return changed ? merged : targetText;
3641
- }
3745
+ const section = uniqueSessionLogEntryTemplateSection(merged);
3746
+ const fence = sessionLogTemplateFence(merged, section);
3747
+ if (!section || !fence) return null;
3748
+ const startMarker = "<!-- ack:log-entry:start -->";
3749
+ const endMarker = "<!-- ack:log-entry:end -->";
3750
+ const sectionText = merged.slice(section.start, section.end);
3751
+ if (countText(sectionText, startMarker) > 1 || countText(sectionText, endMarker) > 1) return null;
3752
+ let templateText = fence.templateText;
3753
+ if (!templateText.includes(startMarker)) {
3754
+ templateText = `${startMarker}\n${templateText}`;
3755
+ changed = true;
3756
+ }
3757
+ if (!templateText.includes(endMarker)) {
3758
+ templateText = `${templateText.trimEnd()}\n${endMarker}`;
3759
+ changed = true;
3760
+ }
3761
+ if (templateText !== fence.templateText) {
3762
+ merged = `${merged.slice(0, fence.templateStart)}${templateText}${merged.slice(fence.templateEnd)}`;
3763
+ }
3764
+
3765
+ if (!sessionLogEntryTemplateContract(merged)) return null;
3766
+
3767
+ return changed ? merged : targetText;
3768
+ }
3642
3769
 
3643
3770
  function restoreMissingSessionLogPreambleLines(targetText, sourceText) {
3644
3771
  const sourceEntryIndex = sourceText.search(/^## Entry Template\s*$/m);