@adamchanadam/agent-handoff-kit 0.4.0 → 0.4.1

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.
@@ -1,257 +1,267 @@
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
- const requiredArtifactBoundManagedSegments = Object.freeze([
9
- Object.freeze({ version: "0.3.38", targetRel: "AGENTS.md" }),
10
- Object.freeze({ version: "0.3.41", targetRel: "AGENTS.md" })
11
- ]);
12
-
13
- export const OFFICIAL_ORIGIN_CATALOG_SCHEMA = 1;
14
-
15
- export async function loadOfficialOriginCatalog(catalogPath = defaultCatalogPath) {
16
- const catalog = JSON.parse(await readFile(catalogPath, "utf8"));
17
- validateOfficialOriginCatalog(catalog);
18
- return catalog;
19
- }
20
-
21
- export function validateOfficialOriginCatalog(catalog) {
22
- assertCatalogShape(catalog);
23
- const digestCopy = { ...catalog };
24
- delete digestCopy.catalogDigestSha256;
25
- const expectedDigest = sha256(`${JSON.stringify(digestCopy)}\n`);
26
- if (catalog.catalogDigestSha256 !== expectedDigest) throw new Error("official origin catalog integrity digest mismatch");
27
-
28
- const targets = catalog.installedTargets.map((item) => item.targetRel);
29
- const referenced = new Set();
30
- for (const [version, release] of Object.entries(catalog.releases)) {
31
- if (JSON.stringify(Object.keys(release.manifest)) !== JSON.stringify(targets)) {
32
- throw new Error(`official origin catalog manifest coverage mismatch: ${version}`);
33
- }
34
- for (const [targetRel, entry] of Object.entries(release.manifest)) {
35
- if (entry.state === "absent") continue;
36
- if (entry.state !== "present" || !/^[0-9a-f]{64}$/.test(entry.rawSha256) || !/^[0-9a-f]{64}$/.test(entry.normalizedSha256)) {
37
- throw new Error(`official origin catalog manifest entry invalid: ${version} ${targetRel}`);
38
- }
39
- const content = catalog.contents[entry.contentId];
40
- if (!content || content.targetRel !== targetRel) {
41
- throw new Error(`official origin catalog content target mismatch: ${version} ${targetRel}`);
42
- }
43
- if (entry.canonicalSha256 !== content.canonicalSha256) {
44
- throw new Error(`official origin catalog canonical hash mismatch: ${version} ${targetRel}`);
45
- }
46
- referenced.add(entry.contentId);
47
- }
48
- for (const targetRel of Object.keys(release.managedSegments ?? {})) {
49
- getArtifactBoundManagedSegment({ version, targetRel, catalog });
50
- }
51
- }
52
- for (const required of requiredArtifactBoundManagedSegments) {
53
- if (!getArtifactBoundManagedSegment({ ...required, catalog })) {
54
- throw new Error(`official origin catalog missing required managed segment: ${required.version} ${required.targetRel}`);
55
- }
56
- }
57
-
58
- for (const [contentId, content] of Object.entries(catalog.contents)) {
59
- if (contentId !== sha256(`${content.targetRel}\0${content.text}`)) {
60
- throw new Error(`official origin catalog content ID mismatch: ${contentId}`);
61
- }
62
- if (content.canonicalSha256 !== sha256(canonicalizeOfficialText(content.targetRel, content.text))) {
63
- throw new Error(`official origin catalog content hash mismatch: ${contentId}`);
64
- }
65
- if (!referenced.has(contentId)) throw new Error(`official origin catalog has orphan content: ${contentId}`);
66
- }
67
- return true;
68
- }
69
-
70
- export function identifyOfficialOrigin({ targetRel, text, bytes = null, catalog }) {
71
- assertCatalogShape(catalog);
72
- const sourceText = String(text);
73
- const rawBytes = bytes == null ? Buffer.from(sourceText, "utf8") : Buffer.from(bytes);
74
- const rawSha256 = createHash("sha256").update(rawBytes).digest("hex");
75
- const normalizedSha256 = sha256(normalizeNewlines(sourceText));
76
- const canonicalSha256 = sha256(canonicalizeOfficialText(targetRel, sourceText));
77
- const rawExactVersions = [];
78
- const exactVersions = [];
79
- const canonicalVersions = [];
80
-
81
- for (const [version, release] of Object.entries(catalog.releases)) {
82
- const entry = release.manifest[targetRel];
83
- if (!entry || entry.state !== "present") continue;
84
- if (entry.rawSha256 === rawSha256) rawExactVersions.push(version);
85
- if (entry.normalizedSha256 === normalizedSha256) exactVersions.push(version);
86
- else if (entry.canonicalSha256 === canonicalSha256) canonicalVersions.push(version);
87
- }
88
-
89
- return {
90
- targetRel,
91
- rawSha256,
92
- rawExact: rawExactVersions.length > 0,
93
- rawExactVersions,
94
- normalizedSha256,
95
- canonicalSha256,
96
- exact: exactVersions.length > 0,
97
- exactVersions,
98
- canonicalVersions
99
- };
100
- }
101
-
102
- export function getOfficialBaseline({ version, targetRel, catalog, root = null }) {
103
- assertCatalogShape(catalog);
104
- const release = catalog.releases[stripVersionPrefix(version)];
105
- if (!release) return null;
106
- const entry = release.manifest[targetRel];
107
- if (!entry) return null;
108
- if (entry.state === "absent") return { state: "absent", version: stripVersionPrefix(version), targetRel };
109
- const content = catalog.contents[entry.contentId];
110
- if (!content || content.targetRel !== targetRel) {
111
- throw new Error(`official origin catalog content mismatch: ${version} ${targetRel}`);
112
- }
113
- return {
114
- state: "present",
115
- version: stripVersionPrefix(version),
116
- targetRel,
117
- text: materializeOfficialText(targetRel, content.text, { version: stripVersionPrefix(version), root }),
118
- normalizedSha256: entry.normalizedSha256,
119
- canonicalSha256: entry.canonicalSha256
120
- };
121
- }
122
-
123
- // A managed segment is deliberately narrower than a whole-file catalog
124
- // identity. It exists only when the release is tied to an npm artifact and
125
- // its raw source plus transformed core bytes are recorded in this catalog.
126
- // Markers, filenames, headings, and language never grant this authority.
127
- export function getArtifactBoundManagedSegment({ version, targetRel, catalog }) {
128
- assertCatalogShape(catalog);
129
- const normalizedVersion = stripVersionPrefix(version);
130
- const release = catalog.releases[normalizedVersion];
131
- const segment = release?.managedSegments?.[targetRel];
132
- if (!segment) return null;
133
- const npm = release.source?.npm;
134
- if (!npm || typeof npm.spec !== "string" || !/^[a-f0-9]{40}$/.test(npm.shasum)
135
- || typeof npm.integrity !== "string" || !npm.integrity.startsWith("sha512-")) {
136
- throw new Error(`official origin catalog managed segment has no artifact identity: ${normalizedVersion} ${targetRel}`);
137
- }
138
- if (!segment || typeof segment !== "object" || Array.isArray(segment)
139
- || segment.sourceRel !== "runtime-core/AGENTS.core.md"
140
- || segment.transform?.kind !== "utf8-trim-wrapped-managed-core"
141
- || typeof segment.transform.beginMarker !== "string" || !segment.transform.beginMarker
142
- || typeof segment.transform.endMarker !== "string" || !segment.transform.endMarker
143
- || !validSegmentByteIdentity(segment.artifactSource)
144
- || !validSegmentByteIdentity(segment.transform.core)) {
145
- throw new Error(`official origin catalog managed segment is invalid: ${normalizedVersion} ${targetRel}`);
146
- }
147
- return Object.freeze({
148
- version: normalizedVersion,
149
- targetRel,
150
- sourceRel: segment.sourceRel,
151
- artifact: Object.freeze({ spec: npm.spec, shasum: npm.shasum, integrity: npm.integrity }),
152
- artifactSource: Object.freeze({ ...segment.artifactSource }),
153
- transform: Object.freeze({
154
- kind: segment.transform.kind,
155
- beginMarker: segment.transform.beginMarker,
156
- endMarker: segment.transform.endMarker,
157
- core: Object.freeze({ ...segment.transform.core })
158
- })
159
- });
160
- }
161
-
162
- export function normalizeNewlines(text) {
163
- return String(text).replace(/\r\n?/g, "\n");
164
- }
165
-
166
- export function canonicalizeOfficialText(targetRel, text) {
167
- let normalized = normalizeNewlines(text);
168
- if (targetRel === "dev/PROJECT_INDEX.md") {
169
- normalized = normalized.replace(
170
- /^(\|\s*Agent Handoff Kit template version\s*\|)\s*[^|\n]+?(\s*\|.*)$/m,
171
- "$1 <VERSION>$2"
172
- );
173
- }
174
- if (targetRel === "START_NEXT_SESSION_PROMPT.txt") {
175
- normalized = canonicalizeOpeningRootLine(normalized);
176
- }
177
- if (targetRel === "dev/SESSION_HANDOFF.md") {
178
- normalized = canonicalizeHandoffOpeningRoot(normalized);
179
- }
180
- return normalized;
181
- }
182
-
183
- export function materializeOfficialText(targetRel, text, { version = null, root = null } = {}) {
184
- let materialized = normalizeNewlines(text);
185
- if (targetRel === "dev/PROJECT_INDEX.md" && version) {
186
- materialized = materialized.replace(
187
- /^(\|\s*Agent Handoff Kit template version\s*\|)\s*<VERSION>(\s*\|.*)$/m,
188
- `$1 ${stripVersionPrefix(version)}$2`
189
- );
190
- }
191
- if (root && targetRel === "START_NEXT_SESSION_PROMPT.txt") {
192
- materialized = materializeOpeningRootLine(materialized, root);
193
- }
194
- if (root && targetRel === "dev/SESSION_HANDOFF.md") {
195
- materialized = materializeHandoffOpeningRoot(materialized, root);
196
- }
197
- return materialized;
198
- }
199
-
200
- export function sha256(text) {
201
- return createHash("sha256").update(text, "utf8").digest("hex");
202
- }
203
-
204
- function canonicalizeOpeningRootLine(text) {
205
- return text.replace(/^(Work in )[^\n]+?(\.(?: Read AGENTS\.md, then dev\/SESSION_HANDOFF\.md\.)?)$/m, "$1<ROOT>$2");
206
- }
207
-
208
- function canonicalizeHandoffOpeningRoot(text) {
209
- const marker = "<!-- ack:section:next-session-opening-message -->";
210
- const markerIndex = text.indexOf(marker);
211
- if (markerIndex < 0) return text;
212
- const fenceStart = text.indexOf("```text\n", markerIndex);
213
- if (fenceStart < 0) return text;
214
- const contentStart = fenceStart + "```text\n".length;
215
- const fenceEnd = text.indexOf("\n```", contentStart);
216
- if (fenceEnd < 0) return text;
217
- const before = text.slice(0, contentStart);
218
- const opening = canonicalizeOpeningRootLine(text.slice(contentStart, fenceEnd));
219
- return `${before}${opening}${text.slice(fenceEnd)}`;
220
- }
221
-
222
- function materializeOpeningRootLine(text, root) {
223
- return text.replace(/^(Work in )<ROOT>(\.(?: Read AGENTS\.md, then dev\/SESSION_HANDOFF\.md\.)?)$/m, `$1${root}$2`);
224
- }
225
-
226
- function materializeHandoffOpeningRoot(text, root) {
227
- const marker = "<!-- ack:section:next-session-opening-message -->";
228
- const markerIndex = text.indexOf(marker);
229
- if (markerIndex < 0) return text;
230
- const fenceStart = text.indexOf("```text\n", markerIndex);
231
- if (fenceStart < 0) return text;
232
- const contentStart = fenceStart + "```text\n".length;
233
- const fenceEnd = text.indexOf("\n```", contentStart);
234
- if (fenceEnd < 0) return text;
235
- const before = text.slice(0, contentStart);
236
- const opening = materializeOpeningRootLine(text.slice(contentStart, fenceEnd), root);
237
- return `${before}${opening}${text.slice(fenceEnd)}`;
238
- }
239
-
240
- function stripVersionPrefix(version) {
241
- return String(version ?? "").replace(/^v/, "");
242
- }
243
-
244
- function validSegmentByteIdentity(value) {
245
- return Boolean(value && typeof value === "object" && !Array.isArray(value)
246
- && /^[a-f0-9]{64}$/.test(value.sha256)
247
- && Number.isInteger(value.bytes) && value.bytes >= 0);
248
- }
249
-
250
- function assertCatalogShape(catalog) {
251
- if (!catalog || catalog.schemaVersion !== OFFICIAL_ORIGIN_CATALOG_SCHEMA) {
252
- throw new Error(`unsupported official origin catalog schema: ${catalog?.schemaVersion ?? "missing"}`);
253
- }
254
- if (!catalog.releases || !catalog.contents || !Array.isArray(catalog.installedTargets)) {
255
- throw new Error("official origin catalog is incomplete");
256
- }
257
- }
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
+ const requiredArtifactBoundManagedSegments = Object.freeze([
9
+ Object.freeze({ version: "0.3.38", targetRel: "AGENTS.md" }),
10
+ Object.freeze({ version: "0.3.41", targetRel: "AGENTS.md" })
11
+ ]);
12
+
13
+ export const OFFICIAL_ORIGIN_CATALOG_SCHEMA = 1;
14
+
15
+ export async function loadOfficialOriginCatalog(catalogPath = defaultCatalogPath) {
16
+ const catalog = JSON.parse(await readFile(catalogPath, "utf8"));
17
+ validateOfficialOriginCatalog(catalog);
18
+ return catalog;
19
+ }
20
+
21
+ export function validateOfficialOriginCatalog(catalog) {
22
+ assertCatalogShape(catalog);
23
+ const digestCopy = { ...catalog };
24
+ delete digestCopy.catalogDigestSha256;
25
+ const expectedDigest = sha256(`${JSON.stringify(digestCopy)}\n`);
26
+ if (catalog.catalogDigestSha256 !== expectedDigest) throw new Error("official origin catalog integrity digest mismatch");
27
+
28
+ const targets = catalog.installedTargets.map((item) => item.targetRel);
29
+ const referenced = new Set();
30
+ for (const [version, release] of Object.entries(catalog.releases)) {
31
+ if (JSON.stringify(Object.keys(release.manifest)) !== JSON.stringify(targets)) {
32
+ throw new Error(`official origin catalog manifest coverage mismatch: ${version}`);
33
+ }
34
+ for (const [targetRel, entry] of Object.entries(release.manifest)) {
35
+ if (entry.state === "absent") continue;
36
+ if (entry.state !== "present" || !/^[0-9a-f]{64}$/.test(entry.rawSha256) || !/^[0-9a-f]{64}$/.test(entry.normalizedSha256)) {
37
+ throw new Error(`official origin catalog manifest entry invalid: ${version} ${targetRel}`);
38
+ }
39
+ const content = catalog.contents[entry.contentId];
40
+ if (!content || content.targetRel !== targetRel) {
41
+ throw new Error(`official origin catalog content target mismatch: ${version} ${targetRel}`);
42
+ }
43
+ if (entry.canonicalSha256 !== content.canonicalSha256) {
44
+ throw new Error(`official origin catalog canonical hash mismatch: ${version} ${targetRel}`);
45
+ }
46
+ referenced.add(entry.contentId);
47
+ }
48
+ for (const targetRel of Object.keys(release.managedSegments ?? {})) {
49
+ getArtifactBoundManagedSegment({ version, targetRel, catalog });
50
+ }
51
+ }
52
+ for (const required of requiredArtifactBoundManagedSegments) {
53
+ if (!getArtifactBoundManagedSegment({ ...required, catalog })) {
54
+ throw new Error(`official origin catalog missing required managed segment: ${required.version} ${required.targetRel}`);
55
+ }
56
+ }
57
+
58
+ for (const [contentId, content] of Object.entries(catalog.contents)) {
59
+ if (contentId !== sha256(`${content.targetRel}\0${content.text}`)) {
60
+ throw new Error(`official origin catalog content ID mismatch: ${contentId}`);
61
+ }
62
+ if (content.canonicalSha256 !== sha256(canonicalizeOfficialText(content.targetRel, content.text))) {
63
+ throw new Error(`official origin catalog content hash mismatch: ${contentId}`);
64
+ }
65
+ if (!referenced.has(contentId)) throw new Error(`official origin catalog has orphan content: ${contentId}`);
66
+ }
67
+ for (const [version, entry] of Object.entries(catalog.generatedShortcuts ?? {})) {
68
+ if (!/^\d+\.\d+\.\d+$/.test(version) || entry.npm?.spec !== catalog.packageName + '@' + version
69
+ || !/^[a-f0-9]{40}$/.test(entry.npm?.shasum) || !entry.npm?.integrity?.startsWith('sha512-')
70
+ || !/^[a-f0-9]{64}$/.test(entry.npm?.tarballSha256) || !/^[a-f0-9]{64}$/.test(entry.generatorSha256)
71
+ || !entry.files || !Object.keys(entry.files).length) throw Error('invalid official shortcut artifact: ' + version);
72
+ for (const [file, digest] of Object.entries(entry.files)) {
73
+ if (!/^(?:dev\/handoff-kit\/(?:launch|open|server|projection|dashboard|project-version|assets)\.mjs|\.(?:agents|claude)\/skills\/handoff-kit-[a-z]+\/(?:SKILL\.md|agents\/openai\.yaml)|\.gemini\/commands\/handoff-kit-[a-z]+\.toml)$/.test(file)
74
+ || !/^[a-f0-9]{64}$/.test(digest)) throw Error('invalid official shortcut path/hash: ' + version);
75
+ }
76
+ }
77
+ return true;
78
+ }
79
+
80
+ export function identifyOfficialOrigin({ targetRel, text, bytes = null, catalog }) {
81
+ assertCatalogShape(catalog);
82
+ const sourceText = String(text);
83
+ const rawBytes = bytes == null ? Buffer.from(sourceText, "utf8") : Buffer.from(bytes);
84
+ const rawSha256 = createHash("sha256").update(rawBytes).digest("hex");
85
+ const normalizedSha256 = sha256(normalizeNewlines(sourceText));
86
+ const canonicalSha256 = sha256(canonicalizeOfficialText(targetRel, sourceText));
87
+ const rawExactVersions = [];
88
+ const exactVersions = [];
89
+ const canonicalVersions = [];
90
+
91
+ for (const [version, release] of Object.entries(catalog.releases)) {
92
+ const entry = release.manifest[targetRel];
93
+ if (!entry || entry.state !== "present") continue;
94
+ if (entry.rawSha256 === rawSha256) rawExactVersions.push(version);
95
+ if (entry.normalizedSha256 === normalizedSha256) exactVersions.push(version);
96
+ else if (entry.canonicalSha256 === canonicalSha256) canonicalVersions.push(version);
97
+ }
98
+
99
+ return {
100
+ targetRel,
101
+ rawSha256,
102
+ rawExact: rawExactVersions.length > 0,
103
+ rawExactVersions,
104
+ normalizedSha256,
105
+ canonicalSha256,
106
+ exact: exactVersions.length > 0,
107
+ exactVersions,
108
+ canonicalVersions
109
+ };
110
+ }
111
+
112
+ export function getOfficialBaseline({ version, targetRel, catalog, root = null }) {
113
+ assertCatalogShape(catalog);
114
+ const release = catalog.releases[stripVersionPrefix(version)];
115
+ if (!release) return null;
116
+ const entry = release.manifest[targetRel];
117
+ if (!entry) return null;
118
+ if (entry.state === "absent") return { state: "absent", version: stripVersionPrefix(version), targetRel };
119
+ const content = catalog.contents[entry.contentId];
120
+ if (!content || content.targetRel !== targetRel) {
121
+ throw new Error(`official origin catalog content mismatch: ${version} ${targetRel}`);
122
+ }
123
+ return {
124
+ state: "present",
125
+ version: stripVersionPrefix(version),
126
+ targetRel,
127
+ text: materializeOfficialText(targetRel, content.text, { version: stripVersionPrefix(version), root }),
128
+ normalizedSha256: entry.normalizedSha256,
129
+ canonicalSha256: entry.canonicalSha256
130
+ };
131
+ }
132
+
133
+ // A managed segment is deliberately narrower than a whole-file catalog
134
+ // identity. It exists only when the release is tied to an npm artifact and
135
+ // its raw source plus transformed core bytes are recorded in this catalog.
136
+ // Markers, filenames, headings, and language never grant this authority.
137
+ export function getArtifactBoundManagedSegment({ version, targetRel, catalog }) {
138
+ assertCatalogShape(catalog);
139
+ const normalizedVersion = stripVersionPrefix(version);
140
+ const release = catalog.releases[normalizedVersion];
141
+ const segment = release?.managedSegments?.[targetRel];
142
+ if (!segment) return null;
143
+ const npm = release.source?.npm;
144
+ if (!npm || typeof npm.spec !== "string" || !/^[a-f0-9]{40}$/.test(npm.shasum)
145
+ || typeof npm.integrity !== "string" || !npm.integrity.startsWith("sha512-")) {
146
+ throw new Error(`official origin catalog managed segment has no artifact identity: ${normalizedVersion} ${targetRel}`);
147
+ }
148
+ if (!segment || typeof segment !== "object" || Array.isArray(segment)
149
+ || segment.sourceRel !== "runtime-core/AGENTS.core.md"
150
+ || segment.transform?.kind !== "utf8-trim-wrapped-managed-core"
151
+ || typeof segment.transform.beginMarker !== "string" || !segment.transform.beginMarker
152
+ || typeof segment.transform.endMarker !== "string" || !segment.transform.endMarker
153
+ || !validSegmentByteIdentity(segment.artifactSource)
154
+ || !validSegmentByteIdentity(segment.transform.core)) {
155
+ throw new Error(`official origin catalog managed segment is invalid: ${normalizedVersion} ${targetRel}`);
156
+ }
157
+ return Object.freeze({
158
+ version: normalizedVersion,
159
+ targetRel,
160
+ sourceRel: segment.sourceRel,
161
+ artifact: Object.freeze({ spec: npm.spec, shasum: npm.shasum, integrity: npm.integrity }),
162
+ artifactSource: Object.freeze({ ...segment.artifactSource }),
163
+ transform: Object.freeze({
164
+ kind: segment.transform.kind,
165
+ beginMarker: segment.transform.beginMarker,
166
+ endMarker: segment.transform.endMarker,
167
+ core: Object.freeze({ ...segment.transform.core })
168
+ })
169
+ });
170
+ }
171
+
172
+ export function normalizeNewlines(text) {
173
+ return String(text).replace(/\r\n?/g, "\n");
174
+ }
175
+
176
+ export function canonicalizeOfficialText(targetRel, text) {
177
+ let normalized = normalizeNewlines(text);
178
+ if (targetRel === "dev/PROJECT_INDEX.md") {
179
+ normalized = normalized.replace(
180
+ /^(\|\s*Agent Handoff Kit template version\s*\|)\s*[^|\n]+?(\s*\|.*)$/m,
181
+ "$1 <VERSION>$2"
182
+ );
183
+ }
184
+ if (targetRel === "START_NEXT_SESSION_PROMPT.txt") {
185
+ normalized = canonicalizeOpeningRootLine(normalized);
186
+ }
187
+ if (targetRel === "dev/SESSION_HANDOFF.md") {
188
+ normalized = canonicalizeHandoffOpeningRoot(normalized);
189
+ }
190
+ return normalized;
191
+ }
192
+
193
+ export function materializeOfficialText(targetRel, text, { version = null, root = null } = {}) {
194
+ let materialized = normalizeNewlines(text);
195
+ if (targetRel === "dev/PROJECT_INDEX.md" && version) {
196
+ materialized = materialized.replace(
197
+ /^(\|\s*Agent Handoff Kit template version\s*\|)\s*<VERSION>(\s*\|.*)$/m,
198
+ `$1 ${stripVersionPrefix(version)}$2`
199
+ );
200
+ }
201
+ if (root && targetRel === "START_NEXT_SESSION_PROMPT.txt") {
202
+ materialized = materializeOpeningRootLine(materialized, root);
203
+ }
204
+ if (root && targetRel === "dev/SESSION_HANDOFF.md") {
205
+ materialized = materializeHandoffOpeningRoot(materialized, root);
206
+ }
207
+ return materialized;
208
+ }
209
+
210
+ export function sha256(text) {
211
+ return createHash("sha256").update(text, "utf8").digest("hex");
212
+ }
213
+
214
+ function canonicalizeOpeningRootLine(text) {
215
+ return text.replace(/^(Work in )[^\n]+?(\.(?: Read AGENTS\.md, then dev\/SESSION_HANDOFF\.md\.)?)$/m, "$1<ROOT>$2");
216
+ }
217
+
218
+ function canonicalizeHandoffOpeningRoot(text) {
219
+ const marker = "<!-- ack:section:next-session-opening-message -->";
220
+ const markerIndex = text.indexOf(marker);
221
+ if (markerIndex < 0) return text;
222
+ const fenceStart = text.indexOf("```text\n", markerIndex);
223
+ if (fenceStart < 0) return text;
224
+ const contentStart = fenceStart + "```text\n".length;
225
+ const fenceEnd = text.indexOf("\n```", contentStart);
226
+ if (fenceEnd < 0) return text;
227
+ const before = text.slice(0, contentStart);
228
+ const opening = canonicalizeOpeningRootLine(text.slice(contentStart, fenceEnd));
229
+ return `${before}${opening}${text.slice(fenceEnd)}`;
230
+ }
231
+
232
+ function materializeOpeningRootLine(text, root) {
233
+ return text.replace(/^(Work in )<ROOT>(\.(?: Read AGENTS\.md, then dev\/SESSION_HANDOFF\.md\.)?)$/m, `$1${root}$2`);
234
+ }
235
+
236
+ function materializeHandoffOpeningRoot(text, root) {
237
+ const marker = "<!-- ack:section:next-session-opening-message -->";
238
+ const markerIndex = text.indexOf(marker);
239
+ if (markerIndex < 0) return text;
240
+ const fenceStart = text.indexOf("```text\n", markerIndex);
241
+ if (fenceStart < 0) return text;
242
+ const contentStart = fenceStart + "```text\n".length;
243
+ const fenceEnd = text.indexOf("\n```", contentStart);
244
+ if (fenceEnd < 0) return text;
245
+ const before = text.slice(0, contentStart);
246
+ const opening = materializeOpeningRootLine(text.slice(contentStart, fenceEnd), root);
247
+ return `${before}${opening}${text.slice(fenceEnd)}`;
248
+ }
249
+
250
+ function stripVersionPrefix(version) {
251
+ return String(version ?? "").replace(/^v/, "");
252
+ }
253
+
254
+ function validSegmentByteIdentity(value) {
255
+ return Boolean(value && typeof value === "object" && !Array.isArray(value)
256
+ && /^[a-f0-9]{64}$/.test(value.sha256)
257
+ && Number.isInteger(value.bytes) && value.bytes >= 0);
258
+ }
259
+
260
+ function assertCatalogShape(catalog) {
261
+ if (!catalog || catalog.schemaVersion !== OFFICIAL_ORIGIN_CATALOG_SCHEMA) {
262
+ throw new Error(`unsupported official origin catalog schema: ${catalog?.schemaVersion ?? "missing"}`);
263
+ }
264
+ if (!catalog.releases || !catalog.contents || !Array.isArray(catalog.installedTargets)) {
265
+ throw new Error("official origin catalog is incomplete");
266
+ }
267
+ }
@@ -0,0 +1,6 @@
1
+ // Source assets; the normal installer materializes these same bytes locally.
2
+ import {readFileSync} from 'node:fs';
3
+ export const assetNames=Object.freeze(['index.html','styles.css','renderer.js','agent-handoff-kit-logo2-256.png','dashboard-hero.png','icons.svg','ICON-LICENSE.txt']);
4
+ export const installed=false;
5
+ export const runtimeVersion=JSON.parse(readFileSync(new URL('../../package.json',import.meta.url),'utf8')).version;
6
+ export function assetBytes(name){if(!assetNames.includes(name))throw Error('Unknown progress asset');return readFileSync(new URL(name,import.meta.url));}
@@ -3,7 +3,7 @@ import {openSync,closeSync,readSync,fstatSync,statSync,realpathSync,existsSync}
3
3
  import path from 'node:path';
4
4
  import {createHash} from 'node:crypto';
5
5
  import {readBounded,signature,markdown,safe,logEntry} from './projection.mjs';
6
- import {parseProjectIndexTemplateVersion} from '../upgrade-inventory.mjs';
6
+ import {parseProjectIndexTemplateVersion} from './project-version.mjs';
7
7
 
8
8
  export const DASH_LIMITS=Object.freeze({document:1024*1024,metadata:512*1024,items:128,documents:160,historyBytes:256*1024,historyFiles:4,historyPage:20,entryBytes:64*1024,cursors:32});
9
9
  const digest=s=>createHash('sha256').update(s).digest('hex');
@@ -21,7 +21,10 @@
21
21
  <p class="scope-note" data-i18n="dateBoundary">日期只篩選歷程,目前未完事項不受影響。</p><div id="history-status" class="scope-note" role="status"></div><div id="history-list" class="timeline"></div><button id="history-more" class="secondary" hidden data-i18n="loadMore">載入更多紀錄</button>
22
22
  </section>
23
23
  <section id="documents-view" class="view" hidden aria-labelledby="documents-title"><header class="view-header"><div><p class="eyebrow" id="documents-project"></p><h1 id="documents-title" data-i18n="documentsHeading">文件各司其職</h1><p data-i18n="documentsIntro">點選文件,查看用途、來源與相關紀錄。</p></div><div class="segmented"><button id="map-mode" aria-pressed="true" data-i18n="map">地圖</button><button id="list-mode" aria-pressed="false" data-i18n="list">清單</button></div></header><p id="document-status" class="scope-note"></p><div id="document-map" class="document-map"></div><div id="map-detail" class="map-detail panel"></div><div id="document-list" class="document-list" hidden></div><p class="scope-note" data-i18n="mapBoundary">連線表示已記錄的文件角色或關係;不代表已驗收。</p></section>
24
- <footer><p data-i18n="boundary">依已保存紀錄更新;未保存的工作不會出現在這裏。</p><button class="quiet" data-action="sources" data-i18n="sources">資料依據</button></footer>
24
+ <footer>
25
+ <div class="footer-note"><p data-i18n="boundary">依已保存紀錄更新;未保存的工作不會出現在這裏。</p><button class="quiet" data-action="sources" data-i18n="sources">資料依據</button></div>
26
+ <div class="footer-credit"><div class="creator"><span data-i18n="creatorRole">作者|AI 生活策展人</span><strong>Adam Chan</strong></div><div class="creator-links" role="group" aria-label="作者與專案 / Creator and project"><a class="creator-link" href="https://www.facebook.com/chan.adam" target="_blank" rel="noopener noreferrer">Facebook</a><a class="creator-link" href="https://github.com/Adamchanadam/agent-handoff-kit" target="_blank" rel="noopener noreferrer">Agent Handoff Kit · GitHub</a></div></div>
27
+ </footer>
25
28
  <noscript><p class="warning">請啟用 JavaScript 以讀取紀錄。 / Please enable JavaScript to load records.</p></noscript>
26
29
  </main>
27
30
  <dialog id="drawer" aria-labelledby="drawer-title"><header><div><p id="drawer-kicker" class="eyebrow"></p><h2 id="drawer-title"></h2></div><button id="close" class="icon-button" aria-label="關閉 / Close"><svg aria-hidden="true"><use href="icons.svg#close"></use></svg></button></header><div id="drawer-content"></div></dialog><div id="announcement" class="sr-only" role="status" aria-live="polite"></div>
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ // The installed progress entry has no npm, network acquisition or write step.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+
7
+ try {
8
+ const args=process.argv.slice(2),options={port:0,openBrowser:true};let serve=false,version;
9
+ const seen=new Set();
10
+ for(let i=0;i<args.length;i++){
11
+ const arg=args[i];if(seen.has(arg))throw Error('Duplicate progress option');seen.add(arg);
12
+ if(arg==='--no-open')options.openBrowser=false;
13
+ else if(arg==='--serve')serve=true;
14
+ else if(['--root','--port','--version'].includes(arg)){
15
+ const value=args[++i];if(!value||value.startsWith('--'))throw Error('Missing progress option value');
16
+ if(arg==='--root')options.root=path.resolve(value);
17
+ if(arg==='--port'){if(!/^\d{1,5}$/.test(value)||Number(value)>65535)throw Error('Invalid progress port');options.port=Number(value);}
18
+ if(arg==='--version'){if(!/^\d+\.\d+\.\d+$/.test(value))throw Error('Invalid progress version');version=value;}
19
+ }else throw Error('Unknown progress option');
20
+ }
21
+ if(!options.root)throw Error('Select the project with --root');
22
+ const root=options.root;
23
+ if(path.relative(fs.realpathSync(root),root)!=='')throw Error('Linked project root is not supported');
24
+ for(const rel of ['dev','dev/governance_migrations','dev/governance_migrations/.upgrade.lock']){
25
+ const target=path.join(root,rel);let st;try{st=fs.lstatSync(target);}catch(e){if(e.code==='ENOENT')continue;throw e;}
26
+ if(st.isSymbolicLink())throw Error('Linked project state is not supported');
27
+ if(rel.endsWith('.upgrade.lock'))throw Error('Upgrade lock exists; finish upgrade recovery before opening progress');
28
+ if(!st.isDirectory())throw Error('Invalid project state directory');
29
+ }
30
+ const directory=path.dirname(fileURLToPath(import.meta.url));
31
+ if(path.relative(fs.realpathSync(directory),directory)!=='')throw Error('Linked progress program is not supported');
32
+ for(const name of ['assets','open','server','projection','dashboard','project-version','launch']){
33
+ const st=fs.lstatSync(path.join(directory,name+'.mjs'));if(st.isSymbolicLink()||!st.isFile())throw Error('Progress program is incomplete or linked');
34
+ }
35
+ const assets=await import('./assets.mjs');
36
+ if(assets.installed&&path.relative(root,path.resolve(directory,'../..'))!=='')throw Error('Progress entry belongs to a different project');
37
+ options.version=version??assets.runtimeVersion;
38
+ if(serve){const {startProgress}=await import('./server.mjs');await startProgress(options);}
39
+ else{const {openProgress}=await import('./open.mjs');const result=await openProgress(options);console.log(JSON.stringify(result));}
40
+ }catch(e){console.error('Progress could not open: '+e.message);process.exitCode=1;}