@adamchanadam/agent-handoff-kit 0.3.52 → 0.3.53

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,12 +1,13 @@
1
1
  import { createHash } from "node:crypto";
2
- import { lstat, readdir, readFile, realpath } from "node:fs/promises";
3
- import path from "node:path";
4
- import { installedFileContracts, upgradeStateFileContracts, INSTALLED_FILE_CONTRACT_SCHEMA } from "./installed-file-contract.mjs";
5
- import { loadOfficialOriginCatalog } from "./official-origin-catalog.mjs";
2
+ import { lstat, readdir, readFile, realpath } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { installedFileContracts, upgradeStateFileContracts, INSTALLED_FILE_CONTRACT_SCHEMA } from "./installed-file-contract.mjs";
5
+ import { loadOfficialOriginCatalog } from "./official-origin-catalog.mjs";
6
+ import { FORMAL_USER_RULES_ENTRY_ANCHOR, readFormalUserRules } from "./user-rules-router.mjs";
6
7
 
7
- export const UPGRADE_INVENTORY_SCHEMA = 1;
8
- export const GATE5_FROZEN_SET_SCHEMA = 2;
9
- export const GATE5_ROOT_SOURCE_INVENTORY_SCHEMA = 1;
8
+ export const UPGRADE_INVENTORY_SCHEMA = 1;
9
+ export const GATE5_FROZEN_SET_SCHEMA = 2;
10
+ export const GATE5_ROOT_SOURCE_INVENTORY_SCHEMA = 1;
10
11
 
11
12
  const formalEntryTargets = Object.freeze([
12
13
  "AGENTS.md",
@@ -15,20 +16,21 @@ const formalEntryTargets = Object.freeze([
15
16
  "START_NEXT_SESSION_PROMPT.txt"
16
17
  ]);
17
18
 
18
- const dynamicDirectories = Object.freeze([
19
- { relative: "dev/governance_migrations", classification: "transaction-state" },
19
+ const transactionRegistryRoot = "dev/governance_migrations";
20
+
21
+ const archiveDirectories = Object.freeze([
20
22
  { relative: "dev/SESSION_LOG_archive", classification: "session-log-archive" },
21
23
  { relative: "dev/session_log_archive", classification: "legacy-session-log-archive" }
22
24
  ]);
23
-
24
- export function gate5ItemRequiresSourceConservation(item) {
25
- return Boolean(item && Array.isArray(item.classifications)
26
- && item.classifications.some((classification) => classification !== "root-source"));
27
- }
28
-
29
- export function gate5SourceConservationItems(frozen) {
30
- return Object.freeze((frozen?.items ?? []).filter(gate5ItemRequiresSourceConservation));
31
- }
25
+
26
+ export function gate5ItemRequiresSourceConservation(item) {
27
+ return Boolean(item && Array.isArray(item.classifications)
28
+ && item.classifications.some((classification) => classification !== "root-source"));
29
+ }
30
+
31
+ export function gate5SourceConservationItems(frozen) {
32
+ return Object.freeze((frozen?.items ?? []).filter(gate5ItemRequiresSourceConservation));
33
+ }
32
34
 
33
35
  /**
34
36
  * Builds a read-only, hash-bound description of the Kit data that an upgrade
@@ -47,17 +49,15 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
47
49
  throw new Error("upgrade inventory root must be a real directory");
48
50
  }
49
51
  const realRoot = await realpath(rootPath);
50
- const entries = new Map();
51
- const blockers = [];
52
- const queue = [];
53
- const queued = new Set();
52
+ const entries = new Map();
53
+ const blockers = [];
54
54
 
55
55
  const addBlocker = (relative, reason) => {
56
56
  const key = `${relative}\0${reason}`;
57
57
  if (!blockers.some((item) => `${item.path}\0${item.reason}` === key)) blockers.push({ path: relative, reason });
58
58
  };
59
59
 
60
- async function addFile(relative, classification, reachability = null, enqueueForReferences = false) {
60
+ async function addFile(relative, classification, reachability = null) {
61
61
  const normalized = normalizeProjectRelative(relative);
62
62
  if (!normalized) {
63
63
  addBlocker(String(relative), "reference escapes the selected project root");
@@ -102,41 +102,36 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
102
102
  }
103
103
  entry.classifications.add(classification);
104
104
  if (reachability) entry.reachability.set(`${reachability.from}\0${reachability.via}`, reachability);
105
- if (enqueueForReferences && entry.text != null && !queued.has(normalized)) {
106
- queued.add(normalized);
107
- queue.push(entry);
108
- }
109
- return entry;
110
- }
105
+ return entry;
106
+ }
111
107
 
112
108
  for (const contract of contracts) {
113
109
  const isFormalEntry = formalEntryTargets.includes(contract.targetRel);
114
110
  await addFile(
115
- contract.targetRel,
116
- "managed-contract",
117
- isFormalEntry ? { from: "formal-entry", via: contract.targetRel } : { from: "managed-contract", via: contract.targetRel },
118
- true
119
- );
120
- }
121
-
122
- for (const directory of dynamicDirectories) {
123
- await addTree(directory.relative, directory.classification);
124
- }
125
-
126
- for (const contract of contracts) {
127
- if (!contract.targetRel.startsWith("dev/rules/")) continue;
128
- const legacy = `dev/${path.posix.basename(contract.targetRel)}`;
129
- await addFile(legacy, "legacy-rule-location", { from: "legacy-location", via: legacy }, true);
130
- }
131
-
132
- while (queue.length > 0) {
133
- const source = queue.shift();
134
- for (const reference of extractExplicitLocalReferences(source.text)) {
135
- const target = normalizeProjectRelative(reference.path);
136
- if (!target) continue;
137
- await addFile(target, "formal-reference", { from: source.path, via: reference.via }, true);
138
- }
139
- }
111
+ contract.targetRel,
112
+ "managed-contract",
113
+ isFormalEntry ? { from: "formal-entry", via: contract.targetRel } : { from: "managed-contract", via: contract.targetRel }
114
+ );
115
+ }
116
+
117
+ await addTransactionRegistry(transactionRegistryRoot);
118
+
119
+ for (const directory of archiveDirectories) {
120
+ await addTree(directory.relative, directory.classification);
121
+ }
122
+
123
+ const agentsEntry = entries.get("AGENTS.md");
124
+ if (agentsEntry?.text?.includes(FORMAL_USER_RULES_ENTRY_ANCHOR)) {
125
+ try {
126
+ const formal = await readFormalUserRules({ root: rootPath, allowActiveTransaction: true });
127
+ await addFile(formal.routerPath, "formal-user-rules-router", { from: formal.entryPath, via: formal.routerPath });
128
+ for (const rule of formal.rules) {
129
+ await addFile(rule.path, "formal-user-rule-content", { from: formal.routerPath, via: rule.path });
130
+ }
131
+ } catch (error) {
132
+ addBlocker("dev/USER_RULES.md", `formal user-rules state is unsafe: ${String(error?.message ?? error)}`);
133
+ }
134
+ }
140
135
 
141
136
  const frozenEntries = [...entries.values()]
142
137
  .map((entry) => ({
@@ -164,16 +159,58 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
164
159
  formalEntryTargets: formalEntryTargets.filter((target) => entries.has(target))
165
160
  });
166
161
 
167
- async function addTree(relativeDirectory, classification) {
162
+ async function addTransactionRegistry(relativeDirectory) {
163
+ const normalized = normalizeProjectRelative(relativeDirectory);
164
+ if (!normalized) {
165
+ addBlocker(String(relativeDirectory), "transaction registry escapes the selected project root");
166
+ return;
167
+ }
168
+ const absolute = path.resolve(rootPath, normalized);
169
+ const stats = await lstat(absolute).catch((error) => {
170
+ if (error?.code === "ENOENT") return null;
171
+ throw error;
172
+ });
173
+ if (!stats) return;
174
+ if (!stats.isDirectory() || stats.isSymbolicLink()) {
175
+ addBlocker(normalized, "transaction registry is not a safe real directory");
176
+ return;
177
+ }
178
+ const resolved = await realpath(absolute);
179
+ if (!isInside(realRoot, resolved)) {
180
+ addBlocker(normalized, "transaction registry resolves outside the selected project root");
181
+ return;
182
+ }
183
+ for (const item of await readdir(absolute, { withFileTypes: true })) {
184
+ const child = `${normalized}/${item.name}`;
185
+ const childAbsolute = path.join(absolute, item.name);
186
+ const childStats = await lstat(childAbsolute).catch((error) => {
187
+ if (error?.code === "ENOENT") return null;
188
+ throw error;
189
+ });
190
+ if (!childStats) continue;
191
+ if (childStats.isFile()) continue;
192
+ if (childStats.isSymbolicLink() || !childStats.isDirectory()) {
193
+ addBlocker(child, "transaction registry child is not a safe real directory");
194
+ continue;
195
+ }
196
+ const childResolved = await realpath(childAbsolute);
197
+ if (!isInside(realRoot, childResolved)) {
198
+ addBlocker(child, "transaction registry child resolves outside the selected project root");
199
+ continue;
200
+ }
201
+ await addFile(`${child}/transaction.json`, "transaction-state", { from: "transaction-registry", via: normalized });
202
+ }
203
+ }
204
+
205
+ async function addTree(relativeDirectory, classification) {
168
206
  const normalized = normalizeProjectRelative(relativeDirectory);
169
207
  if (!normalized) {
170
- addBlocker(String(relativeDirectory), "dynamic directory escapes the selected project root");
171
- return;
172
- }
173
- if (!(await hasExactProjectPath(rootPath, normalized))) return;
174
- const absolute = path.resolve(rootPath, normalized);
175
- const stats = await lstat(absolute).catch((error) => {
176
- if (error?.code === "ENOENT") return null;
208
+ addBlocker(String(relativeDirectory), "dynamic directory escapes the selected project root");
209
+ return;
210
+ }
211
+ const absolute = path.resolve(rootPath, normalized);
212
+ const stats = await lstat(absolute).catch((error) => {
213
+ if (error?.code === "ENOENT") return null;
177
214
  throw error;
178
215
  });
179
216
  if (!stats) return;
@@ -186,45 +223,38 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
186
223
  addBlocker(normalized, "dynamic inventory directory resolves outside the selected project root");
187
224
  return;
188
225
  }
189
- for (const item of await readdir(absolute, { withFileTypes: true })) {
190
- const child = `${normalized}/${item.name}`;
191
- if (item.isDirectory()) await addTree(child, classification);
192
- else if (item.isFile()) await addFile(child, classification, { from: "dynamic-state", via: normalized }, false);
193
- else addBlocker(child, "dynamic inventory source is not a regular file or directory");
194
- }
195
- }
196
- }
197
-
198
- async function hasExactProjectPath(rootPath, normalized) {
199
- const parts = normalized.split("/");
200
- let current = rootPath;
201
- for (const part of parts) {
202
- const entries = await readdir(current, { withFileTypes: true }).catch((error) => {
203
- if (error?.code === "ENOENT") return null;
204
- throw error;
205
- });
206
- if (!entries) return false;
207
- const exact = entries.find((entry) => entry.name === part);
208
- if (!exact) return false;
209
- current = path.join(current, exact.name);
210
- }
211
- return true;
212
- }
213
-
214
- /**
215
- * Gate 5 needs a stronger closure than the shared semantic-candidate
216
- * inventory: every regular project source under the selected root receives a
217
- * raw-byte witness, even when no currently known Kit reader reaches it. The
218
- * latter is recorded as explicitly outside the known Kit reachability set,
219
- * never silently omitted. This is read-only evidence; it does not choose an
220
- * upgrade action or make an unknown source Kit-managed.
221
- */
222
- export async function buildGate5RootSourceInventory({ root, reachableInventory } = {}) {
226
+ for (const item of await readdir(absolute, { withFileTypes: true })) {
227
+ const child = `${normalized}/${item.name}`;
228
+ const childAbsolute = path.join(absolute, item.name);
229
+ const childStats = await lstat(childAbsolute).catch((error) => {
230
+ if (error?.code === "ENOENT") return null;
231
+ throw error;
232
+ });
233
+ if (!childStats) continue;
234
+ if (childStats.isSymbolicLink()) {
235
+ addBlocker(child, "dynamic inventory source is not a safe real file or directory");
236
+ } else if (childStats.isDirectory()) {
237
+ await addTree(child, classification);
238
+ } else if (childStats.isFile()) {
239
+ await addFile(child, classification, { from: "dynamic-state", via: normalized });
240
+ } else {
241
+ addBlocker(child, "dynamic inventory source is not a regular file or directory");
242
+ }
243
+ }
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Gate 5 current scope is the typed reachable inventory. It deliberately does
249
+ * not walk the project root: ordinary files outside installed/runtime/formal
250
+ * user-rule/transaction/archive contracts are outside machine authority.
251
+ */
252
+ export async function buildGate5RootSourceInventory({ root, reachableInventory } = {}) {
223
253
  if (!root) throw new Error("Gate 5 root-source inventory requires a project root");
224
254
  if (!reachableInventory || reachableInventory.schemaVersion !== UPGRADE_INVENTORY_SCHEMA) {
225
255
  throw new Error("Gate 5 root-source inventory requires the current reachable inventory");
226
256
  }
227
- const rootPath = path.resolve(root);
257
+ const rootPath = path.resolve(root);
228
258
  const rootStats = await lstat(rootPath).catch((error) => {
229
259
  if (error?.code === "ENOENT") return null;
230
260
  throw error;
@@ -232,97 +262,28 @@ export async function buildGate5RootSourceInventory({ root, reachableInventory }
232
262
  if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) {
233
263
  throw new Error("Gate 5 root-source inventory root must be a real directory");
234
264
  }
235
- const rootReal = await realpath(rootPath);
236
- const reachableByPath = new Map(reachableInventory.entries.map((entry) => [entry.path, entry]));
237
- const entries = new Map();
238
- const blockers = [...reachableInventory.blockers];
239
- const exclusions = Object.freeze([{ path: ".git", reason: "version-control metadata is not project content unless a formal reader explicitly reaches it" }]);
240
-
241
- const addBlocker = (relative, reason) => {
242
- const key = `${relative}\0${reason}`;
243
- if (!blockers.some((item) => `${item.path}\0${item.reason}` === key)) blockers.push({ path: relative, reason });
244
- };
245
-
246
- async function addFile(relative) {
247
- const normalized = normalizeProjectRelative(relative);
248
- if (!normalized) {
249
- addBlocker(String(relative), "root-source path escapes the selected project root");
250
- return;
251
- }
252
- const absolute = path.resolve(rootPath, normalized);
253
- if (!isInside(rootPath, absolute)) {
254
- addBlocker(normalized, "root-source path escapes the selected project root");
255
- return;
256
- }
257
- const stats = await lstat(absolute).catch((error) => {
258
- if (error?.code === "ENOENT") return null;
259
- throw error;
260
- });
261
- if (!stats) return;
262
- if (stats.isSymbolicLink()) {
263
- addBlocker(normalized, "symbolic links and junctions are not accepted as root-source inputs");
264
- return;
265
- }
266
- if (!stats.isFile()) {
267
- addBlocker(normalized, "root-source input is not a regular file");
268
- return;
269
- }
270
- const resolved = await realpath(absolute);
271
- if (!isInside(rootReal, resolved)) {
272
- addBlocker(normalized, "root-source input resolves outside the selected project root");
273
- return;
274
- }
275
- const bytes = await readFile(absolute);
276
- const reachable = reachableByPath.get(normalized);
277
- // A same-name dev/<rule>.md probe is discovery-only. It is neither a
278
- // package contract nor a formal reader/effect witness, so Gate 5 must not
279
- // let that path shape turn an ordinary root source into a Kit item. Actual
280
- // formal references remain intact and continue to establish reachability.
281
- const classifications = (reachable?.classifications ?? []).filter((classification) => classification !== "legacy-rule-location");
282
- const reachability = (reachable?.reachability ?? []).filter((entry) => entry.from !== "legacy-location");
283
- entries.set(normalized, Object.freeze({
284
- path: normalized,
285
- sha256: sha256(bytes),
286
- bytes: bytes.length,
287
- classifications: Object.freeze(["root-source", ...classifications].sort()),
288
- reachability: Object.freeze([...reachability]
289
- .sort((left, right) => `${left.from}\0${left.via}`.localeCompare(`${right.from}\0${right.via}`)))
290
- }));
291
- }
292
-
293
- async function walk(relative = "") {
294
- const absolute = relative ? path.join(rootPath, relative) : rootPath;
295
- const children = await readdir(absolute, { withFileTypes: true });
296
- children.sort((left, right) => left.name.localeCompare(right.name));
297
- for (const child of children) {
298
- const childRelative = relative ? `${relative}/${child.name}` : child.name;
299
- if (childRelative === ".git") continue;
300
- if (child.isSymbolicLink()) {
301
- addBlocker(childRelative, "symbolic links and junctions are not accepted as root-source inputs");
302
- } else if (child.isDirectory()) {
303
- await walk(childRelative);
304
- } else if (child.isFile()) {
305
- await addFile(childRelative);
306
- } else {
307
- addBlocker(childRelative, "root-source input is not a regular file or directory");
308
- }
309
- }
310
- }
311
-
312
- await walk();
313
- for (const reachable of reachableInventory.entries) {
314
- if (!entries.has(reachable.path)) {
315
- addBlocker(reachable.path, "reachable inventory source was absent from the root-source scan");
316
- }
317
- }
318
- const frozenEntries = [...entries.values()].sort((left, right) => left.path.localeCompare(right.path));
319
- const sortedBlockers = blockers.sort((left, right) => `${left.path}\0${left.reason}`.localeCompare(`${right.path}\0${right.reason}`));
320
- const body = {
321
- schemaVersion: GATE5_ROOT_SOURCE_INVENTORY_SCHEMA,
322
- entries: frozenEntries,
323
- blockers: sortedBlockers,
324
- exclusions
325
- };
265
+ const entries = new Map();
266
+ const blockers = [...reachableInventory.blockers];
267
+
268
+ for (const reachable of reachableInventory.entries) {
269
+ const classifications = reachable.classifications ?? [];
270
+ const reachability = reachable.reachability ?? [];
271
+ entries.set(reachable.path, Object.freeze({
272
+ path: reachable.path,
273
+ sha256: reachable.sha256,
274
+ bytes: reachable.bytes,
275
+ classifications: Object.freeze(["root-source", ...classifications].sort()),
276
+ reachability: Object.freeze([...reachability]
277
+ .sort((left, right) => `${left.from}\0${left.via}`.localeCompare(`${right.from}\0${right.via}`)))
278
+ }));
279
+ }
280
+ const frozenEntries = [...entries.values()].sort((left, right) => left.path.localeCompare(right.path));
281
+ const sortedBlockers = blockers.sort((left, right) => `${left.path}\0${left.reason}`.localeCompare(`${right.path}\0${right.reason}`));
282
+ const body = {
283
+ schemaVersion: GATE5_ROOT_SOURCE_INVENTORY_SCHEMA,
284
+ entries: frozenEntries,
285
+ blockers: sortedBlockers
286
+ };
326
287
  return Object.freeze({
327
288
  ...body,
328
289
  status: sortedBlockers.length === 0 ? "ready" : "blocked",
@@ -353,7 +314,7 @@ export async function freezeGate5Set({ root, contracts = installedFileContracts,
353
314
  transition: transitionContracts.map(({ sourceRel, targetRel, strategy }) => ({ sourceRel, targetRel, strategy }))
354
315
  };
355
316
  const contractDigestSha256 = sha256(Buffer.from(`${JSON.stringify(contractBody)}\n`, "utf8"));
356
- const installedTemplateVersion = await readInstalledTemplateVersion(rootPath);
317
+ const installedTemplateVersion = await readProjectIndexTemplateVersion(rootPath);
357
318
  const release = installedTemplateVersion ? officialCatalog.releases?.[installedTemplateVersion] : null;
358
319
  const entryByPath = new Map(rootSourceInventory.entries.map((entry) => [entry.path, entry]));
359
320
  const items = rootSourceInventory.entries.map((entry) => {
@@ -430,21 +391,20 @@ export async function freezeGate5Set({ root, contracts = installedFileContracts,
430
391
  const unresolvedContractTargets = contractCoverage
431
392
  .filter((item) => item.sourceStatus === "unresolved-missing-installed-source")
432
393
  .map((item) => Object.freeze({ sourcePath: item.targetRel, reason: "installed package target is missing from the root-source set" }));
433
- const bridgePaths = ["CLAUDE.md", "GEMINI.md"];
434
- const sourceConservationPaths = items
435
- .filter(gate5ItemRequiresSourceConservation)
436
- .map((item) => item.sourcePath);
437
- const body = {
438
- schemaVersion: GATE5_FROZEN_SET_SCHEMA,
439
- operationAuthority: "none",
394
+ const bridgePaths = ["CLAUDE.md", "GEMINI.md"];
395
+ const sourceConservationPaths = items
396
+ .filter(gate5ItemRequiresSourceConservation)
397
+ .map((item) => item.sourcePath);
398
+ const body = {
399
+ schemaVersion: GATE5_FROZEN_SET_SCHEMA,
400
+ operationAuthority: "none",
440
401
  activationStatus: "not-authorized",
441
402
  inventory: Object.freeze({ schemaVersion: inventory.schemaVersion, sha256: inventory.inventorySha256 }),
442
- rootSourceInventory: Object.freeze({
443
- schemaVersion: rootSourceInventory.schemaVersion,
444
- sha256: rootSourceInventory.rootSourceSha256,
445
- entryCount: rootSourceInventory.entries.length,
446
- exclusions: rootSourceInventory.exclusions
447
- }),
403
+ rootSourceInventory: Object.freeze({
404
+ schemaVersion: rootSourceInventory.schemaVersion,
405
+ sha256: rootSourceInventory.rootSourceSha256,
406
+ entryCount: rootSourceInventory.entries.length
407
+ }),
448
408
  packageContract: Object.freeze({
449
409
  schemaVersion: INSTALLED_FILE_CONTRACT_SCHEMA,
450
410
  digestSha256: contractDigestSha256,
@@ -460,23 +420,23 @@ export async function freezeGate5Set({ root, contracts = installedFileContracts,
460
420
  packageIntegrity: release?.source?.npm?.integrity ?? null,
461
421
  status: release ? "bound-to-installed-catalog-identity" : "unresolved-no-catalog-release-for-installed-version"
462
422
  }),
463
- formalSurfaces: Object.freeze({
464
- entry: binding(entryByPath, "AGENTS.md"),
465
- bridges: Object.freeze(bridgePaths.map((targetRel) => binding(entryByPath, targetRel))),
466
- router: binding(entryByPath, "dev/USER_RULES.md"),
423
+ formalSurfaces: Object.freeze({
424
+ entry: binding(entryByPath, "AGENTS.md"),
425
+ bridges: Object.freeze(bridgePaths.map((targetRel) => binding(entryByPath, targetRel))),
426
+ router: binding(entryByPath, "dev/USER_RULES.md"),
467
427
  transactionRegistry: Object.freeze({
468
428
  root: "dev/governance_migrations",
469
- entries: Object.freeze(items.filter((item) => item.classifications.includes("transaction-state")).map((item) => item.sourcePath))
470
- })
471
- }),
472
- sourceConservation: Object.freeze({
473
- selection: "known-kit-reachability",
474
- protectedEntryCount: sourceConservationPaths.length,
475
- sourcePaths: Object.freeze(sourceConservationPaths)
476
- }),
477
- items: Object.freeze(items),
478
- unresolved: Object.freeze([...unresolvedItems, ...unresolvedContractTargets]
479
- .sort((left, right) => `${left.sourcePath}\0${left.reason}`.localeCompare(`${right.sourcePath}\0${right.reason}`)))
429
+ entries: Object.freeze(items.filter((item) => item.classifications.includes("transaction-state")).map((item) => item.sourcePath))
430
+ })
431
+ }),
432
+ sourceConservation: Object.freeze({
433
+ selection: "known-kit-reachability",
434
+ protectedEntryCount: sourceConservationPaths.length,
435
+ sourcePaths: Object.freeze(sourceConservationPaths)
436
+ }),
437
+ items: Object.freeze(items),
438
+ unresolved: Object.freeze([...unresolvedItems, ...unresolvedContractTargets]
439
+ .sort((left, right) => `${left.sourcePath}\0${left.reason}`.localeCompare(`${right.sourcePath}\0${right.reason}`)))
480
440
  };
481
441
  return Object.freeze({ ...body, frozenSetSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) });
482
442
  }
@@ -486,23 +446,22 @@ export function assertGate5FrozenSet(frozen) {
486
446
  if (frozen.schemaVersion !== GATE5_FROZEN_SET_SCHEMA) throw new Error("unsupported Gate 5 frozen-set schema");
487
447
  if (frozen.operationAuthority !== "none" || frozen.activationStatus !== "not-authorized") throw new Error("Gate 5 frozen set must not claim operation authority");
488
448
  if (!Array.isArray(frozen.items) || frozen.items.length === 0) throw new Error("Gate 5 frozen set has no items");
489
- if (!frozen.rootSourceInventory || frozen.rootSourceInventory.schemaVersion !== GATE5_ROOT_SOURCE_INVENTORY_SCHEMA
490
- || !/^[0-9a-f]{64}$/.test(frozen.rootSourceInventory.sha256)
491
- || !Number.isInteger(frozen.rootSourceInventory.entryCount) || frozen.rootSourceInventory.entryCount !== frozen.items.length
492
- || !Array.isArray(frozen.rootSourceInventory.exclusions)) {
493
- throw new Error("Gate 5 frozen set does not bind a complete root-source inventory");
494
- }
495
- if (!frozen.packageContract || !Array.isArray(frozen.packageContract.coverage)) {
496
- throw new Error("Gate 5 frozen set does not bind package-contract coverage");
497
- }
498
- if (!frozen.sourceConservation || frozen.sourceConservation.selection !== "known-kit-reachability"
499
- || !Number.isInteger(frozen.sourceConservation.protectedEntryCount)
500
- || !Array.isArray(frozen.sourceConservation.sourcePaths)) {
501
- throw new Error("Gate 5 frozen set does not define its current-state source-conservation selection");
449
+ if (!frozen.rootSourceInventory || frozen.rootSourceInventory.schemaVersion !== GATE5_ROOT_SOURCE_INVENTORY_SCHEMA
450
+ || !/^[0-9a-f]{64}$/.test(frozen.rootSourceInventory.sha256)
451
+ || !Number.isInteger(frozen.rootSourceInventory.entryCount) || frozen.rootSourceInventory.entryCount !== frozen.items.length) {
452
+ throw new Error("Gate 5 frozen set does not bind its scoped typed source inventory");
502
453
  }
503
- const paths = new Set();
504
- const orderedPaths = [];
505
- for (const item of frozen.items) {
454
+ if (!frozen.packageContract || !Array.isArray(frozen.packageContract.coverage)) {
455
+ throw new Error("Gate 5 frozen set does not bind package-contract coverage");
456
+ }
457
+ if (!frozen.sourceConservation || frozen.sourceConservation.selection !== "known-kit-reachability"
458
+ || !Number.isInteger(frozen.sourceConservation.protectedEntryCount)
459
+ || !Array.isArray(frozen.sourceConservation.sourcePaths)) {
460
+ throw new Error("Gate 5 frozen set does not define its current-state source-conservation selection");
461
+ }
462
+ const paths = new Set();
463
+ const orderedPaths = [];
464
+ for (const item of frozen.items) {
506
465
  if (!item || typeof item !== "object" || typeof item.sourcePath !== "string" || paths.has(item.sourcePath)) throw new Error("Gate 5 frozen set has duplicate or invalid source paths");
507
466
  paths.add(item.sourcePath);
508
467
  orderedPaths.push(item.sourcePath);
@@ -525,19 +484,19 @@ export function assertGate5FrozenSet(frozen) {
525
484
  throw new Error("Gate 5 frozen set package-contract coverage is invalid");
526
485
  }
527
486
  if (coverage.sourceStatus === "unresolved-missing-installed-source") {
528
- expectedUnresolved.push(`${coverage.targetRel}\0installed package target is missing from the root-source set`);
529
- }
530
- }
531
- const expectedSourceConservationPaths = frozen.items
532
- .filter(gate5ItemRequiresSourceConservation)
533
- .map((item) => item.sourcePath);
534
- if (frozen.sourceConservation.protectedEntryCount !== expectedSourceConservationPaths.length
535
- || JSON.stringify(frozen.sourceConservation.sourcePaths) !== JSON.stringify(expectedSourceConservationPaths)) {
536
- throw new Error("Gate 5 frozen set source-conservation selection does not match known Kit reachability");
537
- }
538
- if (JSON.stringify(orderedPaths) !== JSON.stringify([...orderedPaths].sort((left, right) => left.localeCompare(right)))) {
539
- throw new Error("Gate 5 frozen set items are not in canonical source-path order");
540
- }
487
+ expectedUnresolved.push(`${coverage.targetRel}\0installed package target is missing from the root-source set`);
488
+ }
489
+ }
490
+ const expectedSourceConservationPaths = frozen.items
491
+ .filter(gate5ItemRequiresSourceConservation)
492
+ .map((item) => item.sourcePath);
493
+ if (frozen.sourceConservation.protectedEntryCount !== expectedSourceConservationPaths.length
494
+ || JSON.stringify(frozen.sourceConservation.sourcePaths) !== JSON.stringify(expectedSourceConservationPaths)) {
495
+ throw new Error("Gate 5 frozen set source-conservation selection does not match known Kit reachability");
496
+ }
497
+ if (JSON.stringify(orderedPaths) !== JSON.stringify([...orderedPaths].sort((left, right) => left.localeCompare(right)))) {
498
+ throw new Error("Gate 5 frozen set items are not in canonical source-path order");
499
+ }
541
500
  if (JSON.stringify(actualUnresolved) !== JSON.stringify([...actualUnresolved].sort((left, right) => left.localeCompare(right)))) {
542
501
  throw new Error("Gate 5 frozen set unresolved list is not in canonical order");
543
502
  }
@@ -576,17 +535,138 @@ function isFormalReader(reader) {
576
535
  return reader === "formal-entry" || !["managed-contract", "legacy-location", "dynamic-state"].includes(reader);
577
536
  }
578
537
 
579
- async function readInstalledTemplateVersion(root) {
580
- const bytes = await readFile(path.join(root, "dev", "PROJECT_INDEX.md")).catch((error) => {
581
- if (error?.code === "ENOENT") return null;
582
- throw error;
583
- });
584
- if (!bytes) return null;
585
- const match = /^\| Agent Handoff Kit template version \| ([0-9]+\.[0-9]+\.[0-9]+) \|/m.exec(bytes.toString("utf8"));
586
- return match?.[1] ?? null;
587
- }
588
-
589
- export function extractExplicitLocalReferences(text) {
538
+ export async function readProjectIndexTemplateVersion(root) {
539
+ const bytes = await readFile(path.join(root, "dev", "PROJECT_INDEX.md")).catch((error) => {
540
+ if (error?.code === "ENOENT") return null;
541
+ throw error;
542
+ });
543
+ if (!bytes) return null;
544
+ return parseProjectIndexTemplateVersion(bytes.toString("utf8"));
545
+ }
546
+
547
+ export function parseProjectIndexTemplateVersion(text) {
548
+ return projectIndexTemplateVersionEvidence(text)?.version ?? null;
549
+ }
550
+
551
+ export function projectIndexTemplateVersionRow(text) {
552
+ return projectIndexTemplateVersionEvidence(text)?.row ?? null;
553
+ }
554
+
555
+ export function materializeProjectIndexTemplateVersion(text, version) {
556
+ if (!isStableSemver(version)) return text;
557
+ const evidence = projectIndexTemplateVersionEvidence(text);
558
+ if (!evidence) return text;
559
+ return String(text).slice(0, evidence.rowStart)
560
+ + evidence.row.replace(`| ${evidence.version} |`, `| ${version} |`)
561
+ + String(text).slice(evidence.rowEnd);
562
+ }
563
+
564
+ function projectIndexTemplateVersionEvidence(text) {
565
+ const value = String(text);
566
+ const normalized = value.replace(/\r\n/g, "\n");
567
+ const visibleLines = markdownVisibleLinesOutsideHiddenBlocks(value);
568
+ const headings = [];
569
+ for (const item of visibleLines) if (/^## [^\r\n]+$/u.test(item.text)) headings.push({ title: item.text.trim(), line: item.line, offset: item.normalizedStart });
570
+ const stackHeadings = headings.filter((heading) => heading.title === "## Stack");
571
+ if (stackHeadings.length !== 1) return null;
572
+ const stack = stackHeadings[0];
573
+ const nextHeading = headings.find((heading) => heading.line > stack.line);
574
+ const stackStart = stack.offset + visibleLines.find((line) => line.line === stack.line)?.text.length + 1;
575
+ const stackEnd = nextHeading ? nextHeading.offset : normalized.length;
576
+ const stackLines = visibleLines.filter((line) => line.normalizedStart >= stackStart && line.normalizedStart < stackEnd);
577
+ const candidateRows = [];
578
+ const rowPattern = /^\| Agent Handoff Kit template version \| ([^|\n]+) \| [^|\n]+ \|$/u;
579
+ for (const line of stackLines) {
580
+ const match = rowPattern.exec(line.text);
581
+ if (!match) continue;
582
+ const version = match[1].trim();
583
+ if (!isStableSemver(version)) return null;
584
+ candidateRows.push({
585
+ version,
586
+ row: line.text,
587
+ rowStart: line.start,
588
+ rowEnd: line.end
589
+ });
590
+ }
591
+ const versionLabelRows = stackLines.filter((line) => line.text.startsWith("| Agent Handoff Kit template version |"));
592
+ if (versionLabelRows.length !== candidateRows.length || candidateRows.length !== 1) return null;
593
+ const [row] = candidateRows;
594
+ return { version: row.version, row: row.row, rowStart: row.rowStart, rowEnd: row.rowEnd };
595
+ }
596
+
597
+ export function markdownVisibleLinesOutsideHiddenBlocks(text) {
598
+ const value = String(text);
599
+ const normalized = value.replace(/\r\n/g, "\n");
600
+ const lines = normalized.split("\n");
601
+ const result = [];
602
+ let offset = 0;
603
+ let fence = null;
604
+ let inComment = false;
605
+ for (let index = 0; index < lines.length; index += 1) {
606
+ const line = lines[index];
607
+ if (inComment) {
608
+ if (line.includes("-->")) inComment = false;
609
+ offset += line.length + 1;
610
+ continue;
611
+ }
612
+ const fenceMatch = /^\s{0,3}(`{3,}|~{3,})(?![`~])(.*)$/u.exec(line);
613
+ const fenceRun = fenceMatch?.[1] ?? null;
614
+ if (fence) {
615
+ if (
616
+ fenceRun
617
+ && fenceRun[0] === fence.char
618
+ && fenceRun.length >= fence.length
619
+ && /^\s*$/u.test(fenceMatch?.[2] ?? "")
620
+ ) {
621
+ fence = null;
622
+ }
623
+ offset += line.length + 1;
624
+ continue;
625
+ }
626
+ if (fenceRun) {
627
+ fence = { char: fenceRun[0], length: fenceRun.length };
628
+ offset += line.length + 1;
629
+ continue;
630
+ }
631
+ const commentStart = line.indexOf("<!--");
632
+ if (commentStart >= 0) {
633
+ if (line.indexOf("-->", commentStart + 4) < 0) inComment = true;
634
+ offset += line.length + 1;
635
+ continue;
636
+ }
637
+ result.push({
638
+ text: line,
639
+ line: index,
640
+ normalizedStart: offset,
641
+ normalizedEnd: offset + line.length,
642
+ start: originalOffsetForNormalizedOffset(value, offset),
643
+ end: originalOffsetForNormalizedOffset(value, offset + line.length)
644
+ });
645
+ offset += line.length + 1;
646
+ }
647
+ return result;
648
+ }
649
+
650
+ function originalOffsetForNormalizedOffset(text, normalizedOffset) {
651
+ let original = 0;
652
+ let normalized = 0;
653
+ while (original < text.length && normalized < normalizedOffset) {
654
+ if (text[original] === "\r" && text[original + 1] === "\n") {
655
+ original += 2;
656
+ normalized += 1;
657
+ } else {
658
+ original += 1;
659
+ normalized += 1;
660
+ }
661
+ }
662
+ return original;
663
+ }
664
+
665
+ function isStableSemver(value) {
666
+ return /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(String(value));
667
+ }
668
+
669
+ export function extractExplicitLocalReferences(text) {
590
670
  const matches = new Map();
591
671
  const add = (raw, via) => {
592
672
  const normalized = normalizeReference(raw);