@moldea.ai/cli 13.0.3 → 14.0.0

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.
@@ -0,0 +1,4138 @@
1
+ import { d as ERRORS, f as Exception, m as hasErrorCode, n as CoreOperationException, u as isObjectValid } from "./chunk-728df961.mjs";
2
+ import { a as createCoreOperationOptionsSnapshot, c as locateDiagnosticRanges, d as normalizeDiagnostics, f as parseStrictYaml, g as countUtf8Bytes, h as compareCodePoints, i as createCoreDiagnosticCollector, l as measureYamlRetainedBytes, o as createNullPrototypeRecord, p as deepFreeze, r as countDiagnosticsBySeverity, s as escapeJsonPointerSegment, t as ACCEPTABLE_WARNING_CODES, u as normalizeCoreOptions } from "./chunk-a5514957.mjs";
3
+ import { a as compareRepositoryPaths, c as isRepositoryPath, i as RepositorySourceException, l as parseRepositoryPath, n as REPOSITORY_ROOT, s as createRepositoryIdentity, u as resolveRepositoryLink } from "./chunk-8d6114d2.mjs";
4
+ //#region ../../node_modules/.pnpm/jg-utilities@1.7.2/node_modules/jg-utilities/dist/utils/marked-region.js
5
+ var BYTE_ORDER_MARK = "";
6
+ var throwInvalidRegion = (problem) => {
7
+ throw new Exception(problem, { code: ERRORS.INVALID_MARKED_REGION });
8
+ };
9
+ var validateMarkers = ({ start, end }) => {
10
+ for (const marker of [start, end]) if (typeof marker !== "string" || marker === "" || /[\r\n]/.test(marker)) throwInvalidRegion("Each region marker must be a non-empty single line.");
11
+ if (start.includes(end) || end.includes(start)) throwInvalidRegion("Neither region marker may contain the other.");
12
+ };
13
+ var findMarkedRegion = (text, markers) => {
14
+ validateMarkers(markers);
15
+ let start;
16
+ let end;
17
+ let lineStart = 0;
18
+ while (lineStart < text.length) {
19
+ const newline = text.indexOf("\n", lineStart);
20
+ const lineEnd = newline === -1 ? text.length : newline + 1;
21
+ const hasCarriageReturn = newline > lineStart && text[newline - 1] === "\r";
22
+ const contentEnd = newline === -1 ? text.length : newline - (hasCarriageReturn ? 1 : 0);
23
+ const contentStart = lineStart === 0 && text.startsWith(BYTE_ORDER_MARK) ? 1 : lineStart;
24
+ const content = text.slice(contentStart, contentEnd);
25
+ for (const kind of ["start", "end"]) {
26
+ if (!content.includes(markers[kind])) continue;
27
+ if (content !== markers[kind]) throwInvalidRegion(`The ${kind} marker must fill its whole line.`);
28
+ if (kind === "start") {
29
+ if (start !== void 0 || end !== void 0) throwInvalidRegion("The document must hold one start marker, before one end marker.");
30
+ start = {
31
+ offset: contentStart,
32
+ lineEnding: hasCarriageReturn ? "\r\n" : "\n"
33
+ };
34
+ } else {
35
+ if (end !== void 0) throwInvalidRegion("The document must hold one end marker.");
36
+ end = lineEnd;
37
+ }
38
+ }
39
+ lineStart = lineEnd;
40
+ }
41
+ if (start === void 0 && end === void 0) return null;
42
+ if (start === void 0 || end === void 0) return throwInvalidRegion("The document must hold both region markers, or neither.");
43
+ return {
44
+ start: start.offset,
45
+ end,
46
+ lineEnding: start.lineEnding
47
+ };
48
+ };
49
+ //#endregion
50
+ //#region ../core/dist/chunks/scope-DQc5j2tD.js
51
+ var STABLE_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
52
+ var WINDOWS_RESERVED_ID_PATTERN = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/u;
53
+ var LINE_BREAK_CHARACTERS = [
54
+ "\n",
55
+ "\r",
56
+ "…",
57
+ "\u2028",
58
+ "\u2029"
59
+ ];
60
+ var UNSUPPORTED_GLOB_PATTERN = /[!?[\]{}]/u;
61
+ var hasLineBreak = (value) => {
62
+ return LINE_BREAK_CHARACTERS.some((lineBreak) => value.includes(lineBreak));
63
+ };
64
+ var isRepositoryFormatWhitespace = (codePoint) => {
65
+ return codePoint >= 9 && codePoint <= 13 || codePoint === 32 || codePoint === 133 || codePoint === 160 || codePoint === 5760 || codePoint >= 8192 && codePoint <= 8202 || codePoint === 8232 || codePoint === 8233 || codePoint === 8239 || codePoint === 8287 || codePoint === 12288;
66
+ };
67
+ var countUnicodeScalars = (value) => {
68
+ const scalars = value[Symbol.iterator]();
69
+ let count = 0;
70
+ while (scalars.next().done !== true) count += 1;
71
+ return count;
72
+ };
73
+ var hasNonWhitespace = (value) => {
74
+ for (const scalar of value) if (!isRepositoryFormatWhitespace(scalar.codePointAt(0) ?? 0)) return true;
75
+ return false;
76
+ };
77
+ var hasSurroundingWhitespace = (value) => {
78
+ const firstCodePoint = value.codePointAt(0);
79
+ const lastCodePoint = value.codePointAt(value.length - 1);
80
+ return firstCodePoint !== void 0 && isRepositoryFormatWhitespace(firstCodePoint) || lastCodePoint !== void 0 && isRepositoryFormatWhitespace(lastCodePoint);
81
+ };
82
+ var trimRepositoryFormatWhitespace = (value) => {
83
+ let start = 0;
84
+ let end = value.length;
85
+ while (start < end) {
86
+ const codePoint = value.codePointAt(start);
87
+ if (codePoint === void 0 || !isRepositoryFormatWhitespace(codePoint)) break;
88
+ start += codePoint > 65535 ? 2 : 1;
89
+ }
90
+ while (end > start) {
91
+ const codePoint = value.codePointAt(end - 1);
92
+ if (codePoint === void 0 || !isRepositoryFormatWhitespace(codePoint)) break;
93
+ end -= 1;
94
+ }
95
+ return value.slice(start, end);
96
+ };
97
+ var isNonEmptySingleLine = (value) => {
98
+ return value.length > 0 && !hasLineBreak(value);
99
+ };
100
+ var isStableId = (value) => {
101
+ return value.length <= 64 && STABLE_ID_PATTERN.test(value);
102
+ };
103
+ var isReservedId = (value) => WINDOWS_RESERVED_ID_PATTERN.test(value);
104
+ var isCapabilityDescription = (value) => {
105
+ const scalarLength = countUnicodeScalars(value);
106
+ return scalarLength >= 1 && scalarLength <= 1e3 && !hasSurroundingWhitespace(value) && !hasLineBreak(value) && !value.includes("\0");
107
+ };
108
+ var parseManifestPath = (value) => {
109
+ return value !== "/" && isRepositoryPath(value) ? parseRepositoryPath(value) : null;
110
+ };
111
+ var isCanonicalManifestPath = (path) => {
112
+ return path === "/moldea/moldea.yaml";
113
+ };
114
+ var parseDecisionIdFromPath = (path) => {
115
+ const match = /^\/moldea\/decisions\/(\d{13})-([a-z0-9]+(?:-[a-z0-9]+)*)\.md$/u.exec(path);
116
+ const id = match?.[1];
117
+ const slug = match?.[2];
118
+ return id !== void 0 && slug !== void 0 && isStableId(slug) ? id : null;
119
+ };
120
+ var isContextPath = (path, allowProject) => {
121
+ if (allowProject && path === "/moldea/project.md") return true;
122
+ return path.startsWith("/moldea/context/") && path.endsWith(".md");
123
+ };
124
+ var isDecisionPath = (path) => {
125
+ return parseDecisionIdFromPath(path) !== null;
126
+ };
127
+ var isMirrorPath = (path) => {
128
+ return path !== "/moldea" && !path.startsWith("/moldea/");
129
+ };
130
+ var hasUnsupportedGlobMetacharacter = (value) => {
131
+ return UNSUPPORTED_GLOB_PATTERN.test(value);
132
+ };
133
+ var isSimpleGlob = (value) => {
134
+ if (hasUnsupportedGlobMetacharacter(value) || value.includes("***")) return false;
135
+ if (value.slice(1).split("/").some((segment) => segment.includes("**") && segment !== "**")) return false;
136
+ return value.includes("*") && isRepositoryPath(value.replaceAll("*", "x"));
137
+ };
138
+ var isRepositorySymbol = (value) => {
139
+ return isNonEmptySingleLine(value) && !value.includes("\0");
140
+ };
141
+ var isCanonicalMoldeaPath = (path) => {
142
+ return path === "/moldea" || path.startsWith("/moldea/");
143
+ };
144
+ var encoder$2 = new TextEncoder();
145
+ var decoder$1 = new TextDecoder("utf-8", {
146
+ fatal: true,
147
+ ignoreBOM: true
148
+ });
149
+ var collectNulDiagnostics = (value, path, diagnostics) => {
150
+ let column = 1;
151
+ let line = 1;
152
+ let offset = 0;
153
+ for (const scalar of value) {
154
+ if (scalar === "\0") diagnostics.add({
155
+ code: "MOLDEA_TEXT_NUL_FORBIDDEN",
156
+ path,
157
+ range: {
158
+ end: {
159
+ column: column + 1,
160
+ line,
161
+ offset: offset + 1
162
+ },
163
+ start: {
164
+ column,
165
+ line,
166
+ offset
167
+ }
168
+ }
169
+ });
170
+ if (scalar === "\n") {
171
+ column = 1;
172
+ line += 1;
173
+ } else column += 1;
174
+ offset += 1;
175
+ }
176
+ };
177
+ var invalidArgument$1$1 = (operation) => {
178
+ throw new CoreOperationException({
179
+ code: "INVALID_ARGUMENT",
180
+ operation
181
+ });
182
+ };
183
+ var enforceFileLimit = (byteLength, limits, operation, limit) => {
184
+ if (byteLength <= limits[limit]) return;
185
+ throw new CoreOperationException({
186
+ code: "RESOURCE_LIMIT_EXCEEDED",
187
+ limit,
188
+ limitMaximum: limits[limit],
189
+ nextAction: "reduce-input-or-increase-limit",
190
+ observedUsage: byteLength,
191
+ operation
192
+ });
193
+ };
194
+ var invalidResult = (diagnostics) => {
195
+ return deepFreeze({
196
+ diagnostics: [...diagnostics],
197
+ text: null,
198
+ valid: false
199
+ });
200
+ };
201
+ var readInput = (input, limits, operation, limit, diagnostics) => {
202
+ if (!isObjectValid(input, true)) return invalidArgument$1$1(operation);
203
+ const pathCandidate = input["path"];
204
+ const content = input["content"];
205
+ if (typeof pathCandidate !== "string" || typeof content !== "string" && !(content instanceof Uint8Array)) return invalidArgument$1$1(operation);
206
+ const path = parseRepositoryPath(pathCandidate);
207
+ if (typeof content === "string") {
208
+ enforceFileLimit(countUtf8Bytes(content, limits[limit]), limits, operation, limit);
209
+ if (!content.isWellFormed()) {
210
+ diagnostics.add({
211
+ code: "MOLDEA_TEXT_INVALID_UNICODE",
212
+ path
213
+ });
214
+ return invalidResult(diagnostics.finalize());
215
+ }
216
+ return {
217
+ path,
218
+ value: content
219
+ };
220
+ }
221
+ enforceFileLimit(content.byteLength, limits, operation, limit);
222
+ const bytes = new Uint8Array(content);
223
+ try {
224
+ return {
225
+ path,
226
+ value: decoder$1.decode(bytes)
227
+ };
228
+ } catch {
229
+ diagnostics.add({
230
+ code: "MOLDEA_TEXT_INVALID_UTF8",
231
+ path
232
+ });
233
+ return invalidResult(diagnostics.finalize());
234
+ }
235
+ };
236
+ var normalizeTextDocument = (input, limits, operation, limit = "maxFileBytes") => {
237
+ const diagnostics = createCoreDiagnosticCollector(limits, operation);
238
+ const decoded = readInput(input, limits, operation, limit, diagnostics);
239
+ if ("valid" in decoded) return decoded;
240
+ const value = (decoded.value.startsWith("") ? decoded.value.slice(1) : decoded.value).replace(/\r\n?/gu, "\n");
241
+ collectNulDiagnostics(value, decoded.path, diagnostics);
242
+ if (diagnostics.size > 0) return invalidResult(diagnostics.finalize());
243
+ const text = deepFreeze({
244
+ scalarLength: countUnicodeScalars(value),
245
+ utf8ByteLength: countUtf8Bytes(value),
246
+ value
247
+ });
248
+ return deepFreeze({
249
+ diagnostics: [],
250
+ text,
251
+ valid: true
252
+ });
253
+ };
254
+ var toLowercaseHex = (bytes) => {
255
+ let value = "";
256
+ for (const byte of bytes) value += byte.toString(16).padStart(2, "0");
257
+ return value;
258
+ };
259
+ var calculateNormalizedTextDigest = async (text) => {
260
+ const bytes = encoder$2.encode(text.value);
261
+ return `sha256:${toLowercaseHex(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256", bytes)))}`;
262
+ };
263
+ var calculateContentDigest = async (input, limits) => {
264
+ const normalized = normalizeTextDocument(input, limits, "calculate-content-digest");
265
+ if (!normalized.valid || normalized.text === null) return deepFreeze({
266
+ diagnostics: normalized.diagnostics,
267
+ digest: null,
268
+ text: null,
269
+ valid: false
270
+ });
271
+ const digest = await calculateNormalizedTextDigest(normalized.text);
272
+ return deepFreeze({
273
+ diagnostics: [],
274
+ digest,
275
+ text: normalized.text,
276
+ valid: true
277
+ });
278
+ };
279
+ var matchesSegment = (pattern, value) => {
280
+ let patternIndex = 0;
281
+ let valueIndex = 0;
282
+ let starIndex = -1;
283
+ let starValueIndex = -1;
284
+ while (valueIndex < value.length) {
285
+ if (pattern[patternIndex] === value[valueIndex]) {
286
+ patternIndex += 1;
287
+ valueIndex += 1;
288
+ continue;
289
+ }
290
+ if (pattern[patternIndex] === "*") {
291
+ starIndex = patternIndex;
292
+ starValueIndex = valueIndex;
293
+ patternIndex += 1;
294
+ continue;
295
+ }
296
+ if (starIndex === -1) return false;
297
+ patternIndex = starIndex + 1;
298
+ starValueIndex += 1;
299
+ valueIndex = starValueIndex;
300
+ }
301
+ while (pattern[patternIndex] === "*") patternIndex += 1;
302
+ return patternIndex === pattern.length;
303
+ };
304
+ var matchesRepositoryGlob = (patternSegments, path) => {
305
+ const pathSegments = path.slice(1).split("/");
306
+ let reachable = new Uint8Array(pathSegments.length + 1);
307
+ reachable[0] = 1;
308
+ for (const patternSegment of patternSegments) {
309
+ const next = new Uint8Array(pathSegments.length + 1);
310
+ if (patternSegment === "**") {
311
+ let canReach = false;
312
+ for (let index = 0; index < reachable.length; index += 1) {
313
+ canReach ||= reachable[index] === 1;
314
+ next[index] = canReach ? 1 : 0;
315
+ }
316
+ } else for (let index = 0; index < pathSegments.length; index += 1) if (reachable[index] === 1 && matchesSegment(patternSegment, pathSegments[index] ?? "")) next[index + 1] = 1;
317
+ reachable = next;
318
+ }
319
+ return reachable[pathSegments.length] === 1;
320
+ };
321
+ var childPointer$1 = (pointer, segment) => {
322
+ return `${pointer}/${escapeJsonPointerSegment(segment)}`;
323
+ };
324
+ var createOwner = (kind, id, agentId = null) => ({
325
+ agentId,
326
+ id,
327
+ kind
328
+ });
329
+ var compareOwners = (left, right) => {
330
+ return compareCodePoints(left.kind, right.kind) || compareCodePoints(left.agentId ?? "", right.agentId ?? "") || compareCodePoints(left.id, right.id);
331
+ };
332
+ var getDeclarationValue = (declaration) => {
333
+ return declaration.kind === "exact" ? declaration.path : declaration.pattern;
334
+ };
335
+ var compareDeclarations = (left, right) => {
336
+ return compareOwners(left.owner, right.owner) || compareCodePoints(left.field, right.field) || compareCodePoints(getDeclarationValue(left.declaration), getDeclarationValue(right.declaration)) || compareCodePoints(left.pointer, right.pointer);
337
+ };
338
+ var addExactDeclaration = (declarations, owner, field, pointer, reference) => {
339
+ declarations.push({
340
+ declaration: typeof reference === "string" ? {
341
+ kind: "exact",
342
+ path: reference,
343
+ symbol: null
344
+ } : {
345
+ kind: "exact",
346
+ path: reference.path,
347
+ symbol: reference.symbol ?? null
348
+ },
349
+ field,
350
+ owner,
351
+ pointer
352
+ });
353
+ };
354
+ var addReferenceDeclarations = (declarations, references, owner, field, pointer) => {
355
+ for (const [index, reference] of (references ?? []).entries()) addExactDeclaration(declarations, owner, field, childPointer$1(pointer, String(index)), reference);
356
+ };
357
+ var addAffectedByDeclarations = (declarations, affectedBy, owner, pointer) => {
358
+ for (const [index, pattern] of (affectedBy ?? []).entries()) declarations.push({
359
+ declaration: pattern.includes("*") ? {
360
+ kind: "glob",
361
+ pattern
362
+ } : {
363
+ kind: "exact",
364
+ path: pattern,
365
+ symbol: null
366
+ },
367
+ field: "affectedBy",
368
+ owner,
369
+ pointer: childPointer$1(pointer, String(index))
370
+ });
371
+ };
372
+ var addCapabilityDeclarations = (declarations, capabilityId, capability, agentId, pointer) => {
373
+ const owner = createOwner(capability.kind, capabilityId, agentId);
374
+ addExactDeclaration(declarations, owner, "implementation", childPointer$1(pointer, "implementation"), capability.value.implementation);
375
+ if (capability.value.registration !== void 0) addExactDeclaration(declarations, owner, "registration", childPointer$1(pointer, "registration"), capability.value.registration);
376
+ if (capability.kind === "tool") for (const field of ["inputSchema", "outputSchema"]) {
377
+ const reference = capability.value[field];
378
+ if (reference !== void 0) addExactDeclaration(declarations, owner, field, childPointer$1(pointer, field), reference);
379
+ }
380
+ addAffectedByDeclarations(declarations, capability.value.affectedBy, owner, childPointer$1(pointer, "affectedBy"));
381
+ };
382
+ var addAgentDeclarations = (declarations, agentId, agent) => {
383
+ const pointer = childPointer$1("/agents", agentId);
384
+ const owner = createOwner("agent", agentId, agentId);
385
+ const bindingsPointer = childPointer$1(pointer, "bindings");
386
+ for (const field of [
387
+ "runtimeAgent",
388
+ "inputSchema",
389
+ "outputSchema",
390
+ "instructionLoader"
391
+ ]) {
392
+ const reference = agent.bindings?.[field];
393
+ if (reference !== void 0) addExactDeclaration(declarations, owner, field, childPointer$1(bindingsPointer, field), reference);
394
+ }
395
+ addAffectedByDeclarations(declarations, agent.affectedBy, owner, childPointer$1(pointer, "affectedBy"));
396
+ for (const capabilityId of Object.keys(agent.tools ?? {}).sort(compareCodePoints)) {
397
+ const tool = agent.tools?.[capabilityId];
398
+ if (tool !== void 0) addCapabilityDeclarations(declarations, capabilityId, {
399
+ kind: "tool",
400
+ value: tool
401
+ }, agentId, childPointer$1(childPointer$1(pointer, "tools"), capabilityId));
402
+ }
403
+ for (const capabilityId of Object.keys(agent.skills ?? {}).sort(compareCodePoints)) {
404
+ const skill = agent.skills?.[capabilityId];
405
+ if (skill !== void 0) addCapabilityDeclarations(declarations, capabilityId, {
406
+ kind: "skill",
407
+ value: skill
408
+ }, agentId, childPointer$1(childPointer$1(pointer, "skills"), capabilityId));
409
+ }
410
+ for (const [index, mirror] of (agent.mirrors ?? []).entries()) addExactDeclaration(declarations, owner, "mirrors", childPointer$1(childPointer$1(pointer, "mirrors"), String(index)), mirror);
411
+ };
412
+ var collectManifestScopeDeclarations = (manifest) => {
413
+ const declarations = [];
414
+ for (const kind of ["context", "decision"]) {
415
+ const relationships = kind === "context" ? manifest.context : manifest.decisions;
416
+ for (const ownerId of Object.keys(relationships ?? {}).sort(compareCodePoints)) {
417
+ const relationship = relationships?.[ownerId];
418
+ if (relationship === void 0) continue;
419
+ const owner = createOwner(kind, ownerId);
420
+ const pointer = childPointer$1(kind === "context" ? "/context" : "/decisions", ownerId);
421
+ addReferenceDeclarations(declarations, relationship.bindings, owner, "bindings", childPointer$1(pointer, "bindings"));
422
+ addAffectedByDeclarations(declarations, relationship.affectedBy, owner, childPointer$1(pointer, "affectedBy"));
423
+ }
424
+ }
425
+ for (const agentId of Object.keys(manifest.agents ?? {}).sort(compareCodePoints)) {
426
+ const agent = manifest.agents?.[agentId];
427
+ if (agent !== void 0) addAgentDeclarations(declarations, agentId, agent);
428
+ }
429
+ return declarations.sort(compareDeclarations);
430
+ };
431
+ var compileManifestScope = (manifest, limits) => {
432
+ const declarations = collectManifestScopeDeclarations(manifest);
433
+ if (declarations.length > limits.maxEntries) throw new CoreOperationException({
434
+ code: "RESOURCE_LIMIT_EXCEEDED",
435
+ limit: "maxEntries",
436
+ limitMaximum: limits.maxEntries,
437
+ nextAction: "reduce-input-or-increase-limit",
438
+ observedUsage: declarations.length,
439
+ operation: "match-manifest-scope"
440
+ });
441
+ const exact = new Map();
442
+ const globalGlobs = [];
443
+ const globsByFirstSegment = new Map();
444
+ for (const declaration of declarations) {
445
+ if (declaration.declaration.kind === "exact") {
446
+ const existing = exact.get(declaration.declaration.path) ?? [];
447
+ existing.push(declaration);
448
+ exact.set(declaration.declaration.path, existing);
449
+ continue;
450
+ }
451
+ const segments = declaration.declaration.pattern.slice(1).split("/");
452
+ const compiled = {
453
+ declaration,
454
+ segments
455
+ };
456
+ const firstSegment = segments[0] ?? "";
457
+ if (firstSegment === "**" || firstSegment.includes("*")) globalGlobs.push(compiled);
458
+ else {
459
+ const existing = globsByFirstSegment.get(firstSegment) ?? [];
460
+ existing.push(compiled);
461
+ globsByFirstSegment.set(firstSegment, existing);
462
+ }
463
+ }
464
+ return {
465
+ declarations,
466
+ exact,
467
+ globalGlobs,
468
+ globsByFirstSegment
469
+ };
470
+ };
471
+ var compareMatches = (left, right) => {
472
+ return compareOwners(left.owner, right.owner) || compareCodePoints(left.field, right.field) || compareCodePoints(getDeclarationValue(left.declaration), getDeclarationValue(right.declaration)) || compareCodePoints(left.inputPath, right.inputPath) || compareCodePoints(left.pointer, right.pointer);
473
+ };
474
+ var createMatch = (inputPath, relationship) => ({
475
+ declaration: relationship.declaration,
476
+ field: relationship.field,
477
+ inputPath,
478
+ owner: relationship.owner,
479
+ pointer: relationship.pointer
480
+ });
481
+ var addMatch = (matches, inputPath, relationship, limits) => {
482
+ if (matches.length >= limits.maxEntries) throw new CoreOperationException({
483
+ code: "RESOURCE_LIMIT_EXCEEDED",
484
+ limit: "maxEntries",
485
+ limitMaximum: limits.maxEntries,
486
+ nextAction: "reduce-input-or-increase-limit",
487
+ observedUsage: matches.length + 1,
488
+ operation: "match-manifest-scope"
489
+ });
490
+ matches.push(createMatch(inputPath, relationship));
491
+ };
492
+ var addGlobMatches = (matches, inputPath, declarations, limits) => {
493
+ for (const compiled of declarations) if (matchesRepositoryGlob(compiled.segments, inputPath)) addMatch(matches, inputPath, compiled.declaration, limits);
494
+ };
495
+ var calculateManifestScopeInputDigest = async (paths) => {
496
+ const value = paths.join("\0");
497
+ return calculateNormalizedTextDigest({
498
+ scalarLength: countUnicodeScalars(value),
499
+ utf8ByteLength: countUtf8Bytes(value),
500
+ value
501
+ });
502
+ };
503
+ var matchParsedManifestScope = (manifest, paths, limits) => {
504
+ const compiled = compileManifestScope(manifest, limits);
505
+ const matches = [];
506
+ const matchedOwners = new Set();
507
+ const matchedPaths = new Set();
508
+ for (const path of paths) {
509
+ const firstSegment = path.slice(1).split("/", 1)[0] ?? "";
510
+ const exactDeclarations = compiled.exact.get(path) ?? [];
511
+ for (const relationship of exactDeclarations) addMatch(matches, path, relationship, limits);
512
+ addGlobMatches(matches, path, compiled.globalGlobs, limits);
513
+ addGlobMatches(matches, path, compiled.globsByFirstSegment.get(firstSegment) ?? [], limits);
514
+ }
515
+ matches.sort(compareMatches);
516
+ for (const match of matches) {
517
+ matchedOwners.add(`${match.owner.kind}\0${match.owner.agentId ?? ""}\0${match.owner.id}`);
518
+ matchedPaths.add(match.inputPath);
519
+ }
520
+ return deepFreeze({
521
+ counts: {
522
+ declarations: compiled.declarations.length,
523
+ inputPaths: paths.length,
524
+ matchedOwners: matchedOwners.size,
525
+ matchedPaths: matchedPaths.size,
526
+ matches: matches.length
527
+ },
528
+ matches
529
+ });
530
+ };
531
+ var childPointer$2 = (pointer, key) => {
532
+ return `${pointer}/${escapeJsonPointerSegment(key)}`;
533
+ };
534
+ var addInvalidValue = (context, pointer, range, reason, entity = null) => {
535
+ context.diagnostics.add({
536
+ code: "MOLDEA_MANIFEST_VALUE_INVALID",
537
+ details: { reason },
538
+ entity,
539
+ path: context.path,
540
+ pointer,
541
+ range
542
+ });
543
+ };
544
+ var readMapping$1 = (node, pointer, allowedProperties, context, entity = null) => {
545
+ if (node.kind !== "mapping") {
546
+ addInvalidValue(context, pointer, node.range, "mapping-required", entity);
547
+ return null;
548
+ }
549
+ const entries = new Map();
550
+ for (const entry of node.entries) {
551
+ if (entry.key.kind !== "scalar" || typeof entry.key.value !== "string") {
552
+ addInvalidValue(context, pointer, entry.key.range, "string-key-required", entity);
553
+ continue;
554
+ }
555
+ const key = entry.key.value;
556
+ if (allowedProperties !== null && !allowedProperties.has(key)) {
557
+ context.diagnostics.add({
558
+ code: "MOLDEA_MANIFEST_PROPERTY_UNKNOWN",
559
+ entity,
560
+ path: context.path,
561
+ pointer: childPointer$2(pointer, key),
562
+ range: entry.key.range
563
+ });
564
+ continue;
565
+ }
566
+ entries.set(key, {
567
+ key: entry.key,
568
+ value: entry.value
569
+ });
570
+ }
571
+ return entries;
572
+ };
573
+ var readString = (entry, pointer, context, options = {}) => {
574
+ if (entry === void 0) {
575
+ if (options.required === true) addInvalidValue(context, pointer, null, "required", options.entity ?? null);
576
+ return null;
577
+ }
578
+ if (entry.value.kind !== "scalar" || typeof entry.value.value !== "string") {
579
+ addInvalidValue(context, pointer, entry.value.range, "string-required", options.entity ?? null);
580
+ return null;
581
+ }
582
+ const value = entry.value.value;
583
+ if (!hasNonWhitespace(value) || options.singleLine === true && !isNonEmptySingleLine(value)) {
584
+ addInvalidValue(context, pointer, entry.value.range, "string-invalid", options.entity ?? null);
585
+ return null;
586
+ }
587
+ return value;
588
+ };
589
+ var validateStableId = (value, range, pointer, context, entity = null) => {
590
+ if (!isStableId(value)) {
591
+ context.diagnostics.add({
592
+ code: "MOLDEA_ID_INVALID",
593
+ entity,
594
+ path: context.path,
595
+ pointer,
596
+ range
597
+ });
598
+ return false;
599
+ }
600
+ if (isReservedId(value)) {
601
+ context.diagnostics.add({
602
+ code: "MOLDEA_ID_RESERVED",
603
+ entity,
604
+ path: context.path,
605
+ pointer,
606
+ range
607
+ });
608
+ return false;
609
+ }
610
+ return true;
611
+ };
612
+ var readReference = (node, pointer, context, entity = null) => {
613
+ const entries = readMapping$1(node, pointer, new Set(["path", "symbol"]), context, entity);
614
+ if (entries === null) return null;
615
+ const pathEntry = entries.get("path");
616
+ if (pathEntry?.value.kind !== "scalar" || typeof pathEntry.value.value !== "string") {
617
+ context.diagnostics.add({
618
+ code: "MOLDEA_PATH_INVALID",
619
+ details: { reason: pathEntry === void 0 ? "missing" : "type" },
620
+ entity,
621
+ path: context.path,
622
+ pointer: childPointer$2(pointer, "path"),
623
+ range: pathEntry?.value.range ?? null
624
+ });
625
+ return null;
626
+ }
627
+ const path = parseManifestPath(pathEntry.value.value);
628
+ if (path === null) {
629
+ context.diagnostics.add({
630
+ code: "MOLDEA_PATH_INVALID",
631
+ entity,
632
+ path: context.path,
633
+ pointer: childPointer$2(pointer, "path"),
634
+ range: pathEntry.value.range
635
+ });
636
+ return null;
637
+ }
638
+ const symbolEntry = entries.get("symbol");
639
+ if (symbolEntry === void 0) return { path };
640
+ if (symbolEntry.value.kind !== "scalar" || typeof symbolEntry.value.value !== "string" || !isRepositorySymbol(symbolEntry.value.value)) {
641
+ context.diagnostics.add({
642
+ code: "MOLDEA_SYMBOL_INVALID",
643
+ entity,
644
+ path: context.path,
645
+ pointer: childPointer$2(pointer, "symbol"),
646
+ range: symbolEntry.value.range
647
+ });
648
+ return null;
649
+ }
650
+ if (isCanonicalMoldeaPath(path)) {
651
+ context.diagnostics.add({
652
+ code: "MOLDEA_SYMBOL_FORBIDDEN",
653
+ entity,
654
+ path: context.path,
655
+ pointer: childPointer$2(pointer, "symbol"),
656
+ range: symbolEntry.value.range
657
+ });
658
+ return null;
659
+ }
660
+ return {
661
+ path,
662
+ symbol: symbolEntry.value.value
663
+ };
664
+ };
665
+ var readReferenceList = (node, pointer, context, entity = null) => {
666
+ if (node.kind !== "sequence" || node.items.length === 0) {
667
+ addInvalidValue(context, pointer, node.range, "non-empty-sequence-required", entity);
668
+ return [];
669
+ }
670
+ const references = [];
671
+ const seen = new Set();
672
+ node.items.forEach((item, index) => {
673
+ const reference = readReference(item, childPointer$2(pointer, String(index)), context, entity);
674
+ if (reference === null) return;
675
+ const key = `${reference.path}\0${reference.symbol ?? ""}`;
676
+ if (seen.has(key)) {
677
+ context.diagnostics.add({
678
+ code: "MOLDEA_PATH_DUPLICATE",
679
+ entity,
680
+ path: context.path,
681
+ pointer: childPointer$2(pointer, String(index)),
682
+ range: item.range
683
+ });
684
+ return;
685
+ }
686
+ seen.add(key);
687
+ references.push(reference);
688
+ });
689
+ return references;
690
+ };
691
+ var readAffectedBy = (node, pointer, context, entity = null) => {
692
+ if (node.kind !== "sequence" || node.items.length === 0) {
693
+ addInvalidValue(context, pointer, node.range, "non-empty-sequence-required", entity);
694
+ return [];
695
+ }
696
+ const values = [];
697
+ const seen = new Set();
698
+ node.items.forEach((item, index) => {
699
+ const itemPointer = childPointer$2(pointer, String(index));
700
+ if (item.kind !== "scalar" || typeof item.value !== "string") {
701
+ addInvalidValue(context, itemPointer, item.range, "string-required", entity);
702
+ return;
703
+ }
704
+ const isGlob = item.value.includes("*") || hasUnsupportedGlobMetacharacter(item.value);
705
+ if (!(isGlob ? isSimpleGlob(item.value) : parseManifestPath(item.value) !== null)) {
706
+ context.diagnostics.add({
707
+ code: isGlob ? "MOLDEA_GLOB_INVALID" : "MOLDEA_PATH_INVALID",
708
+ entity,
709
+ path: context.path,
710
+ pointer: itemPointer,
711
+ range: item.range
712
+ });
713
+ return;
714
+ }
715
+ if (seen.has(item.value)) {
716
+ context.diagnostics.add({
717
+ code: isGlob ? "MOLDEA_PATTERN_DUPLICATE" : "MOLDEA_PATH_DUPLICATE",
718
+ entity,
719
+ path: context.path,
720
+ pointer: itemPointer,
721
+ range: item.range
722
+ });
723
+ return;
724
+ }
725
+ seen.add(item.value);
726
+ values.push(item.value);
727
+ });
728
+ return values;
729
+ };
730
+ var readRelationship = (node, pointer, context) => {
731
+ const entries = readMapping$1(node, pointer, new Set(["affectedBy", "bindings"]), context);
732
+ if (entries === null) return null;
733
+ const bindingsEntry = entries.get("bindings");
734
+ const affectedByEntry = entries.get("affectedBy");
735
+ if (bindingsEntry === void 0 && affectedByEntry === void 0) context.diagnostics.add({
736
+ code: "MOLDEA_CONTEXT_RELATIONSHIP_EMPTY",
737
+ path: context.path,
738
+ pointer,
739
+ range: node.range
740
+ });
741
+ return {
742
+ ...bindingsEntry === void 0 ? {} : { bindings: readReferenceList(bindingsEntry.value, childPointer$2(pointer, "bindings"), context) },
743
+ ...affectedByEntry === void 0 ? {} : { affectedBy: readAffectedBy(affectedByEntry.value, childPointer$2(pointer, "affectedBy"), context) }
744
+ };
745
+ };
746
+ var readRelationshipRecord = (node, pointer, kind, context) => {
747
+ const entries = readMapping$1(node, pointer, null, context);
748
+ if (entries === null) return null;
749
+ const normalized = [];
750
+ for (const [key, entry] of [...entries].sort(([left], [right]) => compareCodePoints(left, right))) {
751
+ const path = parseManifestPath(key);
752
+ if (!(path !== null && (kind === "context" ? isContextPath(path, true) : isDecisionPath(path)))) {
753
+ context.diagnostics.add({
754
+ code: kind === "context" ? "MOLDEA_CONTEXT_PATH_INVALID" : "MOLDEA_DECISION_FILENAME_INVALID",
755
+ path: context.path,
756
+ pointer: childPointer$2(pointer, key),
757
+ range: entry.key.range
758
+ });
759
+ continue;
760
+ }
761
+ const relationship = readRelationship(entry.value, childPointer$2(pointer, key), context);
762
+ if (relationship !== null) normalized.push([key, relationship]);
763
+ }
764
+ return createNullPrototypeRecord(normalized);
765
+ };
766
+ var readPathList = (node, pointer, kind, context, entity) => {
767
+ if (node.kind !== "sequence") {
768
+ addInvalidValue(context, pointer, node.range, "sequence-required", entity);
769
+ return [];
770
+ }
771
+ const paths = [];
772
+ const seen = new Set();
773
+ node.items.forEach((item, index) => {
774
+ const itemPointer = childPointer$2(pointer, String(index));
775
+ if (item.kind !== "scalar" || typeof item.value !== "string") {
776
+ addInvalidValue(context, itemPointer, item.range, "string-required", entity);
777
+ return;
778
+ }
779
+ const path = parseManifestPath(item.value);
780
+ if (!(path !== null && (kind === "context" ? isContextPath(path, false) : kind === "decision" ? isDecisionPath(path) : isMirrorPath(path))) || path === null) {
781
+ const code = kind === "context" ? "MOLDEA_CONTEXT_PATH_INVALID" : kind === "decision" ? "MOLDEA_DECISION_FILENAME_INVALID" : path !== null && !isMirrorPath(path) ? "MOLDEA_MIRROR_PATH_INSIDE_MOLDEA" : "MOLDEA_MIRROR_PATH_INVALID";
782
+ context.diagnostics.add({
783
+ code,
784
+ entity,
785
+ path: context.path,
786
+ pointer: itemPointer,
787
+ range: item.range
788
+ });
789
+ return;
790
+ }
791
+ if (seen.has(path)) {
792
+ context.diagnostics.add({
793
+ code: kind === "mirror" ? "MOLDEA_MIRROR_PATH_DUPLICATE" : "MOLDEA_PATH_DUPLICATE",
794
+ entity,
795
+ path: context.path,
796
+ pointer: itemPointer,
797
+ range: item.range
798
+ });
799
+ return;
800
+ }
801
+ if (kind === "mirror" && context.mirrorPaths.has(path)) {
802
+ context.diagnostics.add({
803
+ code: "MOLDEA_MIRROR_PATH_DUPLICATE",
804
+ entity,
805
+ path: context.path,
806
+ pointer: itemPointer,
807
+ range: item.range
808
+ });
809
+ return;
810
+ }
811
+ seen.add(path);
812
+ if (kind === "mirror") context.mirrorPaths.add(path);
813
+ paths.push(path);
814
+ });
815
+ return paths;
816
+ };
817
+ var readBindings = (node, pointer, context, agentId) => {
818
+ const entity = { agentId };
819
+ const entries = readMapping$1(node, pointer, new Set([
820
+ "inputSchema",
821
+ "instructionLoader",
822
+ "outputSchema",
823
+ "runtimeAgent"
824
+ ]), context, entity);
825
+ if (entries === null) return null;
826
+ const referenceProperty = (key) => {
827
+ const entry = entries.get(key);
828
+ return entry === void 0 ? null : readReference(entry.value, childPointer$2(pointer, key), context, entity);
829
+ };
830
+ const inputSchema = referenceProperty("inputSchema");
831
+ const instructionLoader = referenceProperty("instructionLoader");
832
+ const outputSchema = referenceProperty("outputSchema");
833
+ const runtimeAgent = referenceProperty("runtimeAgent");
834
+ return {
835
+ ...runtimeAgent === null ? {} : { runtimeAgent },
836
+ ...inputSchema === null ? {} : { inputSchema },
837
+ ...outputSchema === null ? {} : { outputSchema },
838
+ ...instructionLoader === null ? {} : { instructionLoader }
839
+ };
840
+ };
841
+ var readCapability = (node, pointer, context, agentId, capabilityId, kind) => {
842
+ const entity = {
843
+ agentId,
844
+ capabilityId,
845
+ capabilityKind: kind
846
+ };
847
+ const entries = readMapping$1(node, pointer, kind === "tool" ? new Set([
848
+ "affectedBy",
849
+ "description",
850
+ "implementation",
851
+ "inputSchema",
852
+ "name",
853
+ "outputSchema",
854
+ "registration"
855
+ ]) : new Set([
856
+ "affectedBy",
857
+ "description",
858
+ "implementation",
859
+ "name",
860
+ "registration"
861
+ ]), context, entity);
862
+ if (entries === null) return null;
863
+ const name = readString(entries.get("name"), childPointer$2(pointer, "name"), context, {
864
+ entity,
865
+ required: true,
866
+ singleLine: true
867
+ });
868
+ const descriptionEntry = entries.get("description");
869
+ let description = null;
870
+ if (descriptionEntry === void 0) context.diagnostics.add({
871
+ code: "MOLDEA_CAPABILITY_DESCRIPTION_MISSING",
872
+ entity,
873
+ path: context.path,
874
+ pointer: childPointer$2(pointer, "description")
875
+ });
876
+ else if (descriptionEntry.value.kind !== "scalar" || typeof descriptionEntry.value.value !== "string" || !isCapabilityDescription(descriptionEntry.value.value)) context.diagnostics.add({
877
+ code: "MOLDEA_CAPABILITY_DESCRIPTION_INVALID",
878
+ entity,
879
+ path: context.path,
880
+ pointer: childPointer$2(pointer, "description"),
881
+ range: descriptionEntry.value.range
882
+ });
883
+ else description = descriptionEntry.value.value;
884
+ const implementationEntry = entries.get("implementation");
885
+ let implementation = null;
886
+ if (implementationEntry === void 0) context.diagnostics.add({
887
+ code: kind === "tool" ? "MOLDEA_TOOL_IMPLEMENTATION_MISSING" : "MOLDEA_SKILL_IMPLEMENTATION_MISSING",
888
+ entity,
889
+ path: context.path,
890
+ pointer: childPointer$2(pointer, "implementation")
891
+ });
892
+ else implementation = readReference(implementationEntry.value, childPointer$2(pointer, "implementation"), context, entity);
893
+ const optionalReference = (key) => {
894
+ const entry = entries.get(key);
895
+ return entry === void 0 ? null : readReference(entry.value, childPointer$2(pointer, key), context, entity);
896
+ };
897
+ const registration = optionalReference("registration");
898
+ const inputSchema = kind === "tool" ? optionalReference("inputSchema") : null;
899
+ const outputSchema = kind === "tool" ? optionalReference("outputSchema") : null;
900
+ const affectedByEntry = entries.get("affectedBy");
901
+ const affectedBy = affectedByEntry === void 0 ? null : readAffectedBy(affectedByEntry.value, childPointer$2(pointer, "affectedBy"), context, entity);
902
+ if (name === null || description === null || implementation === null) return null;
903
+ return {
904
+ name,
905
+ description,
906
+ implementation,
907
+ ...registration === null ? {} : { registration },
908
+ ...inputSchema === null ? {} : { inputSchema },
909
+ ...outputSchema === null ? {} : { outputSchema },
910
+ ...affectedBy === null ? {} : { affectedBy }
911
+ };
912
+ };
913
+ var readCapabilities = (node, pointer, context, agentId, kind) => {
914
+ const entries = readMapping$1(node, pointer, null, context, { agentId });
915
+ if (entries === null) return null;
916
+ const normalized = [];
917
+ for (const [capabilityId, entry] of [...entries].sort(([left], [right]) => compareCodePoints(left, right))) {
918
+ const entity = {
919
+ agentId,
920
+ capabilityId,
921
+ capabilityKind: kind
922
+ };
923
+ const capabilityPointer = childPointer$2(pointer, capabilityId);
924
+ validateStableId(capabilityId, entry.key.range, capabilityPointer, context, entity);
925
+ const capability = readCapability(entry.value, capabilityPointer, context, agentId, capabilityId, kind);
926
+ if (capability !== null) normalized.push([capabilityId, capability]);
927
+ }
928
+ return createNullPrototypeRecord(normalized);
929
+ };
930
+ var findMappingProperty = (node, property) => {
931
+ if (node.kind !== "mapping") return null;
932
+ for (const entry of node.entries) if (entry.key.kind === "scalar" && entry.key.value === property) return entry.value;
933
+ return null;
934
+ };
935
+ var detectSupportedManifestVersion = (node) => {
936
+ if (node.kind !== "mapping") return null;
937
+ const versionNode = findMappingProperty(node, "version");
938
+ return versionNode?.kind === "scalar" && versionNode.value === 1n ? 1 : null;
939
+ };
940
+ var validateAgentOwnedIdUniqueness = (node, pointer, context, agentId) => {
941
+ const seen = new Set();
942
+ for (const property of ["tools", "skills"]) {
943
+ const record = findMappingProperty(node, property);
944
+ if (record?.kind !== "mapping") continue;
945
+ for (const entry of record.entries) {
946
+ if (entry.key.kind !== "scalar" || typeof entry.key.value !== "string") continue;
947
+ if (seen.has(entry.key.value)) context.diagnostics.add({
948
+ code: "MOLDEA_ID_DUPLICATE",
949
+ entity: { agentId },
950
+ path: context.path,
951
+ pointer: childPointer$2(childPointer$2(pointer, property), entry.key.value),
952
+ range: entry.key.range
953
+ });
954
+ seen.add(entry.key.value);
955
+ }
956
+ }
957
+ };
958
+ var readAgent = (node, pointer, context, agentId) => {
959
+ const entity = { agentId };
960
+ const entries = readMapping$1(node, pointer, new Set([
961
+ "affectedBy",
962
+ "bindings",
963
+ "context",
964
+ "decisions",
965
+ "mirrors",
966
+ "skills",
967
+ "tools"
968
+ ]), context, entity);
969
+ if (entries === null) return null;
970
+ validateAgentOwnedIdUniqueness(node, pointer, context, agentId);
971
+ const bindingsEntry = entries.get("bindings");
972
+ const bindings = bindingsEntry === void 0 ? null : readBindings(bindingsEntry.value, childPointer$2(pointer, "bindings"), context, agentId);
973
+ const contextEntry = entries.get("context");
974
+ const contextPaths = contextEntry === void 0 ? null : readPathList(contextEntry.value, childPointer$2(pointer, "context"), "context", context, entity);
975
+ const decisionsEntry = entries.get("decisions");
976
+ const decisions = decisionsEntry === void 0 ? null : readPathList(decisionsEntry.value, childPointer$2(pointer, "decisions"), "decision", context, entity);
977
+ const toolsEntry = entries.get("tools");
978
+ const tools = toolsEntry === void 0 ? null : readCapabilities(toolsEntry.value, childPointer$2(pointer, "tools"), context, agentId, "tool");
979
+ const skillsEntry = entries.get("skills");
980
+ const skills = skillsEntry === void 0 ? null : readCapabilities(skillsEntry.value, childPointer$2(pointer, "skills"), context, agentId, "skill");
981
+ const affectedByEntry = entries.get("affectedBy");
982
+ const affectedBy = affectedByEntry === void 0 ? null : readAffectedBy(affectedByEntry.value, childPointer$2(pointer, "affectedBy"), context, entity);
983
+ const mirrorsEntry = entries.get("mirrors");
984
+ const mirrors = mirrorsEntry === void 0 ? null : readPathList(mirrorsEntry.value, childPointer$2(pointer, "mirrors"), "mirror", context, entity);
985
+ return {
986
+ ...contextPaths === null ? {} : { context: contextPaths },
987
+ ...decisions === null ? {} : { decisions },
988
+ ...bindings === null ? {} : { bindings },
989
+ ...tools === null ? {} : { tools },
990
+ ...skills === null ? {} : { skills },
991
+ ...affectedBy === null ? {} : { affectedBy },
992
+ ...mirrors === null ? {} : { mirrors }
993
+ };
994
+ };
995
+ var readAgents = (node, pointer, context) => {
996
+ const entries = readMapping$1(node, pointer, null, context);
997
+ if (entries === null) return null;
998
+ const normalized = [];
999
+ for (const [agentId, entry] of [...entries].sort(([left], [right]) => compareCodePoints(left, right))) {
1000
+ const agentPointer = childPointer$2(pointer, agentId);
1001
+ validateStableId(agentId, entry.key.range, agentPointer, context, { agentId });
1002
+ const agent = readAgent(entry.value, agentPointer, context, agentId);
1003
+ if (agent !== null) normalized.push([agentId, agent]);
1004
+ }
1005
+ return createNullPrototypeRecord(normalized);
1006
+ };
1007
+ var readAcceptedWarnings = (node, context) => {
1008
+ const report = (entry, field, range, reason) => {
1009
+ context.diagnostics.add({
1010
+ code: "MOLDEA_MANIFEST_VALUE_INVALID",
1011
+ path: context.path,
1012
+ pointer: entry === null ? "/acceptedWarnings" : `/acceptedWarnings/${entry}/${escapeJsonPointerSegment(field)}`,
1013
+ range,
1014
+ details: {
1015
+ entry,
1016
+ field,
1017
+ reason
1018
+ }
1019
+ });
1020
+ };
1021
+ if (node.kind !== "sequence") {
1022
+ report(null, "acceptedWarnings", node.range, "sequence-required");
1023
+ return null;
1024
+ }
1025
+ if (node.items.length > context.limits.maxAcceptedWarnings) throw new CoreOperationException({
1026
+ code: "RESOURCE_LIMIT_EXCEEDED",
1027
+ operation: context.operation,
1028
+ limit: "maxAcceptedWarnings",
1029
+ limitMaximum: context.limits.maxAcceptedWarnings,
1030
+ observedUsage: node.items.length,
1031
+ nextAction: "reduce-input-or-increase-limit"
1032
+ });
1033
+ const accepted = [];
1034
+ const identities = new Set();
1035
+ for (const [index, item] of node.items.entries()) {
1036
+ if (item.kind !== "mapping") {
1037
+ report(index, "entry", item.range, "mapping-required");
1038
+ continue;
1039
+ }
1040
+ const fields = new Map();
1041
+ let isValid = true;
1042
+ for (const entry of item.entries) if (entry.key.kind !== "scalar" || typeof entry.key.value !== "string" || ![
1043
+ "code",
1044
+ "subject",
1045
+ "qualifier",
1046
+ "reason"
1047
+ ].includes(entry.key.value)) {
1048
+ report(index, entry.key.kind === "scalar" && typeof entry.key.value === "string" ? entry.key.value : "key", entry.key.range, "unknown-field");
1049
+ isValid = false;
1050
+ } else fields.set(entry.key.value, entry.value);
1051
+ const scalar = (field) => {
1052
+ const value = fields.get(field);
1053
+ if (value?.kind !== "scalar" || typeof value.value !== "string" || !hasNonWhitespace(value.value)) {
1054
+ report(index, field, value?.range ?? item.range, value === void 0 ? "required" : "non-empty-string-required");
1055
+ isValid = false;
1056
+ return null;
1057
+ }
1058
+ return value.value;
1059
+ };
1060
+ const code = scalar("code");
1061
+ const subjectText = scalar("subject");
1062
+ const reason = scalar("reason");
1063
+ const subject = subjectText === null ? null : parseManifestPath(subjectText);
1064
+ const qualifierNode = fields.get("qualifier");
1065
+ let qualifier = null;
1066
+ if (qualifierNode !== void 0 && !(qualifierNode.kind === "scalar" && qualifierNode.value === null)) {
1067
+ qualifier = scalar("qualifier");
1068
+ if (qualifier !== null && !isNonEmptySingleLine(qualifier)) {
1069
+ report(index, "qualifier", qualifierNode.range, "single-line-required");
1070
+ isValid = false;
1071
+ }
1072
+ }
1073
+ const acceptedCode = ACCEPTABLE_WARNING_CODES.find((candidate) => candidate === code);
1074
+ if (code !== null && acceptedCode === void 0) {
1075
+ report(index, "code", fields.get("code").range, "code-not-acceptable");
1076
+ isValid = false;
1077
+ }
1078
+ if (subjectText !== null && subject === null) {
1079
+ report(index, "subject", fields.get("subject").range, "repository-path-required");
1080
+ isValid = false;
1081
+ }
1082
+ if (reason !== null && countUnicodeScalars(reason) > 256) {
1083
+ report(index, "reason", fields.get("reason").range, "maximum-256-characters");
1084
+ isValid = false;
1085
+ }
1086
+ if (!isValid || acceptedCode === void 0 || subject === null || reason === null) continue;
1087
+ const identity = JSON.stringify([
1088
+ acceptedCode,
1089
+ subject,
1090
+ qualifier
1091
+ ]);
1092
+ if (identities.has(identity)) {
1093
+ report(index, "code", fields.get("code").range, "duplicate-identity");
1094
+ continue;
1095
+ }
1096
+ identities.add(identity);
1097
+ accepted.push({
1098
+ code: acceptedCode,
1099
+ subject,
1100
+ ...qualifierNode === void 0 ? {} : { qualifier },
1101
+ reason
1102
+ });
1103
+ }
1104
+ return accepted;
1105
+ };
1106
+ var validateManifest = (node, path, diagnostics, limits, operation) => {
1107
+ const context = {
1108
+ diagnostics,
1109
+ operation,
1110
+ limits,
1111
+ mirrorPaths: new Set(),
1112
+ path
1113
+ };
1114
+ if (node.kind !== "mapping") {
1115
+ diagnostics.add({
1116
+ code: "MOLDEA_MANIFEST_ROOT_INVALID",
1117
+ path,
1118
+ range: node.range
1119
+ });
1120
+ return null;
1121
+ }
1122
+ const versionNode = findMappingProperty(node, "version");
1123
+ if (versionNode === null) {
1124
+ diagnostics.add({
1125
+ code: "MOLDEA_MANIFEST_VERSION_MISSING",
1126
+ path,
1127
+ pointer: "/version"
1128
+ });
1129
+ return null;
1130
+ }
1131
+ if (!(versionNode.kind === "scalar" && typeof versionNode.value === "bigint") || versionNode.kind !== "scalar" || versionNode.value <= 0n) {
1132
+ diagnostics.add({
1133
+ code: "MOLDEA_MANIFEST_VERSION_INVALID",
1134
+ path,
1135
+ pointer: "/version",
1136
+ range: versionNode.range
1137
+ });
1138
+ return null;
1139
+ }
1140
+ if (versionNode.value !== 1n) {
1141
+ diagnostics.add({
1142
+ code: "MOLDEA_MANIFEST_VERSION_UNSUPPORTED",
1143
+ path,
1144
+ pointer: "/version",
1145
+ range: versionNode.range
1146
+ });
1147
+ return null;
1148
+ }
1149
+ const entries = readMapping$1(node, "", new Set([
1150
+ "acceptedWarnings",
1151
+ "agents",
1152
+ "context",
1153
+ "decisions",
1154
+ "version"
1155
+ ]), context);
1156
+ if (entries === null) return null;
1157
+ const acceptedWarningsEntry = entries.get("acceptedWarnings");
1158
+ const acceptedWarnings = acceptedWarningsEntry === void 0 ? null : readAcceptedWarnings(acceptedWarningsEntry.value, context);
1159
+ const contextEntry = entries.get("context");
1160
+ const contextRelationships = contextEntry === void 0 ? null : readRelationshipRecord(contextEntry.value, "/context", "context", context);
1161
+ const decisionsEntry = entries.get("decisions");
1162
+ const decisionRelationships = decisionsEntry === void 0 ? null : readRelationshipRecord(decisionsEntry.value, "/decisions", "decision", context);
1163
+ const agentsEntry = entries.get("agents");
1164
+ const agents = agentsEntry === void 0 ? null : readAgents(agentsEntry.value, "/agents", context);
1165
+ return {
1166
+ version: 1,
1167
+ ...acceptedWarnings === null ? {} : { acceptedWarnings },
1168
+ ...contextRelationships === null ? {} : { context: contextRelationships },
1169
+ ...decisionRelationships === null ? {} : { decisions: decisionRelationships },
1170
+ ...agents === null ? {} : { agents }
1171
+ };
1172
+ };
1173
+ var findLineIndex = (lineStarts, offset) => {
1174
+ let lower = 0;
1175
+ let upper = lineStarts.length - 1;
1176
+ while (lower < upper) {
1177
+ const middle = Math.ceil((lower + upper) / 2);
1178
+ if ((lineStarts[middle] ?? 0) <= offset) lower = middle;
1179
+ else upper = middle - 1;
1180
+ }
1181
+ return lower;
1182
+ };
1183
+ var createSourceLocator = (value) => {
1184
+ const scalarOffsets = new Uint32Array(value.length + 1);
1185
+ const lineStarts = [0];
1186
+ let scalarOffset = 0;
1187
+ for (let codeUnitOffset = 0; codeUnitOffset < value.length;) {
1188
+ const codePoint = value.codePointAt(codeUnitOffset);
1189
+ const width = codePoint !== void 0 && codePoint > 65535 ? 2 : 1;
1190
+ scalarOffsets[codeUnitOffset] = scalarOffset;
1191
+ for (let interiorOffset = 1; interiorOffset < width; interiorOffset += 1) scalarOffsets[codeUnitOffset + interiorOffset] = scalarOffset;
1192
+ codeUnitOffset += width;
1193
+ scalarOffset += 1;
1194
+ scalarOffsets[codeUnitOffset] = scalarOffset;
1195
+ if (codePoint === 10) lineStarts.push(codeUnitOffset);
1196
+ }
1197
+ const locatePosition = (candidateOffset) => {
1198
+ const codeUnitOffset = Math.max(0, Math.min(value.length, candidateOffset));
1199
+ const lineIndex = findLineIndex(lineStarts, codeUnitOffset);
1200
+ const lineStart = lineStarts[lineIndex] ?? 0;
1201
+ const positionScalarOffset = scalarOffsets[codeUnitOffset] ?? 0;
1202
+ return {
1203
+ column: positionScalarOffset - (scalarOffsets[lineStart] ?? 0) + 1,
1204
+ line: lineIndex + 1,
1205
+ offset: positionScalarOffset
1206
+ };
1207
+ };
1208
+ return Object.freeze({ locateRange: (startOffset, endOffset) => ({
1209
+ end: locatePosition(endOffset),
1210
+ start: locatePosition(startOffset)
1211
+ }) });
1212
+ };
1213
+ var inspectManifestDocument = async (input, options, operation = "parse-manifest") => {
1214
+ options = createCoreOperationOptionsSnapshot(options);
1215
+ const normalized = normalizeTextDocument(input, options.limits, operation, "maxManifestBytes");
1216
+ const path = parseRepositoryPath(input.path);
1217
+ const diagnostics = createCoreDiagnosticCollector(options.limits, operation);
1218
+ if (!isCanonicalManifestPath(path)) diagnostics.add({
1219
+ code: "MOLDEA_MANIFEST_PATH_INVALID",
1220
+ path
1221
+ });
1222
+ for (const diagnostic of normalized.diagnostics) diagnostics.merge(diagnostic);
1223
+ if (!normalized.valid || normalized.text === null) return deepFreeze({
1224
+ asset: null,
1225
+ diagnostics: diagnostics.finalize(),
1226
+ formatVersion: null,
1227
+ manifest: null,
1228
+ valid: false,
1229
+ yamlRoot: null
1230
+ });
1231
+ const locator = createSourceLocator(normalized.text.value);
1232
+ const parsed = parseStrictYaml(normalized.text.value, path, locator, diagnostics);
1233
+ const formatVersion = parsed.value === null ? null : detectSupportedManifestVersion(parsed.value);
1234
+ const manifest = parsed.valid && parsed.value !== null ? validateManifest(parsed.value, path, diagnostics, options.limits, operation) : null;
1235
+ const locatedDiagnostics = locateDiagnosticRanges(diagnostics.finalize(), new Map(parsed.value === null ? [] : [[path, parsed.value]]));
1236
+ if (manifest === null || diagnostics.size > 0) return deepFreeze({
1237
+ asset: null,
1238
+ diagnostics: locatedDiagnostics,
1239
+ formatVersion,
1240
+ manifest: null,
1241
+ valid: false,
1242
+ yamlRoot: parsed.value
1243
+ });
1244
+ const digest = await calculateNormalizedTextDigest(normalized.text);
1245
+ const asset = {
1246
+ content: normalized.text.value,
1247
+ digest,
1248
+ path,
1249
+ scalarLength: normalized.text.scalarLength,
1250
+ utf8ByteLength: normalized.text.utf8ByteLength
1251
+ };
1252
+ return deepFreeze({
1253
+ asset,
1254
+ diagnostics: locatedDiagnostics,
1255
+ formatVersion,
1256
+ manifest,
1257
+ valid: true,
1258
+ yamlRoot: parsed.value
1259
+ });
1260
+ };
1261
+ var parseManifestDocument = async (input, options, operation = "parse-manifest") => {
1262
+ const inspection = await inspectManifestDocument(input, options, operation);
1263
+ return deepFreeze({
1264
+ asset: inspection.asset,
1265
+ diagnostics: inspection.diagnostics,
1266
+ manifest: inspection.manifest,
1267
+ valid: inspection.valid
1268
+ });
1269
+ };
1270
+ var invalidArgument$3 = () => {
1271
+ throw new CoreOperationException({
1272
+ code: "INVALID_ARGUMENT",
1273
+ operation: "match-manifest-scope"
1274
+ });
1275
+ };
1276
+ var resourceLimitExceeded$1 = (limit, limitMaximum, observedUsage) => {
1277
+ throw new CoreOperationException({
1278
+ code: "RESOURCE_LIMIT_EXCEEDED",
1279
+ limit,
1280
+ limitMaximum,
1281
+ nextAction: "reduce-input-or-increase-limit",
1282
+ observedUsage,
1283
+ operation: "match-manifest-scope"
1284
+ });
1285
+ };
1286
+ var normalizeManifestScopeInput = (input, limits) => {
1287
+ if (!isObjectValid(input, true)) return invalidArgument$3();
1288
+ const manifest = input["manifest"];
1289
+ const pathCandidates = input["paths"];
1290
+ if (!isObjectValid(manifest, true) || !Array.isArray(pathCandidates)) return invalidArgument$3();
1291
+ if (pathCandidates.length > limits.maxEntries) return resourceLimitExceeded$1("maxEntries", limits.maxEntries, pathCandidates.length);
1292
+ const uniquePaths = new Set();
1293
+ let totalBytes = 0;
1294
+ for (const [index, candidate] of pathCandidates.entries()) {
1295
+ if (typeof candidate !== "string") return invalidArgument$3();
1296
+ const path = parseRepositoryPath(candidate);
1297
+ totalBytes += countUtf8Bytes(path) + (index === 0 ? 0 : 1);
1298
+ if (totalBytes > limits.maxTotalBytesRead) return resourceLimitExceeded$1("maxTotalBytesRead", limits.maxTotalBytesRead, totalBytes);
1299
+ uniquePaths.add(path);
1300
+ }
1301
+ return {
1302
+ manifest,
1303
+ paths: [...uniquePaths].sort(compareCodePoints)
1304
+ };
1305
+ };
1306
+ var matchManifestScope = async (input, options) => {
1307
+ const normalized = normalizeManifestScopeInput(input, options.limits);
1308
+ const inputDigest = await calculateManifestScopeInputDigest(normalized.paths);
1309
+ const parsed = await parseManifestDocument(normalized.manifest, options, "match-manifest-scope");
1310
+ if (!parsed.valid || parsed.asset === null || parsed.manifest === null) return deepFreeze({
1311
+ counts: {
1312
+ declarations: 0,
1313
+ inputPaths: normalized.paths.length,
1314
+ matchedOwners: 0,
1315
+ matchedPaths: 0,
1316
+ matches: 0
1317
+ },
1318
+ diagnostics: parsed.diagnostics,
1319
+ inputDigest,
1320
+ manifestDigest: null,
1321
+ matches: [],
1322
+ relevant: false,
1323
+ valid: false
1324
+ });
1325
+ const matched = matchParsedManifestScope(parsed.manifest, normalized.paths, options.limits);
1326
+ return deepFreeze({
1327
+ counts: matched.counts,
1328
+ diagnostics: [],
1329
+ inputDigest,
1330
+ manifestDigest: parsed.asset.digest,
1331
+ matches: matched.matches,
1332
+ relevant: matched.matches.length > 0,
1333
+ valid: true
1334
+ });
1335
+ };
1336
+ //#endregion
1337
+ //#region ../core/dist/chunks/core-Ce0OlySB.js
1338
+ var __defProp = Object.defineProperty;
1339
+ var __exportAll = (all, no_symbols) => {
1340
+ let target = {};
1341
+ for (var name in all) __defProp(target, name, {
1342
+ get: all[name],
1343
+ enumerable: true
1344
+ });
1345
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
1346
+ return target;
1347
+ };
1348
+ var decoder = new TextDecoder("utf-8", {
1349
+ fatal: true,
1350
+ ignoreBOM: true
1351
+ });
1352
+ var invalidArgument$2 = () => {
1353
+ throw new CoreOperationException({
1354
+ code: "INVALID_ARGUMENT",
1355
+ operation: "read-canonical-content-page"
1356
+ });
1357
+ };
1358
+ var invalidContent = () => {
1359
+ throw new CoreOperationException({
1360
+ code: "CONTENT_INVALID",
1361
+ operation: "read-canonical-content-page"
1362
+ });
1363
+ };
1364
+ var isRepositoryReader$1 = (candidate) => typeof candidate === "object" && candidate !== null && typeof candidate.getEntry === "function" && typeof candidate.readFilePage === "function";
1365
+ var readBytes = async (repository, path, offset, maxBytes, signal) => {
1366
+ const chunks = [];
1367
+ let byteLength = 0;
1368
+ let nextOffset = offset;
1369
+ let lastPage = null;
1370
+ let totalBytes = null;
1371
+ while (byteLength < maxBytes) {
1372
+ const page = await repository.readFilePage(path, {
1373
+ maxBytes: maxBytes - byteLength,
1374
+ offset: nextOffset,
1375
+ ...signal === void 0 ? {} : { signal }
1376
+ });
1377
+ if (page.snapshot.id !== repository.snapshot.id || page.offset !== nextOffset || page.bytes.byteLength > maxBytes - byteLength || page.totalBytes < page.offset + page.bytes.byteLength || totalBytes !== null && page.totalBytes !== totalBytes || page.bytes.byteLength === 0 && !page.isComplete) throw new RepositorySourceException({
1378
+ code: "INVALID_SOURCE_DATA",
1379
+ operation: "read-file-page",
1380
+ path,
1381
+ retryable: false
1382
+ });
1383
+ chunks.push(page.bytes);
1384
+ byteLength += page.bytes.byteLength;
1385
+ totalBytes = page.totalBytes;
1386
+ lastPage = page;
1387
+ if (page.isComplete || byteLength === maxBytes) break;
1388
+ if (page.nextOffset !== page.offset + page.bytes.byteLength) throw new RepositorySourceException({
1389
+ code: "INVALID_SOURCE_DATA",
1390
+ operation: "read-file-page",
1391
+ path,
1392
+ retryable: false
1393
+ });
1394
+ nextOffset = page.nextOffset;
1395
+ }
1396
+ if (lastPage === null) return invalidArgument$2();
1397
+ const bytes = new Uint8Array(byteLength);
1398
+ let writeOffset = 0;
1399
+ for (const chunk of chunks) {
1400
+ bytes.set(chunk, writeOffset);
1401
+ writeOffset += chunk.byteLength;
1402
+ }
1403
+ return {
1404
+ bytes,
1405
+ lastPage
1406
+ };
1407
+ };
1408
+ var decodeSafePrefix = (bytes, maximumBytes) => {
1409
+ const minimumCandidate = Math.max(0, maximumBytes - 3);
1410
+ for (let end = maximumBytes; end >= minimumCandidate; end -= 1) try {
1411
+ const content = decoder.decode(bytes.subarray(0, end));
1412
+ if (end === 0 && bytes.byteLength > 0) continue;
1413
+ return [content, end];
1414
+ } catch {}
1415
+ return invalidContent();
1416
+ };
1417
+ var readCanonicalContentPage = async (input, options) => {
1418
+ if (typeof input !== "object" || input === null || Reflect.ownKeys(input).some((key) => key !== "maxBytes" && key !== "offset" && key !== "path" && key !== "repository" && key !== "signal") || !isRepositoryReader$1(input.repository) || !Number.isSafeInteger(input.maxBytes) || input.maxBytes < 1 || input.maxBytes > options.limits.maxFileBytes || !Number.isSafeInteger(input.offset) || input.offset < 0) return invalidArgument$2();
1419
+ const path = parseRepositoryPath(input.path);
1420
+ if (!path.startsWith("/moldea/")) return invalidArgument$2();
1421
+ const operationOptions = input.signal === void 0 ? void 0 : { signal: input.signal };
1422
+ const entry = await input.repository.getEntry(path, operationOptions);
1423
+ if (entry === null) throw new RepositorySourceException({
1424
+ code: "ENTRY_NOT_FOUND",
1425
+ operation: "read-file-page",
1426
+ path,
1427
+ retryable: false
1428
+ });
1429
+ if (entry.type !== "file" || entry.byteLength === null) throw new RepositorySourceException({
1430
+ code: "ENTRY_NOT_FILE",
1431
+ operation: "read-file-page",
1432
+ path,
1433
+ retryable: false
1434
+ });
1435
+ if (entry.byteLength > options.limits.maxFileBytes) throw new CoreOperationException({
1436
+ code: "RESOURCE_LIMIT_EXCEEDED",
1437
+ limit: "maxFileBytes",
1438
+ limitMaximum: options.limits.maxFileBytes,
1439
+ nextAction: "reduce-input-or-increase-limit",
1440
+ observedUsage: entry.byteLength,
1441
+ operation: "read-canonical-content-page"
1442
+ });
1443
+ if (input.offset > entry.byteLength) return invalidArgument$2();
1444
+ if (input.offset === entry.byteLength) return deepFreeze({
1445
+ byteEnd: input.offset,
1446
+ byteStart: input.offset,
1447
+ content: "",
1448
+ contentIdentity: entry.contentIdentity,
1449
+ isComplete: true,
1450
+ nextOffset: null,
1451
+ path,
1452
+ source: input.repository.snapshot,
1453
+ totalBytes: entry.byteLength
1454
+ });
1455
+ const lookaheadBytes = Math.min(entry.byteLength - input.offset, input.maxBytes + 3);
1456
+ const { bytes, lastPage } = await readBytes(input.repository, path, input.offset, lookaheadBytes, input.signal);
1457
+ if (lastPage.totalBytes !== entry.byteLength || (bytes[0] & 192) === 128) return invalidArgument$2();
1458
+ const [content, consumedBytes] = decodeSafePrefix(bytes, Math.min(input.maxBytes, bytes.byteLength));
1459
+ const byteEnd = input.offset + consumedBytes;
1460
+ const isComplete = byteEnd === entry.byteLength;
1461
+ return deepFreeze({
1462
+ byteEnd,
1463
+ byteStart: input.offset,
1464
+ content,
1465
+ contentIdentity: entry.contentIdentity,
1466
+ isComplete,
1467
+ nextOffset: isComplete ? null : byteEnd,
1468
+ path,
1469
+ source: input.repository.snapshot,
1470
+ totalBytes: entry.byteLength
1471
+ });
1472
+ };
1473
+ var DECISION_STATUSES = new Set([
1474
+ "accepted",
1475
+ "proposed",
1476
+ "rejected",
1477
+ "superseded"
1478
+ ]);
1479
+ var DECISION_ID_PATTERN = /^\d{13}$/u;
1480
+ var CREATED_AT_PATTERN = /^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d\.\d{3}Z$/u;
1481
+ var getEntity = (decisionId) => {
1482
+ return decisionId === null ? null : { decisionId };
1483
+ };
1484
+ var addInvalidFrontmatter = (context, range, reason, pointer = null) => {
1485
+ context.diagnostics.add({
1486
+ code: "MOLDEA_DECISION_FRONTMATTER_INVALID",
1487
+ details: { reason },
1488
+ entity: getEntity(context.decisionId),
1489
+ path: context.path,
1490
+ pointer,
1491
+ range
1492
+ });
1493
+ };
1494
+ var isCanonicalCreatedAt = (value) => {
1495
+ if (!CREATED_AT_PATTERN.test(value)) return false;
1496
+ const timestamp = Date.parse(value);
1497
+ return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;
1498
+ };
1499
+ var readMapping = (node, context) => {
1500
+ if (node.kind !== "mapping") {
1501
+ addInvalidFrontmatter(context, node.range, "mapping-required");
1502
+ return null;
1503
+ }
1504
+ const entries = new Map();
1505
+ for (const entry of node.entries) {
1506
+ if (entry.key.kind !== "scalar" || typeof entry.key.value !== "string") {
1507
+ addInvalidFrontmatter(context, entry.key.range, "string-key-required");
1508
+ continue;
1509
+ }
1510
+ const key = entry.key.value;
1511
+ if (key !== "status" && key !== "createdAt" && key !== "supersedes") {
1512
+ context.diagnostics.add({
1513
+ code: "MOLDEA_DECISION_PROPERTY_UNKNOWN",
1514
+ entity: getEntity(context.decisionId),
1515
+ path: context.path,
1516
+ pointer: `/${escapeJsonPointerSegment(key)}`,
1517
+ range: entry.key.range
1518
+ });
1519
+ continue;
1520
+ }
1521
+ entries.set(key, entry.value);
1522
+ }
1523
+ return entries;
1524
+ };
1525
+ var readStatus = (node, context) => {
1526
+ if (node?.kind !== "scalar" || typeof node.value !== "string" || !DECISION_STATUSES.has(node.value)) {
1527
+ context.diagnostics.add({
1528
+ code: "MOLDEA_DECISION_STATUS_INVALID",
1529
+ entity: getEntity(context.decisionId),
1530
+ path: context.path,
1531
+ pointer: "/status",
1532
+ range: node?.range ?? null
1533
+ });
1534
+ return null;
1535
+ }
1536
+ return node.value;
1537
+ };
1538
+ var readCreatedAt = (node, context) => {
1539
+ if (node?.kind !== "scalar" || typeof node.value !== "string" || !isCanonicalCreatedAt(node.value)) {
1540
+ context.diagnostics.add({
1541
+ code: "MOLDEA_DECISION_CREATED_AT_INVALID",
1542
+ entity: getEntity(context.decisionId),
1543
+ path: context.path,
1544
+ pointer: "/createdAt",
1545
+ range: node?.range ?? null
1546
+ });
1547
+ return null;
1548
+ }
1549
+ if (context.decisionId !== null && Date.parse(node.value) !== Number(context.decisionId)) context.diagnostics.add({
1550
+ code: "MOLDEA_DECISION_TIMESTAMP_MISMATCH",
1551
+ entity: getEntity(context.decisionId),
1552
+ path: context.path,
1553
+ pointer: "/createdAt",
1554
+ range: node.range
1555
+ });
1556
+ return node.value;
1557
+ };
1558
+ var readSupersedes = (node, context) => {
1559
+ if (node === void 0) return [];
1560
+ if (node.kind !== "sequence" || node.items.length === 0) {
1561
+ addInvalidFrontmatter(context, node.range, "non-empty-supersedes-sequence-required", "/supersedes");
1562
+ return null;
1563
+ }
1564
+ const supersedes = [];
1565
+ const seen = new Set();
1566
+ node.items.forEach((item, index) => {
1567
+ const pointer = `/supersedes/${index}`;
1568
+ if (item.kind !== "scalar" || typeof item.value !== "string" || !DECISION_ID_PATTERN.test(item.value)) {
1569
+ addInvalidFrontmatter(context, item.range, "decision-id-string-required", pointer);
1570
+ return;
1571
+ }
1572
+ if (seen.has(item.value)) {
1573
+ context.diagnostics.add({
1574
+ code: "MOLDEA_ID_DUPLICATE",
1575
+ entity: getEntity(context.decisionId),
1576
+ path: context.path,
1577
+ pointer,
1578
+ range: item.range
1579
+ });
1580
+ return;
1581
+ }
1582
+ seen.add(item.value);
1583
+ supersedes.push(item.value);
1584
+ if (item.value === context.decisionId) context.diagnostics.add({
1585
+ code: "MOLDEA_DECISION_SELF_SUPERSESSION",
1586
+ entity: getEntity(context.decisionId),
1587
+ path: context.path,
1588
+ pointer,
1589
+ range: item.range
1590
+ });
1591
+ });
1592
+ return supersedes.sort(compareCodePoints);
1593
+ };
1594
+ var extractDecisionSections = (value, locator, context) => {
1595
+ const firstLineEnd = value.indexOf("\n");
1596
+ const openingLineEnd = firstLineEnd === -1 ? value.length : firstLineEnd;
1597
+ if (value.slice(0, openingLineEnd) !== "---") {
1598
+ context.diagnostics.add({
1599
+ code: "MOLDEA_DECISION_FRONTMATTER_MISSING",
1600
+ entity: getEntity(context.decisionId),
1601
+ path: context.path,
1602
+ range: locator.locateRange(0, openingLineEnd)
1603
+ });
1604
+ return null;
1605
+ }
1606
+ let lineStart = firstLineEnd === -1 ? value.length : firstLineEnd + 1;
1607
+ while (lineStart <= value.length) {
1608
+ const nextLineBreak = value.indexOf("\n", lineStart);
1609
+ const lineEnd = nextLineBreak === -1 ? value.length : nextLineBreak;
1610
+ if (value.slice(lineStart, lineEnd) === "---") {
1611
+ const bodyStart = nextLineBreak === -1 ? lineEnd : nextLineBreak + 1;
1612
+ return {
1613
+ body: value.slice(bodyStart),
1614
+ bodyRange: locator.locateRange(bodyStart, value.length),
1615
+ yaml: value.slice(0, lineStart)
1616
+ };
1617
+ }
1618
+ if (nextLineBreak === -1) break;
1619
+ lineStart = nextLineBreak + 1;
1620
+ }
1621
+ context.diagnostics.add({
1622
+ code: "MOLDEA_DECISION_FRONTMATTER_MISSING",
1623
+ entity: getEntity(context.decisionId),
1624
+ path: context.path,
1625
+ range: locator.locateRange(value.length, value.length)
1626
+ });
1627
+ return null;
1628
+ };
1629
+ var validateDecisionFrontmatter = (node, context) => {
1630
+ const initialDiagnosticCount = context.diagnostics.size;
1631
+ const entries = readMapping(node, context);
1632
+ if (entries === null) return null;
1633
+ const status = readStatus(entries.get("status"), context);
1634
+ const createdAt = readCreatedAt(entries.get("createdAt"), context);
1635
+ const supersedes = readSupersedes(entries.get("supersedes"), context);
1636
+ if (status === null || createdAt === null || supersedes === null || context.diagnostics.size > initialDiagnosticCount) return null;
1637
+ return {
1638
+ createdAt,
1639
+ status,
1640
+ supersedes
1641
+ };
1642
+ };
1643
+ var validateDecisionBody = (body, range, context) => {
1644
+ if (hasNonWhitespace(body)) return true;
1645
+ context.diagnostics.add({
1646
+ code: "MOLDEA_DECISION_BODY_EMPTY",
1647
+ entity: getEntity(context.decisionId),
1648
+ path: context.path,
1649
+ range
1650
+ });
1651
+ return false;
1652
+ };
1653
+ var inspectDecisionDocument = async (input, options, operation = "parse-decision") => {
1654
+ options = createCoreOperationOptionsSnapshot(options);
1655
+ const normalized = normalizeTextDocument(input, options.limits, operation);
1656
+ const path = parseRepositoryPath(input.path);
1657
+ const diagnostics = createCoreDiagnosticCollector(options.limits, operation);
1658
+ const decisionId = parseDecisionIdFromPath(path);
1659
+ if (decisionId === null) diagnostics.add({
1660
+ code: "MOLDEA_DECISION_FILENAME_INVALID",
1661
+ path
1662
+ });
1663
+ for (const diagnostic of normalized.diagnostics) diagnostics.merge(diagnostic);
1664
+ if (!normalized.valid || normalized.text === null) return deepFreeze({
1665
+ decision: null,
1666
+ diagnostics: diagnostics.finalize(),
1667
+ valid: false,
1668
+ yamlRoot: null
1669
+ });
1670
+ const context = {
1671
+ decisionId,
1672
+ diagnostics,
1673
+ path
1674
+ };
1675
+ const locator = createSourceLocator(normalized.text.value);
1676
+ const sections = extractDecisionSections(normalized.text.value, locator, context);
1677
+ let metadata = null;
1678
+ let yamlRoot = null;
1679
+ if (sections !== null) {
1680
+ validateDecisionBody(sections.body, sections.bodyRange, context);
1681
+ const parsed = parseStrictYaml(sections.yaml, path, locator, diagnostics);
1682
+ yamlRoot = parsed.value;
1683
+ if (parsed.valid && parsed.value !== null) metadata = validateDecisionFrontmatter(parsed.value, context);
1684
+ }
1685
+ const locatedDiagnostics = locateDiagnosticRanges(diagnostics.finalize(), new Map(yamlRoot === null ? [] : [[path, yamlRoot]]));
1686
+ if (decisionId === null || sections === null || metadata === null || diagnostics.size > 0) return deepFreeze({
1687
+ decision: null,
1688
+ diagnostics: locatedDiagnostics,
1689
+ valid: false,
1690
+ yamlRoot
1691
+ });
1692
+ const digest = await calculateNormalizedTextDigest(normalized.text);
1693
+ const asset = {
1694
+ content: normalized.text.value,
1695
+ digest,
1696
+ path,
1697
+ scalarLength: normalized.text.scalarLength,
1698
+ utf8ByteLength: normalized.text.utf8ByteLength
1699
+ };
1700
+ return deepFreeze({
1701
+ decision: {
1702
+ asset,
1703
+ body: sections.body,
1704
+ createdAt: metadata.createdAt,
1705
+ id: decisionId,
1706
+ path,
1707
+ status: metadata.status,
1708
+ supersedes: metadata.supersedes
1709
+ },
1710
+ diagnostics: locatedDiagnostics,
1711
+ valid: true,
1712
+ yamlRoot
1713
+ });
1714
+ };
1715
+ var parseDecisionDocument = async (input, options, operation = "parse-decision") => {
1716
+ const inspection = await inspectDecisionDocument(input, options, operation);
1717
+ return deepFreeze({
1718
+ decision: inspection.decision,
1719
+ diagnostics: inspection.diagnostics,
1720
+ valid: inspection.valid
1721
+ });
1722
+ };
1723
+ var iterateProjectAgentAssignments = function* (project) {
1724
+ for (const agent of project.agents) yield { agentId: agent.id };
1725
+ };
1726
+ var createAssetItem = (asset, kind, agentId = null, decisionId = null) => ({
1727
+ agentId,
1728
+ byteLength: asset.utf8ByteLength,
1729
+ canonicalDigest: null,
1730
+ decisionId,
1731
+ digest: asset.digest,
1732
+ kind,
1733
+ path: asset.path,
1734
+ scalarLength: asset.scalarLength
1735
+ });
1736
+ var iterateProjectMetadata = function* (project) {
1737
+ yield createAssetItem(project.manifest.asset, "manifest");
1738
+ yield createAssetItem(project.project, "project");
1739
+ for (const context of project.context) yield createAssetItem(context.asset, "context");
1740
+ for (const { decision } of project.decisions) yield createAssetItem(decision.asset, "decision", null, decision.id);
1741
+ for (const agent of project.agents) {
1742
+ yield createAssetItem(agent.description.asset, "agent-description", agent.id);
1743
+ yield createAssetItem(agent.instruction, "agent-instruction", agent.id);
1744
+ for (const mirror of agent.mirrors) yield {
1745
+ agentId: agent.id,
1746
+ byteLength: mirror.byteLength,
1747
+ canonicalDigest: mirror.canonicalDigest,
1748
+ decisionId: null,
1749
+ digest: mirror.digest,
1750
+ kind: "mirror",
1751
+ path: mirror.path,
1752
+ scalarLength: mirror.scalarLength
1753
+ };
1754
+ }
1755
+ };
1756
+ var createProjectSummary = (project) => ({
1757
+ counts: {
1758
+ agents: project.agents.length,
1759
+ context: project.context.length,
1760
+ decisions: project.decisions.length,
1761
+ mirrors: project.agents.reduce((count, agent) => count + agent.mirrors.length, 0)
1762
+ },
1763
+ manifestDigest: project.manifest.asset.digest,
1764
+ manifestPath: project.manifest.asset.path,
1765
+ projectDigest: project.project.digest,
1766
+ projectPath: project.project.path
1767
+ });
1768
+ var countBindingCoverage = (coverage) => ({
1769
+ bindings: coverage.length,
1770
+ exportsPassed: coverage.filter((record) => record.exportCheck === "passed").length,
1771
+ exportsFailed: coverage.filter((record) => record.exportCheck === "failed").length,
1772
+ exportsNotChecked: coverage.filter((record) => record.exportCheck === "not-checked").length
1773
+ });
1774
+ var ledgers = new WeakMap();
1775
+ var registerRetainedMemory = (reader, ledger) => {
1776
+ if (ledgers.has(reader)) throw new TypeError("The inspection reader is already registered.");
1777
+ ledgers.set(reader, ledger);
1778
+ };
1779
+ var getRetainedMemory = (reader) => {
1780
+ const ledger = ledgers.get(reader);
1781
+ if (ledger === void 0) throw new TypeError("The inspection reader has no retained-memory ledger.");
1782
+ return ledger;
1783
+ };
1784
+ var reserveRetainedBytesIfTracked = (reader, bytes) => {
1785
+ ledgers.get(reader)?.reserve(bytes);
1786
+ };
1787
+ var MANIFEST_PATH$2 = parseRepositoryPath("/moldea/moldea.yaml");
1788
+ var INSTRUCTION_PATHS = new Set([
1789
+ "/AGENTS.md",
1790
+ "/CLAUDE.md",
1791
+ "/.claude/CLAUDE.md",
1792
+ "/CLAUDE.local.md"
1793
+ ].map((path) => parseRepositoryPath(path)));
1794
+ var SOURCE_PAGE_ENTRIES = 256;
1795
+ var SOURCE_PAGE_BYTES = 65536;
1796
+ var CANONICAL_BYTE_RETENTION_MULTIPLIER = 4;
1797
+ var RETAINED_PATH_FIXED_BYTES = 64;
1798
+ var RETAINED_PATH_BYTE_MULTIPLIER = 2;
1799
+ var encoder$1 = new TextEncoder();
1800
+ var invalidSourceData$3 = (operation, path) => {
1801
+ throw new RepositorySourceException({
1802
+ code: "INVALID_SOURCE_DATA",
1803
+ operation,
1804
+ path,
1805
+ retryable: false
1806
+ });
1807
+ };
1808
+ var copyReaderEntry$1 = (candidate, operation, fallbackPath, expectedPath) => {
1809
+ if (typeof candidate !== "object" || candidate === null) return invalidSourceData$3(operation, fallbackPath);
1810
+ const record = candidate;
1811
+ const pathCandidate = record["path"];
1812
+ const typeCandidate = record["type"];
1813
+ const byteLength = record["byteLength"];
1814
+ const contentIdentity = record["contentIdentity"];
1815
+ if (typeof pathCandidate !== "string" || !isRepositoryPath(pathCandidate)) return invalidSourceData$3(operation, fallbackPath);
1816
+ const path = parseRepositoryPath(pathCandidate);
1817
+ if (expectedPath !== void 0 && path !== expectedPath) return invalidSourceData$3(operation, path);
1818
+ if (typeCandidate !== "file" && typeCandidate !== "directory" && typeCandidate !== "symlink") return invalidSourceData$3(operation, path);
1819
+ if (typeCandidate === "file" ? !Number.isSafeInteger(byteLength) || byteLength < 0 || contentIdentity !== null && typeof contentIdentity !== "string" : byteLength !== null || contentIdentity !== null) return invalidSourceData$3(operation, path);
1820
+ return {
1821
+ byteLength,
1822
+ contentIdentity,
1823
+ path,
1824
+ type: typeCandidate
1825
+ };
1826
+ };
1827
+ var isStrictDescendant = (path, prefix) => {
1828
+ if (path === prefix) return false;
1829
+ const descendantPrefix = prefix === REPOSITORY_ROOT ? REPOSITORY_ROOT : `${prefix}/`;
1830
+ return path.startsWith(descendantPrefix);
1831
+ };
1832
+ var throwResourceLimitExceeded = (limit, limitMaximum, observedUsage) => {
1833
+ throw new CoreOperationException({
1834
+ code: "RESOURCE_LIMIT_EXCEEDED",
1835
+ limit,
1836
+ limitMaximum,
1837
+ nextAction: "reduce-input-or-increase-limit",
1838
+ observedUsage,
1839
+ operation: "validate-project"
1840
+ });
1841
+ };
1842
+ var createSourceOptions = (sessionSignal, operationSignal) => {
1843
+ const signal = sessionSignal === void 0 ? operationSignal : operationSignal === void 0 || operationSignal === sessionSignal ? sessionSignal : AbortSignal.any([sessionSignal, operationSignal]);
1844
+ return signal === void 0 ? void 0 : { signal };
1845
+ };
1846
+ var createRepositoryInspectionSession = (repository, limits, signal, instructions) => {
1847
+ const seenPaths = new Set();
1848
+ let canonicalBytes = 0;
1849
+ let peakRetainedBytes = 0;
1850
+ let retainedBytes = 0;
1851
+ let totalBytesRead = 0;
1852
+ const createAbortedException = (abortedSignal) => {
1853
+ return new CoreOperationException({
1854
+ cause: abortedSignal.reason,
1855
+ code: "ABORTED",
1856
+ operation: "validate-project"
1857
+ });
1858
+ };
1859
+ const reserveRetainedBytes = (byteLength) => {
1860
+ if (!Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > limits.maxRetainedBytes - retainedBytes) return throwResourceLimitExceeded("maxRetainedBytes", limits.maxRetainedBytes, retainedBytes + byteLength);
1861
+ retainedBytes += byteLength;
1862
+ peakRetainedBytes = Math.max(peakRetainedBytes, retainedBytes);
1863
+ };
1864
+ const observeTransientBytes = (byteLength) => {
1865
+ if (!Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > limits.maxRetainedBytes - retainedBytes) return throwResourceLimitExceeded("maxRetainedBytes", limits.maxRetainedBytes, retainedBytes + byteLength);
1866
+ peakRetainedBytes = Math.max(peakRetainedBytes, retainedBytes + byteLength);
1867
+ };
1868
+ const registerPath = (path) => {
1869
+ if (path === REPOSITORY_ROOT || seenPaths.has(path)) return;
1870
+ if (seenPaths.size >= limits.maxEntries) return throwResourceLimitExceeded("maxEntries", limits.maxEntries, seenPaths.size + 1);
1871
+ reserveRetainedBytes(RETAINED_PATH_FIXED_BYTES + encoder$1.encode(path).byteLength * RETAINED_PATH_BYTE_MULTIPLIER);
1872
+ seenPaths.add(path);
1873
+ };
1874
+ const throwIfSignalAborted = (operationSignal) => {
1875
+ const abortedSignal = signal?.aborted ? signal : operationSignal?.aborted ? operationSignal : null;
1876
+ if (abortedSignal !== null) throw createAbortedException(abortedSignal);
1877
+ };
1878
+ throwIfSignalAborted();
1879
+ const reserveReadBytes = (byteLength) => {
1880
+ if (byteLength > limits.maxTotalBytesRead - totalBytesRead) return throwResourceLimitExceeded("maxTotalBytesRead", limits.maxTotalBytesRead, totalBytesRead + byteLength);
1881
+ totalBytesRead += byteLength;
1882
+ };
1883
+ const repositoryPages = {
1884
+ readPage: (path, options) => repository.readFilePage(path, options),
1885
+ snapshotId: repository.snapshot.id
1886
+ };
1887
+ const getEntryFrom = async (source, path, options) => {
1888
+ const parsedPath = parseRepositoryPath(path);
1889
+ throwIfSignalAborted(options?.signal);
1890
+ registerPath(parsedPath);
1891
+ const candidate = await source.getEntry(parsedPath, createSourceOptions(signal, options?.signal));
1892
+ throwIfSignalAborted(options?.signal);
1893
+ return candidate === null ? null : copyReaderEntry$1(candidate, "get-entry", parsedPath, parsedPath);
1894
+ };
1895
+ const getEntry = (path, options) => getEntryFrom(repository, path, options);
1896
+ const iterateEntries = (options) => {
1897
+ const prefix = options?.prefix === void 0 ? REPOSITORY_ROOT : parseRepositoryPath(options.prefix);
1898
+ return { async *[Symbol.asyncIterator]() {
1899
+ registerPath(prefix);
1900
+ const yieldedPaths = new Set();
1901
+ let cursor;
1902
+ let previousPath = null;
1903
+ do {
1904
+ throwIfSignalAborted(options?.signal);
1905
+ const page = await repository.listEntriesPage({
1906
+ ...cursor === void 0 ? {} : { cursor },
1907
+ maxEntries: Math.min(SOURCE_PAGE_ENTRIES, limits.maxEntries),
1908
+ prefix,
1909
+ ...createSourceOptions(signal, options?.signal) ?? {}
1910
+ });
1911
+ if (page.snapshot.id !== repository.snapshot.id || page.entries.length === 0 && !page.isComplete) return invalidSourceData$3("list-entries-page", prefix);
1912
+ for (const candidate of page.entries) {
1913
+ throwIfSignalAborted(options?.signal);
1914
+ const entry = copyReaderEntry$1(candidate, "list-entries-page", prefix);
1915
+ if (!isStrictDescendant(entry.path, prefix) || yieldedPaths.has(entry.path) || previousPath !== null && compareRepositoryPaths(previousPath, entry.path) >= 0) return invalidSourceData$3("list-entries-page", entry.path);
1916
+ yieldedPaths.add(entry.path);
1917
+ previousPath = entry.path;
1918
+ registerPath(entry.path);
1919
+ yield entry;
1920
+ }
1921
+ if (page.isComplete) {
1922
+ if (page.nextCursor !== null) return invalidSourceData$3("list-entries-page", prefix);
1923
+ return;
1924
+ }
1925
+ if (page.nextCursor === null || page.nextCursor === cursor) return invalidSourceData$3("list-entries-page", prefix);
1926
+ cursor = page.nextCursor;
1927
+ } while (true);
1928
+ } };
1929
+ };
1930
+ const loadFile = async (path, operationSignal, isSource = false, pages = repositoryPages) => {
1931
+ const multiplier = isSource ? 1 : CANONICAL_BYTE_RETENTION_MULTIPLIER;
1932
+ const fileLimit = path === MANIFEST_PATH$2 ? "maxManifestBytes" : "maxFileBytes";
1933
+ const availableRetainedBytes = limits.maxRetainedBytes - retainedBytes;
1934
+ if (availableRetainedBytes < 1) return throwResourceLimitExceeded("maxRetainedBytes", limits.maxRetainedBytes, retainedBytes + 1);
1935
+ const firstPageMaximumBytes = Math.min(SOURCE_PAGE_BYTES, Math.max(1, limits[fileLimit]), availableRetainedBytes);
1936
+ observeTransientBytes(firstPageMaximumBytes);
1937
+ const firstPage = await pages.readPage(path, {
1938
+ maxBytes: firstPageMaximumBytes,
1939
+ offset: 0,
1940
+ ...createSourceOptions(signal, operationSignal) ?? {}
1941
+ });
1942
+ throwIfSignalAborted(operationSignal);
1943
+ if (firstPage.snapshot.id !== pages.snapshotId || firstPage.offset !== 0 || !(firstPage.bytes instanceof Uint8Array) || !Number.isSafeInteger(firstPage.totalBytes) || firstPage.totalBytes < 0 || firstPage.bytes.byteLength > SOURCE_PAGE_BYTES || firstPage.bytes.byteLength > firstPage.totalBytes || firstPage.bytes.byteLength === 0 && !firstPage.isComplete) return invalidSourceData$3("read-file-page", path);
1944
+ if (firstPage.totalBytes > limits[fileLimit]) return throwResourceLimitExceeded(fileLimit, limits[fileLimit], firstPage.totalBytes);
1945
+ const firstPageBytes = firstPage.bytes.byteLength;
1946
+ const retainedBytesAvailableForCanonicalContent = limits.maxRetainedBytes - retainedBytes - firstPageBytes;
1947
+ if (retainedBytesAvailableForCanonicalContent < 0 || firstPage.totalBytes > Math.floor(retainedBytesAvailableForCanonicalContent / multiplier)) {
1948
+ const projectedUsage = retainedBytes + firstPageBytes + firstPage.totalBytes * multiplier;
1949
+ return throwResourceLimitExceeded("maxRetainedBytes", limits.maxRetainedBytes, Number.isSafeInteger(projectedUsage) ? projectedUsage : Number.MAX_SAFE_INTEGER);
1950
+ }
1951
+ reserveReadBytes(firstPage.totalBytes);
1952
+ const canonicalRetainedBytes = firstPage.totalBytes * multiplier;
1953
+ observeTransientBytes(canonicalRetainedBytes + firstPageBytes);
1954
+ reserveRetainedBytes(canonicalRetainedBytes);
1955
+ if (!isSource) canonicalBytes += firstPage.totalBytes;
1956
+ const content = new Uint8Array(firstPage.totalBytes);
1957
+ let offset = 0;
1958
+ let page = firstPage;
1959
+ let isFirstPage = true;
1960
+ while (isFirstPage || offset < content.byteLength) {
1961
+ isFirstPage = false;
1962
+ if (page.snapshot.id !== pages.snapshotId || page.offset !== offset || page.totalBytes !== content.byteLength || !(page.bytes instanceof Uint8Array) || page.bytes.byteLength > SOURCE_PAGE_BYTES || page.bytes.byteLength > content.byteLength - offset || page.bytes.byteLength === 0 && !page.isComplete) return invalidSourceData$3("read-file-page", path);
1963
+ content.set(page.bytes, offset);
1964
+ offset += page.bytes.byteLength;
1965
+ if (page.isComplete) {
1966
+ if (page.nextOffset !== null || offset !== content.byteLength) return invalidSourceData$3("read-file-page", path);
1967
+ break;
1968
+ }
1969
+ if (page.nextOffset !== offset) return invalidSourceData$3("read-file-page", path);
1970
+ page = await pages.readPage(path, {
1971
+ maxBytes: Math.min(SOURCE_PAGE_BYTES, Math.max(1, content.byteLength - offset)),
1972
+ offset,
1973
+ ...createSourceOptions(signal, operationSignal) ?? {}
1974
+ });
1975
+ throwIfSignalAborted(operationSignal);
1976
+ }
1977
+ return content;
1978
+ };
1979
+ const awaitWithCancellation = async (promise, operationSignal) => {
1980
+ const callerSignal = createSourceOptions(signal, operationSignal)?.signal;
1981
+ if (callerSignal === void 0) return promise;
1982
+ return new Promise((resolve, reject) => {
1983
+ const cleanup = () => callerSignal.removeEventListener("abort", abort);
1984
+ const abort = () => {
1985
+ cleanup();
1986
+ reject(createAbortedException(callerSignal));
1987
+ };
1988
+ if (callerSignal.aborted) abort();
1989
+ else callerSignal.addEventListener("abort", abort, { once: true });
1990
+ promise.then((result) => {
1991
+ cleanup();
1992
+ resolve(result);
1993
+ }, (error) => {
1994
+ cleanup();
1995
+ reject(error instanceof Error ? error : new RepositorySourceException({
1996
+ cause: error,
1997
+ code: "INVALID_SOURCE_DATA",
1998
+ operation: "read-file-page",
1999
+ path: null,
2000
+ retryable: false
2001
+ }));
2002
+ });
2003
+ });
2004
+ };
2005
+ const readCompleteFile = async (path, options) => {
2006
+ const parsedPath = parseRepositoryPath(path);
2007
+ throwIfSignalAborted(options?.signal);
2008
+ registerPath(parsedPath);
2009
+ const content = await awaitWithCancellation(loadFile(parsedPath, options?.signal), options?.signal);
2010
+ throwIfSignalAborted(options?.signal);
2011
+ return content.slice();
2012
+ };
2013
+ const readRetainedSource = async (path, pages) => {
2014
+ throwIfSignalAborted();
2015
+ registerPath(path);
2016
+ const bytes = await awaitWithCancellation(loadFile(path, void 0, true, pages));
2017
+ throwIfSignalAborted();
2018
+ let isReleased = false;
2019
+ return {
2020
+ bytes,
2021
+ release: () => {
2022
+ if (!isReleased) retainedBytes -= bytes.byteLength;
2023
+ isReleased = true;
2024
+ }
2025
+ };
2026
+ };
2027
+ const readerFor = (path) => instructions !== void 0 && INSTRUCTION_PATHS.has(path) ? instructions : repository;
2028
+ const pagesFor = (path) => {
2029
+ const source = readerFor(path);
2030
+ return source === repository ? repositoryPages : {
2031
+ readPage: (pagePath, options) => source.readFilePage(pagePath, options),
2032
+ snapshotId: source.snapshot.id
2033
+ };
2034
+ };
2035
+ const readLinkText = async (path, options) => {
2036
+ const parsedPath = parseRepositoryPath(path);
2037
+ throwIfSignalAborted(options?.signal);
2038
+ registerPath(parsedPath);
2039
+ const text = await awaitWithCancellation(readerFor(parsedPath).readLinkText(parsedPath, createSourceOptions(signal, options?.signal)), options?.signal);
2040
+ throwIfSignalAborted(options?.signal);
2041
+ if (text !== null && (typeof text !== "string" || encoder$1.encode(text).byteLength > 4096)) return invalidSourceData$3("read-link-text", parsedPath);
2042
+ return text;
2043
+ };
2044
+ const instructionView = Object.freeze({
2045
+ getEntry: (path, options) => {
2046
+ const parsedPath = parseRepositoryPath(path);
2047
+ return getEntryFrom(readerFor(parsedPath), parsedPath, options);
2048
+ },
2049
+ readLinkText,
2050
+ readSourceFile: (path) => {
2051
+ const parsedPath = parseRepositoryPath(path);
2052
+ return readRetainedSource(parsedPath, pagesFor(parsedPath));
2053
+ }
2054
+ });
2055
+ const reader = Object.freeze({
2056
+ getEntry,
2057
+ iterateEntries,
2058
+ readCompleteFile
2059
+ });
2060
+ registerRetainedMemory(reader, {
2061
+ reserve: reserveRetainedBytes,
2062
+ tryReserve: (bytes) => {
2063
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > limits.maxRetainedBytes - retainedBytes) return false;
2064
+ reserveRetainedBytes(bytes);
2065
+ return true;
2066
+ },
2067
+ release: (bytes) => {
2068
+ if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > retainedBytes) throw new TypeError("The retained-memory release is invalid.");
2069
+ retainedBytes -= bytes;
2070
+ },
2071
+ readSourceFile: (path) => readRetainedSource(path, repositoryPages)
2072
+ });
2073
+ return Object.freeze({
2074
+ getResourceUsage: () => Object.freeze({
2075
+ canonicalBytes,
2076
+ peakRetainedBytes,
2077
+ retainedBytes,
2078
+ totalBytesRead
2079
+ }),
2080
+ instructions: instructionView,
2081
+ reader,
2082
+ throwIfAborted: throwIfSignalAborted
2083
+ });
2084
+ };
2085
+ var OPENING_HEADING_PATTERN = /^#{1,6} /u;
2086
+ var findNonblankLine = (lines, startIndex) => {
2087
+ for (let index = startIndex; index < lines.length; index += 1) {
2088
+ const line = lines[index];
2089
+ if (line !== void 0 && hasNonWhitespace(line)) return index;
2090
+ }
2091
+ return null;
2092
+ };
2093
+ var validateAgentDescription = (asset, agentId, limits) => {
2094
+ const diagnostics = createCoreDiagnosticCollector(limits, "validate-project");
2095
+ const value = trimRepositoryFormatWhitespace(asset.content);
2096
+ const scalarLength = countUnicodeScalars(value);
2097
+ if (scalarLength === 0) diagnostics.add({
2098
+ code: "MOLDEA_AGENT_DESCRIPTION_INVALID",
2099
+ details: { reason: "empty" },
2100
+ entity: { agentId },
2101
+ path: asset.path
2102
+ });
2103
+ if (scalarLength > 1e3) diagnostics.add({
2104
+ code: "MOLDEA_AGENT_DESCRIPTION_INVALID",
2105
+ details: { reason: "too-long" },
2106
+ entity: { agentId },
2107
+ path: asset.path
2108
+ });
2109
+ const finalizedDiagnostics = diagnostics.finalize();
2110
+ return deepFreeze({
2111
+ description: finalizedDiagnostics.length === 0 ? {
2112
+ asset,
2113
+ scalarLength,
2114
+ value
2115
+ } : null,
2116
+ diagnostics: finalizedDiagnostics,
2117
+ valid: finalizedDiagnostics.length === 0
2118
+ });
2119
+ };
2120
+ var validateAgentInstruction = (asset, agentId, limits) => {
2121
+ const diagnostics = createCoreDiagnosticCollector(limits, "validate-project");
2122
+ if (!hasNonWhitespace(asset.content)) {
2123
+ diagnostics.add({
2124
+ code: "MOLDEA_AGENT_INSTRUCTION_EMPTY",
2125
+ entity: { agentId },
2126
+ path: asset.path
2127
+ });
2128
+ return deepFreeze({
2129
+ diagnostics: diagnostics.finalize(),
2130
+ instruction: null,
2131
+ valid: false
2132
+ });
2133
+ }
2134
+ const identityToken = `\`${agentId}\``;
2135
+ const lines = asset.content.split("\n");
2136
+ const openingIndex = findNonblankLine(lines, 0);
2137
+ let identityIndex = openingIndex;
2138
+ if (openingIndex !== null && OPENING_HEADING_PATTERN.test(lines[openingIndex] ?? "")) identityIndex = findNonblankLine(lines, openingIndex + 1);
2139
+ if (identityIndex === null || !(lines[identityIndex] ?? "").includes(identityToken)) diagnostics.add({
2140
+ code: "MOLDEA_AGENT_IDENTITY_INVALID",
2141
+ details: { reason: asset.content.includes(identityToken) ? "misplaced" : "missing" },
2142
+ entity: { agentId },
2143
+ path: asset.path
2144
+ });
2145
+ const finalizedDiagnostics = diagnostics.finalize();
2146
+ return deepFreeze({
2147
+ diagnostics: finalizedDiagnostics,
2148
+ instruction: asset,
2149
+ valid: finalizedDiagnostics.length === 0
2150
+ });
2151
+ };
2152
+ var invalidSourceData$2 = (path) => {
2153
+ throw new RepositorySourceException({
2154
+ code: "INVALID_SOURCE_DATA",
2155
+ operation: "read-file-page",
2156
+ path,
2157
+ retryable: false
2158
+ });
2159
+ };
2160
+ var readRepositoryTextAsset = async (repository, path, limits, signal) => {
2161
+ const content = await repository.readCompleteFile(path, signal === void 0 ? void 0 : { signal });
2162
+ if (!(content instanceof Uint8Array)) return invalidSourceData$2(path);
2163
+ const normalized = normalizeTextDocument({
2164
+ content,
2165
+ path
2166
+ }, limits, "validate-project");
2167
+ if (!normalized.valid || normalized.text === null) return deepFreeze({
2168
+ asset: null,
2169
+ diagnostics: normalized.diagnostics,
2170
+ valid: false
2171
+ });
2172
+ const asset = {
2173
+ content: normalized.text.value,
2174
+ digest: await calculateNormalizedTextDigest(normalized.text),
2175
+ path,
2176
+ scalarLength: normalized.text.scalarLength,
2177
+ utf8ByteLength: normalized.text.utf8ByteLength
2178
+ };
2179
+ return deepFreeze({
2180
+ asset,
2181
+ diagnostics: [],
2182
+ valid: true
2183
+ });
2184
+ };
2185
+ var addDiagnostics$3 = (collector, diagnostics) => {
2186
+ for (const diagnostic of diagnostics) collector.merge(diagnostic);
2187
+ };
2188
+ var isBlockedPath$1 = (path, blockedPaths) => {
2189
+ let candidate = path;
2190
+ while (candidate.length > 0) {
2191
+ if (blockedPaths.has(candidate)) return true;
2192
+ const separatorIndex = candidate.lastIndexOf("/");
2193
+ if (separatorIndex <= 0) return false;
2194
+ candidate = candidate.slice(0, separatorIndex);
2195
+ }
2196
+ return false;
2197
+ };
2198
+ var readDescription = async (repository, path, agentId, options, collector, signal) => {
2199
+ const readResult = await readRepositoryTextAsset(repository, path, options.limits, signal);
2200
+ addDiagnostics$3(collector, readResult.diagnostics);
2201
+ if (readResult.asset === null) return null;
2202
+ const validation = validateAgentDescription(readResult.asset, agentId, options.limits);
2203
+ addDiagnostics$3(collector, validation.diagnostics);
2204
+ return validation.description;
2205
+ };
2206
+ var readInstruction = async (repository, path, agentId, options, collector, signal) => {
2207
+ const readResult = await readRepositoryTextAsset(repository, path, options.limits, signal);
2208
+ addDiagnostics$3(collector, readResult.diagnostics);
2209
+ if (readResult.asset === null) return null;
2210
+ const validation = validateAgentInstruction(readResult.asset, agentId, options.limits);
2211
+ addDiagnostics$3(collector, validation.diagnostics);
2212
+ return validation.instruction;
2213
+ };
2214
+ var inspectAgentAssets = async (repository, manifest, discovery, options, signal) => {
2215
+ options = createCoreOperationOptionsSnapshot(options);
2216
+ const collector = createCoreDiagnosticCollector(options.limits, "validate-project");
2217
+ const agents = [];
2218
+ const registeredAgents = manifest.agents ?? {};
2219
+ const registeredIds = new Set(Object.keys(registeredAgents));
2220
+ const discoveredById = new Map(discovery.inventory.agents.map((agent) => [agent.id, agent]));
2221
+ const blockedPaths = new Set(discovery.diagnostics.flatMap((diagnostic) => diagnostic.path === null ? [] : [diagnostic.path]));
2222
+ for (const discovered of discovery.inventory.agents) if (!registeredIds.has(discovered.id)) collector.add({
2223
+ code: "MOLDEA_AGENT_DIRECTORY_UNREGISTERED",
2224
+ entity: { agentId: discovered.id },
2225
+ path: discovered.path
2226
+ });
2227
+ for (const agentId of [...registeredIds].sort(compareCodePoints)) {
2228
+ const declaration = registeredAgents[agentId];
2229
+ if (declaration === void 0) continue;
2230
+ const discovered = discoveredById.get(agentId);
2231
+ if (discovered === void 0) {
2232
+ const directoryPath = parseRepositoryPath(`/moldea/agents/${agentId}`);
2233
+ if (!isBlockedPath$1(directoryPath, blockedPaths)) collector.add({
2234
+ code: "MOLDEA_AGENT_DIRECTORY_MISSING",
2235
+ entity: { agentId },
2236
+ path: directoryPath
2237
+ });
2238
+ agents.push({
2239
+ declaration,
2240
+ description: null,
2241
+ id: agentId,
2242
+ instruction: null
2243
+ });
2244
+ continue;
2245
+ }
2246
+ let description = null;
2247
+ let instruction = null;
2248
+ if (discovered.description === null) {
2249
+ const path = parseRepositoryPath(`${discovered.path}/description.md`);
2250
+ if (!isBlockedPath$1(path, blockedPaths)) collector.add({
2251
+ code: "MOLDEA_AGENT_DESCRIPTION_MISSING",
2252
+ entity: { agentId },
2253
+ path
2254
+ });
2255
+ } else description = await readDescription(repository, discovered.description, agentId, options, collector, signal);
2256
+ if (discovered.instruction === null) {
2257
+ const path = parseRepositoryPath(`${discovered.path}/instruction.md`);
2258
+ if (!isBlockedPath$1(path, blockedPaths)) collector.add({
2259
+ code: "MOLDEA_AGENT_INSTRUCTION_MISSING",
2260
+ entity: { agentId },
2261
+ path
2262
+ });
2263
+ } else instruction = await readInstruction(repository, discovered.instruction, agentId, options, collector, signal);
2264
+ agents.push({
2265
+ declaration,
2266
+ description,
2267
+ id: agentId,
2268
+ instruction
2269
+ });
2270
+ }
2271
+ const diagnostics = collector.finalize();
2272
+ return deepFreeze({
2273
+ agents,
2274
+ diagnostics,
2275
+ valid: diagnostics.length === 0
2276
+ });
2277
+ };
2278
+ var AGENT_ASSET_PATTERN = /^\/moldea\/agents\/([^/]+)\/(description|instruction)\.md$/u;
2279
+ var AGENT_DIRECTORY_PATTERN = /^\/moldea\/agents\/([^/]+)$/u;
2280
+ var DECISION_CANDIDATE_PATTERN = /^\/moldea\/decisions\/[^/]+\.md$/u;
2281
+ var readCanonicalFile = (path) => {
2282
+ if (path === "/moldea/moldea.yaml") return {
2283
+ agentId: null,
2284
+ fileKind: "manifest",
2285
+ kind: "canonical-file"
2286
+ };
2287
+ if (path === "/moldea/project.md") return {
2288
+ agentId: null,
2289
+ fileKind: "project",
2290
+ kind: "canonical-file"
2291
+ };
2292
+ if (isContextPath(path, false)) return {
2293
+ agentId: null,
2294
+ fileKind: "context",
2295
+ kind: "canonical-file"
2296
+ };
2297
+ if (DECISION_CANDIDATE_PATTERN.test(path)) return {
2298
+ agentId: null,
2299
+ fileKind: "decision",
2300
+ kind: "canonical-file"
2301
+ };
2302
+ const agentAsset = AGENT_ASSET_PATTERN.exec(path);
2303
+ if (agentAsset === null) return null;
2304
+ const agentId = agentAsset[1];
2305
+ const fileName = agentAsset[2];
2306
+ if (agentId === void 0 || fileName === void 0) return null;
2307
+ return {
2308
+ agentId,
2309
+ fileKind: fileName === "description" ? "agent-description" : "agent-instruction",
2310
+ kind: "canonical-file"
2311
+ };
2312
+ };
2313
+ var readAgentDirectoryId = (path) => {
2314
+ return AGENT_DIRECTORY_PATTERN.exec(path)?.[1] ?? null;
2315
+ };
2316
+ var isRequiredDirectoryPath = (path) => {
2317
+ return path === "/moldea" || path === "/moldea/context" || path === "/moldea/decisions" || path === "/moldea/agents";
2318
+ };
2319
+ var isPermittedStructuralDirectoryPath = (path) => {
2320
+ return isRequiredDirectoryPath(path) || path.startsWith("/moldea/context/");
2321
+ };
2322
+ var classifyCanonicalEntry = (entry) => {
2323
+ const canonicalFile = readCanonicalFile(entry.path);
2324
+ if (canonicalFile !== null) {
2325
+ if (entry.type === "file") return canonicalFile;
2326
+ return entry.type === "symlink" ? { kind: "canonical-asset-symlink" } : {
2327
+ expectedType: "file",
2328
+ kind: "entry-type-invalid"
2329
+ };
2330
+ }
2331
+ const agentId = readAgentDirectoryId(entry.path);
2332
+ if (agentId !== null) return entry.type === "directory" ? {
2333
+ agentId,
2334
+ kind: "agent-directory"
2335
+ } : {
2336
+ expectedType: "directory",
2337
+ kind: "entry-type-invalid"
2338
+ };
2339
+ if (isRequiredDirectoryPath(entry.path)) return entry.type === "directory" ? { kind: "structural-directory" } : {
2340
+ expectedType: "directory",
2341
+ kind: "entry-type-invalid"
2342
+ };
2343
+ if (entry.type === "directory") return isPermittedStructuralDirectoryPath(entry.path) ? { kind: "structural-directory" } : { kind: "ignored-directory" };
2344
+ return { kind: "unrecognized" };
2345
+ };
2346
+ var MOLDEA_ROOT$1 = parseRepositoryPath("/moldea");
2347
+ var MANIFEST_PATH$1 = parseRepositoryPath("/moldea/moldea.yaml");
2348
+ var PROJECT_PATH$1 = parseRepositoryPath("/moldea/project.md");
2349
+ var createWorkingInventory = () => ({
2350
+ agents: new Map(),
2351
+ context: new Set(),
2352
+ decisions: new Set(),
2353
+ manifest: null,
2354
+ project: null
2355
+ });
2356
+ var invalidSourceData$1 = (operation, path) => {
2357
+ throw new RepositorySourceException({
2358
+ code: "INVALID_SOURCE_DATA",
2359
+ operation,
2360
+ path,
2361
+ retryable: false
2362
+ });
2363
+ };
2364
+ var copyReaderEntry = (candidate, operation, expectedPath) => {
2365
+ if (typeof candidate !== "object" || candidate === null) return invalidSourceData$1(operation, expectedPath ?? null);
2366
+ const record = candidate;
2367
+ const pathCandidate = record["path"];
2368
+ const typeCandidate = record["type"];
2369
+ const byteLength = record["byteLength"];
2370
+ const contentIdentity = record["contentIdentity"];
2371
+ if (typeof pathCandidate !== "string" || !isRepositoryPath(pathCandidate)) return invalidSourceData$1(operation, expectedPath ?? null);
2372
+ const path = parseRepositoryPath(pathCandidate);
2373
+ if (expectedPath !== void 0 && path !== expectedPath) return invalidSourceData$1(operation, path);
2374
+ if (typeCandidate !== "file" && typeCandidate !== "directory" && typeCandidate !== "symlink") return invalidSourceData$1(operation, path);
2375
+ if (typeCandidate === "file" ? !Number.isSafeInteger(byteLength) || byteLength < 0 || contentIdentity !== null && typeof contentIdentity !== "string" : byteLength !== null || contentIdentity !== null) return invalidSourceData$1(operation, path);
2376
+ return {
2377
+ byteLength,
2378
+ contentIdentity,
2379
+ path,
2380
+ type: typeCandidate
2381
+ };
2382
+ };
2383
+ var readExactEntry = async (repository, path, signal) => {
2384
+ const candidate = await repository.getEntry(path, signal === void 0 ? void 0 : { signal });
2385
+ return candidate === null ? null : copyReaderEntry(candidate, "get-entry", path);
2386
+ };
2387
+ var addEntryTypeDiagnostic = (diagnostics, entry, expectedType) => {
2388
+ diagnostics.add({
2389
+ code: "MOLDEA_ENTRY_TYPE_INVALID",
2390
+ details: {
2391
+ actualType: entry.type,
2392
+ expectedType
2393
+ },
2394
+ path: entry.path
2395
+ });
2396
+ };
2397
+ var getAgent = (agents, agentId) => {
2398
+ const existing = agents.get(agentId);
2399
+ if (existing !== void 0) return existing;
2400
+ const created = {
2401
+ description: null,
2402
+ id: agentId,
2403
+ instruction: null,
2404
+ path: parseRepositoryPath(`/moldea/agents/${agentId}`)
2405
+ };
2406
+ agents.set(agentId, created);
2407
+ return created;
2408
+ };
2409
+ var retainCanonicalFile = (inventory, path, fileKind, agentId) => {
2410
+ switch (fileKind) {
2411
+ case "manifest":
2412
+ inventory.manifest = path;
2413
+ return;
2414
+ case "project":
2415
+ inventory.project = path;
2416
+ return;
2417
+ case "context":
2418
+ inventory.context.add(path);
2419
+ return;
2420
+ case "decision":
2421
+ inventory.decisions.add(path);
2422
+ return;
2423
+ }
2424
+ if (agentId === null) return invalidSourceData$1("list-entries-page", path);
2425
+ const agent = getAgent(inventory.agents, agentId);
2426
+ if (fileKind === "agent-description") agent.description = path;
2427
+ else agent.instruction = path;
2428
+ };
2429
+ var finalizeInventory = (working) => {
2430
+ const sortPaths = (paths) => {
2431
+ return [...paths].sort(compareCodePoints);
2432
+ };
2433
+ const agents = [...working.agents.values()].sort((left, right) => compareCodePoints(left.id, right.id)).map((agent) => deepFreeze({ ...agent }));
2434
+ return deepFreeze({
2435
+ agents,
2436
+ context: sortPaths(working.context),
2437
+ decisions: sortPaths(working.decisions),
2438
+ manifest: working.manifest,
2439
+ project: working.project
2440
+ });
2441
+ };
2442
+ var finalizeResult = (working, diagnostics) => {
2443
+ const finalizedDiagnostics = diagnostics.finalize();
2444
+ return deepFreeze({
2445
+ diagnostics: finalizedDiagnostics,
2446
+ inventory: finalizeInventory(working),
2447
+ valid: finalizedDiagnostics.length === 0
2448
+ });
2449
+ };
2450
+ var retainFoundationEntry = (entry, expectedPath, missingCode, working, diagnostics) => {
2451
+ if (entry === null) {
2452
+ diagnostics.add({
2453
+ code: missingCode,
2454
+ path: expectedPath
2455
+ });
2456
+ return;
2457
+ }
2458
+ if (entry.type === "file") {
2459
+ if (expectedPath === MANIFEST_PATH$1) working.manifest = expectedPath;
2460
+ else working.project = expectedPath;
2461
+ return;
2462
+ }
2463
+ if (entry.type === "symlink") {
2464
+ diagnostics.add({
2465
+ code: "MOLDEA_CANONICAL_ASSET_SYMLINK",
2466
+ path: expectedPath
2467
+ });
2468
+ return;
2469
+ }
2470
+ addEntryTypeDiagnostic(diagnostics, entry, "file");
2471
+ };
2472
+ var checkFoundationListing = (listedEntry, exactEntry) => {
2473
+ if (exactEntry === null || exactEntry.type !== listedEntry.type) return invalidSourceData$1("list-entries-page", listedEntry.path);
2474
+ };
2475
+ var discoverCanonicalAssets = async (repository, limits, signal, foundations) => {
2476
+ const diagnostics = createCoreDiagnosticCollector(limits, "validate-project");
2477
+ const working = createWorkingInventory();
2478
+ const moldeaEntry = foundations === void 0 ? await readExactEntry(repository, MOLDEA_ROOT$1, signal) : foundations.moldeaRoot;
2479
+ if (moldeaEntry === null) {
2480
+ diagnostics.add({
2481
+ code: "MOLDEA_MANIFEST_MISSING",
2482
+ path: MANIFEST_PATH$1
2483
+ });
2484
+ diagnostics.add({
2485
+ code: "MOLDEA_PROJECT_FILE_MISSING",
2486
+ path: PROJECT_PATH$1
2487
+ });
2488
+ return finalizeResult(working, diagnostics);
2489
+ }
2490
+ if (moldeaEntry.type !== "directory") {
2491
+ addEntryTypeDiagnostic(diagnostics, moldeaEntry, "directory");
2492
+ return finalizeResult(working, diagnostics);
2493
+ }
2494
+ const manifestEntry = foundations === void 0 ? await readExactEntry(repository, MANIFEST_PATH$1, signal) : foundations.manifest;
2495
+ const projectEntry = foundations === void 0 ? await readExactEntry(repository, PROJECT_PATH$1, signal) : foundations.project;
2496
+ retainFoundationEntry(manifestEntry, MANIFEST_PATH$1, "MOLDEA_MANIFEST_MISSING", working, diagnostics);
2497
+ retainFoundationEntry(projectEntry, PROJECT_PATH$1, "MOLDEA_PROJECT_FILE_MISSING", working, diagnostics);
2498
+ const seenPaths = new Set();
2499
+ let listedManifest = false;
2500
+ let listedProject = false;
2501
+ const listOptions = signal === void 0 ? { prefix: MOLDEA_ROOT$1 } : {
2502
+ prefix: MOLDEA_ROOT$1,
2503
+ signal
2504
+ };
2505
+ for await (const candidate of repository.iterateEntries(listOptions)) {
2506
+ const entry = copyReaderEntry(candidate, "list-entries-page");
2507
+ if (!entry.path.startsWith("/moldea/")) return invalidSourceData$1("list-entries-page", entry.path);
2508
+ if (seenPaths.has(entry.path)) return invalidSourceData$1("list-entries-page", entry.path);
2509
+ seenPaths.add(entry.path);
2510
+ if (entry.path === MANIFEST_PATH$1) {
2511
+ checkFoundationListing(entry, manifestEntry);
2512
+ listedManifest = true;
2513
+ continue;
2514
+ }
2515
+ if (entry.path === PROJECT_PATH$1) {
2516
+ checkFoundationListing(entry, projectEntry);
2517
+ listedProject = true;
2518
+ continue;
2519
+ }
2520
+ const classification = classifyCanonicalEntry(entry);
2521
+ switch (classification.kind) {
2522
+ case "canonical-file":
2523
+ retainCanonicalFile(working, entry.path, classification.fileKind, classification.agentId);
2524
+ break;
2525
+ case "agent-directory":
2526
+ getAgent(working.agents, classification.agentId);
2527
+ break;
2528
+ case "canonical-asset-symlink":
2529
+ diagnostics.add({
2530
+ code: "MOLDEA_CANONICAL_ASSET_SYMLINK",
2531
+ path: entry.path
2532
+ });
2533
+ break;
2534
+ case "entry-type-invalid":
2535
+ addEntryTypeDiagnostic(diagnostics, entry, classification.expectedType);
2536
+ break;
2537
+ case "unrecognized": diagnostics.add({
2538
+ code: "MOLDEA_CANONICAL_PATH_UNRECOGNIZED",
2539
+ details: { entryType: entry.type },
2540
+ path: entry.path
2541
+ });
2542
+ }
2543
+ }
2544
+ if (manifestEntry !== null !== listedManifest) return invalidSourceData$1("list-entries-page", MANIFEST_PATH$1);
2545
+ if (projectEntry !== null !== listedProject) return invalidSourceData$1("list-entries-page", PROJECT_PATH$1);
2546
+ return finalizeResult(working, diagnostics);
2547
+ };
2548
+ var sortCandidates = (candidates) => {
2549
+ return [...candidates].sort((left, right) => compareCodePoints(left.path, right.path));
2550
+ };
2551
+ var buildGraphIndex = (candidates) => {
2552
+ const mutableGroups = new Map();
2553
+ for (const candidate of sortCandidates(candidates)) {
2554
+ if (candidate.id === null) continue;
2555
+ const group = mutableGroups.get(candidate.id) ?? [];
2556
+ group.push(candidate);
2557
+ mutableGroups.set(candidate.id, group);
2558
+ }
2559
+ const candidateGroups = new Map();
2560
+ const nodes = new Map();
2561
+ for (const id of [...mutableGroups.keys()].sort(compareCodePoints)) {
2562
+ const group = mutableGroups.get(id) ?? [];
2563
+ candidateGroups.set(id, group);
2564
+ if (group.length === 1 && group[0]?.decision !== null) {
2565
+ const decision = group[0]?.decision;
2566
+ if (decision !== void 0) nodes.set(id, decision);
2567
+ }
2568
+ }
2569
+ const edges = new Map();
2570
+ for (const [id, decision] of nodes) {
2571
+ const resolvedTargets = decision.supersedes.filter((targetId) => {
2572
+ const group = candidateGroups.get(targetId);
2573
+ return group?.length === 1 && group[0]?.decision !== null;
2574
+ });
2575
+ edges.set(id, resolvedTargets);
2576
+ }
2577
+ return {
2578
+ candidateGroups,
2579
+ edges,
2580
+ nodes
2581
+ };
2582
+ };
2583
+ var collectDuplicateDiagnostics = (index, diagnostics) => {
2584
+ for (const [id, candidates] of index.candidateGroups) {
2585
+ if (candidates.length < 2) continue;
2586
+ for (const candidate of candidates) diagnostics.add({
2587
+ code: "MOLDEA_DECISION_ID_DUPLICATE",
2588
+ details: { occurrences: candidates.length },
2589
+ entity: { decisionId: id },
2590
+ path: candidate.path
2591
+ });
2592
+ }
2593
+ };
2594
+ var collectReferenceDiagnostics = (index, diagnostics) => {
2595
+ for (const decision of index.nodes.values()) for (const targetId of decision.supersedes) {
2596
+ if (index.candidateGroups.has(targetId)) continue;
2597
+ diagnostics.add({
2598
+ code: "MOLDEA_DECISION_REFERENCE_MISSING",
2599
+ details: { referencedDecisionId: targetId },
2600
+ entity: { decisionId: decision.id },
2601
+ path: decision.path,
2602
+ pointer: "/supersedes"
2603
+ });
2604
+ }
2605
+ };
2606
+ var collectStatusDiagnostics = (index, diagnostics) => {
2607
+ const activelySupersededIds = new Set();
2608
+ for (const decision of index.nodes.values()) {
2609
+ if (decision.status !== "accepted" && decision.status !== "superseded") continue;
2610
+ for (const targetId of index.edges.get(decision.id) ?? []) {
2611
+ const target = index.nodes.get(targetId);
2612
+ if (target === void 0) continue;
2613
+ if (target.status === "superseded") {
2614
+ activelySupersededIds.add(targetId);
2615
+ continue;
2616
+ }
2617
+ diagnostics.add({
2618
+ code: "MOLDEA_DECISION_SUPERSESSION_STATUS_INVALID",
2619
+ details: {
2620
+ referencedDecisionId: targetId,
2621
+ sourceStatus: decision.status,
2622
+ targetStatus: target.status
2623
+ },
2624
+ entity: { decisionId: decision.id },
2625
+ path: decision.path,
2626
+ pointer: "/supersedes"
2627
+ });
2628
+ }
2629
+ }
2630
+ return activelySupersededIds;
2631
+ };
2632
+ var collectOrphanDiagnostics = (index, activelySupersededIds, diagnostics) => {
2633
+ for (const decision of index.nodes.values()) if (decision.status === "superseded" && !activelySupersededIds.has(decision.id)) diagnostics.add({
2634
+ code: "MOLDEA_DECISION_SUPERSEDED_ORPHAN",
2635
+ entity: { decisionId: decision.id },
2636
+ path: decision.path
2637
+ });
2638
+ };
2639
+ var calculateFinishOrder = (index) => {
2640
+ const visited = new Set();
2641
+ const finished = [];
2642
+ for (const startId of index.nodes.keys()) {
2643
+ if (visited.has(startId)) continue;
2644
+ const stack = [{
2645
+ id: startId,
2646
+ nextNeighbor: 0
2647
+ }];
2648
+ visited.add(startId);
2649
+ while (stack.length > 0) {
2650
+ const current = stack.at(-1);
2651
+ if (current === void 0) break;
2652
+ const neighbor = (index.edges.get(current.id) ?? [])[current.nextNeighbor];
2653
+ if (neighbor === void 0) {
2654
+ finished.push(current.id);
2655
+ stack.pop();
2656
+ continue;
2657
+ }
2658
+ current.nextNeighbor += 1;
2659
+ if (!visited.has(neighbor)) {
2660
+ visited.add(neighbor);
2661
+ stack.push({
2662
+ id: neighbor,
2663
+ nextNeighbor: 0
2664
+ });
2665
+ }
2666
+ }
2667
+ }
2668
+ return finished;
2669
+ };
2670
+ var buildReverseEdges = (index) => {
2671
+ const reverseEdges = new Map();
2672
+ for (const id of index.nodes.keys()) reverseEdges.set(id, []);
2673
+ for (const [sourceId, targets] of index.edges) for (const targetId of targets) reverseEdges.get(targetId)?.push(sourceId);
2674
+ for (const sources of reverseEdges.values()) sources.sort(compareCodePoints);
2675
+ return reverseEdges;
2676
+ };
2677
+ var findStronglyConnectedComponents = (index) => {
2678
+ const reverseEdges = buildReverseEdges(index);
2679
+ const visited = new Set();
2680
+ const components = [];
2681
+ for (const startId of [...calculateFinishOrder(index)].reverse()) {
2682
+ if (visited.has(startId)) continue;
2683
+ const component = [];
2684
+ const stack = [startId];
2685
+ visited.add(startId);
2686
+ while (stack.length > 0) {
2687
+ const currentId = stack.pop();
2688
+ if (currentId === void 0) break;
2689
+ component.push(currentId);
2690
+ for (const sourceId of [...reverseEdges.get(currentId) ?? []].reverse()) if (!visited.has(sourceId)) {
2691
+ visited.add(sourceId);
2692
+ stack.push(sourceId);
2693
+ }
2694
+ }
2695
+ components.push(component.sort(compareCodePoints));
2696
+ }
2697
+ return components.sort((left, right) => compareCodePoints(left[0] ?? "", right[0] ?? ""));
2698
+ };
2699
+ var collectCycleDiagnostics = (index, diagnostics) => {
2700
+ for (const component of findStronglyConnectedComponents(index)) {
2701
+ if (component.length < 2) continue;
2702
+ const cycleRepresentativeDecisionId = component[0];
2703
+ if (cycleRepresentativeDecisionId === void 0) continue;
2704
+ for (const decisionId of component) {
2705
+ const decision = index.nodes.get(decisionId);
2706
+ if (decision !== void 0) diagnostics.add({
2707
+ code: "MOLDEA_DECISION_SUPERSESSION_CYCLE",
2708
+ details: {
2709
+ cycleRepresentativeDecisionId,
2710
+ cycleSize: component.length
2711
+ },
2712
+ entity: { decisionId },
2713
+ path: decision.path,
2714
+ pointer: "/supersedes"
2715
+ });
2716
+ }
2717
+ }
2718
+ };
2719
+ var validateDecisionGraph = (candidates, limits) => {
2720
+ const diagnostics = createCoreDiagnosticCollector(limits, "validate-project");
2721
+ const index = buildGraphIndex(candidates);
2722
+ collectDuplicateDiagnostics(index, diagnostics);
2723
+ collectReferenceDiagnostics(index, diagnostics);
2724
+ collectCycleDiagnostics(index, diagnostics);
2725
+ collectOrphanDiagnostics(index, collectStatusDiagnostics(index, diagnostics), diagnostics);
2726
+ return diagnostics.finalize();
2727
+ };
2728
+ var invalidSourceData = (path) => {
2729
+ throw new RepositorySourceException({
2730
+ code: "INVALID_SOURCE_DATA",
2731
+ operation: "read-file-page",
2732
+ path,
2733
+ retryable: false
2734
+ });
2735
+ };
2736
+ var sortDecisions = (decisions) => {
2737
+ return [...decisions].sort((left, right) => {
2738
+ return compareCodePoints(left.id, right.id) || compareCodePoints(left.path, right.path);
2739
+ });
2740
+ };
2741
+ var readDecisionGraph = async (repository, paths, options, signal, retainYamlRoot) => {
2742
+ options = createCoreOperationOptionsSnapshot(options);
2743
+ const diagnostics = createCoreDiagnosticCollector(options.limits, "validate-project");
2744
+ const candidates = [];
2745
+ const decisions = [];
2746
+ const readOptions = signal === void 0 ? void 0 : { signal };
2747
+ for (const path of [...paths].sort(compareCodePoints)) {
2748
+ const content = await repository.readCompleteFile(path, readOptions);
2749
+ if (!(content instanceof Uint8Array)) return invalidSourceData(path);
2750
+ const parsed = await inspectDecisionDocument({
2751
+ content: content.slice(),
2752
+ path
2753
+ }, options, "validate-project");
2754
+ if (parsed.decision !== null && parsed.yamlRoot !== null) retainYamlRoot?.(path, parsed.yamlRoot);
2755
+ for (const diagnostic of parsed.diagnostics) diagnostics.merge(diagnostic);
2756
+ candidates.push({
2757
+ decision: parsed.decision,
2758
+ id: parseDecisionIdFromPath(path),
2759
+ path
2760
+ });
2761
+ if (parsed.decision !== null) decisions.push(parsed.decision);
2762
+ }
2763
+ for (const diagnostic of validateDecisionGraph(candidates, options.limits)) diagnostics.merge(diagnostic);
2764
+ const finalizedDiagnostics = diagnostics.finalize();
2765
+ return deepFreeze({
2766
+ decisions: sortDecisions(decisions),
2767
+ diagnostics: finalizedDiagnostics,
2768
+ valid: finalizedDiagnostics.length === 0
2769
+ });
2770
+ };
2771
+ var createDecisionEntity = (decisionPath, agentId) => {
2772
+ const decisionId = parseDecisionIdFromPath(decisionPath);
2773
+ return {
2774
+ ...agentId === void 0 ? {} : { agentId },
2775
+ ...decisionId === null ? {} : { decisionId }
2776
+ };
2777
+ };
2778
+ var validateContextRelationship = (referencedPath, pointer, validContextPaths, context, agentId) => {
2779
+ if (validContextPaths.has(referencedPath) || context.blockedPaths.has(referencedPath)) return;
2780
+ context.collector.add({
2781
+ code: "MOLDEA_REFERENCE_MISSING",
2782
+ details: { referencedPath },
2783
+ entity: agentId === void 0 ? null : { agentId },
2784
+ path: context.manifestPath,
2785
+ pointer
2786
+ });
2787
+ };
2788
+ var validateDecisionRelationship = (referencedPath, pointer, context, agentId) => {
2789
+ if (!context.discoveredDecisionPaths.has(referencedPath)) {
2790
+ if (context.blockedPaths.has(referencedPath)) return;
2791
+ context.collector.add({
2792
+ code: "MOLDEA_DECISION_REFERENCE_MISSING",
2793
+ details: { referencedPath },
2794
+ entity: createDecisionEntity(referencedPath, agentId),
2795
+ path: context.manifestPath,
2796
+ pointer
2797
+ });
2798
+ return;
2799
+ }
2800
+ const parsedDecision = context.parsedDecisionsByPath.get(referencedPath);
2801
+ if (parsedDecision === void 0 || parsedDecision.status === "accepted") return;
2802
+ context.collector.add({
2803
+ code: "MOLDEA_DECISION_RELATIONSHIP_INACTIVE",
2804
+ details: {
2805
+ referencedPath,
2806
+ targetStatus: parsedDecision.status
2807
+ },
2808
+ entity: createDecisionEntity(referencedPath, agentId),
2809
+ path: context.manifestPath,
2810
+ pointer
2811
+ });
2812
+ };
2813
+ var validateManifestRelationships = (manifestPath, manifest, discovery, decisions, limits) => {
2814
+ const collector = createCoreDiagnosticCollector(limits, "validate-project");
2815
+ const validAgentContextPaths = new Set(discovery.inventory.context);
2816
+ const validTopLevelContextPaths = new Set(validAgentContextPaths);
2817
+ if (discovery.inventory.project !== null) validTopLevelContextPaths.add(discovery.inventory.project);
2818
+ const validationContext = {
2819
+ blockedPaths: new Set(discovery.diagnostics.flatMap((diagnostic) => diagnostic.path === null ? [] : [diagnostic.path])),
2820
+ collector,
2821
+ discoveredDecisionPaths: new Set(discovery.inventory.decisions),
2822
+ manifestPath,
2823
+ parsedDecisionsByPath: new Map(decisions.map((decision) => [decision.path, decision])),
2824
+ validAgentContextPaths,
2825
+ validTopLevelContextPaths
2826
+ };
2827
+ for (const referencedPathValue of Object.keys(manifest.context ?? {}).sort(compareCodePoints)) validateContextRelationship(parseRepositoryPath(referencedPathValue), `/context/${escapeJsonPointerSegment(referencedPathValue)}`, validationContext.validTopLevelContextPaths, validationContext);
2828
+ for (const referencedPathValue of Object.keys(manifest.decisions ?? {}).sort(compareCodePoints)) validateDecisionRelationship(parseRepositoryPath(referencedPathValue), `/decisions/${escapeJsonPointerSegment(referencedPathValue)}`, validationContext);
2829
+ for (const agentId of Object.keys(manifest.agents ?? {}).sort(compareCodePoints)) {
2830
+ const agent = manifest.agents?.[agentId];
2831
+ if (agent === void 0) continue;
2832
+ const escapedAgentId = escapeJsonPointerSegment(agentId);
2833
+ for (const [index, referencedPath] of (agent.context ?? []).entries()) validateContextRelationship(referencedPath, `/agents/${escapedAgentId}/context/${index}`, validationContext.validAgentContextPaths, validationContext, agentId);
2834
+ for (const [index, referencedPath] of (agent.decisions ?? []).entries()) validateDecisionRelationship(referencedPath, `/agents/${escapedAgentId}/decisions/${index}`, validationContext, agentId);
2835
+ }
2836
+ return collector.finalize();
2837
+ };
2838
+ var MARKERS = {
2839
+ start: "<!-- moldea:start -->",
2840
+ end: "<!-- moldea:end -->"
2841
+ };
2842
+ var parseManagedIntegrationRegion = (text) => {
2843
+ try {
2844
+ const region = findMarkedRegion(text.replace(/(<!-- moldea:(?:start|end) -->)[ \t]+(?=\r?$)/gmu, "$1"), MARKERS);
2845
+ if (region === null) return "block-missing";
2846
+ const start = text.indexOf(MARKERS.start);
2847
+ const closingLineBreak = text.indexOf("\n", text.indexOf(MARKERS.end));
2848
+ return {
2849
+ start,
2850
+ end: closingLineBreak === -1 ? text.length : closingLineBreak + 1,
2851
+ lineEnding: region.lineEnding
2852
+ };
2853
+ } catch (error) {
2854
+ if (hasErrorCode(error, ERRORS.INVALID_MARKED_REGION)) return "block-invalid";
2855
+ throw error;
2856
+ }
2857
+ };
2858
+ var normalizeManagedIntegrationBlock = (text) => {
2859
+ const normalized = text.replaceAll("\r\n", "\n").replace(/(<!-- moldea:(?:start|end) -->)[ \t]+(?=\n|$)/gu, "$1");
2860
+ if (!normalized.startsWith(`${MARKERS.start}\n`) || !(normalized.endsWith(MARKERS.end) || normalized.endsWith(`${MARKERS.end}\n`))) return normalized;
2861
+ let start = MARKERS.start.length;
2862
+ let end = normalized.lastIndexOf(MARKERS.end);
2863
+ while (start < end && normalized[start] === "\n") start++;
2864
+ while (end > start && normalized[end - 1] === "\n") end--;
2865
+ return `${MARKERS.start}\n${normalized.slice(start, end)}\n${MARKERS.end}`;
2866
+ };
2867
+ var parseIntegrationBlock = (text) => {
2868
+ const region = parseManagedIntegrationRegion(text);
2869
+ if (typeof region === "string") return {
2870
+ kind: "missing",
2871
+ reason: region
2872
+ };
2873
+ const matches = text.slice(region.start, region.end).matchAll(/^node "<repo-root>\/([^"\r\n]+)\/scripts\/relevance-gate\.mjs"(?=[ \t\r]|$)([^\r\n]*)/gm);
2874
+ const paths = new Map();
2875
+ for (const match of matches) {
2876
+ const skillPath = match[1];
2877
+ const mode = /(?:^|[ \t])--adoption-only(?:[ \t]|$)/u.test(match[2] ?? "") ? "adoption" : "paths";
2878
+ if (skillPath === void 0 || paths.has(mode)) return {
2879
+ kind: "missing",
2880
+ reason: "skill-path-missing"
2881
+ };
2882
+ paths.set(mode, skillPath);
2883
+ }
2884
+ const skillPath = paths.get("paths") ?? paths.get("adoption");
2885
+ if (paths.size === 0 || paths.size === 2 && paths.get("adoption") !== skillPath) return {
2886
+ kind: "missing",
2887
+ reason: "skill-path-missing"
2888
+ };
2889
+ if (skillPath === void 0 || !/^[A-Za-z0-9._/-]+$/.test(skillPath) || skillPath.startsWith("/") || skillPath.endsWith("/") || skillPath.includes("//") || /(?:^|\/)\.{1,2}(?:\/|$)/.test(skillPath)) return {
2890
+ kind: "missing",
2891
+ reason: "skill-path-invalid"
2892
+ };
2893
+ return {
2894
+ kind: "found",
2895
+ skillPath
2896
+ };
2897
+ };
2898
+ var ROOT_AGENTS_IMPORTS = new Set(["@AGENTS.md", "@./AGENTS.md"]);
2899
+ var NESTED_AGENTS_IMPORTS = new Set(["@../AGENTS.md"]);
2900
+ var hasAgentsImport = (text, isNested) => {
2901
+ const imports = isNested ? NESTED_AGENTS_IMPORTS : ROOT_AGENTS_IMPORTS;
2902
+ let fence = null;
2903
+ for (const rawLine of text.replace(/^\uFEFF/u, "").split(/\r\n|\n|\r/u)) {
2904
+ const line = rawLine.replace(/^[ \t]+|[ \t]+$/gu, "");
2905
+ const marker = /^(`{3,}|~{3,})/u.exec(line)?.[1];
2906
+ if (fence !== null) {
2907
+ if (marker !== void 0 && marker[0] === fence[0] && marker.length >= fence.length) fence = null;
2908
+ } else if (marker !== void 0) fence = marker;
2909
+ else if (imports.has(line)) return true;
2910
+ }
2911
+ return false;
2912
+ };
2913
+ var readRetainedText = async (ledger, load) => {
2914
+ const source = await load();
2915
+ const reservation = source.bytes.byteLength * 8;
2916
+ let isReserved = false;
2917
+ try {
2918
+ ledger.reserve(reservation);
2919
+ isReserved = true;
2920
+ let text;
2921
+ try {
2922
+ text = new TextDecoder("utf-8", { fatal: true }).decode(source.bytes);
2923
+ } catch {
2924
+ text = null;
2925
+ }
2926
+ return {
2927
+ text,
2928
+ release: () => ledger.release(reservation)
2929
+ };
2930
+ } catch (error) {
2931
+ if (isReserved) ledger.release(reservation);
2932
+ throw error;
2933
+ } finally {
2934
+ source.release();
2935
+ }
2936
+ };
2937
+ var getAbsentKind = (error) => error instanceof RepositorySourceException ? error.code === "ENTRY_NOT_FOUND" ? "missing" : error.code === "ENTRY_NOT_FILE" ? "non-regular" : null : null;
2938
+ var AGENTS_PATH$1 = parseRepositoryPath("/AGENTS.md");
2939
+ var reportUnresolvedLink = (report, reason) => report("MOLDEA_INTEGRATION_LINK_UNRESOLVED", {
2940
+ entryKind: "symlink",
2941
+ reason
2942
+ }, reason);
2943
+ var checkAgentsDocument = async (context, report, load, entryDetails) => {
2944
+ const { ledger, reader, signal } = context;
2945
+ let document;
2946
+ try {
2947
+ document = await readRetainedText(ledger, load);
2948
+ } catch (error) {
2949
+ const absentKind = getAbsentKind(error);
2950
+ if (absentKind === null) throw error;
2951
+ return entryDetails["entryKind"] === "symlink" ? reportUnresolvedLink(report, absentKind === "missing" ? "missing" : "not-file") : report("MOLDEA_INTEGRATION_BLOCK_MISSING", { entryKind: absentKind });
2952
+ }
2953
+ try {
2954
+ if (document.text === null) return report("MOLDEA_INTEGRATION_BLOCK_MISSING", {
2955
+ ...entryDetails,
2956
+ reason: "invalid-utf8"
2957
+ });
2958
+ const parsed = parseIntegrationBlock(document.text);
2959
+ if (parsed.kind === "missing") return report(parsed.reason.startsWith("block-") ? "MOLDEA_INTEGRATION_BLOCK_MISSING" : "MOLDEA_INTEGRATION_SKILL_MISSING", {
2960
+ ...entryDetails,
2961
+ reason: parsed.reason
2962
+ });
2963
+ const { skillPath } = parsed;
2964
+ for (const file of ["SKILL.md", "scripts/relevance-gate.mjs"]) {
2965
+ const path = parseRepositoryPath(`/${skillPath}/${file}`);
2966
+ const skillEntry = await reader.getEntry(path, signal === void 0 ? void 0 : { signal });
2967
+ if (skillEntry?.type !== "file") return report("MOLDEA_INTEGRATION_SKILL_MISSING", {
2968
+ referencedPath: `/${skillPath}`,
2969
+ missingFile: path,
2970
+ entryKind: skillEntry?.type ?? "missing"
2971
+ });
2972
+ }
2973
+ const assetPath = parseRepositoryPath(`/${skillPath}/assets/managed-agents-block.md`);
2974
+ let asset;
2975
+ try {
2976
+ asset = await readRetainedText(ledger, () => ledger.readSourceFile(assetPath));
2977
+ } catch (error) {
2978
+ const entryKind = getAbsentKind(error);
2979
+ if (entryKind !== null) return report("MOLDEA_INTEGRATION_SKILL_MISSING", {
2980
+ referencedPath: `/${skillPath}`,
2981
+ missingFile: assetPath,
2982
+ entryKind
2983
+ });
2984
+ throw error;
2985
+ }
2986
+ try {
2987
+ if (asset.text === null) return report("MOLDEA_INTEGRATION_BLOCK_STALE", {
2988
+ referencedPath: `/${skillPath}`,
2989
+ reason: "invalid-utf8-asset"
2990
+ });
2991
+ const region = parseManagedIntegrationRegion(document.text);
2992
+ let occurrences = 0;
2993
+ let offset = 0;
2994
+ while ((offset = asset.text.indexOf("{{skill-path}}", offset)) !== -1) {
2995
+ occurrences++;
2996
+ offset += 14;
2997
+ }
2998
+ const renderedReservation = (asset.text.length + occurrences * skillPath.length) * 8;
2999
+ ledger.reserve(renderedReservation);
3000
+ try {
3001
+ const expected = normalizeManagedIntegrationBlock(asset.text.replaceAll("{{skill-path}}", skillPath).replace(/\r\n?/gu, "\n"));
3002
+ if (normalizeManagedIntegrationBlock(document.text.slice(region.start, region.end)) !== expected) return report("MOLDEA_INTEGRATION_BLOCK_STALE", { referencedPath: `/${skillPath}` });
3003
+ } finally {
3004
+ ledger.release(renderedReservation);
3005
+ }
3006
+ } finally {
3007
+ asset.release();
3008
+ }
3009
+ } finally {
3010
+ document.release();
3011
+ }
3012
+ };
3013
+ var inspectAgentsIntegration = async (context) => {
3014
+ const { instructions } = context;
3015
+ const report = (code, details, qualifier) => context.report(code, AGENTS_PATH$1, details, qualifier);
3016
+ const entry = await instructions.getEntry(AGENTS_PATH$1);
3017
+ if (entry === null) {
3018
+ report("MOLDEA_INTEGRATION_BLOCK_MISSING", { entryKind: "missing" });
3019
+ return { kind: "missing" };
3020
+ }
3021
+ if (entry.type === "directory") {
3022
+ report("MOLDEA_INTEGRATION_BLOCK_MISSING", { entryKind: "directory" });
3023
+ return { kind: "directory" };
3024
+ }
3025
+ if (entry.type === "file") {
3026
+ await checkAgentsDocument(context, report, () => instructions.readSourceFile(AGENTS_PATH$1), { entryKind: "file" });
3027
+ return { kind: "file" };
3028
+ }
3029
+ const resolution = await resolveRepositoryLink(instructions, AGENTS_PATH$1);
3030
+ if (resolution.state === "file") {
3031
+ const { targetPath } = resolution;
3032
+ await checkAgentsDocument(context, report, () => instructions.readSourceFile(targetPath), { entryKind: "symlink" });
3033
+ } else reportUnresolvedLink(report, resolution.state);
3034
+ return {
3035
+ kind: "link",
3036
+ resolution
3037
+ };
3038
+ };
3039
+ var AGENTS_PATH = parseRepositoryPath("/AGENTS.md");
3040
+ var CLAUDE_PATH = parseRepositoryPath("/CLAUDE.md");
3041
+ var NESTED_CLAUDE_PATH = parseRepositoryPath("/.claude/CLAUDE.md");
3042
+ var LOCAL_CLAUDE_PATH = parseRepositoryPath("/CLAUDE.local.md");
3043
+ var getAgentsTargetPath = (agents) => {
3044
+ if (agents.kind === "file") return AGENTS_PATH;
3045
+ return agents.kind === "link" && agents.resolution.state === "file" ? agents.resolution.targetPath : null;
3046
+ };
3047
+ var isLinkedToAgents = (path, resolution, agents) => {
3048
+ const agentsTargetPath = getAgentsTargetPath(agents);
3049
+ if (agents.kind === "link" && agentsTargetPath === path) return true;
3050
+ return resolution?.state === "file" && resolution.targetPath === agentsTargetPath;
3051
+ };
3052
+ var assessClaudeFile = async (context, path, agents) => {
3053
+ const { instructions, ledger } = context;
3054
+ const entry = await instructions.getEntry(path);
3055
+ if (entry === null) return { kind: "absent" };
3056
+ if (isLinkedToAgents(path, null, agents)) return { kind: "loads" };
3057
+ if (entry.type === "directory") return {
3058
+ entryKind: "directory",
3059
+ kind: "not-loading"
3060
+ };
3061
+ let load = () => instructions.readSourceFile(path);
3062
+ if (entry.type === "symlink") {
3063
+ const resolution = await resolveRepositoryLink(instructions, path);
3064
+ if (isLinkedToAgents(path, resolution, agents)) return { kind: "loads" };
3065
+ if (resolution.state !== "file") return {
3066
+ kind: "unresolved",
3067
+ reason: resolution.state
3068
+ };
3069
+ const { targetPath } = resolution;
3070
+ load = () => instructions.readSourceFile(targetPath);
3071
+ }
3072
+ let document;
3073
+ try {
3074
+ document = await readRetainedText(ledger, load);
3075
+ } catch (error) {
3076
+ const absentKind = getAbsentKind(error);
3077
+ if (absentKind === null) throw error;
3078
+ if (entry.type !== "symlink") return { kind: "absent" };
3079
+ return {
3080
+ kind: "unresolved",
3081
+ reason: absentKind === "missing" ? "missing" : "not-file"
3082
+ };
3083
+ }
3084
+ try {
3085
+ return document.text !== null && hasAgentsImport(document.text, path === NESTED_CLAUDE_PATH) ? { kind: "loads" } : {
3086
+ entryKind: entry.type,
3087
+ kind: "not-loading"
3088
+ };
3089
+ } finally {
3090
+ document.release();
3091
+ }
3092
+ };
3093
+ var inspectClaudeIntegration = async (context, agents) => {
3094
+ const counted = [];
3095
+ for (const path of [CLAUDE_PATH, NESTED_CLAUDE_PATH]) {
3096
+ const assessment = await assessClaudeFile(context, path, agents);
3097
+ if (assessment.kind === "loads") return;
3098
+ if (assessment.kind !== "absent") counted.push({
3099
+ assessment,
3100
+ path
3101
+ });
3102
+ }
3103
+ if (counted.length === 0) {
3104
+ const assessment = await assessClaudeFile(context, LOCAL_CLAUDE_PATH, agents);
3105
+ if (assessment.kind === "absent" || assessment.kind === "loads") return;
3106
+ counted.push({
3107
+ assessment,
3108
+ path: LOCAL_CLAUDE_PATH
3109
+ });
3110
+ }
3111
+ const unresolved = counted.find(({ assessment }) => assessment.kind === "unresolved");
3112
+ if (unresolved?.assessment.kind === "unresolved") {
3113
+ const { reason } = unresolved.assessment;
3114
+ context.report("MOLDEA_INTEGRATION_LINK_UNRESOLVED", unresolved.path, {
3115
+ entryKind: "symlink",
3116
+ reason
3117
+ }, reason);
3118
+ return;
3119
+ }
3120
+ const governing = counted[0];
3121
+ if (governing?.assessment.kind === "not-loading") context.report("MOLDEA_INTEGRATION_CLAUDE_IMPORT_MISSING", governing.path, { entryKind: governing.assessment.entryKind });
3122
+ };
3123
+ var inspectCodingAgentIntegration = async (reader, instructions, limits, signal) => {
3124
+ const collector = createCoreDiagnosticCollector(limits, "validate-project");
3125
+ const context = {
3126
+ instructions,
3127
+ ledger: getRetainedMemory(reader),
3128
+ reader,
3129
+ report: (code, subject, details, qualifier) => {
3130
+ collector.add({
3131
+ code,
3132
+ path: subject,
3133
+ subject,
3134
+ qualifier: qualifier ?? null,
3135
+ entity: { integrationPath: subject },
3136
+ details
3137
+ });
3138
+ },
3139
+ ...signal === void 0 ? {} : { signal }
3140
+ };
3141
+ await inspectClaudeIntegration(context, await inspectAgentsIntegration(context));
3142
+ return collector.finalize();
3143
+ };
3144
+ var getOwner = (owner) => {
3145
+ if (owner.kind === "context") return {
3146
+ subject: parseRepositoryPath(owner.id),
3147
+ entity: { contextPath: parseRepositoryPath(owner.id) }
3148
+ };
3149
+ if (owner.kind === "decision") return {
3150
+ subject: parseRepositoryPath(owner.id),
3151
+ entity: { decisionId: parseDecisionIdFromPath(parseRepositoryPath(owner.id)) ?? owner.id }
3152
+ };
3153
+ const agentId = owner.agentId ?? owner.id;
3154
+ return {
3155
+ subject: parseRepositoryPath(`/moldea/agents/${agentId}/instruction.md`),
3156
+ entity: {
3157
+ agentId,
3158
+ ...owner.kind === "tool" || owner.kind === "skill" ? {
3159
+ capabilityId: owner.id,
3160
+ capabilityKind: owner.kind
3161
+ } : {}
3162
+ }
3163
+ };
3164
+ };
3165
+ var groupPatterns = (manifest) => {
3166
+ const groups = new Map();
3167
+ for (const declaration of collectManifestScopeDeclarations(manifest)) {
3168
+ if (declaration.field !== "affectedBy" || declaration.declaration.kind !== "glob") continue;
3169
+ const pattern = declaration.declaration.pattern;
3170
+ const segments = pattern.slice(1).split("/");
3171
+ const wildcard = segments.findIndex((segment) => segment.includes("*"));
3172
+ const prefix = parseRepositoryPath("/" + segments.slice(0, wildcard).join("/"));
3173
+ const group = groups.get(prefix) ?? [];
3174
+ group.push({
3175
+ declaration,
3176
+ pattern,
3177
+ segments
3178
+ });
3179
+ groups.set(prefix, group);
3180
+ }
3181
+ return groups;
3182
+ };
3183
+ var inspectImpactPatterns = async (reader, manifest, limits, signal) => {
3184
+ const unmatched = [];
3185
+ try {
3186
+ for (const [prefix, patterns] of groupPatterns(manifest)) {
3187
+ const pending = new Set(patterns);
3188
+ if ((await reader.getEntry(prefix, signal === void 0 ? void 0 : { signal }))?.type === "directory") for await (const candidate of reader.iterateEntries({
3189
+ prefix,
3190
+ ...signal === void 0 ? {} : { signal }
3191
+ })) {
3192
+ if (candidate.type !== "file") continue;
3193
+ for (const pattern of pending) if (matchesRepositoryGlob(pattern.segments, candidate.path)) pending.delete(pattern);
3194
+ if (pending.size === 0) break;
3195
+ }
3196
+ unmatched.push(...pending);
3197
+ }
3198
+ } catch (error) {
3199
+ if (error instanceof CoreOperationException && error.code === "RESOURCE_LIMIT_EXCEEDED" || error instanceof RepositorySourceException && error.code === "RESOURCE_LIMIT_EXCEEDED") return {
3200
+ completed: false,
3201
+ diagnostics: []
3202
+ };
3203
+ throw error;
3204
+ }
3205
+ const collector = createCoreDiagnosticCollector(limits, "validate-project");
3206
+ for (const { declaration, pattern } of unmatched) {
3207
+ const { subject, entity } = getOwner(declaration.owner);
3208
+ collector.add({
3209
+ code: "MOLDEA_IMPACT_PATTERN_UNMATCHED",
3210
+ path: parseRepositoryPath("/moldea/moldea.yaml"),
3211
+ pointer: declaration.pointer,
3212
+ subject,
3213
+ qualifier: pattern,
3214
+ entity,
3215
+ details: {
3216
+ pattern,
3217
+ owner: subject
3218
+ }
3219
+ });
3220
+ }
3221
+ return {
3222
+ completed: true,
3223
+ diagnostics: collector.finalize()
3224
+ };
3225
+ };
3226
+ var identity = (entry) => JSON.stringify([
3227
+ entry.code,
3228
+ entry.subject,
3229
+ entry.qualifier ?? null
3230
+ ]);
3231
+ var applyWarningAcceptances = (diagnostics, entries, completed, limits) => {
3232
+ const acceptances = new Map(entries.map((entry, index) => [identity(entry), {
3233
+ entry,
3234
+ index
3235
+ }]));
3236
+ const matched = new Set();
3237
+ const results = diagnostics.map((diagnostic) => {
3238
+ if (diagnostic.severity !== "warning" || !diagnostic.acceptable || !completed.has(diagnostic.code)) return diagnostic;
3239
+ const key = identity(diagnostic);
3240
+ const acceptance = acceptances.get(key);
3241
+ if (acceptance === void 0) return diagnostic;
3242
+ matched.add(key);
3243
+ return deepFreeze({
3244
+ ...diagnostic,
3245
+ accepted: true,
3246
+ reason: acceptance.entry.reason
3247
+ });
3248
+ });
3249
+ const collector = createCoreDiagnosticCollector(limits, "validate-project");
3250
+ for (const [key, { entry, index }] of acceptances) {
3251
+ if (matched.has(key) || !completed.has(entry.code)) continue;
3252
+ const pointer = `/acceptedWarnings/${index}`;
3253
+ collector.add({
3254
+ code: "MOLDEA_ACCEPTANCE_UNMATCHED",
3255
+ path: parseRepositoryPath("/moldea/moldea.yaml"),
3256
+ pointer,
3257
+ subject: parseRepositoryPath("/moldea/moldea.yaml"),
3258
+ qualifier: pointer,
3259
+ details: {
3260
+ code: entry.code,
3261
+ subject: entry.subject,
3262
+ qualifier: entry.qualifier ?? null
3263
+ }
3264
+ });
3265
+ }
3266
+ return normalizeDiagnostics([...results, ...collector.finalize()]);
3267
+ };
3268
+ var addDiagnostics$2 = (collector, diagnostics) => {
3269
+ for (const diagnostic of diagnostics) collector.merge(diagnostic);
3270
+ };
3271
+ var addMirrorDiagnostic = (collector, code, manifestPath, mirrorPath, pointer, agentId, entry) => {
3272
+ collector.add({
3273
+ code,
3274
+ details: {
3275
+ ...entry === void 0 ? {} : { actualType: entry.type },
3276
+ mirrorPath
3277
+ },
3278
+ entity: { agentId },
3279
+ path: manifestPath,
3280
+ pointer
3281
+ });
3282
+ };
3283
+ var inspectMirror = async (repository, manifestPath, canonicalInstruction, mirrorPath, pointer, agentId, options, collector, operationOptions, signal) => {
3284
+ const entry = await repository.getEntry(mirrorPath, operationOptions);
3285
+ if (entry === null) {
3286
+ addMirrorDiagnostic(collector, "MOLDEA_MIRROR_MISSING", manifestPath, mirrorPath, pointer, agentId);
3287
+ return null;
3288
+ }
3289
+ if (entry.type === "symlink") {
3290
+ addMirrorDiagnostic(collector, "MOLDEA_MIRROR_SYMLINK", manifestPath, mirrorPath, pointer, agentId, entry);
3291
+ return null;
3292
+ }
3293
+ if (entry.type !== "file") {
3294
+ addMirrorDiagnostic(collector, "MOLDEA_MIRROR_NOT_FILE", manifestPath, mirrorPath, pointer, agentId, entry);
3295
+ return null;
3296
+ }
3297
+ const mirrorResult = await readRepositoryTextAsset(repository, mirrorPath, options.limits, signal);
3298
+ addDiagnostics$2(collector, mirrorResult.diagnostics);
3299
+ if (mirrorResult.asset === null) return null;
3300
+ if (mirrorResult.asset.content !== canonicalInstruction.content) {
3301
+ addMirrorDiagnostic(collector, "MOLDEA_MIRROR_STALE", manifestPath, mirrorPath, pointer, agentId);
3302
+ return null;
3303
+ }
3304
+ return {
3305
+ byteLength: mirrorResult.asset.utf8ByteLength,
3306
+ canonicalDigest: canonicalInstruction.digest,
3307
+ digest: mirrorResult.asset.digest,
3308
+ path: mirrorPath,
3309
+ scalarLength: mirrorResult.asset.scalarLength
3310
+ };
3311
+ };
3312
+ var inspectMirrors = async (repository, manifestPath, agents, options, signal) => {
3313
+ options = createCoreOperationOptionsSnapshot(options);
3314
+ const collector = createCoreDiagnosticCollector(options.limits, "validate-project");
3315
+ const agentMirrors = [];
3316
+ const operationOptions = signal === void 0 ? void 0 : { signal };
3317
+ for (const agent of [...agents].sort((left, right) => compareCodePoints(left.id, right.id))) {
3318
+ const mirrors = [];
3319
+ if (agent.instruction !== null) {
3320
+ const declaredMirrors = agent.declaration.mirrors ?? [];
3321
+ for (const [index, mirrorPath] of declaredMirrors.entries()) {
3322
+ const mirror = await inspectMirror(repository, manifestPath, agent.instruction, mirrorPath, `/agents/${escapeJsonPointerSegment(agent.id)}/mirrors/${index}`, agent.id, options, collector, operationOptions, signal);
3323
+ if (mirror !== null) mirrors.push(mirror);
3324
+ }
3325
+ }
3326
+ agentMirrors.push({
3327
+ id: agent.id,
3328
+ mirrors
3329
+ });
3330
+ }
3331
+ const diagnostics = collector.finalize();
3332
+ return deepFreeze({
3333
+ agentMirrors,
3334
+ diagnostics,
3335
+ valid: diagnostics.length === 0
3336
+ });
3337
+ };
3338
+ var addDiagnostics$1 = (collector, diagnostics) => {
3339
+ for (const diagnostic of diagnostics) collector.merge(diagnostic);
3340
+ };
3341
+ var readProjectFile = async (repository, path, options, signal) => {
3342
+ options = createCoreOperationOptionsSnapshot(options);
3343
+ const collector = createCoreDiagnosticCollector(options.limits, "validate-project");
3344
+ let project = null;
3345
+ if (path !== null) {
3346
+ const result = await readRepositoryTextAsset(repository, path, options.limits, signal);
3347
+ addDiagnostics$1(collector, result.diagnostics);
3348
+ if (result.asset !== null) {
3349
+ if (hasNonWhitespace(result.asset.content)) project = result.asset;
3350
+ else collector.add({
3351
+ code: "MOLDEA_PROJECT_FILE_EMPTY",
3352
+ path: result.asset.path
3353
+ });
3354
+ }
3355
+ }
3356
+ const diagnostics = collector.finalize();
3357
+ return deepFreeze({
3358
+ diagnostics,
3359
+ project,
3360
+ valid: diagnostics.length === 0
3361
+ });
3362
+ };
3363
+ var readProjectAssets = async (repository, manifest, discovery, options, signal, projectFile) => {
3364
+ options = createCoreOperationOptionsSnapshot(options);
3365
+ const collector = createCoreDiagnosticCollector(options.limits, "validate-project");
3366
+ const context = [];
3367
+ const inspectedProject = projectFile ?? await readProjectFile(repository, discovery.inventory.project, options, signal);
3368
+ addDiagnostics$1(collector, inspectedProject.diagnostics);
3369
+ for (const path of [...discovery.inventory.context].sort(compareCodePoints)) {
3370
+ const result = await readRepositoryTextAsset(repository, path, options.limits, signal);
3371
+ addDiagnostics$1(collector, result.diagnostics);
3372
+ if (result.asset === null) continue;
3373
+ if (!hasNonWhitespace(result.asset.content)) {
3374
+ collector.add({
3375
+ code: "MOLDEA_CONTEXT_FILE_EMPTY",
3376
+ path
3377
+ });
3378
+ continue;
3379
+ }
3380
+ context.push({
3381
+ asset: result.asset,
3382
+ relationships: manifest?.context?.[path] ?? null
3383
+ });
3384
+ }
3385
+ const diagnostics = collector.finalize();
3386
+ return deepFreeze({
3387
+ context,
3388
+ diagnostics,
3389
+ project: inspectedProject.project,
3390
+ valid: diagnostics.length === 0
3391
+ });
3392
+ };
3393
+ var createIndexedDecisions = (decisions, manifest) => {
3394
+ return [...decisions].sort((left, right) => compareCodePoints(left.id, right.id) || compareCodePoints(left.path, right.path)).map((decision) => ({
3395
+ decision,
3396
+ relationships: manifest.value.decisions?.[decision.path] ?? null
3397
+ }));
3398
+ };
3399
+ var createIndexedAgents = (agents, agentMirrors) => {
3400
+ const mirrorsByAgent = new Map(agentMirrors.map((entry) => [entry.id, entry.mirrors]));
3401
+ const indexedAgents = [];
3402
+ if (mirrorsByAgent.size !== agents.length) return null;
3403
+ for (const agent of [...agents].sort((left, right) => compareCodePoints(left.id, right.id))) {
3404
+ const mirrors = mirrorsByAgent.get(agent.id);
3405
+ if (agent.description === null || agent.instruction === null || mirrors === void 0) return null;
3406
+ indexedAgents.push({
3407
+ context: [...agent.declaration.context ?? []].sort(compareCodePoints),
3408
+ decisions: [...agent.declaration.decisions ?? []].sort(compareCodePoints),
3409
+ declaration: agent.declaration,
3410
+ description: agent.description,
3411
+ id: agent.id,
3412
+ instruction: agent.instruction,
3413
+ mirrors: [...mirrors].sort((left, right) => compareCodePoints(left.path, right.path))
3414
+ });
3415
+ }
3416
+ return indexedAgents;
3417
+ };
3418
+ var createProjectIndex = (input) => {
3419
+ const agents = createIndexedAgents(input.agents, input.agentMirrors);
3420
+ if (agents === null) return null;
3421
+ return deepFreeze({
3422
+ agents,
3423
+ context: [...input.context].sort((left, right) => compareCodePoints(left.asset.path, right.asset.path)),
3424
+ decisions: createIndexedDecisions(input.decisions, input.manifest),
3425
+ formatVersion: 1,
3426
+ manifest: input.manifest,
3427
+ project: input.project
3428
+ });
3429
+ };
3430
+ var isSupportedExportSource = (path) => !/\.d\.(?:ts|tsx|mts|cts)$/.test(path) && /\.(?:ts|tsx|mts|cts|js|mjs|jsx)$/.test(path);
3431
+ var readExportInventory = async (reader, path, byteLength, maxFileBytes) => {
3432
+ if (!isSupportedExportSource(path)) return {
3433
+ kind: "not-checked",
3434
+ reason: "unsupported-file-type"
3435
+ };
3436
+ const ledger = getRetainedMemory(reader);
3437
+ const reservation = 65536 + byteLength * 520;
3438
+ const readHeadroom = Math.max(1, byteLength + Math.min(65536, byteLength));
3439
+ if (byteLength > maxFileBytes || !ledger.tryReserve(reservation + readHeadroom)) return {
3440
+ kind: "not-checked",
3441
+ reason: "resource-limit"
3442
+ };
3443
+ ledger.release(readHeadroom);
3444
+ try {
3445
+ const source = await ledger.readSourceFile(path);
3446
+ try {
3447
+ if (source.bytes.byteLength !== byteLength) throw new RepositorySourceException({
3448
+ code: "INVALID_SOURCE_DATA",
3449
+ operation: "read-file-page",
3450
+ path,
3451
+ retryable: false
3452
+ });
3453
+ const { inventoryExports } = await import("./chunk-fcbcf4e3.mjs");
3454
+ const result = inventoryExports(path, source.bytes);
3455
+ if (result.kind === "parsed") {
3456
+ let bytes = 64;
3457
+ for (const name of result.names) bytes += 64 + name.length * 2;
3458
+ ledger.reserve(bytes);
3459
+ }
3460
+ return result;
3461
+ } finally {
3462
+ source.release();
3463
+ }
3464
+ } finally {
3465
+ ledger.release(reservation);
3466
+ }
3467
+ };
3468
+ var childPointer = (pointer, segment) => {
3469
+ return `${pointer}/${escapeJsonPointerSegment(segment)}`;
3470
+ };
3471
+ var addReferenceCandidates = (candidates, references, pointer, entity, relationship) => {
3472
+ for (const [index, reference] of (references ?? []).entries()) candidates.push({
3473
+ entity,
3474
+ kind: "reference",
3475
+ path: reference.path,
3476
+ pointer: childPointer(pointer, String(index)),
3477
+ ...relationship === void 0 ? {} : { relationship },
3478
+ ...reference.symbol === void 0 ? {} : { symbol: reference.symbol }
3479
+ });
3480
+ };
3481
+ var addImpactCandidates = (candidates, affectedBy, pointer, entity) => {
3482
+ for (const [index, pattern] of (affectedBy ?? []).entries()) {
3483
+ if (pattern.includes("*")) continue;
3484
+ candidates.push({
3485
+ entity,
3486
+ kind: "impact",
3487
+ path: parseRepositoryPath(pattern),
3488
+ pointer: childPointer(pointer, String(index))
3489
+ });
3490
+ }
3491
+ };
3492
+ var addRelationshipCandidates = (candidates, relationship, pointer, entity) => {
3493
+ addReferenceCandidates(candidates, relationship.bindings, childPointer(pointer, "bindings"), entity, pointer.startsWith("/context/") ? "context-binding" : "decision-binding");
3494
+ addImpactCandidates(candidates, relationship.affectedBy, childPointer(pointer, "affectedBy"), entity);
3495
+ };
3496
+ var addCapabilityCandidates = (candidates, capability, capabilityKind, capabilityId, agentId, collectionPointer, additionalReferences = []) => {
3497
+ const capabilityPointer = childPointer(collectionPointer, capabilityId);
3498
+ const capabilityEntity = {
3499
+ agentId,
3500
+ capabilityId,
3501
+ capabilityKind
3502
+ };
3503
+ candidates.push({
3504
+ entity: capabilityEntity,
3505
+ kind: `${capabilityKind}-implementation`,
3506
+ relationship: `${capabilityKind}-implementation`,
3507
+ ...capability.implementation.symbol === void 0 ? {} : { symbol: capability.implementation.symbol },
3508
+ path: capability.implementation.path,
3509
+ pointer: childPointer(capabilityPointer, "implementation")
3510
+ });
3511
+ for (const [property, reference] of [["registration", capability.registration], ...additionalReferences]) if (reference !== void 0) candidates.push({
3512
+ entity: capabilityEntity,
3513
+ kind: "reference",
3514
+ path: reference.path,
3515
+ pointer: childPointer(capabilityPointer, property),
3516
+ relationship: `${capabilityKind}-${property === "inputSchema" ? "input-schema" : property === "outputSchema" ? "output-schema" : "registration"}`,
3517
+ ...reference.symbol === void 0 ? {} : { symbol: reference.symbol }
3518
+ });
3519
+ addImpactCandidates(candidates, capability.affectedBy, childPointer(capabilityPointer, "affectedBy"), capabilityEntity);
3520
+ };
3521
+ var addAgentCandidates = (candidates, agentId, agent) => {
3522
+ const pointer = `/agents/${escapeJsonPointerSegment(agentId)}`;
3523
+ const entity = { agentId };
3524
+ const bindingsPointer = childPointer(pointer, "bindings");
3525
+ const bindings = agent.bindings;
3526
+ for (const property of [
3527
+ "runtimeAgent",
3528
+ "inputSchema",
3529
+ "outputSchema",
3530
+ "instructionLoader"
3531
+ ]) {
3532
+ const reference = bindings?.[property];
3533
+ if (reference !== void 0) candidates.push({
3534
+ entity,
3535
+ kind: "reference",
3536
+ path: reference.path,
3537
+ pointer: childPointer(bindingsPointer, property),
3538
+ relationship: {
3539
+ runtimeAgent: "runtime-agent",
3540
+ inputSchema: "agent-input-schema",
3541
+ outputSchema: "agent-output-schema",
3542
+ instructionLoader: "instruction-loader"
3543
+ }[property],
3544
+ ...reference.symbol === void 0 ? {} : { symbol: reference.symbol }
3545
+ });
3546
+ }
3547
+ addImpactCandidates(candidates, agent.affectedBy, childPointer(pointer, "affectedBy"), entity);
3548
+ const toolsPointer = childPointer(pointer, "tools");
3549
+ for (const capabilityId of Object.keys(agent.tools ?? {}).sort(compareCodePoints)) {
3550
+ const capability = agent.tools?.[capabilityId];
3551
+ if (capability !== void 0) addCapabilityCandidates(candidates, capability, "tool", capabilityId, agentId, toolsPointer, [["inputSchema", capability.inputSchema], ["outputSchema", capability.outputSchema]]);
3552
+ }
3553
+ const skillsPointer = childPointer(pointer, "skills");
3554
+ for (const capabilityId of Object.keys(agent.skills ?? {}).sort(compareCodePoints)) {
3555
+ const capability = agent.skills?.[capabilityId];
3556
+ if (capability !== void 0) addCapabilityCandidates(candidates, capability, "skill", capabilityId, agentId, skillsPointer);
3557
+ }
3558
+ };
3559
+ var collectCandidates = (manifest) => {
3560
+ const candidates = [];
3561
+ for (const property of ["context", "decisions"]) {
3562
+ const relationships = manifest[property];
3563
+ for (const referencedPath of Object.keys(relationships ?? {}).sort(compareCodePoints)) {
3564
+ const relationship = relationships?.[referencedPath];
3565
+ if (relationship === void 0) continue;
3566
+ const pointer = childPointer(`/${property}`, referencedPath);
3567
+ const decisionId = property === "decisions" ? parseDecisionIdFromPath(parseRepositoryPath(referencedPath)) : null;
3568
+ addRelationshipCandidates(candidates, relationship, pointer, decisionId === null ? { contextPath: parseRepositoryPath(referencedPath) } : { decisionId });
3569
+ }
3570
+ }
3571
+ for (const agentId of Object.keys(manifest.agents ?? {}).sort(compareCodePoints)) {
3572
+ const agent = manifest.agents?.[agentId];
3573
+ if (agent !== void 0) addAgentCandidates(candidates, agentId, agent);
3574
+ }
3575
+ return candidates.sort((left, right) => compareCodePoints(left.pointer, right.pointer));
3576
+ };
3577
+ var isBlockedPath = (path, blockedPaths) => {
3578
+ let candidate = path;
3579
+ while (candidate.length > 0) {
3580
+ if (blockedPaths.has(candidate)) return true;
3581
+ const separatorIndex = candidate.lastIndexOf("/");
3582
+ if (separatorIndex <= 0) return false;
3583
+ candidate = candidate.slice(0, separatorIndex);
3584
+ }
3585
+ return false;
3586
+ };
3587
+ var createCandidateDetails = (candidate, entry) => {
3588
+ const details = { [candidate.kind === "impact" ? "impactPath" : "referencedPath"]: candidate.path };
3589
+ if (entry !== null) details["actualType"] = entry.type;
3590
+ if (candidate.kind === "tool-implementation" || candidate.kind === "skill-implementation") details["reason"] = entry === null ? "missing" : entry.type === "symlink" ? "symlink" : "not-file";
3591
+ return details;
3592
+ };
3593
+ var getCandidateCode = (candidate, entry) => {
3594
+ if (entry?.type === "file") return null;
3595
+ if (candidate.kind === "tool-implementation") return "MOLDEA_TOOL_IMPLEMENTATION_MISSING";
3596
+ if (candidate.kind === "skill-implementation") return "MOLDEA_SKILL_IMPLEMENTATION_MISSING";
3597
+ if (candidate.kind === "impact") return entry === null ? "MOLDEA_IMPACT_PATH_MISSING" : "MOLDEA_IMPACT_PATH_NOT_FILE";
3598
+ if (entry === null) return "MOLDEA_REFERENCE_MISSING";
3599
+ return entry.type === "symlink" ? "MOLDEA_REFERENCE_SYMLINK" : "MOLDEA_REFERENCE_NOT_FILE";
3600
+ };
3601
+ var validateCandidate = (candidate, entry, manifestPath, collector) => {
3602
+ const code = getCandidateCode(candidate, entry);
3603
+ if (code === null) return;
3604
+ collector.add({
3605
+ code,
3606
+ details: createCandidateDetails(candidate, entry),
3607
+ entity: candidate.entity,
3608
+ path: manifestPath,
3609
+ pointer: candidate.pointer
3610
+ });
3611
+ };
3612
+ var validateRepositoryReferences = async (repository, manifestPath, manifest, discovery, limits, signal, coverage = []) => {
3613
+ const collector = createCoreDiagnosticCollector(limits, "validate-project");
3614
+ const blockedPaths = new Set(discovery.diagnostics.flatMap((diagnostic) => diagnostic.path === null ? [] : [diagnostic.path]));
3615
+ const inventories = new Map();
3616
+ const entryCache = new Map();
3617
+ const operationOptions = signal === void 0 ? void 0 : { signal };
3618
+ for (const candidate of collectCandidates(manifest)) {
3619
+ if (isBlockedPath(candidate.path, blockedPaths)) continue;
3620
+ let entryPromise = entryCache.get(candidate.path);
3621
+ if (entryPromise === void 0) {
3622
+ entryPromise = repository.getEntry(candidate.path, operationOptions);
3623
+ entryCache.set(candidate.path, entryPromise);
3624
+ }
3625
+ const entry = await entryPromise;
3626
+ validateCandidate(candidate, entry, manifestPath, collector);
3627
+ if (entry?.type !== "file" || candidate.relationship === void 0) continue;
3628
+ if (entry.byteLength === null) throw new TypeError("A repository file entry must declare its byte length.");
3629
+ if (coverage.length >= limits.maxCoverage) throw new CoreOperationException({
3630
+ code: "RESOURCE_LIMIT_EXCEEDED",
3631
+ operation: "validate-project",
3632
+ limit: "maxCoverage",
3633
+ limitMaximum: limits.maxCoverage,
3634
+ observedUsage: coverage.length + 1,
3635
+ nextAction: "reduce-input-or-increase-limit"
3636
+ });
3637
+ const base = {
3638
+ entity: candidate.entity ?? {},
3639
+ relationship: candidate.relationship,
3640
+ path: candidate.path,
3641
+ symbol: candidate.symbol ?? null,
3642
+ fileCheck: "passed"
3643
+ };
3644
+ let record;
3645
+ if (candidate.symbol === void 0) record = {
3646
+ ...base,
3647
+ exportCheck: "not-checked",
3648
+ exportNotCheckedReason: "no-symbol"
3649
+ };
3650
+ else {
3651
+ let inventory = inventories.get(candidate.path);
3652
+ if (inventory === void 0) {
3653
+ inventory = await readExportInventory(repository, candidate.path, entry.byteLength, limits.maxFileBytes);
3654
+ inventories.set(candidate.path, inventory);
3655
+ }
3656
+ if (inventory.kind === "not-checked") record = {
3657
+ ...base,
3658
+ exportCheck: "not-checked",
3659
+ exportNotCheckedReason: inventory.reason
3660
+ };
3661
+ else if (!inventory.complete) record = {
3662
+ ...base,
3663
+ exportCheck: "not-checked",
3664
+ exportNotCheckedReason: "unresolved-exports"
3665
+ };
3666
+ else if (inventory.names.has(candidate.symbol)) record = {
3667
+ ...base,
3668
+ exportCheck: "passed"
3669
+ };
3670
+ else {
3671
+ record = {
3672
+ ...base,
3673
+ exportCheck: "failed"
3674
+ };
3675
+ collector.add({
3676
+ code: "MOLDEA_REFERENCE_EXPORT_MISSING",
3677
+ entity: candidate.entity,
3678
+ path: manifestPath,
3679
+ pointer: candidate.pointer,
3680
+ details: {
3681
+ referencedPath: candidate.path,
3682
+ symbol: candidate.symbol,
3683
+ relationship: candidate.relationship
3684
+ }
3685
+ });
3686
+ }
3687
+ }
3688
+ reserveRetainedBytesIfTracked(repository, 512 + JSON.stringify(record).length * 2);
3689
+ coverage.push(record);
3690
+ }
3691
+ return collector.finalize();
3692
+ };
3693
+ var MOLDEA_ROOT = parseRepositoryPath("/moldea");
3694
+ var MANIFEST_PATH = parseRepositoryPath("/moldea/moldea.yaml");
3695
+ var PROJECT_PATH = parseRepositoryPath("/moldea/project.md");
3696
+ var addDiagnostics = (collector, diagnostics) => {
3697
+ for (const diagnostic of diagnostics) collector.merge(diagnostic);
3698
+ };
3699
+ var inspectUniversalProject = async (context, options) => {
3700
+ options = createCoreOperationOptionsSnapshot(options);
3701
+ const { session, signal } = context;
3702
+ const coverage = [];
3703
+ const collector = createCoreDiagnosticCollector(options.limits, "validate-project");
3704
+ const operationOptions = signal === void 0 ? void 0 : { signal };
3705
+ const yamlRoots = new Map();
3706
+ const memory = getRetainedMemory(session.reader);
3707
+ let retainedYamlBytes = 0;
3708
+ const retainYamlRoot = (path, root) => {
3709
+ const bytes = measureYamlRetainedBytes(root);
3710
+ memory.reserve(bytes);
3711
+ retainedYamlBytes += bytes;
3712
+ yamlRoots.set(path, root);
3713
+ };
3714
+ try {
3715
+ const moldeaRoot = await session.reader.getEntry(MOLDEA_ROOT, operationOptions);
3716
+ let manifestEntry = null;
3717
+ let projectEntry = null;
3718
+ let indexedManifest = null;
3719
+ let formatVersion = null;
3720
+ if (moldeaRoot?.type === "directory") {
3721
+ manifestEntry = await session.reader.getEntry(MANIFEST_PATH, operationOptions);
3722
+ if (manifestEntry?.type === "file") {
3723
+ const parsedManifest = await inspectManifestDocument({
3724
+ content: await session.reader.readCompleteFile(MANIFEST_PATH, operationOptions),
3725
+ path: MANIFEST_PATH
3726
+ }, options, "validate-project");
3727
+ if (parsedManifest.manifest !== null && parsedManifest.yamlRoot !== null) retainYamlRoot(MANIFEST_PATH, parsedManifest.yamlRoot);
3728
+ formatVersion = parsedManifest.formatVersion;
3729
+ addDiagnostics(collector, parsedManifest.diagnostics);
3730
+ if (parsedManifest.asset !== null && parsedManifest.manifest !== null) indexedManifest = {
3731
+ asset: parsedManifest.asset,
3732
+ value: parsedManifest.manifest
3733
+ };
3734
+ }
3735
+ projectEntry = await session.reader.getEntry(PROJECT_PATH, operationOptions);
3736
+ }
3737
+ const projectFile = await readProjectFile(session.reader, projectEntry?.type === "file" ? PROJECT_PATH : null, options, signal);
3738
+ addDiagnostics(collector, projectFile.diagnostics);
3739
+ const discovery = await discoverCanonicalAssets(session.reader, options.limits, signal, {
3740
+ manifest: manifestEntry,
3741
+ moldeaRoot,
3742
+ project: projectEntry
3743
+ });
3744
+ addDiagnostics(collector, discovery.diagnostics);
3745
+ session.throwIfAborted();
3746
+ const projectAssets = await readProjectAssets(session.reader, indexedManifest?.value ?? null, discovery, options, signal, projectFile);
3747
+ addDiagnostics(collector, projectAssets.diagnostics);
3748
+ const decisionGraph = await readDecisionGraph(session.reader, discovery.inventory.decisions, options, signal, retainYamlRoot);
3749
+ addDiagnostics(collector, decisionGraph.diagnostics);
3750
+ let agents = [];
3751
+ let agentMirrors = [];
3752
+ if (indexedManifest !== null) {
3753
+ const manifestPath = indexedManifest.asset.path;
3754
+ const agentAssets = await inspectAgentAssets(session.reader, indexedManifest.value, discovery, options, signal);
3755
+ agents = agentAssets.agents;
3756
+ addDiagnostics(collector, agentAssets.diagnostics);
3757
+ addDiagnostics(collector, validateManifestRelationships(manifestPath, indexedManifest.value, discovery, decisionGraph.decisions, options.limits));
3758
+ addDiagnostics(collector, await validateRepositoryReferences(session.reader, manifestPath, indexedManifest.value, discovery, options.limits, signal, coverage));
3759
+ const mirrorInspection = await inspectMirrors(session.reader, manifestPath, agents, options, signal);
3760
+ agentMirrors = mirrorInspection.agentMirrors;
3761
+ addDiagnostics(collector, mirrorInspection.diagnostics);
3762
+ }
3763
+ session.throwIfAborted();
3764
+ addDiagnostics(collector, await inspectCodingAgentIntegration(session.reader, session.instructions, options.limits, signal));
3765
+ const patterns = indexedManifest === null ? {
3766
+ completed: false,
3767
+ diagnostics: []
3768
+ } : await inspectImpactPatterns(session.reader, indexedManifest.value, options.limits, signal);
3769
+ session.throwIfAborted();
3770
+ addDiagnostics(collector, patterns.diagnostics);
3771
+ const diagnostics = locateDiagnosticRanges(applyWarningAcceptances(collector.finalize(), indexedManifest?.value.acceptedWarnings ?? [], new Set([...[
3772
+ "MOLDEA_INTEGRATION_BLOCK_MISSING",
3773
+ "MOLDEA_INTEGRATION_SKILL_MISSING",
3774
+ "MOLDEA_INTEGRATION_BLOCK_STALE",
3775
+ "MOLDEA_INTEGRATION_LINK_UNRESOLVED",
3776
+ "MOLDEA_INTEGRATION_CLAUDE_IMPORT_MISSING"
3777
+ ], ...patterns.completed ? ["MOLDEA_IMPACT_PATTERN_UNMATCHED"] : []]), options.limits), yamlRoots);
3778
+ const project = !diagnostics.some((diagnostic) => diagnostic.severity === "error") && indexedManifest !== null && projectAssets.project !== null ? createProjectIndex({
3779
+ agentMirrors,
3780
+ agents,
3781
+ context: projectAssets.context,
3782
+ decisions: decisionGraph.decisions,
3783
+ manifest: indexedManifest,
3784
+ project: projectAssets.project
3785
+ }) : null;
3786
+ return deepFreeze({
3787
+ diagnostics,
3788
+ coverage,
3789
+ formatVersion,
3790
+ project
3791
+ });
3792
+ } finally {
3793
+ yamlRoots.clear();
3794
+ memory.release(retainedYamlBytes);
3795
+ }
3796
+ };
3797
+ var invalidArgument$1 = () => {
3798
+ throw new CoreOperationException({
3799
+ code: "INVALID_ARGUMENT",
3800
+ operation: "validate-project"
3801
+ });
3802
+ };
3803
+ var isRepositoryReader = (candidate) => {
3804
+ return isObjectValid(candidate, true) && isObjectValid(candidate["snapshot"], true) && typeof candidate["snapshot"]["id"] === "string" && typeof candidate["snapshot"]["sourceKind"] === "string" && typeof candidate["compare"] === "function" && typeof candidate["getEntry"] === "function" && typeof candidate["listEntriesPage"] === "function" && typeof candidate["readFilePage"] === "function" && typeof candidate["readLinkText"] === "function";
3805
+ };
3806
+ var isAbortSignal = (candidate) => {
3807
+ return isObjectValid(candidate, true) && typeof candidate["aborted"] === "boolean" && typeof candidate["addEventListener"] === "function" && typeof candidate["removeEventListener"] === "function";
3808
+ };
3809
+ var validateInput = (candidate) => {
3810
+ try {
3811
+ if (!isObjectValid(candidate, true)) return invalidArgument$1();
3812
+ const repository = candidate["repository"];
3813
+ const instructions = candidate["instructions"];
3814
+ const signal = candidate["signal"];
3815
+ if (Reflect.ownKeys(candidate).some((key) => key !== "repository" && key !== "instructions" && key !== "signal") || !isRepositoryReader(repository) || instructions !== void 0 && !isRepositoryReader(instructions) || signal !== void 0 && !isAbortSignal(signal)) return invalidArgument$1();
3816
+ return {
3817
+ ...instructions === void 0 ? {} : { instructions },
3818
+ repository,
3819
+ ...signal === void 0 ? {} : { signal }
3820
+ };
3821
+ } catch (error) {
3822
+ if (error instanceof CoreOperationException) throw error;
3823
+ return invalidArgument$1();
3824
+ }
3825
+ };
3826
+ var validateProjectState = async (input, options) => {
3827
+ const validatedInput = validateInput(input);
3828
+ const operationOptions = createCoreOperationOptionsSnapshot(options);
3829
+ const session = createRepositoryInspectionSession(validatedInput.repository, operationOptions.limits, validatedInput.signal, validatedInput.instructions);
3830
+ const universal = await inspectUniversalProject({
3831
+ session,
3832
+ ...validatedInput.signal === void 0 ? {} : { signal: validatedInput.signal }
3833
+ }, operationOptions);
3834
+ session.throwIfAborted();
3835
+ const counts = countDiagnosticsBySeverity(universal.diagnostics);
3836
+ return deepFreeze({
3837
+ project: universal.project,
3838
+ resourceUsage: session.getResourceUsage(),
3839
+ result: {
3840
+ diagnostics: universal.diagnostics,
3841
+ ...counts,
3842
+ coverage: universal.coverage,
3843
+ coverageCounts: countBindingCoverage(universal.coverage),
3844
+ formatVersion: universal.formatVersion,
3845
+ source: validatedInput.repository.snapshot,
3846
+ summary: universal.project === null ? null : createProjectSummary(universal.project),
3847
+ valid: counts.errorCount === 0
3848
+ }
3849
+ });
3850
+ };
3851
+ var validateProject = async (input, options) => (await validateProjectState(input, options)).result;
3852
+ var CURSOR_PREFIX = "core7";
3853
+ var PREPARED_FIXED_BYTES = 512;
3854
+ var PREPARED_ITEM_FIXED_BYTES = 64;
3855
+ var PREPARED_TEXT_BYTE_MULTIPLIER = 2;
3856
+ var PREPARED_VIEW_REFERENCE_BYTES = 8;
3857
+ var encoder = new TextEncoder();
3858
+ var invalidArgument = () => {
3859
+ throw new CoreOperationException({
3860
+ code: "INVALID_ARGUMENT",
3861
+ operation: "create-project-inspection"
3862
+ });
3863
+ };
3864
+ var resourceLimitExceeded = (limitMaximum, observedUsage) => {
3865
+ throw new CoreOperationException({
3866
+ code: "RESOURCE_LIMIT_EXCEEDED",
3867
+ limit: "maxRetainedBytes",
3868
+ limitMaximum,
3869
+ nextAction: "reduce-input-or-increase-limit",
3870
+ observedUsage,
3871
+ operation: "create-project-inspection"
3872
+ });
3873
+ };
3874
+ var serializeDeterministically = (candidate) => {
3875
+ if (candidate === null || typeof candidate !== "object") {
3876
+ const serialized = JSON.stringify(candidate);
3877
+ return serialized === void 0 ? "null" : serialized;
3878
+ }
3879
+ if (Array.isArray(candidate)) return `[${candidate.map((item) => serializeDeterministically(item)).join(",")}]`;
3880
+ return `{${Object.entries(candidate).filter(([, value]) => value !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, value]) => `${JSON.stringify(key)}:${serializeDeterministically(value)}`).join(",")}}`;
3881
+ };
3882
+ var createIdentity = (parts) => createRepositoryIdentity((function* () {
3883
+ for (const part of parts) yield encoder.encode(part);
3884
+ })());
3885
+ var createItemBaseKey = (item) => {
3886
+ if (item.kind === "agent") return ["3", item.agent.agentId].join("\0");
3887
+ if (item.kind === "metadata") return [
3888
+ "0",
3889
+ item.metadata.path,
3890
+ item.metadata.kind,
3891
+ item.metadata.agentId ?? "",
3892
+ item.metadata.decisionId ?? "",
3893
+ item.metadata.digest
3894
+ ].join(":");
3895
+ if (item.kind === "diagnostic") return [
3896
+ "1",
3897
+ item.diagnostic.source,
3898
+ item.diagnostic.code,
3899
+ item.diagnostic.path ?? "",
3900
+ createIdentity([serializeDeterministically(item.diagnostic)])
3901
+ ].join(":");
3902
+ return [
3903
+ "2",
3904
+ item.coverage.path,
3905
+ item.coverage.relationship,
3906
+ item.coverage.entity.agentId ?? "",
3907
+ createIdentity([serializeDeterministically(item.coverage)])
3908
+ ].join(":");
3909
+ };
3910
+ var createKeyedItems = (items) => {
3911
+ const sorted = Array.from(items, (item) => ({
3912
+ item,
3913
+ key: createItemBaseKey(item)
3914
+ })).sort((left, right) => left.key < right.key ? -1 : left.key > right.key ? 1 : 0);
3915
+ let previousBaseKey = null;
3916
+ let occurrence = 0;
3917
+ for (const item of sorted) {
3918
+ const baseKey = item.key;
3919
+ occurrence = baseKey === previousBaseKey ? occurrence + 1 : 0;
3920
+ previousBaseKey = baseKey;
3921
+ item.key = `${baseKey}:${String(occurrence).padStart(10, "0")}`;
3922
+ }
3923
+ return sorted;
3924
+ };
3925
+ var createCursorChecksum = (inspectionDigest, lastKey, view) => createIdentity([
3926
+ CURSOR_PREFIX,
3927
+ inspectionDigest,
3928
+ lastKey,
3929
+ view
3930
+ ]);
3931
+ var encodeCursor = (inspectionDigest, view, lastKey) => [
3932
+ CURSOR_PREFIX,
3933
+ view,
3934
+ encodeURIComponent(lastKey),
3935
+ inspectionDigest,
3936
+ createCursorChecksum(inspectionDigest, lastKey, view)
3937
+ ].join(":");
3938
+ var decodeCursor = (cursor, inspectionDigest, view) => {
3939
+ if (cursor === void 0) return null;
3940
+ const match = /^core7:(all|diagnostics|coverage|metadata):([^:]+):(sha256:[0-9a-f]{64}):(sha256:[0-9a-f]{64})$/u.exec(cursor);
3941
+ if (match === null || match[1] !== view || match[3] !== inspectionDigest) return invalidArgument();
3942
+ let lastKey;
3943
+ try {
3944
+ lastKey = decodeURIComponent(match[2]);
3945
+ } catch {
3946
+ return invalidArgument();
3947
+ }
3948
+ if (lastKey.length === 0 || match[4] !== createCursorChecksum(inspectionDigest, lastKey, view)) return invalidArgument();
3949
+ return lastKey;
3950
+ };
3951
+ var createViews = (items) => deepFreeze({
3952
+ all: items,
3953
+ diagnostics: items.filter(({ item }) => item.kind === "diagnostic"),
3954
+ coverage: items.filter(({ item }) => item.kind === "coverage"),
3955
+ metadata: items.filter(({ item }) => item.kind === "metadata" || item.kind === "agent")
3956
+ });
3957
+ var addRetainedBytes = (current, additional, retainedBeforePreparation, maximum) => {
3958
+ const projectedUsage = retainedBeforePreparation + current + additional;
3959
+ if (!Number.isSafeInteger(additional) || additional < 0 || !Number.isSafeInteger(projectedUsage) || projectedUsage > maximum) return resourceLimitExceeded(maximum, Number.isSafeInteger(projectedUsage) ? projectedUsage : Number.MAX_SAFE_INTEGER);
3960
+ return current + additional;
3961
+ };
3962
+ var iterateProjectInspectionItems = function* (state) {
3963
+ if (state.project !== null) for (const metadata of iterateProjectMetadata(state.project)) yield {
3964
+ kind: "metadata",
3965
+ metadata
3966
+ };
3967
+ for (const diagnostic of state.result.diagnostics) yield {
3968
+ diagnostic,
3969
+ kind: "diagnostic"
3970
+ };
3971
+ for (const coverage of state.result.coverage) yield {
3972
+ coverage,
3973
+ kind: "coverage"
3974
+ };
3975
+ if (state.project !== null) for (const agent of iterateProjectAgentAssignments(state.project)) yield {
3976
+ agent,
3977
+ kind: "agent"
3978
+ };
3979
+ };
3980
+ var estimatePreparedProjectInspection = (state, baseCounts, maximum) => {
3981
+ const retainedBeforePreparation = state.resourceUsage.retainedBytes;
3982
+ let bytes = addRetainedBytes(0, PREPARED_FIXED_BYTES, retainedBeforePreparation, maximum);
3983
+ let metadataCount = 0;
3984
+ for (const item of iterateProjectInspectionItems(state)) {
3985
+ const key = `${createItemBaseKey(item)}:0000000000`;
3986
+ const encodedBytes = encoder.encode(key).byteLength + encoder.encode(serializeDeterministically(item)).byteLength;
3987
+ bytes = addRetainedBytes(bytes, PREPARED_ITEM_FIXED_BYTES + encodedBytes * PREPARED_TEXT_BYTE_MULTIPLIER + PREPARED_VIEW_REFERENCE_BYTES, retainedBeforePreparation, maximum);
3988
+ if (item.kind === "metadata") metadataCount += 1;
3989
+ }
3990
+ const counts = {
3991
+ agents: baseCounts.agents,
3992
+ context: baseCounts.context,
3993
+ decisions: baseCounts.decisions,
3994
+ diagnostics: baseCounts.diagnostics,
3995
+ errors: baseCounts.errors,
3996
+ coverage: baseCounts.coverage,
3997
+ metadata: metadataCount,
3998
+ mirrors: baseCounts.mirrors,
3999
+ warnings: baseCounts.warnings,
4000
+ acceptedWarnings: baseCounts.acceptedWarnings
4001
+ };
4002
+ bytes = addRetainedBytes(bytes, encoder.encode(serializeDeterministically({
4003
+ counts,
4004
+ formatVersion: state.result.formatVersion,
4005
+ inspectionDigest: "sha256:0000000000000000000000000000000000000000000000000000000000000000",
4006
+ source: state.result.source,
4007
+ summary: state.result.summary,
4008
+ valid: state.result.valid
4009
+ })).byteLength * PREPARED_TEXT_BYTE_MULTIPLIER, retainedBeforePreparation, maximum);
4010
+ return {
4011
+ counts,
4012
+ preparedBytes: bytes
4013
+ };
4014
+ };
4015
+ var createInspectionDigest = (counts, coverageCounts, formatVersion, items, summary, valid) => createIdentity((function* () {
4016
+ yield "core7-prepared-inspection";
4017
+ yield serializeDeterministically({
4018
+ counts,
4019
+ coverageCounts,
4020
+ formatVersion,
4021
+ summary,
4022
+ valid
4023
+ });
4024
+ for (const { key } of items) yield key;
4025
+ })());
4026
+ var findStartIndex = (items, lastKey) => {
4027
+ if (lastKey === null) return 0;
4028
+ let lower = 0;
4029
+ let upper = items.length - 1;
4030
+ while (lower <= upper) {
4031
+ const middle = lower + Math.floor((upper - lower) / 2);
4032
+ const candidate = items[middle];
4033
+ if (candidate === void 0) return invalidArgument();
4034
+ if (candidate.key === lastKey) return middle + 1;
4035
+ if (candidate.key < lastKey) lower = middle + 1;
4036
+ else upper = middle - 1;
4037
+ }
4038
+ return invalidArgument();
4039
+ };
4040
+ var createPreparedProjectInspection = (input) => {
4041
+ const { counts, coverageCounts, formatVersion, items, maxEntries, preparedBytes, resourceUsage: validationUsage, source, summary, valid } = input;
4042
+ const views = createViews(items);
4043
+ const inspectionDigest = createInspectionDigest(counts, coverageCounts, formatVersion, items, summary, valid);
4044
+ const resourceUsage = deepFreeze({
4045
+ canonicalBytes: validationUsage.canonicalBytes,
4046
+ peakRetainedBytes: Math.max(validationUsage.peakRetainedBytes, validationUsage.retainedBytes + preparedBytes),
4047
+ preparedBytes,
4048
+ retainedBytes: preparedBytes,
4049
+ totalBytesRead: validationUsage.totalBytesRead
4050
+ });
4051
+ const readPage = (pageInput) => {
4052
+ if (typeof pageInput !== "object" || pageInput === null || Reflect.ownKeys(pageInput).some((key) => key !== "cursor" && key !== "maxItems" && key !== "view") || !Number.isSafeInteger(pageInput.maxItems) || pageInput.maxItems < 1 || pageInput.maxItems > maxEntries || pageInput.cursor !== void 0 && typeof pageInput.cursor !== "string" || pageInput.view !== "all" && pageInput.view !== "diagnostics" && pageInput.view !== "coverage" && pageInput.view !== "metadata") return invalidArgument();
4053
+ const viewItems = views[pageInput.view];
4054
+ const startIndex = findStartIndex(viewItems, decodeCursor(pageInput.cursor, inspectionDigest, pageInput.view));
4055
+ const records = viewItems.slice(startIndex, startIndex + pageInput.maxItems).map(({ item, key }, index) => {
4056
+ return {
4057
+ item,
4058
+ nextCursor: startIndex + index + 1 >= viewItems.length ? null : encodeCursor(inspectionDigest, pageInput.view, key)
4059
+ };
4060
+ });
4061
+ const nextCursor = records.at(-1)?.nextCursor ?? null;
4062
+ return deepFreeze({
4063
+ counts,
4064
+ coverageCounts,
4065
+ formatVersion,
4066
+ inspectionDigest,
4067
+ page: {
4068
+ isComplete: nextCursor === null,
4069
+ nextCursor,
4070
+ records,
4071
+ totalItems: viewItems.length
4072
+ },
4073
+ source,
4074
+ summary,
4075
+ valid,
4076
+ view: pageInput.view
4077
+ });
4078
+ };
4079
+ return deepFreeze({
4080
+ counts,
4081
+ coverageCounts,
4082
+ formatVersion,
4083
+ inspectionDigest,
4084
+ readPage,
4085
+ resourceUsage,
4086
+ source,
4087
+ summary,
4088
+ valid
4089
+ });
4090
+ };
4091
+ var createProjectInspection = async (input, options) => {
4092
+ const state = await validateProjectState(input, options);
4093
+ const estimate = estimatePreparedProjectInspection(state, {
4094
+ agents: state.result.summary?.counts.agents ?? 0,
4095
+ context: state.result.summary?.counts.context ?? 0,
4096
+ decisions: state.result.summary?.counts.decisions ?? 0,
4097
+ diagnostics: state.result.diagnostics.length,
4098
+ errors: state.result.errorCount,
4099
+ coverage: state.result.coverage.length,
4100
+ mirrors: state.result.summary?.counts.mirrors ?? 0,
4101
+ warnings: state.result.warningCount,
4102
+ acceptedWarnings: state.result.acceptedWarningCount
4103
+ }, options.limits.maxRetainedBytes);
4104
+ const counts = deepFreeze(estimate.counts);
4105
+ const items = deepFreeze(createKeyedItems(iterateProjectInspectionItems(state)));
4106
+ return createPreparedProjectInspection({
4107
+ counts,
4108
+ coverageCounts: state.result.coverageCounts,
4109
+ formatVersion: state.result.formatVersion,
4110
+ items,
4111
+ maxEntries: options.limits.maxEntries,
4112
+ preparedBytes: estimate.preparedBytes,
4113
+ resourceUsage: state.resourceUsage,
4114
+ source: state.result.source,
4115
+ summary: state.result.summary,
4116
+ valid: state.result.valid
4117
+ });
4118
+ };
4119
+ var core_exports = __exportAll({ createCore: () => createCore });
4120
+ var createCore = (options) => {
4121
+ const snapshot = normalizeCoreOptions(options);
4122
+ return deepFreeze({
4123
+ calculateContentDigest: (input) => {
4124
+ return calculateContentDigest(input, createCoreOperationOptionsSnapshot(snapshot).limits);
4125
+ },
4126
+ createProjectInspection: (input) => createProjectInspection(input, createCoreOperationOptionsSnapshot(snapshot)),
4127
+ validateProject: (input) => validateProject(input, createCoreOperationOptionsSnapshot(snapshot)),
4128
+ matchManifestScope: (input) => matchManifestScope(input, createCoreOperationOptionsSnapshot(snapshot)),
4129
+ normalizeText: (input) => {
4130
+ return normalizeTextDocument(input, createCoreOperationOptionsSnapshot(snapshot).limits, "normalize-text");
4131
+ },
4132
+ parseDecision: (input) => parseDecisionDocument(input, createCoreOperationOptionsSnapshot(snapshot)),
4133
+ parseManifest: (input) => parseManifestDocument(input, createCoreOperationOptionsSnapshot(snapshot)),
4134
+ readCanonicalContentPage: (input) => readCanonicalContentPage(input, createCoreOperationOptionsSnapshot(snapshot))
4135
+ });
4136
+ };
4137
+ //#endregion
4138
+ export { parseIntegrationBlock as i, createCore as n, isSupportedExportSource as r, core_exports as t };