@adamchanadam/agent-handoff-kit 0.3.40 → 0.3.41

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.
@@ -0,0 +1,192 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+ const defaultCatalogPath = path.join(__dirname, "migration-baselines", "official-origin-catalog.json");
8
+
9
+ export const OFFICIAL_ORIGIN_CATALOG_SCHEMA = 1;
10
+
11
+ export async function loadOfficialOriginCatalog(catalogPath = defaultCatalogPath) {
12
+ const catalog = JSON.parse(await readFile(catalogPath, "utf8"));
13
+ validateOfficialOriginCatalog(catalog);
14
+ return catalog;
15
+ }
16
+
17
+ export function validateOfficialOriginCatalog(catalog) {
18
+ assertCatalogShape(catalog);
19
+ const digestCopy = { ...catalog };
20
+ delete digestCopy.catalogDigestSha256;
21
+ const expectedDigest = sha256(`${JSON.stringify(digestCopy)}\n`);
22
+ if (catalog.catalogDigestSha256 !== expectedDigest) throw new Error("official origin catalog integrity digest mismatch");
23
+
24
+ const targets = catalog.installedTargets.map((item) => item.targetRel);
25
+ const referenced = new Set();
26
+ for (const [version, release] of Object.entries(catalog.releases)) {
27
+ if (JSON.stringify(Object.keys(release.manifest)) !== JSON.stringify(targets)) {
28
+ throw new Error(`official origin catalog manifest coverage mismatch: ${version}`);
29
+ }
30
+ for (const [targetRel, entry] of Object.entries(release.manifest)) {
31
+ if (entry.state === "absent") continue;
32
+ if (entry.state !== "present" || !/^[0-9a-f]{64}$/.test(entry.rawSha256) || !/^[0-9a-f]{64}$/.test(entry.normalizedSha256)) {
33
+ throw new Error(`official origin catalog manifest entry invalid: ${version} ${targetRel}`);
34
+ }
35
+ const content = catalog.contents[entry.contentId];
36
+ if (!content || content.targetRel !== targetRel) {
37
+ throw new Error(`official origin catalog content target mismatch: ${version} ${targetRel}`);
38
+ }
39
+ if (entry.canonicalSha256 !== content.canonicalSha256) {
40
+ throw new Error(`official origin catalog canonical hash mismatch: ${version} ${targetRel}`);
41
+ }
42
+ referenced.add(entry.contentId);
43
+ }
44
+ }
45
+
46
+ for (const [contentId, content] of Object.entries(catalog.contents)) {
47
+ if (contentId !== sha256(`${content.targetRel}\0${content.text}`)) {
48
+ throw new Error(`official origin catalog content ID mismatch: ${contentId}`);
49
+ }
50
+ if (content.canonicalSha256 !== sha256(canonicalizeOfficialText(content.targetRel, content.text))) {
51
+ throw new Error(`official origin catalog content hash mismatch: ${contentId}`);
52
+ }
53
+ if (!referenced.has(contentId)) throw new Error(`official origin catalog has orphan content: ${contentId}`);
54
+ }
55
+ return true;
56
+ }
57
+
58
+ export function identifyOfficialOrigin({ targetRel, text, catalog }) {
59
+ assertCatalogShape(catalog);
60
+ const normalizedSha256 = sha256(normalizeNewlines(text));
61
+ const canonicalSha256 = sha256(canonicalizeOfficialText(targetRel, text));
62
+ const exactVersions = [];
63
+ const canonicalVersions = [];
64
+
65
+ for (const [version, release] of Object.entries(catalog.releases)) {
66
+ const entry = release.manifest[targetRel];
67
+ if (!entry || entry.state !== "present") continue;
68
+ if (entry.normalizedSha256 === normalizedSha256) exactVersions.push(version);
69
+ else if (entry.canonicalSha256 === canonicalSha256) canonicalVersions.push(version);
70
+ }
71
+
72
+ return {
73
+ targetRel,
74
+ normalizedSha256,
75
+ canonicalSha256,
76
+ exact: exactVersions.length > 0,
77
+ exactVersions,
78
+ canonicalVersions
79
+ };
80
+ }
81
+
82
+ export function getOfficialBaseline({ version, targetRel, catalog, root = null }) {
83
+ assertCatalogShape(catalog);
84
+ const release = catalog.releases[stripVersionPrefix(version)];
85
+ if (!release) return null;
86
+ const entry = release.manifest[targetRel];
87
+ if (!entry) return null;
88
+ if (entry.state === "absent") return { state: "absent", version: stripVersionPrefix(version), targetRel };
89
+ const content = catalog.contents[entry.contentId];
90
+ if (!content || content.targetRel !== targetRel) {
91
+ throw new Error(`official origin catalog content mismatch: ${version} ${targetRel}`);
92
+ }
93
+ return {
94
+ state: "present",
95
+ version: stripVersionPrefix(version),
96
+ targetRel,
97
+ text: materializeOfficialText(targetRel, content.text, { version: stripVersionPrefix(version), root }),
98
+ normalizedSha256: entry.normalizedSha256,
99
+ canonicalSha256: entry.canonicalSha256
100
+ };
101
+ }
102
+
103
+ export function normalizeNewlines(text) {
104
+ return String(text).replace(/\r\n?/g, "\n");
105
+ }
106
+
107
+ export function canonicalizeOfficialText(targetRel, text) {
108
+ let normalized = normalizeNewlines(text);
109
+ if (targetRel === "dev/PROJECT_INDEX.md") {
110
+ normalized = normalized.replace(
111
+ /^(\|\s*Agent Handoff Kit template version\s*\|)\s*[^|\n]+?(\s*\|.*)$/m,
112
+ "$1 <VERSION>$2"
113
+ );
114
+ }
115
+ if (targetRel === "START_NEXT_SESSION_PROMPT.txt") {
116
+ normalized = canonicalizeOpeningRootLine(normalized);
117
+ }
118
+ if (targetRel === "dev/SESSION_HANDOFF.md") {
119
+ normalized = canonicalizeHandoffOpeningRoot(normalized);
120
+ }
121
+ return normalized;
122
+ }
123
+
124
+ export function materializeOfficialText(targetRel, text, { version = null, root = null } = {}) {
125
+ let materialized = normalizeNewlines(text);
126
+ if (targetRel === "dev/PROJECT_INDEX.md" && version) {
127
+ materialized = materialized.replace(
128
+ /^(\|\s*Agent Handoff Kit template version\s*\|)\s*<VERSION>(\s*\|.*)$/m,
129
+ `$1 ${stripVersionPrefix(version)}$2`
130
+ );
131
+ }
132
+ if (root && targetRel === "START_NEXT_SESSION_PROMPT.txt") {
133
+ materialized = materializeOpeningRootLine(materialized, root);
134
+ }
135
+ if (root && targetRel === "dev/SESSION_HANDOFF.md") {
136
+ materialized = materializeHandoffOpeningRoot(materialized, root);
137
+ }
138
+ return materialized;
139
+ }
140
+
141
+ export function sha256(text) {
142
+ return createHash("sha256").update(text, "utf8").digest("hex");
143
+ }
144
+
145
+ function canonicalizeOpeningRootLine(text) {
146
+ return text.replace(/^(Work in )[^\n]+?(\.(?: Read AGENTS\.md, then dev\/SESSION_HANDOFF\.md\.)?)$/m, "$1<ROOT>$2");
147
+ }
148
+
149
+ function canonicalizeHandoffOpeningRoot(text) {
150
+ const marker = "<!-- ack:section:next-session-opening-message -->";
151
+ const markerIndex = text.indexOf(marker);
152
+ if (markerIndex < 0) return text;
153
+ const fenceStart = text.indexOf("```text\n", markerIndex);
154
+ if (fenceStart < 0) return text;
155
+ const contentStart = fenceStart + "```text\n".length;
156
+ const fenceEnd = text.indexOf("\n```", contentStart);
157
+ if (fenceEnd < 0) return text;
158
+ const before = text.slice(0, contentStart);
159
+ const opening = canonicalizeOpeningRootLine(text.slice(contentStart, fenceEnd));
160
+ return `${before}${opening}${text.slice(fenceEnd)}`;
161
+ }
162
+
163
+ function materializeOpeningRootLine(text, root) {
164
+ return text.replace(/^(Work in )<ROOT>(\.(?: Read AGENTS\.md, then dev\/SESSION_HANDOFF\.md\.)?)$/m, `$1${root}$2`);
165
+ }
166
+
167
+ function materializeHandoffOpeningRoot(text, root) {
168
+ const marker = "<!-- ack:section:next-session-opening-message -->";
169
+ const markerIndex = text.indexOf(marker);
170
+ if (markerIndex < 0) return text;
171
+ const fenceStart = text.indexOf("```text\n", markerIndex);
172
+ if (fenceStart < 0) return text;
173
+ const contentStart = fenceStart + "```text\n".length;
174
+ const fenceEnd = text.indexOf("\n```", contentStart);
175
+ if (fenceEnd < 0) return text;
176
+ const before = text.slice(0, contentStart);
177
+ const opening = materializeOpeningRootLine(text.slice(contentStart, fenceEnd), root);
178
+ return `${before}${opening}${text.slice(fenceEnd)}`;
179
+ }
180
+
181
+ function stripVersionPrefix(version) {
182
+ return String(version ?? "").replace(/^v/, "");
183
+ }
184
+
185
+ function assertCatalogShape(catalog) {
186
+ if (!catalog || catalog.schemaVersion !== OFFICIAL_ORIGIN_CATALOG_SCHEMA) {
187
+ throw new Error(`unsupported official origin catalog schema: ${catalog?.schemaVersion ?? "missing"}`);
188
+ }
189
+ if (!catalog.releases || !catalog.contents || !Array.isArray(catalog.installedTargets)) {
190
+ throw new Error("official origin catalog is incomplete");
191
+ }
192
+ }
@@ -1,4 +1,4 @@
1
- import { lstatSync, readFileSync, readdirSync } from "node:fs";
1
+ import { lstatSync, readFileSync, readdirSync } from "node:fs";
2
2
  import path from "node:path";
3
3
 
4
4
  const openingSectionMarker = "<!-- ack:section:next-session-opening-message -->";
@@ -26,28 +26,28 @@ export function assessPromptMirrorRoot(root) {
26
26
  return { status: "missing", ok: false, reason: "prompt copy unreadable" };
27
27
  }
28
28
 
29
- const otherTexts = collectCurrentGovernanceTexts(root, new Set([
30
- path.resolve(handoffPath),
31
- path.resolve(promptPath)
32
- ]));
33
- return assessPromptMirrorTexts(handoffText, promptText, otherTexts);
34
- }
35
-
36
- export function assessPromptMirrorTexts(handoffText, promptText, otherTexts = []) {
37
- const markerCount = countLiteral(handoffText, openingSectionMarker);
38
- const headingCount = (handoffText.match(new RegExp(openingHeadingPattern.source, "gm")) ?? []).length;
39
- const contentMarkerCount = openingContentMarkers.reduce((sum, marker) => sum + countLiteral(handoffText, marker), 0);
40
- const openingSection = markerCount === 1 ? handoffText.slice(handoffText.indexOf(openingSectionMarker)) : "";
41
- const fenceCount = (openingSection.match(/```text[^\r\n]*(?:\r\n?|\n)[\s\S]*?(?:\r\n?|\n)```/g) ?? []).length;
42
- if (markerCount !== 1 || headingCount > 1 || contentMarkerCount !== 1 || fenceCount !== 1) {
43
- return {
44
- status: "structure-invalid",
45
- ok: false,
46
- reason: `opening structure must be unique (section marker=${markerCount}, heading=${headingCount}, copy marker=${contentMarkerCount}, fenced text=${fenceCount})`
47
- };
48
- }
49
-
50
- const openingMessage = extractOpeningMessage(handoffText);
29
+ const otherTexts = collectCurrentGovernanceTexts(root, new Set([
30
+ path.resolve(handoffPath),
31
+ path.resolve(promptPath)
32
+ ]));
33
+ return assessPromptMirrorTexts(handoffText, promptText, otherTexts);
34
+ }
35
+
36
+ export function assessPromptMirrorTexts(handoffText, promptText, otherTexts = []) {
37
+ const markerCount = countLiteral(handoffText, openingSectionMarker);
38
+ const headingCount = (handoffText.match(new RegExp(openingHeadingPattern.source, "gm")) ?? []).length;
39
+ const contentMarkerCount = openingContentMarkers.reduce((sum, marker) => sum + countLiteral(handoffText, marker), 0);
40
+ const openingSection = markerCount === 1 ? handoffText.slice(handoffText.indexOf(openingSectionMarker)) : "";
41
+ const fenceCount = (openingSection.match(/```text[^\r\n]*(?:\r\n?|\n)[\s\S]*?(?:\r\n?|\n)```/g) ?? []).length;
42
+ if (markerCount !== 1 || headingCount > 1 || contentMarkerCount !== 1 || fenceCount !== 1) {
43
+ return {
44
+ status: "structure-invalid",
45
+ ok: false,
46
+ reason: `opening structure must be unique (section marker=${markerCount}, heading=${headingCount}, copy marker=${contentMarkerCount}, fenced text=${fenceCount})`
47
+ };
48
+ }
49
+
50
+ const openingMessage = extractOpeningMessage(handoffText);
51
51
  if (openingMessage == null) {
52
52
  return {
53
53
  status: "missing",
@@ -56,19 +56,19 @@ export function assessPromptMirrorTexts(handoffText, promptText, otherTexts = []
56
56
  };
57
57
  }
58
58
 
59
- const normalizedOpening = normalizePrompt(openingMessage);
60
- const thirdCopies = otherTexts.filter(({ text }) => normalizePrompt(text).includes(normalizedOpening));
61
- if (thirdCopies.length > 0) {
62
- return {
63
- status: "third-copy",
64
- ok: false,
65
- reason: `full opening message also appears in: ${thirdCopies.map(({ relative }) => relative).join(", ")}`,
66
- openingMessage,
67
- thirdCopies: thirdCopies.map(({ relative }) => relative)
68
- };
69
- }
70
-
71
- if (openingMessage === promptText) {
59
+ const normalizedOpening = normalizePrompt(openingMessage);
60
+ const thirdCopies = otherTexts.filter(({ text }) => normalizePrompt(text).includes(normalizedOpening));
61
+ if (thirdCopies.length > 0) {
62
+ return {
63
+ status: "third-copy",
64
+ ok: false,
65
+ reason: `full opening message also appears in: ${thirdCopies.map(({ relative }) => relative).join(", ")}`,
66
+ openingMessage,
67
+ thirdCopies: thirdCopies.map(({ relative }) => relative)
68
+ };
69
+ }
70
+
71
+ if (openingMessage === promptText) {
72
72
  return {
73
73
  status: "match",
74
74
  ok: true,
@@ -78,7 +78,7 @@ export function assessPromptMirrorTexts(handoffText, promptText, otherTexts = []
78
78
  };
79
79
  }
80
80
 
81
- const normalizedPrompt = normalizePrompt(promptText);
81
+ const normalizedPrompt = normalizePrompt(promptText);
82
82
  if (normalizedOpening === normalizedPrompt) {
83
83
  return {
84
84
  status: "newline-only",
@@ -125,7 +125,7 @@ function findOpeningSectionStart(text) {
125
125
  return headingMatch ? headingMatch.index : -1;
126
126
  }
127
127
 
128
- function firstDiff(left, right) {
128
+ function firstDiff(left, right) {
129
129
  const leftLines = left.split("\n");
130
130
  const rightLines = right.split("\n");
131
131
  const count = Math.max(leftLines.length, rightLines.length);
@@ -139,49 +139,49 @@ function firstDiff(left, right) {
139
139
  }
140
140
  }
141
141
  return null;
142
- }
143
-
144
- function countLiteral(text, token) {
145
- if (!token) return 0;
146
- let count = 0;
147
- let offset = 0;
148
- while ((offset = text.indexOf(token, offset)) >= 0) {
149
- count += 1;
150
- offset += token.length;
151
- }
152
- return count;
153
- }
154
-
155
- function collectCurrentGovernanceTexts(root, excluded) {
156
- const candidates = [
157
- "AGENTS.md",
158
- "CLAUDE.md",
159
- "GEMINI.md",
160
- "dev/SESSION_LOG.md",
161
- "dev/PROJECT_INDEX.md",
162
- "dev/DOC_SYNC_REGISTRY.md",
163
- "dev/RULE_PACKS.md",
164
- "dev/PROJECT_DECISIONS.md"
165
- ];
166
- const rulesDir = path.join(root, "dev", "rules");
167
- try {
168
- for (const entry of readdirSync(rulesDir, { withFileTypes: true })) {
169
- if (entry.isFile() && entry.name.endsWith(".md")) candidates.push(`dev/rules/${entry.name}`);
170
- }
171
- } catch {
172
- // Missing rules are reported by normal doctor checks.
173
- }
174
-
175
- const results = [];
176
- for (const relative of candidates) {
177
- const absolute = path.resolve(root, relative);
178
- if (excluded.has(absolute)) continue;
179
- try {
180
- if (lstatSync(absolute).isSymbolicLink()) continue;
181
- results.push({ relative, text: readFileSync(absolute, "utf8") });
182
- } catch {
183
- // Missing or unreadable files are handled by their owning checks.
184
- }
185
- }
186
- return results;
187
- }
142
+ }
143
+
144
+ function countLiteral(text, token) {
145
+ if (!token) return 0;
146
+ let count = 0;
147
+ let offset = 0;
148
+ while ((offset = text.indexOf(token, offset)) >= 0) {
149
+ count += 1;
150
+ offset += token.length;
151
+ }
152
+ return count;
153
+ }
154
+
155
+ function collectCurrentGovernanceTexts(root, excluded) {
156
+ const candidates = [
157
+ "AGENTS.md",
158
+ "CLAUDE.md",
159
+ "GEMINI.md",
160
+ "dev/SESSION_LOG.md",
161
+ "dev/PROJECT_INDEX.md",
162
+ "dev/DOC_SYNC_REGISTRY.md",
163
+ "dev/RULE_PACKS.md",
164
+ "dev/PROJECT_DECISIONS.md"
165
+ ];
166
+ const rulesDir = path.join(root, "dev", "rules");
167
+ try {
168
+ for (const entry of readdirSync(rulesDir, { withFileTypes: true })) {
169
+ if (entry.isFile() && entry.name.endsWith(".md")) candidates.push(`dev/rules/${entry.name}`);
170
+ }
171
+ } catch {
172
+ // Missing rules are reported by normal doctor checks.
173
+ }
174
+
175
+ const results = [];
176
+ for (const relative of candidates) {
177
+ const absolute = path.resolve(root, relative);
178
+ if (excluded.has(absolute)) continue;
179
+ try {
180
+ if (lstatSync(absolute).isSymbolicLink()) continue;
181
+ results.push({ relative, text: readFileSync(absolute, "utf8") });
182
+ } catch {
183
+ // Missing or unreadable files are handled by their owning checks.
184
+ }
185
+ }
186
+ return results;
187
+ }
package/package.json CHANGED
@@ -1,20 +1,32 @@
1
- {
2
- "name": "@adamchanadam/agent-handoff-kit",
3
- "version": "0.3.40",
4
- "description": "Lightweight agent harness for project memory, handoff, and multi-session continuity.",
5
- "type": "module",
6
- "bin": {
7
- "agent-handoff-kit": "bin/agent-handoff-kit.mjs"
8
- },
9
- "files": [
10
- "bin/",
11
- "runtime-core/",
12
- "packs/",
13
- "README.md",
14
- "LICENSE"
15
- ],
16
- "engines": {
17
- "node": ">=18"
18
- },
19
- "license": "MIT"
20
- }
1
+ {
2
+ "name": "@adamchanadam/agent-handoff-kit",
3
+ "version": "0.3.41",
4
+ "description": "Lightweight agent harness for project memory, handoff, and multi-session continuity.",
5
+ "type": "module",
6
+ "bin": {
7
+ "agent-handoff-kit": "bin/agent-handoff-kit.mjs"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "runtime-core/",
12
+ "packs/",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "doctor": "node bin/agent-handoff-kit.mjs doctor --root .",
18
+ "dry-run": "node bin/agent-handoff-kit.mjs init --dry-run --root .",
19
+ "qa:prototype": "node scripts/check-public-prototype.mjs",
20
+ "qa:public-mirror": "node scripts/build-public-mirror.mjs",
21
+ "qa:packs": "node scripts/check-pack-scenarios.mjs",
22
+ "qa:upgrade": "node scripts/check-upgrade-safety.mjs",
23
+ "qa:release": "node scripts/check-release-readiness.mjs",
24
+ "qa:prompt-mirror": "node scripts/check-prompt-mirror.mjs",
25
+ "qa:fixtures": "node scripts/generate-upgrade-fixtures.mjs",
26
+ "qa:catalog": "node scripts/check-official-origin-catalog.mjs"
27
+ },
28
+ "engines": {
29
+ "node": ">=18"
30
+ },
31
+ "license": "MIT"
32
+ }