@adamchanadam/agent-handoff-kit 0.3.42 → 0.3.43
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +81 -0
- package/README.md +5 -3
- package/bin/agent-handoff-kit.mjs +45 -12
- package/bin/installed-file-contract.mjs +74 -74
- package/bin/migration-baselines/official-origin-catalog.json +10039 -10039
- package/bin/official-origin-catalog.mjs +74 -74
- package/bin/semantic-candidate.mjs +594 -594
- package/bin/upgrade-inventory.mjs +587 -587
- package/bin/user-rules-router.mjs +461 -461
- package/package.json +20 -20
- package/packs/closeout.md +15 -15
- package/packs/communication.md +8 -8
- package/packs/onboarding.md +1 -1
- package/runtime-core/AGENTS.core.md +8 -8
- package/runtime-core/PROJECT_INDEX.md +1 -1
- package/runtime-core/SESSION_HANDOFF.md +12 -12
- package/runtime-core/START_NEXT_SESSION_PROMPT.txt +1 -1
- package/runtime-core/USER_RULES.md +30 -30
- package/runtime-core/USER_RULES_ENTRY.md +7 -7
|
@@ -1,587 +1,587 @@
|
|
|
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";
|
|
6
|
-
|
|
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
|
-
|
|
11
|
-
const formalEntryTargets = Object.freeze([
|
|
12
|
-
"AGENTS.md",
|
|
13
|
-
"CLAUDE.md",
|
|
14
|
-
"GEMINI.md",
|
|
15
|
-
"START_NEXT_SESSION_PROMPT.txt"
|
|
16
|
-
]);
|
|
17
|
-
|
|
18
|
-
const dynamicDirectories = Object.freeze([
|
|
19
|
-
{ relative: "dev/governance_migrations", classification: "transaction-state" },
|
|
20
|
-
{ relative: "dev/session_log_archive", classification: "legacy-session-log-archive" }
|
|
21
|
-
]);
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Builds a read-only, hash-bound description of the Kit data that an upgrade
|
|
25
|
-
* can reach. It deliberately records whole source files before any semantic
|
|
26
|
-
* candidate tries to divide or merge their contents: a heading, language, or
|
|
27
|
-
* layout is never treated as ownership evidence.
|
|
28
|
-
*/
|
|
29
|
-
export async function buildUpgradeInventory({ root, contracts = installedFileContracts } = {}) {
|
|
30
|
-
if (!root) throw new Error("upgrade inventory requires a project root");
|
|
31
|
-
const rootPath = path.resolve(root);
|
|
32
|
-
const rootStats = await lstat(rootPath).catch((error) => {
|
|
33
|
-
if (error?.code === "ENOENT") return null;
|
|
34
|
-
throw error;
|
|
35
|
-
});
|
|
36
|
-
if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) {
|
|
37
|
-
throw new Error("upgrade inventory root must be a real directory");
|
|
38
|
-
}
|
|
39
|
-
const realRoot = await realpath(rootPath);
|
|
40
|
-
const entries = new Map();
|
|
41
|
-
const blockers = [];
|
|
42
|
-
const queue = [];
|
|
43
|
-
const queued = new Set();
|
|
44
|
-
|
|
45
|
-
const addBlocker = (relative, reason) => {
|
|
46
|
-
const key = `${relative}\0${reason}`;
|
|
47
|
-
if (!blockers.some((item) => `${item.path}\0${item.reason}` === key)) blockers.push({ path: relative, reason });
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
async function addFile(relative, classification, reachability = null, enqueueForReferences = false) {
|
|
51
|
-
const normalized = normalizeProjectRelative(relative);
|
|
52
|
-
if (!normalized) {
|
|
53
|
-
addBlocker(String(relative), "reference escapes the selected project root");
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
const absolute = path.resolve(rootPath, normalized);
|
|
57
|
-
if (!isInside(rootPath, absolute)) {
|
|
58
|
-
addBlocker(normalized, "reference escapes the selected project root");
|
|
59
|
-
return null;
|
|
60
|
-
}
|
|
61
|
-
const stats = await lstat(absolute).catch((error) => {
|
|
62
|
-
if (error?.code === "ENOENT") return null;
|
|
63
|
-
throw error;
|
|
64
|
-
});
|
|
65
|
-
if (!stats) return null;
|
|
66
|
-
if (stats.isSymbolicLink()) {
|
|
67
|
-
addBlocker(normalized, "symbolic links and junctions are not accepted as inventory sources");
|
|
68
|
-
return null;
|
|
69
|
-
}
|
|
70
|
-
if (!stats.isFile()) {
|
|
71
|
-
addBlocker(normalized, "inventory source is not a regular file");
|
|
72
|
-
return null;
|
|
73
|
-
}
|
|
74
|
-
const resolved = await realpath(absolute);
|
|
75
|
-
if (!isInside(realRoot, resolved)) {
|
|
76
|
-
addBlocker(normalized, "resolved inventory source is outside the selected project root");
|
|
77
|
-
return null;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const buffer = await readFile(absolute);
|
|
81
|
-
let entry = entries.get(normalized);
|
|
82
|
-
if (!entry) {
|
|
83
|
-
entry = {
|
|
84
|
-
path: normalized,
|
|
85
|
-
sha256: sha256(buffer),
|
|
86
|
-
bytes: buffer.length,
|
|
87
|
-
classifications: new Set(),
|
|
88
|
-
reachability: new Map(),
|
|
89
|
-
text: decodeUtf8(buffer)
|
|
90
|
-
};
|
|
91
|
-
entries.set(normalized, entry);
|
|
92
|
-
}
|
|
93
|
-
entry.classifications.add(classification);
|
|
94
|
-
if (reachability) entry.reachability.set(`${reachability.from}\0${reachability.via}`, reachability);
|
|
95
|
-
if (enqueueForReferences && entry.text != null && !queued.has(normalized)) {
|
|
96
|
-
queued.add(normalized);
|
|
97
|
-
queue.push(entry);
|
|
98
|
-
}
|
|
99
|
-
return entry;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
for (const contract of contracts) {
|
|
103
|
-
const isFormalEntry = formalEntryTargets.includes(contract.targetRel);
|
|
104
|
-
await addFile(
|
|
105
|
-
contract.targetRel,
|
|
106
|
-
"managed-contract",
|
|
107
|
-
isFormalEntry ? { from: "formal-entry", via: contract.targetRel } : { from: "managed-contract", via: contract.targetRel },
|
|
108
|
-
true
|
|
109
|
-
);
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
for (const directory of dynamicDirectories) {
|
|
113
|
-
await addTree(directory.relative, directory.classification);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
for (const contract of contracts) {
|
|
117
|
-
if (!contract.targetRel.startsWith("dev/rules/")) continue;
|
|
118
|
-
const legacy = `dev/${path.posix.basename(contract.targetRel)}`;
|
|
119
|
-
await addFile(legacy, "legacy-rule-location", { from: "legacy-location", via: legacy }, true);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
while (queue.length > 0) {
|
|
123
|
-
const source = queue.shift();
|
|
124
|
-
for (const reference of extractExplicitLocalReferences(source.text)) {
|
|
125
|
-
const target = normalizeProjectRelative(reference.path);
|
|
126
|
-
if (!target) continue;
|
|
127
|
-
await addFile(target, "formal-reference", { from: source.path, via: reference.via }, true);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
const frozenEntries = [...entries.values()]
|
|
132
|
-
.map((entry) => ({
|
|
133
|
-
path: entry.path,
|
|
134
|
-
sha256: entry.sha256,
|
|
135
|
-
bytes: entry.bytes,
|
|
136
|
-
classifications: [...entry.classifications].sort(),
|
|
137
|
-
reachability: [...entry.reachability.values()]
|
|
138
|
-
.sort((left, right) => `${left.from}\0${left.via}`.localeCompare(`${right.from}\0${right.via}`))
|
|
139
|
-
}))
|
|
140
|
-
.sort((left, right) => left.path.localeCompare(right.path));
|
|
141
|
-
const sortedBlockers = blockers.sort((left, right) => `${left.path}\0${left.reason}`.localeCompare(`${right.path}\0${right.reason}`));
|
|
142
|
-
const digestInput = {
|
|
143
|
-
schemaVersion: UPGRADE_INVENTORY_SCHEMA,
|
|
144
|
-
entries: frozenEntries,
|
|
145
|
-
blockers: sortedBlockers
|
|
146
|
-
};
|
|
147
|
-
|
|
148
|
-
return Object.freeze({
|
|
149
|
-
schemaVersion: UPGRADE_INVENTORY_SCHEMA,
|
|
150
|
-
status: sortedBlockers.length === 0 ? "ready" : "blocked",
|
|
151
|
-
entries: frozenEntries,
|
|
152
|
-
blockers: sortedBlockers,
|
|
153
|
-
inventorySha256: sha256(Buffer.from(`${JSON.stringify(digestInput)}\n`, "utf8")),
|
|
154
|
-
formalEntryTargets: formalEntryTargets.filter((target) => entries.has(target))
|
|
155
|
-
});
|
|
156
|
-
|
|
157
|
-
async function addTree(relativeDirectory, classification) {
|
|
158
|
-
const normalized = normalizeProjectRelative(relativeDirectory);
|
|
159
|
-
if (!normalized) {
|
|
160
|
-
addBlocker(String(relativeDirectory), "dynamic directory escapes the selected project root");
|
|
161
|
-
return;
|
|
162
|
-
}
|
|
163
|
-
const absolute = path.resolve(rootPath, normalized);
|
|
164
|
-
const stats = await lstat(absolute).catch((error) => {
|
|
165
|
-
if (error?.code === "ENOENT") return null;
|
|
166
|
-
throw error;
|
|
167
|
-
});
|
|
168
|
-
if (!stats) return;
|
|
169
|
-
if (!stats.isDirectory() || stats.isSymbolicLink()) {
|
|
170
|
-
addBlocker(normalized, "dynamic inventory directory is not a safe real directory");
|
|
171
|
-
return;
|
|
172
|
-
}
|
|
173
|
-
const resolved = await realpath(absolute);
|
|
174
|
-
if (!isInside(realRoot, resolved)) {
|
|
175
|
-
addBlocker(normalized, "dynamic inventory directory resolves outside the selected project root");
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
for (const item of await readdir(absolute, { withFileTypes: true })) {
|
|
179
|
-
const child = `${normalized}/${item.name}`;
|
|
180
|
-
if (item.isDirectory()) await addTree(child, classification);
|
|
181
|
-
else if (item.isFile()) await addFile(child, classification, { from: "dynamic-state", via: normalized }, false);
|
|
182
|
-
else addBlocker(child, "dynamic inventory source is not a regular file or directory");
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* Gate 5 needs a stronger closure than the shared semantic-candidate
|
|
189
|
-
* inventory: every regular project source under the selected root receives a
|
|
190
|
-
* raw-byte witness, even when no currently known Kit reader reaches it. The
|
|
191
|
-
* latter is recorded as explicitly outside the known Kit reachability set,
|
|
192
|
-
* never silently omitted. This is read-only evidence; it does not choose an
|
|
193
|
-
* upgrade action or make an unknown source Kit-managed.
|
|
194
|
-
*/
|
|
195
|
-
export async function buildGate5RootSourceInventory({ root, reachableInventory } = {}) {
|
|
196
|
-
if (!root) throw new Error("Gate 5 root-source inventory requires a project root");
|
|
197
|
-
if (!reachableInventory || reachableInventory.schemaVersion !== UPGRADE_INVENTORY_SCHEMA) {
|
|
198
|
-
throw new Error("Gate 5 root-source inventory requires the current reachable inventory");
|
|
199
|
-
}
|
|
200
|
-
const rootPath = path.resolve(root);
|
|
201
|
-
const rootStats = await lstat(rootPath).catch((error) => {
|
|
202
|
-
if (error?.code === "ENOENT") return null;
|
|
203
|
-
throw error;
|
|
204
|
-
});
|
|
205
|
-
if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) {
|
|
206
|
-
throw new Error("Gate 5 root-source inventory root must be a real directory");
|
|
207
|
-
}
|
|
208
|
-
const rootReal = await realpath(rootPath);
|
|
209
|
-
const reachableByPath = new Map(reachableInventory.entries.map((entry) => [entry.path, entry]));
|
|
210
|
-
const entries = new Map();
|
|
211
|
-
const blockers = [...reachableInventory.blockers];
|
|
212
|
-
const exclusions = Object.freeze([{ path: ".git", reason: "version-control metadata is not project content unless a formal reader explicitly reaches it" }]);
|
|
213
|
-
|
|
214
|
-
const addBlocker = (relative, reason) => {
|
|
215
|
-
const key = `${relative}\0${reason}`;
|
|
216
|
-
if (!blockers.some((item) => `${item.path}\0${item.reason}` === key)) blockers.push({ path: relative, reason });
|
|
217
|
-
};
|
|
218
|
-
|
|
219
|
-
async function addFile(relative) {
|
|
220
|
-
const normalized = normalizeProjectRelative(relative);
|
|
221
|
-
if (!normalized) {
|
|
222
|
-
addBlocker(String(relative), "root-source path escapes the selected project root");
|
|
223
|
-
return;
|
|
224
|
-
}
|
|
225
|
-
const absolute = path.resolve(rootPath, normalized);
|
|
226
|
-
if (!isInside(rootPath, absolute)) {
|
|
227
|
-
addBlocker(normalized, "root-source path escapes the selected project root");
|
|
228
|
-
return;
|
|
229
|
-
}
|
|
230
|
-
const stats = await lstat(absolute).catch((error) => {
|
|
231
|
-
if (error?.code === "ENOENT") return null;
|
|
232
|
-
throw error;
|
|
233
|
-
});
|
|
234
|
-
if (!stats) return;
|
|
235
|
-
if (stats.isSymbolicLink()) {
|
|
236
|
-
addBlocker(normalized, "symbolic links and junctions are not accepted as root-source inputs");
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
if (!stats.isFile()) {
|
|
240
|
-
addBlocker(normalized, "root-source input is not a regular file");
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
243
|
-
const resolved = await realpath(absolute);
|
|
244
|
-
if (!isInside(rootReal, resolved)) {
|
|
245
|
-
addBlocker(normalized, "root-source input resolves outside the selected project root");
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
const bytes = await readFile(absolute);
|
|
249
|
-
const reachable = reachableByPath.get(normalized);
|
|
250
|
-
// A same-name dev/<rule>.md probe is discovery-only. It is neither a
|
|
251
|
-
// package contract nor a formal reader/effect witness, so Gate 5 must not
|
|
252
|
-
// let that path shape turn an ordinary root source into a Kit item. Actual
|
|
253
|
-
// formal references remain intact and continue to establish reachability.
|
|
254
|
-
const classifications = (reachable?.classifications ?? []).filter((classification) => classification !== "legacy-rule-location");
|
|
255
|
-
const reachability = (reachable?.reachability ?? []).filter((entry) => entry.from !== "legacy-location");
|
|
256
|
-
entries.set(normalized, Object.freeze({
|
|
257
|
-
path: normalized,
|
|
258
|
-
sha256: sha256(bytes),
|
|
259
|
-
bytes: bytes.length,
|
|
260
|
-
classifications: Object.freeze(["root-source", ...classifications].sort()),
|
|
261
|
-
reachability: Object.freeze([...reachability]
|
|
262
|
-
.sort((left, right) => `${left.from}\0${left.via}`.localeCompare(`${right.from}\0${right.via}`)))
|
|
263
|
-
}));
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
async function walk(relative = "") {
|
|
267
|
-
const absolute = relative ? path.join(rootPath, relative) : rootPath;
|
|
268
|
-
const children = await readdir(absolute, { withFileTypes: true });
|
|
269
|
-
children.sort((left, right) => left.name.localeCompare(right.name));
|
|
270
|
-
for (const child of children) {
|
|
271
|
-
const childRelative = relative ? `${relative}/${child.name}` : child.name;
|
|
272
|
-
if (childRelative === ".git") continue;
|
|
273
|
-
if (child.isSymbolicLink()) {
|
|
274
|
-
addBlocker(childRelative, "symbolic links and junctions are not accepted as root-source inputs");
|
|
275
|
-
} else if (child.isDirectory()) {
|
|
276
|
-
await walk(childRelative);
|
|
277
|
-
} else if (child.isFile()) {
|
|
278
|
-
await addFile(childRelative);
|
|
279
|
-
} else {
|
|
280
|
-
addBlocker(childRelative, "root-source input is not a regular file or directory");
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
await walk();
|
|
286
|
-
for (const reachable of reachableInventory.entries) {
|
|
287
|
-
if (!entries.has(reachable.path)) {
|
|
288
|
-
addBlocker(reachable.path, "reachable inventory source was absent from the root-source scan");
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
const frozenEntries = [...entries.values()].sort((left, right) => left.path.localeCompare(right.path));
|
|
292
|
-
const sortedBlockers = blockers.sort((left, right) => `${left.path}\0${left.reason}`.localeCompare(`${right.path}\0${right.reason}`));
|
|
293
|
-
const body = {
|
|
294
|
-
schemaVersion: GATE5_ROOT_SOURCE_INVENTORY_SCHEMA,
|
|
295
|
-
entries: frozenEntries,
|
|
296
|
-
blockers: sortedBlockers,
|
|
297
|
-
exclusions
|
|
298
|
-
};
|
|
299
|
-
return Object.freeze({
|
|
300
|
-
...body,
|
|
301
|
-
status: sortedBlockers.length === 0 ? "ready" : "blocked",
|
|
302
|
-
rootSourceSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8"))
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
/**
|
|
307
|
-
* Freezes the complete set that a Gate 5 upgrade may reason about before any
|
|
308
|
-
* candidate, transaction, or semantic disposition is attempted. This is not
|
|
309
|
-
* an activation record and grants no write authority: it binds every reached
|
|
310
|
-
* project source's raw bytes to the installed package contract, formal
|
|
311
|
-
* historical source, transaction/registry surface, bridges, router, and
|
|
312
|
-
* formal entry.
|
|
313
|
-
*/
|
|
314
|
-
export async function freezeGate5Set({ root, contracts = installedFileContracts, transitionContracts = upgradeStateFileContracts, catalog = null } = {}) {
|
|
315
|
-
const inventory = await buildUpgradeInventory({ root, contracts });
|
|
316
|
-
if (inventory.status !== "ready") throw new Error("Gate 5 frozen set requires a ready reachable inventory");
|
|
317
|
-
const rootSourceInventory = await buildGate5RootSourceInventory({ root, reachableInventory: inventory });
|
|
318
|
-
if (rootSourceInventory.status !== "ready") throw new Error("Gate 5 frozen set requires a complete safe root-source inventory");
|
|
319
|
-
const rootPath = path.resolve(root);
|
|
320
|
-
const officialCatalog = catalog ?? await loadOfficialOriginCatalog();
|
|
321
|
-
const packageContracts = normalizeContracts(contracts, transitionContracts);
|
|
322
|
-
const contractByTarget = new Map(packageContracts.map((contract) => [contract.targetRel, contract]));
|
|
323
|
-
const contractBody = {
|
|
324
|
-
schemaVersion: INSTALLED_FILE_CONTRACT_SCHEMA,
|
|
325
|
-
installed: contracts.map(({ sourceRel, targetRel, strategy }) => ({ sourceRel, targetRel, strategy })),
|
|
326
|
-
transition: transitionContracts.map(({ sourceRel, targetRel, strategy }) => ({ sourceRel, targetRel, strategy }))
|
|
327
|
-
};
|
|
328
|
-
const contractDigestSha256 = sha256(Buffer.from(`${JSON.stringify(contractBody)}\n`, "utf8"));
|
|
329
|
-
const installedTemplateVersion = await readInstalledTemplateVersion(rootPath);
|
|
330
|
-
const release = installedTemplateVersion ? officialCatalog.releases?.[installedTemplateVersion] : null;
|
|
331
|
-
const entryByPath = new Map(rootSourceInventory.entries.map((entry) => [entry.path, entry]));
|
|
332
|
-
const items = rootSourceInventory.entries.map((entry) => {
|
|
333
|
-
const contract = contractByTarget.get(entry.path) ?? null;
|
|
334
|
-
const historicalEntry = contract && release?.manifest?.[entry.path]?.state === "present"
|
|
335
|
-
? release.manifest[entry.path]
|
|
336
|
-
: null;
|
|
337
|
-
const exactPackageBytes = Boolean(historicalEntry && entry.sha256 === historicalEntry.rawSha256);
|
|
338
|
-
const discoveredReachability = entry.reachability.map(({ from, via }) => ({ reader: from, via }));
|
|
339
|
-
const readers = discoveredReachability.filter(({ reader }) => isFormalReader(reader));
|
|
340
|
-
const kitReachable = entry.classifications.some((classification) => classification !== "root-source");
|
|
341
|
-
const unresolvedReason = !kitReachable
|
|
342
|
-
? null
|
|
343
|
-
: !exactPackageBytes
|
|
344
|
-
? "non-exact-or-unknown bytes require a verified preserve destination or remain unresolved"
|
|
345
|
-
: readers.length === 0
|
|
346
|
-
? "no verified existing reader; priority and effect remain unresolved"
|
|
347
|
-
: "reader is recorded, but priority/conflict and runtime effect remain unresolved before a per-item transaction proof";
|
|
348
|
-
return Object.freeze({
|
|
349
|
-
sourcePath: entry.path,
|
|
350
|
-
sourceIdentity: Object.freeze({ sha256: entry.sha256, bytes: entry.bytes }),
|
|
351
|
-
classifications: Object.freeze([...entry.classifications]),
|
|
352
|
-
existingReaders: Object.freeze(readers),
|
|
353
|
-
discoveredReachability: Object.freeze(discoveredReachability),
|
|
354
|
-
priorityConflict: Object.freeze({
|
|
355
|
-
status: kitReachable ? "unresolved-before-runtime-validation" : "not-applicable-outside-known-kit-reachability",
|
|
356
|
-
relation: !kitReachable ? "outside-known-kit-reachability" : readers.length > 0 ? "reader-reachable-priority-not-proven" : "no-verified-reader"
|
|
357
|
-
}),
|
|
358
|
-
effect: Object.freeze({
|
|
359
|
-
status: kitReachable ? "unresolved-before-runtime-validation" : "not-applicable-outside-known-kit-reachability",
|
|
360
|
-
decision: !kitReachable ? "outside-known-kit-reachability" : readers.length > 0 ? "preserve-existing-route-or-stop" : "unresolved"
|
|
361
|
-
}),
|
|
362
|
-
packageContract: contract
|
|
363
|
-
? Object.freeze({ sourceRel: contract.sourceRel, targetRel: contract.targetRel, strategy: contract.strategy, scope: contract.scope })
|
|
364
|
-
: null,
|
|
365
|
-
historicalOrigin: historicalEntry
|
|
366
|
-
? Object.freeze({
|
|
367
|
-
packageIdentity: release.source.npm.spec,
|
|
368
|
-
installedTemplateVersion,
|
|
369
|
-
rawSha256: historicalEntry.rawSha256,
|
|
370
|
-
exactPackageBytes,
|
|
371
|
-
catalogDigestSha256: officialCatalog.catalogDigestSha256
|
|
372
|
-
})
|
|
373
|
-
: null,
|
|
374
|
-
ownership: exactPackageBytes && contract?.scope === "installed"
|
|
375
|
-
? "kit-managed-exact"
|
|
376
|
-
: "user-or-unknown",
|
|
377
|
-
unresolvedReason
|
|
378
|
-
});
|
|
379
|
-
});
|
|
380
|
-
const contractCoverage = packageContracts.map((contract) => {
|
|
381
|
-
const source = entryByPath.get(contract.targetRel) ?? null;
|
|
382
|
-
const historicalState = release?.manifest?.[contract.targetRel]?.state ?? "unavailable";
|
|
383
|
-
const status = source
|
|
384
|
-
? "source-frozen"
|
|
385
|
-
: historicalState === "absent"
|
|
386
|
-
? "not-present-in-historical-package"
|
|
387
|
-
: contract.scope === "transition"
|
|
388
|
-
? "not-present-no-formal-transition-state"
|
|
389
|
-
: "unresolved-missing-installed-source";
|
|
390
|
-
return Object.freeze({
|
|
391
|
-
sourceRel: contract.sourceRel,
|
|
392
|
-
targetRel: contract.targetRel,
|
|
393
|
-
strategy: contract.strategy,
|
|
394
|
-
scope: contract.scope,
|
|
395
|
-
sourceStatus: status,
|
|
396
|
-
sourceIdentity: source ? Object.freeze({ sha256: source.sha256, bytes: source.bytes }) : null,
|
|
397
|
-
historicalState
|
|
398
|
-
});
|
|
399
|
-
});
|
|
400
|
-
const unresolvedItems = items
|
|
401
|
-
.filter((item) => item.unresolvedReason)
|
|
402
|
-
.map((item) => Object.freeze({ sourcePath: item.sourcePath, reason: item.unresolvedReason }));
|
|
403
|
-
const unresolvedContractTargets = contractCoverage
|
|
404
|
-
.filter((item) => item.sourceStatus === "unresolved-missing-installed-source")
|
|
405
|
-
.map((item) => Object.freeze({ sourcePath: item.targetRel, reason: "installed package target is missing from the root-source set" }));
|
|
406
|
-
const bridgePaths = ["CLAUDE.md", "GEMINI.md"];
|
|
407
|
-
const body = {
|
|
408
|
-
schemaVersion: GATE5_FROZEN_SET_SCHEMA,
|
|
409
|
-
operationAuthority: "none",
|
|
410
|
-
activationStatus: "not-authorized",
|
|
411
|
-
inventory: Object.freeze({ schemaVersion: inventory.schemaVersion, sha256: inventory.inventorySha256 }),
|
|
412
|
-
rootSourceInventory: Object.freeze({
|
|
413
|
-
schemaVersion: rootSourceInventory.schemaVersion,
|
|
414
|
-
sha256: rootSourceInventory.rootSourceSha256,
|
|
415
|
-
entryCount: rootSourceInventory.entries.length,
|
|
416
|
-
exclusions: rootSourceInventory.exclusions
|
|
417
|
-
}),
|
|
418
|
-
packageContract: Object.freeze({
|
|
419
|
-
schemaVersion: INSTALLED_FILE_CONTRACT_SCHEMA,
|
|
420
|
-
digestSha256: contractDigestSha256,
|
|
421
|
-
installedTargets: Object.freeze(contracts.map(({ targetRel }) => targetRel)),
|
|
422
|
-
transitionTargets: Object.freeze(transitionContracts.map(({ targetRel }) => targetRel)),
|
|
423
|
-
coverage: Object.freeze(contractCoverage)
|
|
424
|
-
}),
|
|
425
|
-
historicalSource: Object.freeze({
|
|
426
|
-
catalogSchemaVersion: officialCatalog.schemaVersion,
|
|
427
|
-
catalogDigestSha256: officialCatalog.catalogDigestSha256,
|
|
428
|
-
installedTemplateVersion,
|
|
429
|
-
packageIdentity: release?.source?.npm?.spec ?? null,
|
|
430
|
-
packageIntegrity: release?.source?.npm?.integrity ?? null,
|
|
431
|
-
status: release ? "bound-to-installed-catalog-identity" : "unresolved-no-catalog-release-for-installed-version"
|
|
432
|
-
}),
|
|
433
|
-
formalSurfaces: Object.freeze({
|
|
434
|
-
entry: binding(entryByPath, "AGENTS.md"),
|
|
435
|
-
bridges: Object.freeze(bridgePaths.map((targetRel) => binding(entryByPath, targetRel))),
|
|
436
|
-
router: binding(entryByPath, "dev/USER_RULES.md"),
|
|
437
|
-
transactionRegistry: Object.freeze({
|
|
438
|
-
root: "dev/governance_migrations",
|
|
439
|
-
entries: Object.freeze(items.filter((item) => item.classifications.includes("transaction-state")).map((item) => item.sourcePath))
|
|
440
|
-
})
|
|
441
|
-
}),
|
|
442
|
-
items: Object.freeze(items),
|
|
443
|
-
unresolved: Object.freeze([...unresolvedItems, ...unresolvedContractTargets]
|
|
444
|
-
.sort((left, right) => `${left.sourcePath}\0${left.reason}`.localeCompare(`${right.sourcePath}\0${right.reason}`)))
|
|
445
|
-
};
|
|
446
|
-
return Object.freeze({ ...body, frozenSetSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) });
|
|
447
|
-
}
|
|
448
|
-
|
|
449
|
-
export function assertGate5FrozenSet(frozen) {
|
|
450
|
-
if (!frozen || typeof frozen !== "object" || Array.isArray(frozen)) throw new Error("Gate 5 frozen set is required");
|
|
451
|
-
if (frozen.schemaVersion !== GATE5_FROZEN_SET_SCHEMA) throw new Error("unsupported Gate 5 frozen-set schema");
|
|
452
|
-
if (frozen.operationAuthority !== "none" || frozen.activationStatus !== "not-authorized") throw new Error("Gate 5 frozen set must not claim operation authority");
|
|
453
|
-
if (!Array.isArray(frozen.items) || frozen.items.length === 0) throw new Error("Gate 5 frozen set has no items");
|
|
454
|
-
if (!frozen.rootSourceInventory || frozen.rootSourceInventory.schemaVersion !== GATE5_ROOT_SOURCE_INVENTORY_SCHEMA
|
|
455
|
-
|| !/^[0-9a-f]{64}$/.test(frozen.rootSourceInventory.sha256)
|
|
456
|
-
|| !Number.isInteger(frozen.rootSourceInventory.entryCount) || frozen.rootSourceInventory.entryCount !== frozen.items.length
|
|
457
|
-
|| !Array.isArray(frozen.rootSourceInventory.exclusions)) {
|
|
458
|
-
throw new Error("Gate 5 frozen set does not bind a complete root-source inventory");
|
|
459
|
-
}
|
|
460
|
-
if (!frozen.packageContract || !Array.isArray(frozen.packageContract.coverage)) {
|
|
461
|
-
throw new Error("Gate 5 frozen set does not bind package-contract coverage");
|
|
462
|
-
}
|
|
463
|
-
const paths = new Set();
|
|
464
|
-
const orderedPaths = [];
|
|
465
|
-
for (const item of frozen.items) {
|
|
466
|
-
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");
|
|
467
|
-
paths.add(item.sourcePath);
|
|
468
|
-
orderedPaths.push(item.sourcePath);
|
|
469
|
-
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}`);
|
|
470
|
-
if (!Array.isArray(item.classifications) || !item.classifications.includes("root-source")
|
|
471
|
-
|| !Array.isArray(item.existingReaders) || !item.priorityConflict?.status || !item.effect?.status
|
|
472
|
-
|| !(item.unresolvedReason === null || typeof item.unresolvedReason === "string")) {
|
|
473
|
-
throw new Error(`Gate 5 frozen set omits root-source, reader, priority/conflict, or effect record: ${item.sourcePath}`);
|
|
474
|
-
}
|
|
475
|
-
if (!item.historicalOrigin && item.ownership !== "user-or-unknown") throw new Error(`Gate 5 frozen set assigns ownership without historical evidence: ${item.sourcePath}`);
|
|
476
|
-
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}`);
|
|
477
|
-
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}`);
|
|
478
|
-
}
|
|
479
|
-
const expectedUnresolved = frozen.items
|
|
480
|
-
.filter((item) => item.unresolvedReason)
|
|
481
|
-
.map((item) => `${item.sourcePath}\0${item.unresolvedReason}`);
|
|
482
|
-
const actualUnresolved = frozen.unresolved?.map((item) => `${item.sourcePath}\0${item.reason}`) ?? [];
|
|
483
|
-
for (const coverage of frozen.packageContract.coverage) {
|
|
484
|
-
if (!coverage || typeof coverage.targetRel !== "string" || typeof coverage.sourceStatus !== "string") {
|
|
485
|
-
throw new Error("Gate 5 frozen set package-contract coverage is invalid");
|
|
486
|
-
}
|
|
487
|
-
if (coverage.sourceStatus === "unresolved-missing-installed-source") {
|
|
488
|
-
expectedUnresolved.push(`${coverage.targetRel}\0installed package target is missing from the root-source set`);
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
if (JSON.stringify(orderedPaths) !== JSON.stringify([...orderedPaths].sort((left, right) => left.localeCompare(right)))) {
|
|
492
|
-
throw new Error("Gate 5 frozen set items are not in canonical source-path order");
|
|
493
|
-
}
|
|
494
|
-
if (JSON.stringify(actualUnresolved) !== JSON.stringify([...actualUnresolved].sort((left, right) => left.localeCompare(right)))) {
|
|
495
|
-
throw new Error("Gate 5 frozen set unresolved list is not in canonical order");
|
|
496
|
-
}
|
|
497
|
-
if (JSON.stringify(actualUnresolved) !== JSON.stringify([...expectedUnresolved].sort((left, right) => left.localeCompare(right)))) {
|
|
498
|
-
throw new Error("Gate 5 frozen set unresolved list does not exactly match item states");
|
|
499
|
-
}
|
|
500
|
-
const { frozenSetSha256, ...body } = frozen;
|
|
501
|
-
if (frozenSetSha256 !== sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8"))) throw new Error("Gate 5 frozen-set digest does not match its contents");
|
|
502
|
-
return true;
|
|
503
|
-
}
|
|
504
|
-
|
|
505
|
-
function normalizeContracts(contracts, transitionContracts) {
|
|
506
|
-
const seen = new Set();
|
|
507
|
-
const all = [];
|
|
508
|
-
for (const [scope, source] of [["installed", contracts], ["transition", transitionContracts]]) {
|
|
509
|
-
for (const contract of source) {
|
|
510
|
-
if (seen.has(contract.targetRel)) continue;
|
|
511
|
-
seen.add(contract.targetRel);
|
|
512
|
-
all.push(Object.freeze({ ...contract, scope }));
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
return all;
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
function binding(entryByPath, targetRel) {
|
|
519
|
-
const entry = entryByPath.get(targetRel);
|
|
520
|
-
return Object.freeze({
|
|
521
|
-
path: targetRel,
|
|
522
|
-
present: Boolean(entry),
|
|
523
|
-
sourceIdentity: entry ? Object.freeze({ sha256: entry.sha256, bytes: entry.bytes }) : null,
|
|
524
|
-
readers: entry ? Object.freeze(entry.reachability.map(({ from, via }) => ({ reader: from, via })).filter(({ reader }) => isFormalReader(reader))) : Object.freeze([])
|
|
525
|
-
});
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
function isFormalReader(reader) {
|
|
529
|
-
return reader === "formal-entry" || !["managed-contract", "legacy-location", "dynamic-state"].includes(reader);
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
async function readInstalledTemplateVersion(root) {
|
|
533
|
-
const bytes = await readFile(path.join(root, "dev", "PROJECT_INDEX.md")).catch((error) => {
|
|
534
|
-
if (error?.code === "ENOENT") return null;
|
|
535
|
-
throw error;
|
|
536
|
-
});
|
|
537
|
-
if (!bytes) return null;
|
|
538
|
-
const match = /^\| Agent Handoff Kit template version \| ([0-9]+\.[0-9]+\.[0-9]+) \|/m.exec(bytes.toString("utf8"));
|
|
539
|
-
return match?.[1] ?? null;
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
export function extractExplicitLocalReferences(text) {
|
|
543
|
-
const matches = new Map();
|
|
544
|
-
const add = (raw, via) => {
|
|
545
|
-
const normalized = normalizeReference(raw);
|
|
546
|
-
if (normalized) matches.set(`${normalized}\0${via}`, { path: normalized, via });
|
|
547
|
-
};
|
|
548
|
-
for (const match of String(text).matchAll(/\[[^\]]*\]\(([^)\s]+)(?:\s+[^)]*)?\)/g)) add(match[1], "markdown-link");
|
|
549
|
-
for (const match of String(text).matchAll(/`([^`\r\n]+)`/g)) add(match[1], "inline-code-path");
|
|
550
|
-
for (const match of String(text).matchAll(/^\s*@([^\s]+)\s*$/gm)) add(match[1], "bridge-import");
|
|
551
|
-
// Do not treat the dot before a filename extension as sentence punctuation.
|
|
552
|
-
// On Windows, the truncated `dev/USER_RULES` then aliases the real
|
|
553
|
-
// `dev/user_rules/` directory, making a valid formal router look unsafe.
|
|
554
|
-
for (const match of String(text).matchAll(/(?:^|[\s("'`])((?:[\p{L}\p{N}_-]+[\\/])+[\p{L}\p{N}_. -]*[\p{L}\p{N}_.-])(?=$|[\s,;:,。!?)\]}>"'])/gu)) add(match[1], "plain-local-path");
|
|
555
|
-
return [...matches.values()].sort((left, right) => `${left.path}\0${left.via}`.localeCompare(`${right.path}\0${right.via}`));
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
function normalizeReference(raw) {
|
|
559
|
-
const value = String(raw).trim().replace(/^<|>$/g, "");
|
|
560
|
-
if (!value || value.includes("://") || value.startsWith("~") || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("/")) return null;
|
|
561
|
-
const withoutFragment = value.split(/[?#]/, 1)[0].replaceAll("\\", "/");
|
|
562
|
-
if (!withoutFragment || withoutFragment.endsWith("/") || (!withoutFragment.includes("/") && !/\.[\p{L}\p{N}]+$/u.test(withoutFragment))) return null;
|
|
563
|
-
return normalizeProjectRelative(withoutFragment);
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
function normalizeProjectRelative(relative) {
|
|
567
|
-
const normalized = path.posix.normalize(String(relative).replaceAll("\\", "/").replace(/^\.\//, ""));
|
|
568
|
-
if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../") || path.posix.isAbsolute(normalized)) return null;
|
|
569
|
-
return normalized;
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
function isInside(root, target) {
|
|
573
|
-
const relative = path.relative(path.resolve(root), path.resolve(target));
|
|
574
|
-
return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
function decodeUtf8(buffer) {
|
|
578
|
-
try {
|
|
579
|
-
return new TextDecoder("utf-8", { fatal: true }).decode(buffer);
|
|
580
|
-
} catch {
|
|
581
|
-
return null;
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
function sha256(value) {
|
|
586
|
-
return createHash("sha256").update(value).digest("hex");
|
|
587
|
-
}
|
|
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";
|
|
6
|
+
|
|
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
|
+
|
|
11
|
+
const formalEntryTargets = Object.freeze([
|
|
12
|
+
"AGENTS.md",
|
|
13
|
+
"CLAUDE.md",
|
|
14
|
+
"GEMINI.md",
|
|
15
|
+
"START_NEXT_SESSION_PROMPT.txt"
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
const dynamicDirectories = Object.freeze([
|
|
19
|
+
{ relative: "dev/governance_migrations", classification: "transaction-state" },
|
|
20
|
+
{ relative: "dev/session_log_archive", classification: "legacy-session-log-archive" }
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Builds a read-only, hash-bound description of the Kit data that an upgrade
|
|
25
|
+
* can reach. It deliberately records whole source files before any semantic
|
|
26
|
+
* candidate tries to divide or merge their contents: a heading, language, or
|
|
27
|
+
* layout is never treated as ownership evidence.
|
|
28
|
+
*/
|
|
29
|
+
export async function buildUpgradeInventory({ root, contracts = installedFileContracts } = {}) {
|
|
30
|
+
if (!root) throw new Error("upgrade inventory requires a project root");
|
|
31
|
+
const rootPath = path.resolve(root);
|
|
32
|
+
const rootStats = await lstat(rootPath).catch((error) => {
|
|
33
|
+
if (error?.code === "ENOENT") return null;
|
|
34
|
+
throw error;
|
|
35
|
+
});
|
|
36
|
+
if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) {
|
|
37
|
+
throw new Error("upgrade inventory root must be a real directory");
|
|
38
|
+
}
|
|
39
|
+
const realRoot = await realpath(rootPath);
|
|
40
|
+
const entries = new Map();
|
|
41
|
+
const blockers = [];
|
|
42
|
+
const queue = [];
|
|
43
|
+
const queued = new Set();
|
|
44
|
+
|
|
45
|
+
const addBlocker = (relative, reason) => {
|
|
46
|
+
const key = `${relative}\0${reason}`;
|
|
47
|
+
if (!blockers.some((item) => `${item.path}\0${item.reason}` === key)) blockers.push({ path: relative, reason });
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
async function addFile(relative, classification, reachability = null, enqueueForReferences = false) {
|
|
51
|
+
const normalized = normalizeProjectRelative(relative);
|
|
52
|
+
if (!normalized) {
|
|
53
|
+
addBlocker(String(relative), "reference escapes the selected project root");
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
const absolute = path.resolve(rootPath, normalized);
|
|
57
|
+
if (!isInside(rootPath, absolute)) {
|
|
58
|
+
addBlocker(normalized, "reference escapes the selected project root");
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
const stats = await lstat(absolute).catch((error) => {
|
|
62
|
+
if (error?.code === "ENOENT") return null;
|
|
63
|
+
throw error;
|
|
64
|
+
});
|
|
65
|
+
if (!stats) return null;
|
|
66
|
+
if (stats.isSymbolicLink()) {
|
|
67
|
+
addBlocker(normalized, "symbolic links and junctions are not accepted as inventory sources");
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
if (!stats.isFile()) {
|
|
71
|
+
addBlocker(normalized, "inventory source is not a regular file");
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
const resolved = await realpath(absolute);
|
|
75
|
+
if (!isInside(realRoot, resolved)) {
|
|
76
|
+
addBlocker(normalized, "resolved inventory source is outside the selected project root");
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const buffer = await readFile(absolute);
|
|
81
|
+
let entry = entries.get(normalized);
|
|
82
|
+
if (!entry) {
|
|
83
|
+
entry = {
|
|
84
|
+
path: normalized,
|
|
85
|
+
sha256: sha256(buffer),
|
|
86
|
+
bytes: buffer.length,
|
|
87
|
+
classifications: new Set(),
|
|
88
|
+
reachability: new Map(),
|
|
89
|
+
text: decodeUtf8(buffer)
|
|
90
|
+
};
|
|
91
|
+
entries.set(normalized, entry);
|
|
92
|
+
}
|
|
93
|
+
entry.classifications.add(classification);
|
|
94
|
+
if (reachability) entry.reachability.set(`${reachability.from}\0${reachability.via}`, reachability);
|
|
95
|
+
if (enqueueForReferences && entry.text != null && !queued.has(normalized)) {
|
|
96
|
+
queued.add(normalized);
|
|
97
|
+
queue.push(entry);
|
|
98
|
+
}
|
|
99
|
+
return entry;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
for (const contract of contracts) {
|
|
103
|
+
const isFormalEntry = formalEntryTargets.includes(contract.targetRel);
|
|
104
|
+
await addFile(
|
|
105
|
+
contract.targetRel,
|
|
106
|
+
"managed-contract",
|
|
107
|
+
isFormalEntry ? { from: "formal-entry", via: contract.targetRel } : { from: "managed-contract", via: contract.targetRel },
|
|
108
|
+
true
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
for (const directory of dynamicDirectories) {
|
|
113
|
+
await addTree(directory.relative, directory.classification);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
for (const contract of contracts) {
|
|
117
|
+
if (!contract.targetRel.startsWith("dev/rules/")) continue;
|
|
118
|
+
const legacy = `dev/${path.posix.basename(contract.targetRel)}`;
|
|
119
|
+
await addFile(legacy, "legacy-rule-location", { from: "legacy-location", via: legacy }, true);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
while (queue.length > 0) {
|
|
123
|
+
const source = queue.shift();
|
|
124
|
+
for (const reference of extractExplicitLocalReferences(source.text)) {
|
|
125
|
+
const target = normalizeProjectRelative(reference.path);
|
|
126
|
+
if (!target) continue;
|
|
127
|
+
await addFile(target, "formal-reference", { from: source.path, via: reference.via }, true);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const frozenEntries = [...entries.values()]
|
|
132
|
+
.map((entry) => ({
|
|
133
|
+
path: entry.path,
|
|
134
|
+
sha256: entry.sha256,
|
|
135
|
+
bytes: entry.bytes,
|
|
136
|
+
classifications: [...entry.classifications].sort(),
|
|
137
|
+
reachability: [...entry.reachability.values()]
|
|
138
|
+
.sort((left, right) => `${left.from}\0${left.via}`.localeCompare(`${right.from}\0${right.via}`))
|
|
139
|
+
}))
|
|
140
|
+
.sort((left, right) => left.path.localeCompare(right.path));
|
|
141
|
+
const sortedBlockers = blockers.sort((left, right) => `${left.path}\0${left.reason}`.localeCompare(`${right.path}\0${right.reason}`));
|
|
142
|
+
const digestInput = {
|
|
143
|
+
schemaVersion: UPGRADE_INVENTORY_SCHEMA,
|
|
144
|
+
entries: frozenEntries,
|
|
145
|
+
blockers: sortedBlockers
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
return Object.freeze({
|
|
149
|
+
schemaVersion: UPGRADE_INVENTORY_SCHEMA,
|
|
150
|
+
status: sortedBlockers.length === 0 ? "ready" : "blocked",
|
|
151
|
+
entries: frozenEntries,
|
|
152
|
+
blockers: sortedBlockers,
|
|
153
|
+
inventorySha256: sha256(Buffer.from(`${JSON.stringify(digestInput)}\n`, "utf8")),
|
|
154
|
+
formalEntryTargets: formalEntryTargets.filter((target) => entries.has(target))
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
async function addTree(relativeDirectory, classification) {
|
|
158
|
+
const normalized = normalizeProjectRelative(relativeDirectory);
|
|
159
|
+
if (!normalized) {
|
|
160
|
+
addBlocker(String(relativeDirectory), "dynamic directory escapes the selected project root");
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const absolute = path.resolve(rootPath, normalized);
|
|
164
|
+
const stats = await lstat(absolute).catch((error) => {
|
|
165
|
+
if (error?.code === "ENOENT") return null;
|
|
166
|
+
throw error;
|
|
167
|
+
});
|
|
168
|
+
if (!stats) return;
|
|
169
|
+
if (!stats.isDirectory() || stats.isSymbolicLink()) {
|
|
170
|
+
addBlocker(normalized, "dynamic inventory directory is not a safe real directory");
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const resolved = await realpath(absolute);
|
|
174
|
+
if (!isInside(realRoot, resolved)) {
|
|
175
|
+
addBlocker(normalized, "dynamic inventory directory resolves outside the selected project root");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
for (const item of await readdir(absolute, { withFileTypes: true })) {
|
|
179
|
+
const child = `${normalized}/${item.name}`;
|
|
180
|
+
if (item.isDirectory()) await addTree(child, classification);
|
|
181
|
+
else if (item.isFile()) await addFile(child, classification, { from: "dynamic-state", via: normalized }, false);
|
|
182
|
+
else addBlocker(child, "dynamic inventory source is not a regular file or directory");
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Gate 5 needs a stronger closure than the shared semantic-candidate
|
|
189
|
+
* inventory: every regular project source under the selected root receives a
|
|
190
|
+
* raw-byte witness, even when no currently known Kit reader reaches it. The
|
|
191
|
+
* latter is recorded as explicitly outside the known Kit reachability set,
|
|
192
|
+
* never silently omitted. This is read-only evidence; it does not choose an
|
|
193
|
+
* upgrade action or make an unknown source Kit-managed.
|
|
194
|
+
*/
|
|
195
|
+
export async function buildGate5RootSourceInventory({ root, reachableInventory } = {}) {
|
|
196
|
+
if (!root) throw new Error("Gate 5 root-source inventory requires a project root");
|
|
197
|
+
if (!reachableInventory || reachableInventory.schemaVersion !== UPGRADE_INVENTORY_SCHEMA) {
|
|
198
|
+
throw new Error("Gate 5 root-source inventory requires the current reachable inventory");
|
|
199
|
+
}
|
|
200
|
+
const rootPath = path.resolve(root);
|
|
201
|
+
const rootStats = await lstat(rootPath).catch((error) => {
|
|
202
|
+
if (error?.code === "ENOENT") return null;
|
|
203
|
+
throw error;
|
|
204
|
+
});
|
|
205
|
+
if (!rootStats?.isDirectory() || rootStats.isSymbolicLink()) {
|
|
206
|
+
throw new Error("Gate 5 root-source inventory root must be a real directory");
|
|
207
|
+
}
|
|
208
|
+
const rootReal = await realpath(rootPath);
|
|
209
|
+
const reachableByPath = new Map(reachableInventory.entries.map((entry) => [entry.path, entry]));
|
|
210
|
+
const entries = new Map();
|
|
211
|
+
const blockers = [...reachableInventory.blockers];
|
|
212
|
+
const exclusions = Object.freeze([{ path: ".git", reason: "version-control metadata is not project content unless a formal reader explicitly reaches it" }]);
|
|
213
|
+
|
|
214
|
+
const addBlocker = (relative, reason) => {
|
|
215
|
+
const key = `${relative}\0${reason}`;
|
|
216
|
+
if (!blockers.some((item) => `${item.path}\0${item.reason}` === key)) blockers.push({ path: relative, reason });
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
async function addFile(relative) {
|
|
220
|
+
const normalized = normalizeProjectRelative(relative);
|
|
221
|
+
if (!normalized) {
|
|
222
|
+
addBlocker(String(relative), "root-source path escapes the selected project root");
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const absolute = path.resolve(rootPath, normalized);
|
|
226
|
+
if (!isInside(rootPath, absolute)) {
|
|
227
|
+
addBlocker(normalized, "root-source path escapes the selected project root");
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
const stats = await lstat(absolute).catch((error) => {
|
|
231
|
+
if (error?.code === "ENOENT") return null;
|
|
232
|
+
throw error;
|
|
233
|
+
});
|
|
234
|
+
if (!stats) return;
|
|
235
|
+
if (stats.isSymbolicLink()) {
|
|
236
|
+
addBlocker(normalized, "symbolic links and junctions are not accepted as root-source inputs");
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (!stats.isFile()) {
|
|
240
|
+
addBlocker(normalized, "root-source input is not a regular file");
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const resolved = await realpath(absolute);
|
|
244
|
+
if (!isInside(rootReal, resolved)) {
|
|
245
|
+
addBlocker(normalized, "root-source input resolves outside the selected project root");
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
const bytes = await readFile(absolute);
|
|
249
|
+
const reachable = reachableByPath.get(normalized);
|
|
250
|
+
// A same-name dev/<rule>.md probe is discovery-only. It is neither a
|
|
251
|
+
// package contract nor a formal reader/effect witness, so Gate 5 must not
|
|
252
|
+
// let that path shape turn an ordinary root source into a Kit item. Actual
|
|
253
|
+
// formal references remain intact and continue to establish reachability.
|
|
254
|
+
const classifications = (reachable?.classifications ?? []).filter((classification) => classification !== "legacy-rule-location");
|
|
255
|
+
const reachability = (reachable?.reachability ?? []).filter((entry) => entry.from !== "legacy-location");
|
|
256
|
+
entries.set(normalized, Object.freeze({
|
|
257
|
+
path: normalized,
|
|
258
|
+
sha256: sha256(bytes),
|
|
259
|
+
bytes: bytes.length,
|
|
260
|
+
classifications: Object.freeze(["root-source", ...classifications].sort()),
|
|
261
|
+
reachability: Object.freeze([...reachability]
|
|
262
|
+
.sort((left, right) => `${left.from}\0${left.via}`.localeCompare(`${right.from}\0${right.via}`)))
|
|
263
|
+
}));
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function walk(relative = "") {
|
|
267
|
+
const absolute = relative ? path.join(rootPath, relative) : rootPath;
|
|
268
|
+
const children = await readdir(absolute, { withFileTypes: true });
|
|
269
|
+
children.sort((left, right) => left.name.localeCompare(right.name));
|
|
270
|
+
for (const child of children) {
|
|
271
|
+
const childRelative = relative ? `${relative}/${child.name}` : child.name;
|
|
272
|
+
if (childRelative === ".git") continue;
|
|
273
|
+
if (child.isSymbolicLink()) {
|
|
274
|
+
addBlocker(childRelative, "symbolic links and junctions are not accepted as root-source inputs");
|
|
275
|
+
} else if (child.isDirectory()) {
|
|
276
|
+
await walk(childRelative);
|
|
277
|
+
} else if (child.isFile()) {
|
|
278
|
+
await addFile(childRelative);
|
|
279
|
+
} else {
|
|
280
|
+
addBlocker(childRelative, "root-source input is not a regular file or directory");
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
await walk();
|
|
286
|
+
for (const reachable of reachableInventory.entries) {
|
|
287
|
+
if (!entries.has(reachable.path)) {
|
|
288
|
+
addBlocker(reachable.path, "reachable inventory source was absent from the root-source scan");
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const frozenEntries = [...entries.values()].sort((left, right) => left.path.localeCompare(right.path));
|
|
292
|
+
const sortedBlockers = blockers.sort((left, right) => `${left.path}\0${left.reason}`.localeCompare(`${right.path}\0${right.reason}`));
|
|
293
|
+
const body = {
|
|
294
|
+
schemaVersion: GATE5_ROOT_SOURCE_INVENTORY_SCHEMA,
|
|
295
|
+
entries: frozenEntries,
|
|
296
|
+
blockers: sortedBlockers,
|
|
297
|
+
exclusions
|
|
298
|
+
};
|
|
299
|
+
return Object.freeze({
|
|
300
|
+
...body,
|
|
301
|
+
status: sortedBlockers.length === 0 ? "ready" : "blocked",
|
|
302
|
+
rootSourceSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8"))
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Freezes the complete set that a Gate 5 upgrade may reason about before any
|
|
308
|
+
* candidate, transaction, or semantic disposition is attempted. This is not
|
|
309
|
+
* an activation record and grants no write authority: it binds every reached
|
|
310
|
+
* project source's raw bytes to the installed package contract, formal
|
|
311
|
+
* historical source, transaction/registry surface, bridges, router, and
|
|
312
|
+
* formal entry.
|
|
313
|
+
*/
|
|
314
|
+
export async function freezeGate5Set({ root, contracts = installedFileContracts, transitionContracts = upgradeStateFileContracts, catalog = null } = {}) {
|
|
315
|
+
const inventory = await buildUpgradeInventory({ root, contracts });
|
|
316
|
+
if (inventory.status !== "ready") throw new Error("Gate 5 frozen set requires a ready reachable inventory");
|
|
317
|
+
const rootSourceInventory = await buildGate5RootSourceInventory({ root, reachableInventory: inventory });
|
|
318
|
+
if (rootSourceInventory.status !== "ready") throw new Error("Gate 5 frozen set requires a complete safe root-source inventory");
|
|
319
|
+
const rootPath = path.resolve(root);
|
|
320
|
+
const officialCatalog = catalog ?? await loadOfficialOriginCatalog();
|
|
321
|
+
const packageContracts = normalizeContracts(contracts, transitionContracts);
|
|
322
|
+
const contractByTarget = new Map(packageContracts.map((contract) => [contract.targetRel, contract]));
|
|
323
|
+
const contractBody = {
|
|
324
|
+
schemaVersion: INSTALLED_FILE_CONTRACT_SCHEMA,
|
|
325
|
+
installed: contracts.map(({ sourceRel, targetRel, strategy }) => ({ sourceRel, targetRel, strategy })),
|
|
326
|
+
transition: transitionContracts.map(({ sourceRel, targetRel, strategy }) => ({ sourceRel, targetRel, strategy }))
|
|
327
|
+
};
|
|
328
|
+
const contractDigestSha256 = sha256(Buffer.from(`${JSON.stringify(contractBody)}\n`, "utf8"));
|
|
329
|
+
const installedTemplateVersion = await readInstalledTemplateVersion(rootPath);
|
|
330
|
+
const release = installedTemplateVersion ? officialCatalog.releases?.[installedTemplateVersion] : null;
|
|
331
|
+
const entryByPath = new Map(rootSourceInventory.entries.map((entry) => [entry.path, entry]));
|
|
332
|
+
const items = rootSourceInventory.entries.map((entry) => {
|
|
333
|
+
const contract = contractByTarget.get(entry.path) ?? null;
|
|
334
|
+
const historicalEntry = contract && release?.manifest?.[entry.path]?.state === "present"
|
|
335
|
+
? release.manifest[entry.path]
|
|
336
|
+
: null;
|
|
337
|
+
const exactPackageBytes = Boolean(historicalEntry && entry.sha256 === historicalEntry.rawSha256);
|
|
338
|
+
const discoveredReachability = entry.reachability.map(({ from, via }) => ({ reader: from, via }));
|
|
339
|
+
const readers = discoveredReachability.filter(({ reader }) => isFormalReader(reader));
|
|
340
|
+
const kitReachable = entry.classifications.some((classification) => classification !== "root-source");
|
|
341
|
+
const unresolvedReason = !kitReachable
|
|
342
|
+
? null
|
|
343
|
+
: !exactPackageBytes
|
|
344
|
+
? "non-exact-or-unknown bytes require a verified preserve destination or remain unresolved"
|
|
345
|
+
: readers.length === 0
|
|
346
|
+
? "no verified existing reader; priority and effect remain unresolved"
|
|
347
|
+
: "reader is recorded, but priority/conflict and runtime effect remain unresolved before a per-item transaction proof";
|
|
348
|
+
return Object.freeze({
|
|
349
|
+
sourcePath: entry.path,
|
|
350
|
+
sourceIdentity: Object.freeze({ sha256: entry.sha256, bytes: entry.bytes }),
|
|
351
|
+
classifications: Object.freeze([...entry.classifications]),
|
|
352
|
+
existingReaders: Object.freeze(readers),
|
|
353
|
+
discoveredReachability: Object.freeze(discoveredReachability),
|
|
354
|
+
priorityConflict: Object.freeze({
|
|
355
|
+
status: kitReachable ? "unresolved-before-runtime-validation" : "not-applicable-outside-known-kit-reachability",
|
|
356
|
+
relation: !kitReachable ? "outside-known-kit-reachability" : readers.length > 0 ? "reader-reachable-priority-not-proven" : "no-verified-reader"
|
|
357
|
+
}),
|
|
358
|
+
effect: Object.freeze({
|
|
359
|
+
status: kitReachable ? "unresolved-before-runtime-validation" : "not-applicable-outside-known-kit-reachability",
|
|
360
|
+
decision: !kitReachable ? "outside-known-kit-reachability" : readers.length > 0 ? "preserve-existing-route-or-stop" : "unresolved"
|
|
361
|
+
}),
|
|
362
|
+
packageContract: contract
|
|
363
|
+
? Object.freeze({ sourceRel: contract.sourceRel, targetRel: contract.targetRel, strategy: contract.strategy, scope: contract.scope })
|
|
364
|
+
: null,
|
|
365
|
+
historicalOrigin: historicalEntry
|
|
366
|
+
? Object.freeze({
|
|
367
|
+
packageIdentity: release.source.npm.spec,
|
|
368
|
+
installedTemplateVersion,
|
|
369
|
+
rawSha256: historicalEntry.rawSha256,
|
|
370
|
+
exactPackageBytes,
|
|
371
|
+
catalogDigestSha256: officialCatalog.catalogDigestSha256
|
|
372
|
+
})
|
|
373
|
+
: null,
|
|
374
|
+
ownership: exactPackageBytes && contract?.scope === "installed"
|
|
375
|
+
? "kit-managed-exact"
|
|
376
|
+
: "user-or-unknown",
|
|
377
|
+
unresolvedReason
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
const contractCoverage = packageContracts.map((contract) => {
|
|
381
|
+
const source = entryByPath.get(contract.targetRel) ?? null;
|
|
382
|
+
const historicalState = release?.manifest?.[contract.targetRel]?.state ?? "unavailable";
|
|
383
|
+
const status = source
|
|
384
|
+
? "source-frozen"
|
|
385
|
+
: historicalState === "absent"
|
|
386
|
+
? "not-present-in-historical-package"
|
|
387
|
+
: contract.scope === "transition"
|
|
388
|
+
? "not-present-no-formal-transition-state"
|
|
389
|
+
: "unresolved-missing-installed-source";
|
|
390
|
+
return Object.freeze({
|
|
391
|
+
sourceRel: contract.sourceRel,
|
|
392
|
+
targetRel: contract.targetRel,
|
|
393
|
+
strategy: contract.strategy,
|
|
394
|
+
scope: contract.scope,
|
|
395
|
+
sourceStatus: status,
|
|
396
|
+
sourceIdentity: source ? Object.freeze({ sha256: source.sha256, bytes: source.bytes }) : null,
|
|
397
|
+
historicalState
|
|
398
|
+
});
|
|
399
|
+
});
|
|
400
|
+
const unresolvedItems = items
|
|
401
|
+
.filter((item) => item.unresolvedReason)
|
|
402
|
+
.map((item) => Object.freeze({ sourcePath: item.sourcePath, reason: item.unresolvedReason }));
|
|
403
|
+
const unresolvedContractTargets = contractCoverage
|
|
404
|
+
.filter((item) => item.sourceStatus === "unresolved-missing-installed-source")
|
|
405
|
+
.map((item) => Object.freeze({ sourcePath: item.targetRel, reason: "installed package target is missing from the root-source set" }));
|
|
406
|
+
const bridgePaths = ["CLAUDE.md", "GEMINI.md"];
|
|
407
|
+
const body = {
|
|
408
|
+
schemaVersion: GATE5_FROZEN_SET_SCHEMA,
|
|
409
|
+
operationAuthority: "none",
|
|
410
|
+
activationStatus: "not-authorized",
|
|
411
|
+
inventory: Object.freeze({ schemaVersion: inventory.schemaVersion, sha256: inventory.inventorySha256 }),
|
|
412
|
+
rootSourceInventory: Object.freeze({
|
|
413
|
+
schemaVersion: rootSourceInventory.schemaVersion,
|
|
414
|
+
sha256: rootSourceInventory.rootSourceSha256,
|
|
415
|
+
entryCount: rootSourceInventory.entries.length,
|
|
416
|
+
exclusions: rootSourceInventory.exclusions
|
|
417
|
+
}),
|
|
418
|
+
packageContract: Object.freeze({
|
|
419
|
+
schemaVersion: INSTALLED_FILE_CONTRACT_SCHEMA,
|
|
420
|
+
digestSha256: contractDigestSha256,
|
|
421
|
+
installedTargets: Object.freeze(contracts.map(({ targetRel }) => targetRel)),
|
|
422
|
+
transitionTargets: Object.freeze(transitionContracts.map(({ targetRel }) => targetRel)),
|
|
423
|
+
coverage: Object.freeze(contractCoverage)
|
|
424
|
+
}),
|
|
425
|
+
historicalSource: Object.freeze({
|
|
426
|
+
catalogSchemaVersion: officialCatalog.schemaVersion,
|
|
427
|
+
catalogDigestSha256: officialCatalog.catalogDigestSha256,
|
|
428
|
+
installedTemplateVersion,
|
|
429
|
+
packageIdentity: release?.source?.npm?.spec ?? null,
|
|
430
|
+
packageIntegrity: release?.source?.npm?.integrity ?? null,
|
|
431
|
+
status: release ? "bound-to-installed-catalog-identity" : "unresolved-no-catalog-release-for-installed-version"
|
|
432
|
+
}),
|
|
433
|
+
formalSurfaces: Object.freeze({
|
|
434
|
+
entry: binding(entryByPath, "AGENTS.md"),
|
|
435
|
+
bridges: Object.freeze(bridgePaths.map((targetRel) => binding(entryByPath, targetRel))),
|
|
436
|
+
router: binding(entryByPath, "dev/USER_RULES.md"),
|
|
437
|
+
transactionRegistry: Object.freeze({
|
|
438
|
+
root: "dev/governance_migrations",
|
|
439
|
+
entries: Object.freeze(items.filter((item) => item.classifications.includes("transaction-state")).map((item) => item.sourcePath))
|
|
440
|
+
})
|
|
441
|
+
}),
|
|
442
|
+
items: Object.freeze(items),
|
|
443
|
+
unresolved: Object.freeze([...unresolvedItems, ...unresolvedContractTargets]
|
|
444
|
+
.sort((left, right) => `${left.sourcePath}\0${left.reason}`.localeCompare(`${right.sourcePath}\0${right.reason}`)))
|
|
445
|
+
};
|
|
446
|
+
return Object.freeze({ ...body, frozenSetSha256: sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8")) });
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
export function assertGate5FrozenSet(frozen) {
|
|
450
|
+
if (!frozen || typeof frozen !== "object" || Array.isArray(frozen)) throw new Error("Gate 5 frozen set is required");
|
|
451
|
+
if (frozen.schemaVersion !== GATE5_FROZEN_SET_SCHEMA) throw new Error("unsupported Gate 5 frozen-set schema");
|
|
452
|
+
if (frozen.operationAuthority !== "none" || frozen.activationStatus !== "not-authorized") throw new Error("Gate 5 frozen set must not claim operation authority");
|
|
453
|
+
if (!Array.isArray(frozen.items) || frozen.items.length === 0) throw new Error("Gate 5 frozen set has no items");
|
|
454
|
+
if (!frozen.rootSourceInventory || frozen.rootSourceInventory.schemaVersion !== GATE5_ROOT_SOURCE_INVENTORY_SCHEMA
|
|
455
|
+
|| !/^[0-9a-f]{64}$/.test(frozen.rootSourceInventory.sha256)
|
|
456
|
+
|| !Number.isInteger(frozen.rootSourceInventory.entryCount) || frozen.rootSourceInventory.entryCount !== frozen.items.length
|
|
457
|
+
|| !Array.isArray(frozen.rootSourceInventory.exclusions)) {
|
|
458
|
+
throw new Error("Gate 5 frozen set does not bind a complete root-source inventory");
|
|
459
|
+
}
|
|
460
|
+
if (!frozen.packageContract || !Array.isArray(frozen.packageContract.coverage)) {
|
|
461
|
+
throw new Error("Gate 5 frozen set does not bind package-contract coverage");
|
|
462
|
+
}
|
|
463
|
+
const paths = new Set();
|
|
464
|
+
const orderedPaths = [];
|
|
465
|
+
for (const item of frozen.items) {
|
|
466
|
+
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");
|
|
467
|
+
paths.add(item.sourcePath);
|
|
468
|
+
orderedPaths.push(item.sourcePath);
|
|
469
|
+
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}`);
|
|
470
|
+
if (!Array.isArray(item.classifications) || !item.classifications.includes("root-source")
|
|
471
|
+
|| !Array.isArray(item.existingReaders) || !item.priorityConflict?.status || !item.effect?.status
|
|
472
|
+
|| !(item.unresolvedReason === null || typeof item.unresolvedReason === "string")) {
|
|
473
|
+
throw new Error(`Gate 5 frozen set omits root-source, reader, priority/conflict, or effect record: ${item.sourcePath}`);
|
|
474
|
+
}
|
|
475
|
+
if (!item.historicalOrigin && item.ownership !== "user-or-unknown") throw new Error(`Gate 5 frozen set assigns ownership without historical evidence: ${item.sourcePath}`);
|
|
476
|
+
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}`);
|
|
477
|
+
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}`);
|
|
478
|
+
}
|
|
479
|
+
const expectedUnresolved = frozen.items
|
|
480
|
+
.filter((item) => item.unresolvedReason)
|
|
481
|
+
.map((item) => `${item.sourcePath}\0${item.unresolvedReason}`);
|
|
482
|
+
const actualUnresolved = frozen.unresolved?.map((item) => `${item.sourcePath}\0${item.reason}`) ?? [];
|
|
483
|
+
for (const coverage of frozen.packageContract.coverage) {
|
|
484
|
+
if (!coverage || typeof coverage.targetRel !== "string" || typeof coverage.sourceStatus !== "string") {
|
|
485
|
+
throw new Error("Gate 5 frozen set package-contract coverage is invalid");
|
|
486
|
+
}
|
|
487
|
+
if (coverage.sourceStatus === "unresolved-missing-installed-source") {
|
|
488
|
+
expectedUnresolved.push(`${coverage.targetRel}\0installed package target is missing from the root-source set`);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (JSON.stringify(orderedPaths) !== JSON.stringify([...orderedPaths].sort((left, right) => left.localeCompare(right)))) {
|
|
492
|
+
throw new Error("Gate 5 frozen set items are not in canonical source-path order");
|
|
493
|
+
}
|
|
494
|
+
if (JSON.stringify(actualUnresolved) !== JSON.stringify([...actualUnresolved].sort((left, right) => left.localeCompare(right)))) {
|
|
495
|
+
throw new Error("Gate 5 frozen set unresolved list is not in canonical order");
|
|
496
|
+
}
|
|
497
|
+
if (JSON.stringify(actualUnresolved) !== JSON.stringify([...expectedUnresolved].sort((left, right) => left.localeCompare(right)))) {
|
|
498
|
+
throw new Error("Gate 5 frozen set unresolved list does not exactly match item states");
|
|
499
|
+
}
|
|
500
|
+
const { frozenSetSha256, ...body } = frozen;
|
|
501
|
+
if (frozenSetSha256 !== sha256(Buffer.from(`${JSON.stringify(body)}\n`, "utf8"))) throw new Error("Gate 5 frozen-set digest does not match its contents");
|
|
502
|
+
return true;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function normalizeContracts(contracts, transitionContracts) {
|
|
506
|
+
const seen = new Set();
|
|
507
|
+
const all = [];
|
|
508
|
+
for (const [scope, source] of [["installed", contracts], ["transition", transitionContracts]]) {
|
|
509
|
+
for (const contract of source) {
|
|
510
|
+
if (seen.has(contract.targetRel)) continue;
|
|
511
|
+
seen.add(contract.targetRel);
|
|
512
|
+
all.push(Object.freeze({ ...contract, scope }));
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return all;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function binding(entryByPath, targetRel) {
|
|
519
|
+
const entry = entryByPath.get(targetRel);
|
|
520
|
+
return Object.freeze({
|
|
521
|
+
path: targetRel,
|
|
522
|
+
present: Boolean(entry),
|
|
523
|
+
sourceIdentity: entry ? Object.freeze({ sha256: entry.sha256, bytes: entry.bytes }) : null,
|
|
524
|
+
readers: entry ? Object.freeze(entry.reachability.map(({ from, via }) => ({ reader: from, via })).filter(({ reader }) => isFormalReader(reader))) : Object.freeze([])
|
|
525
|
+
});
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function isFormalReader(reader) {
|
|
529
|
+
return reader === "formal-entry" || !["managed-contract", "legacy-location", "dynamic-state"].includes(reader);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async function readInstalledTemplateVersion(root) {
|
|
533
|
+
const bytes = await readFile(path.join(root, "dev", "PROJECT_INDEX.md")).catch((error) => {
|
|
534
|
+
if (error?.code === "ENOENT") return null;
|
|
535
|
+
throw error;
|
|
536
|
+
});
|
|
537
|
+
if (!bytes) return null;
|
|
538
|
+
const match = /^\| Agent Handoff Kit template version \| ([0-9]+\.[0-9]+\.[0-9]+) \|/m.exec(bytes.toString("utf8"));
|
|
539
|
+
return match?.[1] ?? null;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export function extractExplicitLocalReferences(text) {
|
|
543
|
+
const matches = new Map();
|
|
544
|
+
const add = (raw, via) => {
|
|
545
|
+
const normalized = normalizeReference(raw);
|
|
546
|
+
if (normalized) matches.set(`${normalized}\0${via}`, { path: normalized, via });
|
|
547
|
+
};
|
|
548
|
+
for (const match of String(text).matchAll(/\[[^\]]*\]\(([^)\s]+)(?:\s+[^)]*)?\)/g)) add(match[1], "markdown-link");
|
|
549
|
+
for (const match of String(text).matchAll(/`([^`\r\n]+)`/g)) add(match[1], "inline-code-path");
|
|
550
|
+
for (const match of String(text).matchAll(/^\s*@([^\s]+)\s*$/gm)) add(match[1], "bridge-import");
|
|
551
|
+
// Do not treat the dot before a filename extension as sentence punctuation.
|
|
552
|
+
// On Windows, the truncated `dev/USER_RULES` then aliases the real
|
|
553
|
+
// `dev/user_rules/` directory, making a valid formal router look unsafe.
|
|
554
|
+
for (const match of String(text).matchAll(/(?:^|[\s("'`])((?:[\p{L}\p{N}_-]+[\\/])+[\p{L}\p{N}_. -]*[\p{L}\p{N}_.-])(?=$|[\s,;:,。!?)\]}>"'])/gu)) add(match[1], "plain-local-path");
|
|
555
|
+
return [...matches.values()].sort((left, right) => `${left.path}\0${left.via}`.localeCompare(`${right.path}\0${right.via}`));
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function normalizeReference(raw) {
|
|
559
|
+
const value = String(raw).trim().replace(/^<|>$/g, "");
|
|
560
|
+
if (!value || value.includes("://") || value.startsWith("~") || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("/")) return null;
|
|
561
|
+
const withoutFragment = value.split(/[?#]/, 1)[0].replaceAll("\\", "/");
|
|
562
|
+
if (!withoutFragment || withoutFragment.endsWith("/") || (!withoutFragment.includes("/") && !/\.[\p{L}\p{N}]+$/u.test(withoutFragment))) return null;
|
|
563
|
+
return normalizeProjectRelative(withoutFragment);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function normalizeProjectRelative(relative) {
|
|
567
|
+
const normalized = path.posix.normalize(String(relative).replaceAll("\\", "/").replace(/^\.\//, ""));
|
|
568
|
+
if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../") || path.posix.isAbsolute(normalized)) return null;
|
|
569
|
+
return normalized;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function isInside(root, target) {
|
|
573
|
+
const relative = path.relative(path.resolve(root), path.resolve(target));
|
|
574
|
+
return Boolean(relative) && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
function decodeUtf8(buffer) {
|
|
578
|
+
try {
|
|
579
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(buffer);
|
|
580
|
+
} catch {
|
|
581
|
+
return null;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function sha256(value) {
|
|
586
|
+
return createHash("sha256").update(value).digest("hex");
|
|
587
|
+
}
|