@adamchanadam/agent-handoff-kit 0.3.52 → 0.3.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,594 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { readFileSync } from "node:fs";
3
- import path from "node:path";
4
- import { fileURLToPath } from "node:url";
5
- import { getOfficialBaseline, validateOfficialOriginCatalog } from "./official-origin-catalog.mjs";
6
- import { UPGRADE_INVENTORY_SCHEMA } from "./upgrade-inventory.mjs";
7
-
8
- export const SEMANTIC_CANDIDATE_SCHEMA = 3;
9
- export const semanticCandidateDecisions = Object.freeze([
10
- "preserve",
11
- "integrate",
12
- "move",
13
- "unchanged",
14
- "unresolved"
15
- ]);
16
- export const semanticCandidateOwnership = Object.freeze([
17
- "kit-managed-exact",
18
- "user-or-unknown"
19
- ]);
20
-
21
- const completeDecisions = new Set(semanticCandidateDecisions.filter((decision) => decision !== "unresolved"));
22
- const ownershipKinds = new Set(semanticCandidateOwnership);
23
- const userRulesRouterPath = "dev/USER_RULES.md";
24
- const userRulesContentRoot = "dev/user_rules/";
25
- const officialPackageName = "@adamchanadam/agent-handoff-kit";
26
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
27
- const officialOriginCatalogPath = path.join(__dirname, "migration-baselines", "official-origin-catalog.json");
28
- let cachedOfficialOriginCatalog = null;
29
-
30
- /**
31
- * Builds an inert semantic-candidate bundle from a frozen inventory. The
32
- * bundle contains no operation authority: it can neither write nor activate
33
- * a project. Its job is only to make every proposed data disposition
34
- * hash-bound, complete, and mechanically inspectable before later stages.
35
- */
36
- export function buildSemanticCandidate({ inventory, sourceContents, proposals, managedOrigins = [], toolVersion, projectRoot } = {}) {
37
- const sourceEntries = assertReadyInventory(inventory);
38
- const sourceByPath = toSourceContentMap(sourceContents, sourceEntries);
39
- const proposalByPath = toProposalMap(proposals, sourceEntries);
40
- const managedOriginByPath = toManagedOriginMap(managedOrigins, sourceEntries, sourceByPath, projectRoot);
41
- const sourceEntryByPath = new Map(sourceEntries.map((entry) => [entry.path, entry]));
42
- const normalizedToolVersion = requiredText(toolVersion, "semantic candidate requires a tool version");
43
- const candidates = [];
44
- const destinationContentByPath = new Map();
45
-
46
- for (const source of sourceEntries) {
47
- const proposal = proposalByPath.get(source.path);
48
- const sourceContent = sourceByPath.get(source.path);
49
- assert(sha256(sourceContent) === source.sha256, `source content no longer matches inventory: ${source.path}`);
50
- const decision = requiredText(proposal.decision, `candidate decision is required: ${source.path}`);
51
- assert(semanticCandidateDecisions.includes(decision), `unsupported semantic decision for ${source.path}: ${decision}`);
52
- const reason = requiredText(proposal.reason, `candidate reason is required: ${source.path}`);
53
- const ownership = normalizeOwnership(proposal.ownership, source, managedOriginByPath);
54
-
55
- const sourceByteRanges = normalizeSourceByteRanges(proposal.sourceByteRanges, source, sourceContent, ownership);
56
-
57
- if (decision === "unresolved") {
58
- candidates.push({
59
- sourcePath: source.path,
60
- sourceSha256: source.sha256,
61
- ownership,
62
- decision,
63
- reason,
64
- originalObligations: normalizeObligations(proposal.originalObligations, source.path),
65
- expectedReachability: formalReachability(source.path, sourceEntryByPath),
66
- expectedEffect: pendingEffect(proposal.expectedEffect, source.path),
67
- sourceByteRanges,
68
- destination: null,
69
- preservationWitness: null,
70
- userOverlay: null,
71
- preservationRoute: null
72
- });
73
- continue;
74
- }
75
-
76
- assert(completeDecisions.has(decision), `unsupported complete decision for ${source.path}: ${decision}`);
77
- const destinationPath = normalizeProjectRelative(proposal.destinationPath);
78
- assert(destinationPath, `candidate destination escapes project root: ${source.path}`);
79
- const destinationContent = toBuffer(proposal.destinationContent, `candidate destination content is required: ${source.path}`);
80
- const priorDestination = destinationContentByPath.get(destinationPath);
81
- if (priorDestination) {
82
- assert(priorDestination.equals(destinationContent), `candidate destinations disagree on content: ${destinationPath}`);
83
- } else {
84
- destinationContentByPath.set(destinationPath, destinationContent);
85
- }
86
-
87
- const offset = destinationContent.indexOf(sourceContent);
88
- assert(offset >= 0, `candidate does not preserve exact source bytes: ${source.path}`);
89
- const userOverlay = ownership.kind === "user-or-unknown" && proposal.userOverlay != null
90
- ? normalizeUserOverlay(proposal.userOverlay, source, sourceContent, destinationPath, destinationContent, offset, sourceEntryByPath)
91
- : null;
92
- const expectedReachability = userOverlay?.expectedReachability ?? formalReachability(source.path, sourceEntryByPath);
93
- if (ownership.kind === "user-or-unknown") {
94
- assert(expectedReachability.length > 0, `user-or-unknown source has no verified formal reader: ${source.path}`);
95
- }
96
- const preservationRoute = ownership.kind === "user-or-unknown"
97
- ? normalizePreservationRoute(proposal.preservationRoute, source, destinationPath, expectedReachability, userOverlay)
98
- : null;
99
- candidates.push({
100
- sourcePath: source.path,
101
- sourceSha256: source.sha256,
102
- ownership,
103
- decision,
104
- reason,
105
- originalObligations: normalizeObligations(proposal.originalObligations, source.path),
106
- expectedReachability,
107
- expectedEffect: pendingEffect(proposal.expectedEffect, source.path),
108
- sourceByteRanges,
109
- destination: {
110
- path: destinationPath,
111
- sha256: sha256(destinationContent),
112
- contentBase64: destinationContent.toString("base64")
113
- },
114
- preservationWitness: {
115
- kind: "exact-source-bytes",
116
- offset,
117
- bytes: sourceContent.length
118
- },
119
- userOverlay,
120
- preservationRoute
121
- });
122
- }
123
-
124
- const items = candidates.sort((left, right) => left.sourcePath.localeCompare(right.sourcePath));
125
- const body = {
126
- schemaVersion: SEMANTIC_CANDIDATE_SCHEMA,
127
- inventorySchemaVersion: UPGRADE_INVENTORY_SCHEMA,
128
- inventorySha256: inventory.inventorySha256,
129
- toolVersion: normalizedToolVersion,
130
- operationAuthority: "none",
131
- activationStatus: "not-authorized",
132
- runtimeValidationStatus: "not-run",
133
- status: items.some((item) => item.decision === "unresolved") ? "blocked-unresolved" : "pending-independent-review",
134
- items
135
- };
136
- return Object.freeze({ ...body, candidateSha256: digest(body) });
137
- }
138
-
139
- /**
140
- * Rechecks a serialized candidate against the live source and frozen
141
- * inventory. This is deliberately independent of review/provider data:
142
- * deterministic data validation may inspect a candidate, but it still grants
143
- * no write or activation authority.
144
- */
145
- export function assertCandidateReadyForDeterministicValidation({ candidate, inventory, sourceContents, managedOrigins = [], toolVersion, projectRoot } = {}) {
146
- assert(candidate && typeof candidate === "object", "semantic candidate is required");
147
- const sourceEntries = assertReadyInventory(inventory);
148
- assert(candidate.schemaVersion === SEMANTIC_CANDIDATE_SCHEMA, "semantic candidate schema version is not supported");
149
- assert(candidate.inventorySchemaVersion === UPGRADE_INVENTORY_SCHEMA, "semantic candidate inventory schema is not supported");
150
- assert(candidate.inventorySha256 === inventory.inventorySha256, "semantic candidate inventory digest does not match the frozen inventory");
151
- assert(candidate.toolVersion === requiredText(toolVersion, "deterministic validation requires a tool version"), "semantic candidate tool version does not match the current tool");
152
- assert(candidate.operationAuthority === "none" && candidate.activationStatus === "not-authorized", "semantic candidate must not claim operation authority");
153
- assert(candidate.runtimeValidationStatus === "not-run", "semantic candidate must not claim runtime validation");
154
- assert(["pending-independent-review", "blocked-unresolved"].includes(candidate.status), "semantic candidate has an invalid status");
155
- assert(Array.isArray(candidate.items), "semantic candidate items are required");
156
- assert(candidate.candidateSha256 === digest(candidateBody(candidate)), "semantic candidate digest does not match its contents");
157
-
158
- const sourceByPath = toSourceContentMap(sourceContents, sourceEntries);
159
- const managedOriginByPath = toManagedOriginMap(managedOrigins, sourceEntries, sourceByPath, projectRoot);
160
- const sourceEntryByPath = new Map(sourceEntries.map((entry) => [entry.path, entry]));
161
- const candidateByPath = new Map();
162
- const destinationContentByPath = new Map();
163
- for (const item of candidate.items) {
164
- assert(item && typeof item === "object", "semantic candidate item must be an object");
165
- assert(!candidateByPath.has(item.sourcePath), `semantic candidate duplicates source: ${item.sourcePath}`);
166
- candidateByPath.set(item.sourcePath, item);
167
- }
168
- assert(candidateByPath.size === sourceEntries.length, "semantic candidate does not cover the frozen inventory exactly");
169
-
170
- for (const source of sourceEntries) {
171
- const item = candidateByPath.get(source.path);
172
- assert(item, `semantic candidate omitted source: ${source.path}`);
173
- assert(item.sourceSha256 === source.sha256, `semantic candidate source hash mismatch: ${source.path}`);
174
- const sourceContent = sourceByPath.get(source.path);
175
- assert(sha256(sourceContent) === source.sha256, `source content no longer matches inventory: ${source.path}`);
176
- const ownership = normalizeOwnership(item.ownership, source, managedOriginByPath);
177
- assert(semanticCandidateDecisions.includes(item.decision), `semantic candidate has invalid decision: ${source.path}`);
178
- requiredText(item.reason, `semantic candidate reason is required: ${source.path}`);
179
- normalizeObligations(item.originalObligations, source.path);
180
- const expectedReachability = normalizeReachability(item.expectedReachability, source.path);
181
- pendingEffect(item.expectedEffect, source.path);
182
- const sourceByteRanges = normalizeSourceByteRanges(item.sourceByteRanges, source, sourceContent, ownership);
183
-
184
- if (item.decision === "unresolved") {
185
- assert(item.destination === null && item.preservationWitness === null && item.userOverlay === null && item.preservationRoute === null, `unresolved item must not claim a destination: ${source.path}`);
186
- assert(sameReachability(expectedReachability, formalReachability(source.path, sourceEntryByPath)), `semantic candidate reachability is not derived from the frozen formal reader graph: ${source.path}`);
187
- continue;
188
- }
189
-
190
- assert(completeDecisions.has(item.decision), `semantic candidate has invalid complete decision: ${source.path}`);
191
- assert(item.destination && typeof item.destination === "object", `semantic candidate destination is required: ${source.path}`);
192
- const destinationPath = normalizeProjectRelative(item.destination.path);
193
- assert(destinationPath, `semantic candidate destination escapes project root: ${source.path}`);
194
- const destinationContent = decodeBase64(item.destination.contentBase64, source.path);
195
- assert(sha256(destinationContent) === item.destination.sha256, `semantic candidate destination hash mismatch: ${source.path}`);
196
- const previous = destinationContentByPath.get(destinationPath);
197
- if (previous) assert(previous.equals(destinationContent), `semantic candidate destinations disagree on content: ${destinationPath}`);
198
- else destinationContentByPath.set(destinationPath, destinationContent);
199
- assert(item.preservationWitness?.kind === "exact-source-bytes", `semantic candidate preservation witness is invalid: ${source.path}`);
200
- assert(Number.isInteger(item.preservationWitness.offset) && item.preservationWitness.offset >= 0, `semantic candidate preservation offset is invalid: ${source.path}`);
201
- assert(item.preservationWitness.bytes === sourceContent.length, `semantic candidate preservation byte count is invalid: ${source.path}`);
202
- assert(item.preservationWitness.offset + sourceContent.length <= destinationContent.length, `semantic candidate preservation range is invalid: ${source.path}`);
203
- assert(destinationContent.subarray(item.preservationWitness.offset, item.preservationWitness.offset + sourceContent.length).equals(sourceContent), `semantic candidate preservation witness does not match source: ${source.path}`);
204
- if (ownership.kind === "user-or-unknown") {
205
- const userOverlay = item.userOverlay == null
206
- ? null
207
- : normalizeUserOverlay(item.userOverlay, source, sourceContent, destinationPath, destinationContent, item.preservationWitness.offset, sourceEntryByPath);
208
- const verifiedReachability = userOverlay?.expectedReachability ?? formalReachability(source.path, sourceEntryByPath);
209
- assert(sameReachability(expectedReachability, verifiedReachability), `semantic candidate reachability is not derived from the frozen formal reader graph: ${source.path}`);
210
- assert(verifiedReachability.length > 0, `user-or-unknown source has no verified formal reader: ${source.path}`);
211
- normalizePreservationRoute(item.preservationRoute, source, destinationPath, expectedReachability, userOverlay);
212
- } else {
213
- assert(item.userOverlay === null && item.preservationRoute === null, `exact Kit-managed item must not claim a user preservation route: ${source.path}`);
214
- assert(sameReachability(expectedReachability, formalReachability(source.path, sourceEntryByPath)), `semantic candidate reachability is not derived from the frozen formal reader graph: ${source.path}`);
215
- }
216
- }
217
-
218
- assert(candidate.status !== "blocked-unresolved", "unresolved semantic items block deterministic validation");
219
- return candidate;
220
- }
221
-
222
- function assertReadyInventory(inventory) {
223
- assert(inventory && typeof inventory === "object", "semantic candidate requires an inventory");
224
- assert(inventory.schemaVersion === UPGRADE_INVENTORY_SCHEMA, "semantic candidate inventory schema is not supported");
225
- assert(inventory.status === "ready", "semantic candidate requires a ready inventory");
226
- assert(Array.isArray(inventory.entries) && inventory.entries.length > 0, "semantic candidate inventory entries are required");
227
- assert(typeof inventory.inventorySha256 === "string" && /^[a-f0-9]{64}$/.test(inventory.inventorySha256), "semantic candidate inventory digest is invalid");
228
- const entries = [...inventory.entries].sort((left, right) => left.path.localeCompare(right.path));
229
- const paths = new Set();
230
- for (const entry of entries) {
231
- assert(entry && typeof entry === "object", "semantic candidate inventory entry must be an object");
232
- assert(normalizeProjectRelative(entry.path) === entry.path, `semantic candidate inventory path is invalid: ${entry.path}`);
233
- assert(!paths.has(entry.path), `semantic candidate inventory duplicates source: ${entry.path}`);
234
- paths.add(entry.path);
235
- assert(typeof entry.sha256 === "string" && /^[a-f0-9]{64}$/.test(entry.sha256), `semantic candidate inventory hash is invalid: ${entry.path}`);
236
- assert(Array.isArray(entry.reachability), `semantic candidate inventory reachability is invalid: ${entry.path}`);
237
- for (const reachability of entry.reachability) {
238
- assert(reachability && typeof reachability === "object", `semantic candidate inventory reachability is invalid: ${entry.path}`);
239
- assert(typeof reachability.from === "string" && reachability.from.trim(), `semantic candidate inventory reachability source is invalid: ${entry.path}`);
240
- assert(typeof reachability.via === "string" && reachability.via.trim(), `semantic candidate inventory reachability route is invalid: ${entry.path}`);
241
- }
242
- }
243
- return entries;
244
- }
245
-
246
- function toSourceContentMap(sourceContents, sourceEntries) {
247
- const map = new Map();
248
- const pairs = sourceContents instanceof Map
249
- ? [...sourceContents]
250
- : Array.isArray(sourceContents)
251
- ? sourceContents
252
- : sourceContents && typeof sourceContents === "object"
253
- ? Object.entries(sourceContents)
254
- : [];
255
- for (const pair of pairs) {
256
- assert(Array.isArray(pair) && pair.length === 2, "source contents must contain path/content pairs");
257
- const sourcePath = normalizeProjectRelative(pair[0]);
258
- assert(sourcePath, "source content path escapes project root");
259
- assert(!map.has(sourcePath), `source contents duplicate path: ${sourcePath}`);
260
- map.set(sourcePath, toBuffer(pair[1], `source content is required: ${sourcePath}`));
261
- }
262
- const expectedPaths = new Set(sourceEntries.map((entry) => entry.path));
263
- assert(map.size === expectedPaths.size, "source contents do not cover the frozen inventory exactly");
264
- for (const sourcePath of expectedPaths) assert(map.has(sourcePath), `source content missing for inventory path: ${sourcePath}`);
265
- for (const sourcePath of map.keys()) assert(expectedPaths.has(sourcePath), `source content is outside the frozen inventory: ${sourcePath}`);
266
- return map;
267
- }
268
-
269
- function toProposalMap(proposals, sourceEntries) {
270
- assert(Array.isArray(proposals), "semantic candidate proposals are required");
271
- const map = new Map();
272
- for (const proposal of proposals) {
273
- assert(proposal && typeof proposal === "object", "semantic candidate proposal must be an object");
274
- const sourcePath = normalizeProjectRelative(proposal.sourcePath);
275
- assert(sourcePath, "semantic candidate proposal source escapes project root");
276
- assert(!map.has(sourcePath), `semantic candidate proposals duplicate source: ${sourcePath}`);
277
- map.set(sourcePath, proposal);
278
- }
279
- const expectedPaths = new Set(sourceEntries.map((entry) => entry.path));
280
- assert(map.size === expectedPaths.size, "semantic candidate proposals do not cover the frozen inventory exactly");
281
- for (const sourcePath of expectedPaths) assert(map.has(sourcePath), `semantic candidate proposal omitted source: ${sourcePath}`);
282
- for (const sourcePath of map.keys()) assert(expectedPaths.has(sourcePath), `semantic candidate proposal is outside the frozen inventory: ${sourcePath}`);
283
- return map;
284
- }
285
-
286
- /**
287
- * An exact Kit claim is deliberately whole-file evidence. A source that no
288
- * longer equals its packaged bytes cannot donate a "mostly official" range
289
- * to an automatic upgrade; it remains user-or-unknown until a human-review
290
- * candidate chooses a safe preservation route.
291
- */
292
- function toManagedOriginMap(value, sourceEntries, sourceByPath, projectRoot) {
293
- const map = new Map();
294
- const pairs = value instanceof Map
295
- ? [...value]
296
- : Array.isArray(value)
297
- ? value.map((item) => [item?.sourcePath, item])
298
- : value && typeof value === "object"
299
- ? Object.entries(value)
300
- : [];
301
- const expectedPaths = new Set(sourceEntries.map((entry) => entry.path));
302
- for (const [rawPath, rawOrigin] of pairs) {
303
- assert(rawOrigin && typeof rawOrigin === "object", "managed origin must be an object");
304
- const sourcePath = normalizeProjectRelative(rawOrigin.sourcePath ?? rawPath);
305
- assert(sourcePath && expectedPaths.has(sourcePath), `managed origin is outside frozen inventory: ${String(rawPath)}`);
306
- assert(!map.has(sourcePath), `managed origins duplicate source: ${sourcePath}`);
307
- const targetPath = normalizeProjectRelative(rawOrigin.targetPath);
308
- assert(targetPath === sourcePath, `managed origin target does not match source: ${sourcePath}`);
309
- const sourceSha256 = requiredText(rawOrigin.sourceSha256, `managed origin source hash is required: ${sourcePath}`);
310
- assert(sourceSha256 === sha256(sourceByPath.get(sourcePath)), `managed origin source hash does not match source: ${sourcePath}`);
311
- const packageProof = verifyPackageIdentity(rawOrigin.packageIdentity, sourcePath, sourceByPath.get(sourcePath), projectRoot);
312
- map.set(sourcePath, {
313
- packageIdentity: packageProof.packageIdentity,
314
- targetPath,
315
- sourceSha256,
316
- packageEvidence: packageProof.packageEvidence
317
- });
318
- }
319
- return map;
320
- }
321
-
322
- function normalizeOwnership(value, source, managedOriginByPath) {
323
- assert(value && typeof value === "object", `semantic candidate ownership is required: ${source.path}`);
324
- const kind = requiredText(value.kind, `semantic candidate ownership kind is required: ${source.path}`);
325
- assert(ownershipKinds.has(kind), `semantic candidate ownership kind is invalid: ${source.path}`);
326
- if (kind === "kit-managed-exact") {
327
- const expectedOrigin = managedOriginByPath.get(source.path);
328
- assert(expectedOrigin, `exact Kit-managed ownership lacks package evidence: ${source.path}`);
329
- const supplied = value.managedOrigin;
330
- if (supplied != null) {
331
- assert(supplied && typeof supplied === "object", `managed origin is invalid: ${source.path}`);
332
- assert(
333
- supplied.packageIdentity === expectedOrigin.packageIdentity
334
- && normalizeProjectRelative(supplied.targetPath) === expectedOrigin.targetPath
335
- && supplied.sourceSha256 === expectedOrigin.sourceSha256
336
- && (supplied.packageEvidence == null || samePackageEvidence(supplied.packageEvidence, expectedOrigin.packageEvidence)),
337
- `exact Kit-managed ownership evidence does not match source: ${source.path}`
338
- );
339
- }
340
- return { kind, managedOrigin: expectedOrigin };
341
- }
342
- assert(value.managedOrigin == null, `user-or-unknown ownership must not claim package origin: ${source.path}`);
343
- return { kind, managedOrigin: null };
344
- }
345
-
346
- function normalizeSourceByteRanges(value, source, sourceContent, ownership) {
347
- assert(Array.isArray(value) && value.length > 0, `semantic candidate requires source byte ranges: ${source.path}`);
348
- const ranges = [];
349
- let cursor = 0;
350
- for (const rawRange of value) {
351
- assert(rawRange && typeof rawRange === "object", `semantic candidate source byte range is invalid: ${source.path}`);
352
- const kind = requiredText(rawRange.kind, `semantic candidate source byte range kind is invalid: ${source.path}`);
353
- assert(["kit-managed-exact", "user-or-unknown"].includes(kind), `semantic candidate source byte range kind is invalid: ${source.path}`);
354
- const sourceOffset = rawRange.sourceOffset;
355
- const bytes = rawRange.bytes;
356
- assert(Number.isInteger(sourceOffset) && sourceOffset === cursor, `semantic candidate source byte ranges must be complete, ordered, and non-overlapping: ${source.path}`);
357
- assert(Number.isInteger(bytes) && bytes > 0 && sourceOffset + bytes <= sourceContent.length, `semantic candidate source byte range length is invalid: ${source.path}`);
358
- const sourceSha256 = requiredText(rawRange.sourceSha256, `semantic candidate source byte range hash is required: ${source.path}`);
359
- assert(sourceSha256 === sha256(sourceContent.subarray(sourceOffset, sourceOffset + bytes)), `semantic candidate source byte range hash mismatch: ${source.path}`);
360
- assert(kind === ownership.kind, `semantic candidate cannot auto-split ownership inside a source: ${source.path}`);
361
- ranges.push({ kind, sourceOffset, bytes, sourceSha256 });
362
- cursor += bytes;
363
- }
364
- assert(cursor === sourceContent.length, `semantic candidate source byte ranges do not reconstruct source exactly: ${source.path}`);
365
- if (ownership.kind === "kit-managed-exact") {
366
- assert(ranges.length === 1 && ranges[0].sourceOffset === 0 && ranges[0].bytes === sourceContent.length, `exact Kit-managed ownership must cover the whole source: ${source.path}`);
367
- }
368
- return ranges;
369
- }
370
-
371
- function normalizeUserOverlay(value, source, sourceContent, destinationPath, destinationContent, wholeOffset, sourceEntryByPath) {
372
- assert(value && typeof value === "object", `user overlay is required: ${source.path}`);
373
- const entryId = requiredText(value.entryId, `user overlay entry id is required: ${source.path}`);
374
- assert(/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(entryId), `user overlay entry id is invalid: ${source.path}`);
375
- const routerPath = normalizeProjectRelative(value.routerPath);
376
- assert(routerPath === userRulesRouterPath, `user overlay must use ${userRulesRouterPath}: ${source.path}`);
377
- const contentPath = normalizeProjectRelative(value.contentPath);
378
- assert(contentPath === destinationPath && contentPath.startsWith(userRulesContentRoot), `user overlay destination must be a registered user-rule file: ${source.path}`);
379
- assert(value.reader?.reader === "AGENTS.md" && value.reader?.via === userRulesRouterPath, `user overlay reader is not the formal runtime entry: ${source.path}`);
380
- const priorityRelation = requiredText(value.priorityRelation, `user overlay priority relation is required: ${source.path}`);
381
- assert(priorityRelation === "after-kit-base-before-task-packs", `user overlay priority relation is not the formal router order: ${source.path}`);
382
- assert(Array.isArray(value.sourceRangeWitnesses) && value.sourceRangeWitnesses.length > 0, `user overlay source range witnesses are required: ${source.path}`);
383
- const ranges = [];
384
- let cursor = 0;
385
- for (const rawRange of value.sourceRangeWitnesses) {
386
- assert(rawRange && typeof rawRange === "object", `user overlay source range witness is invalid: ${source.path}`);
387
- const sourceOffset = rawRange.sourceOffset;
388
- const bytes = rawRange.bytes;
389
- const destinationOffset = rawRange.destinationOffset;
390
- assert(Number.isInteger(sourceOffset) && sourceOffset === cursor, `user overlay source ranges must be complete, ordered, and non-overlapping: ${source.path}`);
391
- assert(Number.isInteger(bytes) && bytes > 0 && sourceOffset + bytes <= sourceContent.length, `user overlay source range length is invalid: ${source.path}`);
392
- assert(Number.isInteger(destinationOffset) && destinationOffset === wholeOffset + sourceOffset, `user overlay destination offset is invalid: ${source.path}`);
393
- const sourceSha256 = requiredText(rawRange.sourceSha256, `user overlay source range hash is required: ${source.path}`);
394
- const bytesFromSource = sourceContent.subarray(sourceOffset, sourceOffset + bytes);
395
- assert(sourceSha256 === sha256(bytesFromSource), `user overlay source range hash mismatch: ${source.path}`);
396
- assert(destinationContent.subarray(destinationOffset, destinationOffset + bytes).equals(bytesFromSource), `user overlay source range is not preserved at destination: ${source.path}`);
397
- ranges.push({ sourceOffset, bytes, sourceSha256, destinationOffset });
398
- cursor += bytes;
399
- }
400
- assert(cursor === sourceContent.length, `user overlay source ranges do not reconstruct source exactly: ${source.path}`);
401
- const expectedReachability = formalReachability(routerPath, sourceEntryByPath);
402
- assert(expectedReachability.some((entry) => entry.reader === "AGENTS.md" && entry.via === userRulesRouterPath), `user overlay router has no verified formal entry path: ${source.path}`);
403
- return {
404
- entryId,
405
- routerPath,
406
- contentPath,
407
- reader: { reader: "AGENTS.md", via: userRulesRouterPath },
408
- priorityRelation,
409
- sourceRangeWitnesses: ranges,
410
- expectedReachability
411
- };
412
- }
413
-
414
- function normalizePreservationRoute(value, source, destinationPath, expectedReachability, userOverlay) {
415
- assert(value && typeof value === "object", `user-or-unknown source requires a preservation route: ${source.path}`);
416
- const kind = requiredText(value.kind, `preservation route kind is required: ${source.path}`);
417
- const priorityRelation = requiredText(value.priorityRelation, `preservation route priority relation is required: ${source.path}`);
418
- if (kind === "formal-user-overlay") {
419
- assert(userOverlay, `formal user overlay route lacks registered content: ${source.path}`);
420
- assert(value.entryId === userOverlay.entryId && normalizeProjectRelative(value.routerPath) === userOverlay.routerPath && normalizeProjectRelative(value.contentPath) === userOverlay.contentPath, `formal user overlay route does not match its registered content: ${source.path}`);
421
- assert(value.reader?.reader === "AGENTS.md" && value.reader?.via === userRulesRouterPath, `formal user overlay route is not reachable from the runtime entry: ${source.path}`);
422
- assert(priorityRelation === userOverlay.priorityRelation, `formal user overlay route priority differs from registered content: ${source.path}`);
423
- assert(priorityRelation === "after-kit-base-before-task-packs", `formal user overlay route priority is not the formal router order: ${source.path}`);
424
- assert(expectedReachability.some((entry) => entry.reader === "AGENTS.md" && entry.via === userRulesRouterPath), `formal user overlay reachability is absent: ${source.path}`);
425
- return {
426
- kind,
427
- entryId: userOverlay.entryId,
428
- routerPath: userOverlay.routerPath,
429
- contentPath: userOverlay.contentPath,
430
- reader: { reader: "AGENTS.md", via: userRulesRouterPath },
431
- priorityRelation
432
- };
433
- }
434
- assert(kind === "existing-formal-reader", `preservation route kind is invalid: ${source.path}`);
435
- assert(userOverlay === null, `existing reader route must not silently move content into a user overlay: ${source.path}`);
436
- assert(priorityRelation === "preserve-existing-effect-pending-runtime-validation", `existing reader route priority is not a safe pending relation: ${source.path}`);
437
- const reader = requiredText(value.reader, `existing reader route reader is required: ${source.path}`);
438
- const via = requiredText(value.via, `existing reader route path is required: ${source.path}`);
439
- assert(normalizeProjectRelative(value.contentPath) === destinationPath, `existing reader route must preserve its destination path: ${source.path}`);
440
- assert(expectedReachability.some((entry) => entry.reader === reader && entry.via === via), `existing reader route is not in expected reachability: ${source.path}`);
441
- return { kind, contentPath: destinationPath, reader, via, priorityRelation };
442
- }
443
-
444
- function normalizeObligations(value, sourcePath) {
445
- assert(Array.isArray(value) && value.length > 0, `semantic candidate requires original obligations: ${sourcePath}`);
446
- const obligations = [...new Set(value.map((item) => requiredText(item, `semantic candidate obligation is invalid: ${sourcePath}`)))].sort((left, right) => left.localeCompare(right));
447
- assert(obligations.length === value.length, `semantic candidate obligations must be unique: ${sourcePath}`);
448
- return obligations;
449
- }
450
-
451
- function normalizeReachability(value, sourcePath) {
452
- assert(Array.isArray(value), `semantic candidate requires expected reachability: ${sourcePath}`);
453
- const entries = value.map((entry) => ({
454
- reader: requiredText(entry?.reader, `semantic candidate reachability reader is invalid: ${sourcePath}`),
455
- via: requiredText(entry?.via, `semantic candidate reachability route is invalid: ${sourcePath}`)
456
- }));
457
- entries.sort((left, right) => `${left.reader}\0${left.via}`.localeCompare(`${right.reader}\0${right.via}`));
458
- for (let index = 1; index < entries.length; index += 1) {
459
- assert(`${entries[index - 1].reader}\0${entries[index - 1].via}` !== `${entries[index].reader}\0${entries[index].via}`, `semantic candidate reachability must be unique: ${sourcePath}`);
460
- }
461
- return entries;
462
- }
463
-
464
- function formalReachability(sourcePath, sourceEntryByPath) {
465
- const readers = new Set();
466
- const visit = (currentPath, ancestors) => {
467
- if (ancestors.has(currentPath)) return;
468
- const source = sourceEntryByPath.get(currentPath);
469
- if (!source) return;
470
- const nextAncestors = new Set(ancestors);
471
- nextAncestors.add(currentPath);
472
- for (const edge of source.reachability) {
473
- if (edge.from === "formal-entry") readers.add(source.path);
474
- else if (sourceEntryByPath.has(edge.from)) visit(edge.from, nextAncestors);
475
- }
476
- };
477
- visit(sourcePath, new Set());
478
- return [...readers]
479
- .sort((left, right) => left.localeCompare(right))
480
- .map((reader) => ({ reader, via: sourcePath }));
481
- }
482
-
483
- function sameReachability(left, right) {
484
- return JSON.stringify(left) === JSON.stringify(right);
485
- }
486
-
487
- function verifyPackageIdentity(value, sourcePath, sourceContent, projectRoot) {
488
- const packageIdentity = requiredText(value, `managed origin package identity is required: ${sourcePath}`);
489
- const match = new RegExp(`^${escapeRegExp(officialPackageName)}@([0-9]+\\.[0-9]+\\.[0-9]+)$`).exec(packageIdentity);
490
- assert(match, `managed origin package identity is not an installed Kit release: ${sourcePath}`);
491
- assert(typeof projectRoot === "string" && projectRoot.trim(), `managed origin verification requires the selected project root: ${sourcePath}`);
492
- const version = match[1];
493
- const rootPath = path.resolve(projectRoot);
494
- const catalog = trustedOfficialOriginCatalog();
495
- const release = catalog.releases[version];
496
- const npm = release?.source?.npm;
497
- assert(npm?.spec === packageIdentity && /^[0-9a-f]{40}$/.test(npm.shasum) && typeof npm.integrity === "string" && npm.integrity.startsWith("sha512-") && Number.isInteger(npm.entryCount), `managed origin package artifact evidence is invalid: ${sourcePath}`);
498
- const installedTemplateVersion = readInstalledTemplateVersion(rootPath);
499
- assert(installedTemplateVersion === version, `managed origin package identity does not match the installed project package: ${sourcePath}`);
500
- const baseline = getOfficialBaseline({
501
- version,
502
- targetRel: sourcePath,
503
- catalog,
504
- root: rootPath
505
- });
506
- assert(baseline?.state === "present", `managed origin package does not contain target: ${sourcePath}`);
507
- assert(Buffer.from(baseline.text, "utf8").equals(sourceContent), `managed origin package bytes do not match source: ${sourcePath}`);
508
- return {
509
- packageIdentity,
510
- packageEvidence: Object.freeze({
511
- installedTemplateVersion,
512
- catalogDigestSha256: catalog.catalogDigestSha256,
513
- npm: Object.freeze({ spec: npm.spec, shasum: npm.shasum, integrity: npm.integrity, entryCount: npm.entryCount })
514
- })
515
- };
516
- }
517
-
518
- function readInstalledTemplateVersion(projectRoot) {
519
- let indexText;
520
- try {
521
- indexText = readFileSync(path.join(projectRoot, "dev", "PROJECT_INDEX.md"), "utf8");
522
- } catch {
523
- throw new Error("managed origin installed project package evidence is missing");
524
- }
525
- const match = /^\| Agent Handoff Kit template version \| ([0-9]+\.[0-9]+\.[0-9]+) \| [^|\n]+ \|$/m.exec(indexText);
526
- if (!match) throw new Error("managed origin installed project package evidence is invalid");
527
- return match[1];
528
- }
529
-
530
- function samePackageEvidence(left, right) {
531
- return JSON.stringify(left) === JSON.stringify(right);
532
- }
533
-
534
- function trustedOfficialOriginCatalog() {
535
- if (cachedOfficialOriginCatalog) return cachedOfficialOriginCatalog;
536
- const catalog = JSON.parse(readFileSync(officialOriginCatalogPath, "utf8"));
537
- validateOfficialOriginCatalog(catalog);
538
- cachedOfficialOriginCatalog = catalog;
539
- return catalog;
540
- }
541
-
542
- function escapeRegExp(value) {
543
- return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
544
- }
545
-
546
- function pendingEffect(value, sourcePath) {
547
- assert(value && typeof value === "object", `semantic candidate requires expected effect: ${sourcePath}`);
548
- assert(value.status === "pending-runtime-validation", `semantic candidate cannot claim runtime effect before validation: ${sourcePath}`);
549
- assert(value.decision === "preserve-source-obligations-and-priority", `semantic candidate effect decision is invalid: ${sourcePath}`);
550
- return {
551
- status: "pending-runtime-validation",
552
- decision: "preserve-source-obligations-and-priority"
553
- };
554
- }
555
-
556
- function candidateBody(candidate) {
557
- const { candidateSha256, ...body } = candidate;
558
- return body;
559
- }
560
-
561
- function normalizeProjectRelative(value) {
562
- if (typeof value !== "string") return null;
563
- const normalized = path.posix.normalize(value.replaceAll("\\", "/").replace(/^\.\//, ""));
564
- if (!normalized || normalized === "." || normalized === ".." || normalized.startsWith("../") || path.posix.isAbsolute(normalized)) return null;
565
- return normalized;
566
- }
567
-
568
- function toBuffer(value, message) {
569
- if (Buffer.isBuffer(value)) return Buffer.from(value);
570
- if (typeof value === "string") return Buffer.from(value, "utf8");
571
- throw new Error(message);
572
- }
573
-
574
- function decodeBase64(value, sourcePath) {
575
- assert(typeof value === "string" && /^[A-Za-z0-9+/]*={0,2}$/.test(value) && value.length % 4 === 0, `semantic candidate destination encoding is invalid: ${sourcePath}`);
576
- return Buffer.from(value, "base64");
577
- }
578
-
579
- function requiredText(value, message) {
580
- assert(typeof value === "string" && value.trim().length > 0, message);
581
- return value.trim();
582
- }
583
-
584
- function digest(value) {
585
- return sha256(Buffer.from(`${JSON.stringify(value)}\n`, "utf8"));
586
- }
587
-
588
- function sha256(value) {
589
- return createHash("sha256").update(value).digest("hex");
590
- }
591
-
592
- function assert(condition, message) {
593
- if (!condition) throw new Error(message);
594
- }