@adamchanadam/agent-handoff-kit 0.3.52 → 0.3.54

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,10 @@
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 } from "./installed-file-contract.mjs";
5
+ import { FORMAL_USER_RULES_ENTRY_ANCHOR, readFormalUserRules } from "./user-rules-router.mjs";
6
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;
10
8
 
11
9
  const formalEntryTargets = Object.freeze([
12
10
  "AGENTS.md",
@@ -15,27 +13,16 @@ const formalEntryTargets = Object.freeze([
15
13
  "START_NEXT_SESSION_PROMPT.txt"
16
14
  ]);
17
15
 
18
- const dynamicDirectories = Object.freeze([
19
- { relative: "dev/governance_migrations", classification: "transaction-state" },
16
+ const archiveDirectories = Object.freeze([
20
17
  { relative: "dev/SESSION_LOG_archive", classification: "session-log-archive" },
21
18
  { relative: "dev/session_log_archive", classification: "legacy-session-log-archive" }
22
19
  ]);
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
- }
32
20
 
33
- /**
34
- * Builds a read-only, hash-bound description of the Kit data that an upgrade
35
- * can reach. It deliberately records whole source files before any semantic
36
- * candidate tries to divide or merge their contents: a heading, language, or
37
- * layout is never treated as ownership evidence.
38
- */
21
+ /**
22
+ * Builds a read-only, hash-bound description of the Kit data that an upgrade
23
+ * can reach now. Ordinary workspace files, generic Markdown references, and
24
+ * committed historical transaction receipts are not current upgrade authority.
25
+ */
39
26
  export async function buildUpgradeInventory({ root, contracts = installedFileContracts } = {}) {
40
27
  if (!root) throw new Error("upgrade inventory requires a project root");
41
28
  const rootPath = path.resolve(root);
@@ -47,17 +34,15 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
47
34
  throw new Error("upgrade inventory root must be a real directory");
48
35
  }
49
36
  const realRoot = await realpath(rootPath);
50
- const entries = new Map();
51
- const blockers = [];
52
- const queue = [];
53
- const queued = new Set();
37
+ const entries = new Map();
38
+ const blockers = [];
54
39
 
55
40
  const addBlocker = (relative, reason) => {
56
41
  const key = `${relative}\0${reason}`;
57
42
  if (!blockers.some((item) => `${item.path}\0${item.reason}` === key)) blockers.push({ path: relative, reason });
58
43
  };
59
44
 
60
- async function addFile(relative, classification, reachability = null, enqueueForReferences = false) {
45
+ async function addFile(relative, classification, reachability = null) {
61
46
  const normalized = normalizeProjectRelative(relative);
62
47
  if (!normalized) {
63
48
  addBlocker(String(relative), "reference escapes the selected project root");
@@ -102,41 +87,34 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
102
87
  }
103
88
  entry.classifications.add(classification);
104
89
  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
- }
90
+ return entry;
91
+ }
111
92
 
112
93
  for (const contract of contracts) {
113
94
  const isFormalEntry = formalEntryTargets.includes(contract.targetRel);
114
95
  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
- }
96
+ contract.targetRel,
97
+ "managed-contract",
98
+ isFormalEntry ? { from: "formal-entry", via: contract.targetRel } : { from: "managed-contract", via: contract.targetRel }
99
+ );
100
+ }
101
+
102
+ for (const directory of archiveDirectories) {
103
+ await addTree(directory.relative, directory.classification);
104
+ }
105
+
106
+ const agentsEntry = entries.get("AGENTS.md");
107
+ if (agentsEntry?.text?.includes(FORMAL_USER_RULES_ENTRY_ANCHOR)) {
108
+ try {
109
+ const formal = await readFormalUserRules({ root: rootPath, allowActiveTransaction: true });
110
+ await addFile(formal.routerPath, "formal-user-rules-router", { from: formal.entryPath, via: formal.routerPath });
111
+ for (const rule of formal.rules) {
112
+ await addFile(rule.path, "formal-user-rule-content", { from: formal.routerPath, via: rule.path });
113
+ }
114
+ } catch (error) {
115
+ addBlocker("dev/USER_RULES.md", `formal user-rules state is unsafe: ${String(error?.message ?? error)}`);
116
+ }
117
+ }
140
118
 
141
119
  const frozenEntries = [...entries.values()]
142
120
  .map((entry) => ({
@@ -164,16 +142,15 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
164
142
  formalEntryTargets: formalEntryTargets.filter((target) => entries.has(target))
165
143
  });
166
144
 
167
- async function addTree(relativeDirectory, classification) {
145
+ async function addTree(relativeDirectory, classification) {
168
146
  const normalized = normalizeProjectRelative(relativeDirectory);
169
147
  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;
148
+ addBlocker(String(relativeDirectory), "dynamic directory escapes the selected project root");
149
+ return;
150
+ }
151
+ const absolute = path.resolve(rootPath, normalized);
152
+ const stats = await lstat(absolute).catch((error) => {
153
+ if (error?.code === "ENOENT") return null;
177
154
  throw error;
178
155
  });
179
156
  if (!stats) return;
@@ -186,407 +163,159 @@ export async function buildUpgradeInventory({ root, contracts = installedFileCon
186
163
  addBlocker(normalized, "dynamic inventory directory resolves outside the selected project root");
187
164
  return;
188
165
  }
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 } = {}) {
223
- if (!root) throw new Error("Gate 5 root-source inventory requires a project root");
224
- if (!reachableInventory || reachableInventory.schemaVersion !== UPGRADE_INVENTORY_SCHEMA) {
225
- throw new Error("Gate 5 root-source inventory requires the current reachable inventory");
226
- }
227
- const rootPath = path.resolve(root);
228
- const rootStats = await lstat(rootPath).catch((error) => {
229
- if (error?.code === "ENOENT") return null;
230
- throw error;
231
- });
232
- if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) {
233
- throw new Error("Gate 5 root-source inventory root must be a real directory");
234
- }
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
- };
326
- return Object.freeze({
327
- ...body,
328
- status: sortedBlockers.length === 0 ? "ready" : "blocked",
329
- rootSourceSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8"))
330
- });
331
- }
332
-
333
- /**
334
- * Freezes the complete set that a Gate 5 upgrade may reason about before any
335
- * candidate, transaction, or semantic disposition is attempted. This is not
336
- * an activation record and grants no write authority: it binds every reached
337
- * project source's raw bytes to the installed package contract, formal
338
- * historical source, transaction/registry surface, bridges, router, and
339
- * formal entry.
340
- */
341
- export async function freezeGate5Set({ root, contracts = installedFileContracts, transitionContracts = upgradeStateFileContracts, catalog = null } = {}) {
342
- const inventory = await buildUpgradeInventory({ root, contracts });
343
- if (inventory.status !== "ready") throw new Error("Gate 5 frozen set requires a ready reachable inventory");
344
- const rootSourceInventory = await buildGate5RootSourceInventory({ root, reachableInventory: inventory });
345
- if (rootSourceInventory.status !== "ready") throw new Error("Gate 5 frozen set requires a complete safe root-source inventory");
346
- const rootPath = path.resolve(root);
347
- const officialCatalog = catalog ?? await loadOfficialOriginCatalog();
348
- const packageContracts = normalizeContracts(contracts, transitionContracts);
349
- const contractByTarget = new Map(packageContracts.map((contract) => [contract.targetRel, contract]));
350
- const contractBody = {
351
- schemaVersion: INSTALLED_FILE_CONTRACT_SCHEMA,
352
- installed: contracts.map(({ sourceRel, targetRel, strategy }) => ({ sourceRel, targetRel, strategy })),
353
- transition: transitionContracts.map(({ sourceRel, targetRel, strategy }) => ({ sourceRel, targetRel, strategy }))
354
- };
355
- const contractDigestSha256 = sha256(Buffer.from(`${JSON.stringify(contractBody)}\n`, "utf8"));
356
- const installedTemplateVersion = await readInstalledTemplateVersion(rootPath);
357
- const release = installedTemplateVersion ? officialCatalog.releases?.[installedTemplateVersion] : null;
358
- const entryByPath = new Map(rootSourceInventory.entries.map((entry) => [entry.path, entry]));
359
- const items = rootSourceInventory.entries.map((entry) => {
360
- const contract = contractByTarget.get(entry.path) ?? null;
361
- const historicalEntry = contract && release?.manifest?.[entry.path]?.state === "present"
362
- ? release.manifest[entry.path]
363
- : null;
364
- const exactPackageBytes = Boolean(historicalEntry && entry.sha256 === historicalEntry.rawSha256);
365
- const discoveredReachability = entry.reachability.map(({ from, via }) => ({ reader: from, via }));
366
- const readers = discoveredReachability.filter(({ reader }) => isFormalReader(reader));
367
- const kitReachable = entry.classifications.some((classification) => classification !== "root-source");
368
- const unresolvedReason = !kitReachable
369
- ? null
370
- : !exactPackageBytes
371
- ? "non-exact-or-unknown bytes require a verified preserve destination or remain unresolved"
372
- : readers.length === 0
373
- ? "no verified existing reader; priority and effect remain unresolved"
374
- : "reader is recorded, but priority/conflict and runtime effect remain unresolved before a per-item transaction proof";
375
- return Object.freeze({
376
- sourcePath: entry.path,
377
- sourceIdentity: Object.freeze({ sha256: entry.sha256, bytes: entry.bytes }),
378
- classifications: Object.freeze([...entry.classifications]),
379
- existingReaders: Object.freeze(readers),
380
- discoveredReachability: Object.freeze(discoveredReachability),
381
- priorityConflict: Object.freeze({
382
- status: kitReachable ? "unresolved-before-runtime-validation" : "not-applicable-outside-known-kit-reachability",
383
- relation: !kitReachable ? "outside-known-kit-reachability" : readers.length > 0 ? "reader-reachable-priority-not-proven" : "no-verified-reader"
384
- }),
385
- effect: Object.freeze({
386
- status: kitReachable ? "unresolved-before-runtime-validation" : "not-applicable-outside-known-kit-reachability",
387
- decision: !kitReachable ? "outside-known-kit-reachability" : readers.length > 0 ? "preserve-existing-route-or-stop" : "unresolved"
388
- }),
389
- packageContract: contract
390
- ? Object.freeze({ sourceRel: contract.sourceRel, targetRel: contract.targetRel, strategy: contract.strategy, scope: contract.scope })
391
- : null,
392
- historicalOrigin: historicalEntry
393
- ? Object.freeze({
394
- packageIdentity: release.source.npm.spec,
395
- installedTemplateVersion,
396
- rawSha256: historicalEntry.rawSha256,
397
- exactPackageBytes,
398
- catalogDigestSha256: officialCatalog.catalogDigestSha256
399
- })
400
- : null,
401
- ownership: exactPackageBytes && contract?.scope === "installed"
402
- ? "kit-managed-exact"
403
- : "user-or-unknown",
404
- unresolvedReason
405
- });
406
- });
407
- const contractCoverage = packageContracts.map((contract) => {
408
- const source = entryByPath.get(contract.targetRel) ?? null;
409
- const historicalState = release?.manifest?.[contract.targetRel]?.state ?? "unavailable";
410
- const status = source
411
- ? "source-frozen"
412
- : historicalState === "absent"
413
- ? "not-present-in-historical-package"
414
- : contract.scope === "transition"
415
- ? "not-present-no-formal-transition-state"
416
- : "unresolved-missing-installed-source";
417
- return Object.freeze({
418
- sourceRel: contract.sourceRel,
419
- targetRel: contract.targetRel,
420
- strategy: contract.strategy,
421
- scope: contract.scope,
422
- sourceStatus: status,
423
- sourceIdentity: source ? Object.freeze({ sha256: source.sha256, bytes: source.bytes }) : null,
424
- historicalState
425
- });
426
- });
427
- const unresolvedItems = items
428
- .filter((item) => item.unresolvedReason)
429
- .map((item) => Object.freeze({ sourcePath: item.sourcePath, reason: item.unresolvedReason }));
430
- const unresolvedContractTargets = contractCoverage
431
- .filter((item) => item.sourceStatus === "unresolved-missing-installed-source")
432
- .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",
440
- activationStatus: "not-authorized",
441
- 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
- }),
448
- packageContract: Object.freeze({
449
- schemaVersion: INSTALLED_FILE_CONTRACT_SCHEMA,
450
- digestSha256: contractDigestSha256,
451
- installedTargets: Object.freeze(contracts.map(({ targetRel }) => targetRel)),
452
- transitionTargets: Object.freeze(transitionContracts.map(({ targetRel }) => targetRel)),
453
- coverage: Object.freeze(contractCoverage)
454
- }),
455
- historicalSource: Object.freeze({
456
- catalogSchemaVersion: officialCatalog.schemaVersion,
457
- catalogDigestSha256: officialCatalog.catalogDigestSha256,
458
- installedTemplateVersion,
459
- packageIdentity: release?.source?.npm?.spec ?? null,
460
- packageIntegrity: release?.source?.npm?.integrity ?? null,
461
- status: release ? "bound-to-installed-catalog-identity" : "unresolved-no-catalog-release-for-installed-version"
462
- }),
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"),
467
- transactionRegistry: Object.freeze({
468
- 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}`)))
480
- };
481
- return Object.freeze({ ...body, frozenSetSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) });
482
- }
483
-
484
- export function assertGate5FrozenSet(frozen) {
485
- if (!frozen || typeof frozen !== "object" || Array.isArray(frozen)) throw new Error("Gate 5 frozen set is required");
486
- if (frozen.schemaVersion !== GATE5_FROZEN_SET_SCHEMA) throw new Error("unsupported Gate 5 frozen-set schema");
487
- if (frozen.operationAuthority !== "none" || frozen.activationStatus !== "not-authorized") throw new Error("Gate 5 frozen set must not claim operation authority");
488
- 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");
166
+ for (const item of await readdir(absolute, { withFileTypes: true })) {
167
+ const child = `${normalized}/${item.name}`;
168
+ const childAbsolute = path.join(absolute, item.name);
169
+ const childStats = await lstat(childAbsolute).catch((error) => {
170
+ if (error?.code === "ENOENT") return null;
171
+ throw error;
172
+ });
173
+ if (!childStats) continue;
174
+ if (childStats.isSymbolicLink()) {
175
+ addBlocker(child, "dynamic inventory source is not a safe real file or directory");
176
+ } else if (childStats.isDirectory()) {
177
+ await addTree(child, classification);
178
+ } else if (childStats.isFile()) {
179
+ await addFile(child, classification, { from: "dynamic-state", via: normalized });
180
+ } else {
181
+ addBlocker(child, "dynamic inventory source is not a regular file or directory");
182
+ }
183
+ }
497
184
  }
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");
185
+ }
186
+
187
+ export async function readProjectIndexTemplateVersion(root) {
188
+ const bytes = await readFile(path.join(root, "dev", "PROJECT_INDEX.md")).catch((error) => {
189
+ if (error?.code === "ENOENT") return null;
190
+ throw error;
191
+ });
192
+ if (!bytes) return null;
193
+ return parseProjectIndexTemplateVersion(bytes.toString("utf8"));
194
+ }
195
+
196
+ export function parseProjectIndexTemplateVersion(text) {
197
+ return projectIndexTemplateVersionEvidence(text)?.version ?? null;
198
+ }
199
+
200
+ export function projectIndexTemplateVersionRow(text) {
201
+ return projectIndexTemplateVersionEvidence(text)?.row ?? null;
202
+ }
203
+
204
+ export function materializeProjectIndexTemplateVersion(text, version) {
205
+ if (!isStableSemver(version)) return text;
206
+ const evidence = projectIndexTemplateVersionEvidence(text);
207
+ if (!evidence) return text;
208
+ return String(text).slice(0, evidence.rowStart)
209
+ + evidence.row.replace(`| ${evidence.version} |`, `| ${version} |`)
210
+ + String(text).slice(evidence.rowEnd);
211
+ }
212
+
213
+ function projectIndexTemplateVersionEvidence(text) {
214
+ const value = String(text);
215
+ const normalized = value.replace(/\r\n/g, "\n");
216
+ const visibleLines = markdownVisibleLinesOutsideHiddenBlocks(value);
217
+ const headings = [];
218
+ for (const item of visibleLines) if (/^## [^\r\n]+$/u.test(item.text)) headings.push({ title: item.text.trim(), line: item.line, offset: item.normalizedStart });
219
+ const stackHeadings = headings.filter((heading) => heading.title === "## Stack");
220
+ if (stackHeadings.length !== 1) return null;
221
+ const stack = stackHeadings[0];
222
+ const nextHeading = headings.find((heading) => heading.line > stack.line);
223
+ const stackStart = stack.offset + visibleLines.find((line) => line.line === stack.line)?.text.length + 1;
224
+ const stackEnd = nextHeading ? nextHeading.offset : normalized.length;
225
+ const stackLines = visibleLines.filter((line) => line.normalizedStart >= stackStart && line.normalizedStart < stackEnd);
226
+ const candidateRows = [];
227
+ const rowPattern = /^\| Agent Handoff Kit template version \| ([^|\n]+) \| [^|\n]+ \|$/u;
228
+ for (const line of stackLines) {
229
+ const match = rowPattern.exec(line.text);
230
+ if (!match) continue;
231
+ const version = match[1].trim();
232
+ if (!isStableSemver(version)) return null;
233
+ candidateRows.push({
234
+ version,
235
+ row: line.text,
236
+ rowStart: line.start,
237
+ rowEnd: line.end
238
+ });
502
239
  }
503
- const paths = new Set();
504
- const orderedPaths = [];
505
- for (const item of frozen.items) {
506
- 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
- paths.add(item.sourcePath);
508
- orderedPaths.push(item.sourcePath);
509
- if (!/^[0-9a-f]{64}$/.test(item.sourceIdentity?.sha256) || !Number.isInteger(item.sourceIdentity?.bytes) || item.sourceIdentity.bytes < 0) throw new Error(`Gate 5 frozen set source identity is invalid: ${item.sourcePath}`);
510
- if (!Array.isArray(item.classifications) || !item.classifications.includes("root-source")
511
- || !Array.isArray(item.existingReaders) || !item.priorityConflict?.status || !item.effect?.status
512
- || !(item.unresolvedReason === null || typeof item.unresolvedReason === "string")) {
513
- throw new Error(`Gate 5 frozen set omits root-source, reader, priority/conflict, or effect record: ${item.sourcePath}`);
514
- }
515
- if (!item.historicalOrigin && item.ownership !== "user-or-unknown") throw new Error(`Gate 5 frozen set assigns ownership without historical evidence: ${item.sourcePath}`);
516
- if (item.historicalOrigin?.exactPackageBytes && item.packageContract?.scope === "installed" && item.ownership !== "kit-managed-exact") throw new Error(`Gate 5 frozen set rejects exact managed ownership: ${item.sourcePath}`);
517
- if (item.historicalOrigin && !item.historicalOrigin.exactPackageBytes && item.ownership !== "user-or-unknown") throw new Error(`Gate 5 frozen set accepts non-exact package bytes: ${item.sourcePath}`);
518
- }
519
- const expectedUnresolved = frozen.items
520
- .filter((item) => item.unresolvedReason)
521
- .map((item) => `${item.sourcePath}\0${item.unresolvedReason}`);
522
- const actualUnresolved = frozen.unresolved?.map((item) => `${item.sourcePath}\0${item.reason}`) ?? [];
523
- for (const coverage of frozen.packageContract.coverage) {
524
- if (!coverage || typeof coverage.targetRel !== "string" || typeof coverage.sourceStatus !== "string") {
525
- throw new Error("Gate 5 frozen set package-contract coverage is invalid");
526
- }
527
- if (coverage.sourceStatus === "unresolved-missing-installed-source") {
528
- expectedUnresolved.push(`${coverage.targetRel}\0installed package target is missing from the root-source set`);
240
+ const versionLabelRows = stackLines.filter((line) => line.text.startsWith("| Agent Handoff Kit template version |"));
241
+ if (versionLabelRows.length !== candidateRows.length || candidateRows.length !== 1) return null;
242
+ const [row] = candidateRows;
243
+ return { version: row.version, row: row.row, rowStart: row.rowStart, rowEnd: row.rowEnd };
244
+ }
245
+
246
+ export function markdownVisibleLinesOutsideHiddenBlocks(text) {
247
+ const value = String(text);
248
+ const normalized = value.replace(/\r\n/g, "\n");
249
+ const lines = normalized.split("\n");
250
+ const result = [];
251
+ let offset = 0;
252
+ let fence = null;
253
+ let inComment = false;
254
+ for (let index = 0; index < lines.length; index += 1) {
255
+ const line = lines[index];
256
+ if (inComment) {
257
+ if (line.includes("-->")) inComment = false;
258
+ offset += line.length + 1;
259
+ continue;
529
260
  }
261
+ const fenceMatch = /^\s{0,3}(`{3,}|~{3,})(?![`~])(.*)$/u.exec(line);
262
+ const fenceRun = fenceMatch?.[1] ?? null;
263
+ if (fence) {
264
+ if (
265
+ fenceRun
266
+ && fenceRun[0] === fence.char
267
+ && fenceRun.length >= fence.length
268
+ && /^\s*$/u.test(fenceMatch?.[2] ?? "")
269
+ ) {
270
+ fence = null;
271
+ }
272
+ offset += line.length + 1;
273
+ continue;
274
+ }
275
+ if (fenceRun) {
276
+ fence = { char: fenceRun[0], length: fenceRun.length };
277
+ offset += line.length + 1;
278
+ continue;
279
+ }
280
+ const commentStart = line.indexOf("<!--");
281
+ if (commentStart >= 0) {
282
+ if (line.indexOf("-->", commentStart + 4) < 0) inComment = true;
283
+ offset += line.length + 1;
284
+ continue;
285
+ }
286
+ result.push({
287
+ text: line,
288
+ line: index,
289
+ normalizedStart: offset,
290
+ normalizedEnd: offset + line.length,
291
+ start: originalOffsetForNormalizedOffset(value, offset),
292
+ end: originalOffsetForNormalizedOffset(value, offset + line.length)
293
+ });
294
+ offset += line.length + 1;
530
295
  }
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");
296
+ return result;
297
+ }
298
+
299
+ function originalOffsetForNormalizedOffset(text, normalizedOffset) {
300
+ let original = 0;
301
+ let normalized = 0;
302
+ while (original < text.length && normalized < normalizedOffset) {
303
+ if (text[original] === "\r" && text[original + 1] === "\n") {
304
+ original += 2;
305
+ normalized += 1;
306
+ } else {
307
+ original += 1;
308
+ normalized += 1;
309
+ }
540
310
  }
541
- if (JSON.stringify(actualUnresolved) !== JSON.stringify([...actualUnresolved].sort((left, right) => left.localeCompare(right)))) {
542
- throw new Error("Gate 5 frozen set unresolved list is not in canonical order");
543
- }
544
- if (JSON.stringify(actualUnresolved) !== JSON.stringify([...expectedUnresolved].sort((left, right) => left.localeCompare(right)))) {
545
- throw new Error("Gate 5 frozen set unresolved list does not exactly match item states");
546
- }
547
- const { frozenSetSha256, ...body } = frozen;
548
- if (frozenSetSha256 !== sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8"))) throw new Error("Gate 5 frozen-set digest does not match its contents");
549
- return true;
550
- }
551
-
552
- function normalizeContracts(contracts, transitionContracts) {
553
- const seen = new Set();
554
- const all = [];
555
- for (const [scope, source] of [["installed", contracts], ["transition", transitionContracts]]) {
556
- for (const contract of source) {
557
- if (seen.has(contract.targetRel)) continue;
558
- seen.add(contract.targetRel);
559
- all.push(Object.freeze({ ...contract, scope }));
560
- }
561
- }
562
- return all;
563
- }
564
-
565
- function binding(entryByPath, targetRel) {
566
- const entry = entryByPath.get(targetRel);
567
- return Object.freeze({
568
- path: targetRel,
569
- present: Boolean(entry),
570
- sourceIdentity: entry ? Object.freeze({ sha256: entry.sha256, bytes: entry.bytes }) : null,
571
- readers: entry ? Object.freeze(entry.reachability.map(({ from, via }) => ({ reader: from, via })).filter(({ reader }) => isFormalReader(reader))) : Object.freeze([])
572
- });
573
- }
574
-
575
- function isFormalReader(reader) {
576
- return reader === "formal-entry" || !["managed-contract", "legacy-location", "dynamic-state"].includes(reader);
577
- }
578
-
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) {
311
+ return original;
312
+ }
313
+
314
+ function isStableSemver(value) {
315
+ return /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(String(value));
316
+ }
317
+
318
+ export function extractExplicitLocalReferences(text) {
590
319
  const matches = new Map();
591
320
  const add = (raw, via) => {
592
321
  const normalized = normalizeReference(raw);