@moldea.ai/core 5.0.1 → 7.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.
- package/README.md +12 -11
- package/dist/analysis-worker.js +180 -0
- package/dist/analysis-worker.js.map +1 -0
- package/dist/binding-coverage/index.d.ts +26 -0
- package/dist/binding-coverage/index.d.ts.map +1 -0
- package/dist/chunks/core-Cdeiu6xG.js +3364 -0
- package/dist/chunks/core-Cdeiu6xG.js.map +1 -0
- package/dist/chunks/errors-BE4DS3Ak.js +435 -0
- package/dist/chunks/errors-BE4DS3Ak.js.map +1 -0
- package/dist/chunks/{exceptions-HS9ofVy2.js → exceptions-IXsorE8t.js} +27 -28
- package/dist/chunks/exceptions-IXsorE8t.js.map +1 -0
- package/dist/chunks/lifecycle-D_RvxhDC.js +67 -0
- package/dist/chunks/lifecycle-D_RvxhDC.js.map +1 -0
- package/dist/chunks/options-5x9gu2Qb.js +604 -0
- package/dist/chunks/options-5x9gu2Qb.js.map +1 -0
- package/dist/chunks/repository-rpc-B_y0Kspf.js +124 -0
- package/dist/chunks/repository-rpc-B_y0Kspf.js.map +1 -0
- package/dist/chunks/scope-AGMcHUE_.js +1827 -0
- package/dist/chunks/scope-AGMcHUE_.js.map +1 -0
- package/dist/chunks/syntax-CVvExx4R.js +137 -0
- package/dist/chunks/syntax-CVvExx4R.js.map +1 -0
- package/dist/constants/index.d.ts +2 -1
- package/dist/constants/index.d.ts.map +1 -1
- package/dist/contracts/index.d.ts +37 -27
- package/dist/contracts/index.d.ts.map +1 -1
- package/dist/core/index.d.ts +1 -4
- package/dist/core/index.d.ts.map +1 -1
- package/dist/decision/index.d.ts +1 -1
- package/dist/decision-graph/index.d.ts +9 -7
- package/dist/decision-graph/index.d.ts.map +1 -1
- package/dist/diagnostic-utilities/index.d.ts +6 -2
- package/dist/diagnostic-utilities/index.d.ts.map +1 -1
- package/dist/diagnostics/index.d.ts +21 -33
- package/dist/diagnostics/index.d.ts.map +1 -1
- package/dist/exceptions/index.d.ts +25 -10
- package/dist/exceptions/index.d.ts.map +1 -1
- package/dist/export-inventory/index.d.ts +3 -0
- package/dist/export-inventory/index.d.ts.map +1 -0
- package/dist/export-inventory/inventory.d.ts +22 -0
- package/dist/export-inventory/inventory.d.ts.map +1 -0
- package/dist/export-inventory/syntax.d.ts +4 -0
- package/dist/export-inventory/syntax.d.ts.map +1 -0
- package/dist/export-inventory/types.d.ts +9 -0
- package/dist/export-inventory/types.d.ts.map +1 -0
- package/dist/format/index.d.ts +8 -0
- package/dist/format/index.d.ts.map +1 -1
- package/dist/impact-pattern-validation/index.d.ts +2 -0
- package/dist/impact-pattern-validation/index.d.ts.map +1 -0
- package/dist/impact-pattern-validation/inspection.d.ts +24 -0
- package/dist/impact-pattern-validation/inspection.d.ts.map +1 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -5776
- package/dist/integration-validation/index.d.ts +4 -0
- package/dist/integration-validation/index.d.ts.map +1 -0
- package/dist/integration-validation/inspection.d.ts +18 -0
- package/dist/integration-validation/inspection.d.ts.map +1 -0
- package/dist/integration-validation/parser.d.ts +9 -0
- package/dist/integration-validation/parser.d.ts.map +1 -0
- package/dist/integration-validation/types.d.ts +13 -0
- package/dist/integration-validation/types.d.ts.map +1 -0
- package/dist/manifest/index.d.ts +2 -4
- package/dist/manifest/index.d.ts.map +1 -1
- package/dist/manifest-validation/index.d.ts +7 -10
- package/dist/manifest-validation/index.d.ts.map +1 -1
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.d.ts.map +1 -0
- package/dist/node-inspection/analysis-worker.d.ts +2 -0
- package/dist/node-inspection/analysis-worker.d.ts.map +1 -0
- package/dist/node-inspection/client.d.ts +28 -0
- package/dist/node-inspection/client.d.ts.map +1 -0
- package/dist/node-inspection/constants.d.ts +21 -0
- package/dist/node-inspection/constants.d.ts.map +1 -0
- package/dist/node-inspection/errors.d.ts +11 -0
- package/dist/node-inspection/errors.d.ts.map +1 -0
- package/dist/node-inspection/lifecycle.d.ts +15 -0
- package/dist/node-inspection/lifecycle.d.ts.map +1 -0
- package/dist/node-inspection/protocol.d.ts +20 -0
- package/dist/node-inspection/protocol.d.ts.map +1 -0
- package/dist/node-inspection/repository-rpc.d.ts +28 -0
- package/dist/node-inspection/repository-rpc.d.ts.map +1 -0
- package/dist/node-inspection/runner.d.ts +2 -0
- package/dist/node-inspection/runner.d.ts.map +1 -0
- package/dist/node-inspection/types.d.ts +95 -0
- package/dist/node-inspection/types.d.ts.map +1 -0
- package/dist/node-runner.js +149 -0
- package/dist/node-runner.js.map +1 -0
- package/dist/node.js +335 -0
- package/dist/node.js.map +1 -0
- package/dist/options/index.d.ts +2 -14
- package/dist/options/index.d.ts.map +1 -1
- package/dist/project-inspection/index.d.ts +21 -1
- package/dist/project-inspection/index.d.ts.map +1 -1
- package/dist/project-validation/index.d.ts +33 -11
- package/dist/project-validation/index.d.ts.map +1 -1
- package/dist/repository-inspection-session/index.d.ts +2 -4
- package/dist/repository-inspection-session/index.d.ts.map +1 -1
- package/dist/repository-reference-validation/index.d.ts +12 -6
- package/dist/repository-reference-validation/index.d.ts.map +1 -1
- package/dist/retained-memory/index.d.ts +18 -0
- package/dist/retained-memory/index.d.ts.map +1 -0
- package/dist/scope/index.d.ts +3 -0
- package/dist/scope/index.d.ts.map +1 -0
- package/dist/scope/scope.d.ts +13 -0
- package/dist/scope/scope.d.ts.map +1 -0
- package/dist/scope-matching/index.d.ts +2 -1
- package/dist/scope-matching/index.d.ts.map +1 -1
- package/dist/scope-matching/matching.d.ts +11 -2
- package/dist/scope-matching/matching.d.ts.map +1 -1
- package/dist/scope-matching/patterns.d.ts +4 -0
- package/dist/scope-matching/patterns.d.ts.map +1 -0
- package/dist/scope.js +17 -0
- package/dist/scope.js.map +1 -0
- package/dist/universal-project-inspection/index.d.ts +13 -11
- package/dist/universal-project-inspection/index.d.ts.map +1 -1
- package/dist/warning-acceptance/acceptance.d.ts +11 -0
- package/dist/warning-acceptance/acceptance.d.ts.map +1 -0
- package/dist/warning-acceptance/index.d.ts +2 -0
- package/dist/warning-acceptance/index.d.ts.map +1 -0
- package/package.json +14 -6
- package/dist/adapter/index.d.ts +0 -131
- package/dist/adapter/index.d.ts.map +0 -1
- package/dist/adapter-availability/index.d.ts +0 -15
- package/dist/adapter-availability/index.d.ts.map +0 -1
- package/dist/adapter-execution/index.d.ts +0 -31
- package/dist/adapter-execution/index.d.ts.map +0 -1
- package/dist/adapter-repository/index.d.ts +0 -27
- package/dist/adapter-repository/index.d.ts.map +0 -1
- package/dist/adapter-retained-memory/index.d.ts +0 -8
- package/dist/adapter-retained-memory/index.d.ts.map +0 -1
- package/dist/adapter-validation/index.d.ts +0 -43
- package/dist/adapter-validation/index.d.ts.map +0 -1
- package/dist/adapter.js +0 -115
- package/dist/adapter.js.map +0 -1
- package/dist/chunks/exceptions-HS9ofVy2.js.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/constants/index.ts","../src/immutable/index.ts","../src/canonical-content-page/index.ts","../src/format-validation/index.ts","../src/diagnostic-utilities/index.ts","../src/decision-validation/index.ts","../src/options/index.ts","../src/source-location/index.ts","../src/text/index.ts","../src/yaml/index.ts","../src/decision/index.ts","../src/manifest-validation/index.ts","../src/manifest/index.ts","../src/project-agent-assignments/index.ts","../src/project-metadata/index.ts","../src/adapter-availability/index.ts","../src/adapter-validation/index.ts","../src/adapter-execution/index.ts","../src/repository-inspection-session/index.ts","../src/agent-asset-validation/index.ts","../src/repository-text/index.ts","../src/runtime-placeholder-validation/index.ts","../src/agent-assets/index.ts","../src/canonical-discovery-validation/index.ts","../src/canonical-discovery/index.ts","../src/decision-graph-validation/index.ts","../src/decision-graph/index.ts","../src/manifest-relationship-validation/index.ts","../src/mirrors/index.ts","../src/project-assets/index.ts","../src/project-index/index.ts","../src/repository-reference-validation/index.ts","../src/runtime-guidance/index.ts","../src/universal-project-inspection/index.ts","../src/project-validation/index.ts","../src/project-inspection/index.ts","../src/scope-matching/validations.ts","../src/scope-matching/matching.ts","../src/scope-matching/scope.ts","../src/core/index.ts"],"sourcesContent":["import type { ICoreResourceLimits } from '../contracts/index.js';\nimport type { IRepositoryFormatVersion } from '../format/index.js';\n\n// official runtime adapter IDs recognized by this Core release\nexport const RECOGNIZED_RUNTIME_ADAPTER_IDS = Object.freeze([\n 'anthropic',\n 'claude-agent-sdk',\n 'cloudflare-agents',\n 'custom',\n 'eve',\n 'google-genai',\n 'langchain',\n 'langgraph',\n 'openai',\n 'openai-agents-sdk',\n 'vercel-ai-sdk',\n] as const);\n\n// repository-format major versions interpreted by this Core release\nexport const SUPPORTED_REPOSITORY_FORMAT_VERSIONS: readonly IRepositoryFormatVersion[] =\n Object.freeze([1]);\n\n// default safety budgets applied independently to each Core operation\nexport const DEFAULT_CORE_RESOURCE_LIMITS: ICoreResourceLimits = Object.freeze({\n maxDiagnostics: 10_000,\n maxEntries: 100_000,\n maxEvidence: 10_000,\n maxFileBytes: 8_388_608,\n maxManifestBytes: 2_097_152,\n maxRetainedBytes: 536_870_912,\n maxTotalBytesRead: 134_217_728,\n});\n","/**\n * Recursively freezes a Core-owned value without cloning it.\n * @param value The detached acyclic value whose already-frozen objects are deeply frozen.\n * @returns The same value with every mutable reachable object frozen.\n */\nexport const freezeRecursively = <Value>(value: Value): Readonly<Value> => {\n if (typeof value !== 'object' || value === null || Object.isFrozen(value)) {\n return value;\n }\n\n for (const key of Reflect.ownKeys(value)) {\n const child = (value as Readonly<Record<PropertyKey, unknown>>)[key];\n freezeRecursively(child);\n }\n\n return Object.freeze(value);\n};\n\n/**\n * Creates a record that cannot collide with prototype-chain properties.\n * @param entries The own string-keyed entries to assign.\n * @returns A mutable null-prototype record for later normalization and freezing.\n */\nexport const createNullPrototypeRecord = <Value>(\n entries: Iterable<readonly [string, Value]>,\n): Record<string, Value> => {\n const record = Object.create(null) as Record<string, Value>;\n\n for (const [key, value] of entries) {\n record[key] = value;\n }\n\n return record;\n};\n","import {\n RepositorySourceException,\n parseRepositoryPath,\n type IRepositoryFilePage,\n type IRepositoryPath,\n type IRepositoryReader,\n} from '@moldea.ai/repository';\n\nimport type {\n ICanonicalContentPageInput,\n ICanonicalContentPageResult,\n} from '../contracts/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport type { ICoreOptionsSnapshot } from '../options/index.js';\n\nconst decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\nconst invalidArgument = (): never => {\n throw new CoreOperationException({\n code: 'INVALID_ARGUMENT',\n operation: 'read-canonical-content-page',\n });\n};\n\nconst invalidContent = (): never => {\n throw new CoreOperationException({\n code: 'CONTENT_INVALID',\n operation: 'read-canonical-content-page',\n });\n};\n\nconst isRepositoryReader = (candidate: unknown): candidate is IRepositoryReader =>\n typeof candidate === 'object' &&\n candidate !== null &&\n typeof (candidate as Partial<IRepositoryReader>).getEntry === 'function' &&\n typeof (candidate as Partial<IRepositoryReader>).readFilePage === 'function';\n\nconst readBytes = async (\n repository: IRepositoryReader,\n path: IRepositoryPath,\n offset: number,\n maxBytes: number,\n signal?: AbortSignal,\n): Promise<{ readonly bytes: Uint8Array; readonly lastPage: IRepositoryFilePage }> => {\n const chunks: Uint8Array[] = [];\n let byteLength = 0;\n let nextOffset = offset;\n let lastPage: IRepositoryFilePage | null = null;\n let totalBytes: number | null = null;\n\n while (byteLength < maxBytes) {\n const page = await repository.readFilePage(path, {\n maxBytes: maxBytes - byteLength,\n offset: nextOffset,\n ...(signal === undefined ? {} : { signal }),\n });\n\n if (\n page.snapshot.id !== repository.snapshot.id ||\n page.offset !== nextOffset ||\n page.bytes.byteLength > maxBytes - byteLength ||\n page.totalBytes < page.offset + page.bytes.byteLength ||\n (totalBytes !== null && page.totalBytes !== totalBytes) ||\n (page.bytes.byteLength === 0 && !page.isComplete)\n ) {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n }\n\n chunks.push(page.bytes);\n byteLength += page.bytes.byteLength;\n totalBytes = page.totalBytes;\n lastPage = page;\n\n if (page.isComplete || byteLength === maxBytes) {\n break;\n }\n\n if (page.nextOffset !== page.offset + page.bytes.byteLength) {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n }\n\n nextOffset = page.nextOffset;\n }\n\n if (lastPage === null) {\n return invalidArgument();\n }\n\n const bytes = new Uint8Array(byteLength);\n let writeOffset = 0;\n\n for (const chunk of chunks) {\n bytes.set(chunk, writeOffset);\n writeOffset += chunk.byteLength;\n }\n\n return { bytes, lastPage };\n};\n\nconst decodeSafePrefix = (bytes: Uint8Array, maximumBytes: number): [string, number] => {\n const minimumCandidate = Math.max(0, maximumBytes - 3);\n\n for (let end = maximumBytes; end >= minimumCandidate; end -= 1) {\n try {\n const content = decoder.decode(bytes.subarray(0, end));\n\n if (end === 0 && bytes.byteLength > 0) {\n continue;\n }\n\n return [content, end];\n } catch {\n // a UTF-8 scalar may cross the requested byte boundary by at most three bytes\n }\n }\n\n return invalidContent();\n};\n\n/** Reads one explicit canonical file range without materializing the complete file. */\nexport const readCanonicalContentPage = async (\n input: ICanonicalContentPageInput,\n options: ICoreOptionsSnapshot,\n): Promise<ICanonicalContentPageResult> => {\n if (\n typeof input !== 'object' ||\n input === null ||\n Reflect.ownKeys(input).some(\n (key) =>\n key !== 'maxBytes' &&\n key !== 'offset' &&\n key !== 'path' &&\n key !== 'repository' &&\n key !== 'signal',\n ) ||\n !isRepositoryReader(input.repository) ||\n !Number.isSafeInteger(input.maxBytes) ||\n input.maxBytes < 1 ||\n input.maxBytes > options.limits.maxFileBytes ||\n !Number.isSafeInteger(input.offset) ||\n input.offset < 0\n ) {\n return invalidArgument();\n }\n\n const path = parseRepositoryPath(input.path);\n\n if (!path.startsWith('/moldea/')) {\n return invalidArgument();\n }\n\n const operationOptions = input.signal === undefined ? undefined : { signal: input.signal };\n const entry = await input.repository.getEntry(path, operationOptions);\n\n if (entry === null) {\n throw new RepositorySourceException({\n code: 'ENTRY_NOT_FOUND',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n }\n\n if (entry.type !== 'file' || entry.byteLength === null) {\n throw new RepositorySourceException({\n code: 'ENTRY_NOT_FILE',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n }\n\n if (entry.byteLength > options.limits.maxFileBytes) {\n throw new CoreOperationException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit: 'maxFileBytes',\n limitMaximum: options.limits.maxFileBytes,\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage: entry.byteLength,\n operation: 'read-canonical-content-page',\n });\n }\n\n if (input.offset > entry.byteLength) {\n return invalidArgument();\n }\n\n if (input.offset === entry.byteLength) {\n return freezeRecursively({\n byteEnd: input.offset,\n byteStart: input.offset,\n content: '',\n contentIdentity: entry.contentIdentity,\n isComplete: true,\n nextOffset: null,\n path,\n source: input.repository.snapshot,\n totalBytes: entry.byteLength,\n });\n }\n\n const lookaheadBytes = Math.min(entry.byteLength - input.offset, input.maxBytes + 3);\n const { bytes, lastPage } = await readBytes(\n input.repository,\n path,\n input.offset,\n lookaheadBytes,\n input.signal,\n );\n\n if (lastPage.totalBytes !== entry.byteLength || ((bytes[0] as number) & 0xc0) === 0x80) {\n return invalidArgument();\n }\n\n const maximumChunkBytes = Math.min(input.maxBytes, bytes.byteLength);\n const [content, consumedBytes] = decodeSafePrefix(bytes, maximumChunkBytes);\n const byteEnd = input.offset + consumedBytes;\n const isComplete = byteEnd === entry.byteLength;\n\n return freezeRecursively({\n byteEnd,\n byteStart: input.offset,\n content,\n contentIdentity: entry.contentIdentity,\n isComplete,\n nextOffset: isComplete ? null : byteEnd,\n path,\n source: input.repository.snapshot,\n totalBytes: entry.byteLength,\n });\n};\n","import { isRepositoryPath, parseRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { IRepositoryReference } from '../format/index.js';\n\nconst STABLE_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\nconst VARIABLE_ID_PATTERN = /^[A-Z][A-Z0-9_]*$/u;\nconst WINDOWS_RESERVED_ID_PATTERN = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/u;\nconst LINE_BREAK_CHARACTERS = ['\\n', '\\r', '\\u0085', '\\u2028', '\\u2029'] as const;\nconst UNSUPPORTED_GLOB_PATTERN = /[!?[\\]{}]/u;\n\nconst hasLineBreak = (value: string): boolean => {\n return LINE_BREAK_CHARACTERS.some((lineBreak) => value.includes(lineBreak));\n};\n\n/** Determines whether a code point belongs to the Repository Format version 1 whitespace set. */\nexport const isRepositoryFormatWhitespace = (codePoint: number): boolean => {\n return (\n (codePoint >= 0x0009 && codePoint <= 0x000d) ||\n codePoint === 0x0020 ||\n codePoint === 0x0085 ||\n codePoint === 0x00a0 ||\n codePoint === 0x1680 ||\n (codePoint >= 0x2000 && codePoint <= 0x200a) ||\n codePoint === 0x2028 ||\n codePoint === 0x2029 ||\n codePoint === 0x202f ||\n codePoint === 0x205f ||\n codePoint === 0x3000\n );\n};\n\n/** Compares strings by exact Unicode code-point order without locale behavior. */\nexport const compareExactStrings = (left: string, right: string): number => {\n const leftScalars = left[Symbol.iterator]();\n const rightScalars = right[Symbol.iterator]();\n\n while (true) {\n const leftScalar = leftScalars.next();\n const rightScalar = rightScalars.next();\n\n if (leftScalar.done === true) {\n return rightScalar.done === true ? 0 : -1;\n }\n\n if (rightScalar.done === true) {\n return 1;\n }\n\n const leftCodePoint = leftScalar.value.codePointAt(0) ?? 0;\n const rightCodePoint = rightScalar.value.codePointAt(0) ?? 0;\n\n if (leftCodePoint !== rightCodePoint) {\n return leftCodePoint < rightCodePoint ? -1 : 1;\n }\n }\n};\n\n/** Counts Unicode scalar values in valid JavaScript text. */\nexport const countUnicodeScalars = (value: string): number => {\n const scalars = value[Symbol.iterator]();\n let count = 0;\n\n while (scalars.next().done !== true) {\n count += 1;\n }\n\n return count;\n};\n\n/** Determines whether a JavaScript string contains only Unicode scalar values. */\nexport const isUnicodeScalarText = (value: string): boolean => {\n for (let index = 0; index < value.length; index += 1) {\n const codeUnit = value.charCodeAt(index);\n\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n if (index + 1 >= value.length) {\n return false;\n }\n\n const nextCodeUnit = value.charCodeAt(index + 1);\n\n if (nextCodeUnit < 0xdc00 || nextCodeUnit > 0xdfff) {\n return false;\n }\n\n index += 1;\n continue;\n }\n\n if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {\n return false;\n }\n }\n\n return true;\n};\n\n/** Determines whether a value contains at least one non-whitespace scalar. */\nexport const hasNonWhitespace = (value: string): boolean => {\n for (const scalar of value) {\n if (!isRepositoryFormatWhitespace(scalar.codePointAt(0) ?? 0)) {\n return true;\n }\n }\n\n return false;\n};\n\n/** Determines whether a value begins or ends with version 1 whitespace. */\nexport const hasSurroundingWhitespace = (value: string): boolean => {\n const firstCodePoint = value.codePointAt(0);\n const lastCodePoint = value.codePointAt(value.length - 1);\n\n return (\n (firstCodePoint !== undefined && isRepositoryFormatWhitespace(firstCodePoint)) ||\n (lastCodePoint !== undefined && isRepositoryFormatWhitespace(lastCodePoint))\n );\n};\n\n/** Removes only Repository Format version 1 whitespace from both edges. */\nexport const trimRepositoryFormatWhitespace = (value: string): string => {\n let start = 0;\n let end = value.length;\n\n while (start < end) {\n const codePoint = value.codePointAt(start);\n\n if (codePoint === undefined || !isRepositoryFormatWhitespace(codePoint)) {\n break;\n }\n\n start += codePoint > 0xffff ? 2 : 1;\n }\n\n while (end > start) {\n const codePoint = value.codePointAt(end - 1);\n\n if (codePoint === undefined || !isRepositoryFormatWhitespace(codePoint)) {\n break;\n }\n\n end -= 1;\n }\n\n return value.slice(start, end);\n};\n\n/** Determines whether a string is non-empty and contains no line break. */\nexport const isNonEmptySingleLine = (value: string): boolean => {\n return value.length > 0 && !hasLineBreak(value);\n};\n\n/** Determines whether a value satisfies stable moldea ID syntax. */\nexport const isStableId = (value: string): boolean => {\n return value.length <= 64 && STABLE_ID_PATTERN.test(value);\n};\n\n/** Determines whether an otherwise valid stable ID is filesystem-reserved. */\nexport const isReservedId = (value: string): boolean => WINDOWS_RESERVED_ID_PATTERN.test(value);\n\n/** Determines whether a value satisfies runtime-variable ID syntax. */\nexport const isVariableId = (value: string): boolean => {\n return value.length <= 64 && VARIABLE_ID_PATTERN.test(value);\n};\n\n/** Determines whether a parsed capability description satisfies version 1 limits. */\nexport const isCapabilityDescription = (value: string): boolean => {\n const scalarLength = countUnicodeScalars(value);\n\n return (\n scalarLength >= 1 &&\n scalarLength <= 1_000 &&\n !hasSurroundingWhitespace(value) &&\n !hasLineBreak(value) &&\n !value.includes('\\0') &&\n !value.includes('{{') &&\n !value.includes('}}')\n );\n};\n\n/** Parses a non-root repository-format logical path without throwing. */\nexport const parseManifestPath = (value: string): IRepositoryPath | null => {\n return value !== '/' && isRepositoryPath(value) ? parseRepositoryPath(value) : null;\n};\n\n/** Determines whether a path is the canonical manifest path. */\nexport const isCanonicalManifestPath = (path: IRepositoryPath): boolean => {\n return path === '/moldea/moldea.yaml';\n};\n\n/** Extracts the stable millisecond ID from one canonical immediate decision path. */\nexport const parseDecisionIdFromPath = (path: IRepositoryPath): string | null => {\n const match = /^\\/moldea\\/decisions\\/(\\d{13})-([a-z0-9]+(?:-[a-z0-9]+)*)\\.md$/u.exec(path);\n const id = match?.[1];\n const slug = match?.[2];\n\n return id !== undefined && slug !== undefined && isStableId(slug) ? id : null;\n};\n\n/** Determines whether a path is an allowed focused-context relationship key. */\nexport const isContextPath = (path: IRepositoryPath, allowProject: boolean): boolean => {\n if (allowProject && path === '/moldea/project.md') {\n return true;\n }\n\n return path.startsWith('/moldea/context/') && path.endsWith('.md');\n};\n\n/** Determines whether a path has the canonical immediate decision filename shape. */\nexport const isDecisionPath = (path: IRepositoryPath): boolean => {\n return parseDecisionIdFromPath(path) !== null;\n};\n\n/** Determines whether a path is canonical runtime guidance. */\nexport const isRuntimeGuidancePath = (path: IRepositoryPath): boolean => {\n return path.startsWith('/moldea/runtimes/') && path.endsWith('.md');\n};\n\n/** Determines whether a mirror path is outside canonical moldea content. */\nexport const isMirrorPath = (path: IRepositoryPath): boolean => {\n return path !== '/moldea' && !path.startsWith('/moldea/');\n};\n\n/** Determines whether an impact path contains prohibited glob metacharacters. */\nexport const hasUnsupportedGlobMetacharacter = (value: string): boolean => {\n return UNSUPPORTED_GLOB_PATTERN.test(value);\n};\n\n/** Determines whether a string satisfies the version 1 simple-glob grammar. */\nexport const isSimpleGlob = (value: string): boolean => {\n if (hasUnsupportedGlobMetacharacter(value) || value.includes('***')) {\n return false;\n }\n\n const segments = value.slice(1).split('/');\n\n if (segments.some((segment) => segment.includes('**') && segment !== '**')) {\n return false;\n }\n\n return value.includes('*') && isRepositoryPath(value.replaceAll('*', 'x'));\n};\n\n/** Determines whether a repository-reference symbol has the common safe shape. */\nexport const isRepositorySymbol = (value: string): boolean => {\n return isNonEmptySingleLine(value) && !value.includes('\\0');\n};\n\n/** Determines whether a canonical moldea reference incorrectly carries a symbol. */\nexport const isCanonicalMoldeaPath = (path: IRepositoryPath): boolean => {\n return path === '/moldea' || path.startsWith('/moldea/');\n};\n\n/** Sorts repository references by path and then optional symbol. */\nexport const sortRepositoryReferences = (\n references: readonly IRepositoryReference[],\n): IRepositoryReference[] => {\n return [...references].sort((left, right) => {\n return (\n compareExactStrings(left.path, right.path) ||\n compareExactStrings(left.symbol ?? '', right.symbol ?? '')\n );\n });\n};\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICoreResourceLimits } from '../contracts/index.js';\nimport type {\n ICoreDiagnostic,\n ICoreDiagnosticCode,\n IDiagnostic,\n IDiagnosticDetails,\n IDiagnosticEntity,\n ISourceRange,\n} from '../diagnostics/index.js';\nimport { CoreOperationException, type ICoreOperation } from '../exceptions/index.js';\nimport { compareExactStrings } from '../format-validation/index.js';\nimport { createNullPrototypeRecord, freezeRecursively } from '../immutable/index.js';\n\nconst CORE_DIAGNOSTIC_MESSAGES: Record<ICoreDiagnosticCode, string> = {\n MOLDEA_AGENT_DESCRIPTION_INVALID: 'The agent description is invalid.',\n MOLDEA_AGENT_DESCRIPTION_MISSING: 'The agent description is missing.',\n MOLDEA_AGENT_DIRECTORY_MISSING: 'The registered agent directory is missing.',\n MOLDEA_AGENT_DIRECTORY_UNREGISTERED: 'The agent directory is not registered.',\n MOLDEA_AGENT_HANDOFF_DESCRIPTION_INVALID: 'The agent handoff description is invalid.',\n MOLDEA_AGENT_IDENTITY_INVALID: 'The agent instruction identity is invalid.',\n MOLDEA_AGENT_INSTRUCTION_EMPTY: 'The agent instruction is empty.',\n MOLDEA_AGENT_INSTRUCTION_MISSING: 'The agent instruction is missing.',\n MOLDEA_CANONICAL_ASSET_SYMLINK: 'The canonical asset is a symlink.',\n MOLDEA_CANONICAL_PATH_UNRECOGNIZED: 'The canonical path is unrecognized.',\n MOLDEA_CAPABILITY_DESCRIPTION_INVALID: 'The capability description is invalid.',\n MOLDEA_CAPABILITY_DESCRIPTION_MISSING: 'The capability description is missing.',\n MOLDEA_CONTEXT_FILE_EMPTY: 'The focused context file is empty.',\n MOLDEA_CONTEXT_PATH_INVALID: 'The context relationship path is invalid.',\n MOLDEA_CONTEXT_RELATIONSHIP_EMPTY: 'The declared relationship has no bindings or impact paths.',\n MOLDEA_DECISION_BODY_EMPTY: 'The decision Markdown body is empty.',\n MOLDEA_DECISION_CREATED_AT_INVALID: 'The decision createdAt value is invalid.',\n MOLDEA_DECISION_FILENAME_INVALID: 'The decision path or filename is invalid.',\n MOLDEA_DECISION_FRONTMATTER_INVALID: 'The decision frontmatter is invalid.',\n MOLDEA_DECISION_FRONTMATTER_MISSING: 'The decision frontmatter or its delimiters are missing.',\n MOLDEA_DECISION_ID_DUPLICATE: 'The decision ID is duplicated.',\n MOLDEA_DECISION_PROPERTY_UNKNOWN: 'The decision frontmatter contains an unknown property.',\n MOLDEA_DECISION_REFERENCE_MISSING: 'The referenced decision does not exist.',\n MOLDEA_DECISION_RELATIONSHIP_INACTIVE: 'The referenced decision is not accepted.',\n MOLDEA_DECISION_SELF_SUPERSESSION: 'The decision supersedes itself.',\n MOLDEA_DECISION_STATUS_INVALID: 'The decision status is invalid.',\n MOLDEA_DECISION_SUPERSEDED_ORPHAN:\n 'The superseded decision has no active supersession relationship.',\n MOLDEA_DECISION_SUPERSESSION_CYCLE: 'The decision supersession graph contains a cycle.',\n MOLDEA_DECISION_SUPERSESSION_STATUS_INVALID:\n 'The decision supersession relationship has inconsistent statuses.',\n MOLDEA_DECISION_TIMESTAMP_MISMATCH:\n 'The decision filename timestamp and createdAt value do not match.',\n MOLDEA_ENTRY_TYPE_INVALID: 'The repository entry type is invalid.',\n MOLDEA_RUNTIME_ADAPTER_FORMAT_UNSUPPORTED:\n 'The configured runtime adapter does not support the repository format version.',\n MOLDEA_RUNTIME_ADAPTER_UNAVAILABLE: 'The declared runtime adapter is unavailable.',\n MOLDEA_RUNTIME_ID_INVALID: 'The runtime adapter ID is invalid.',\n MOLDEA_GLOB_INVALID: 'The impact pattern is invalid.',\n MOLDEA_ID_DUPLICATE: 'An ID is duplicated within its required scope.',\n MOLDEA_ID_INVALID: 'The ID is invalid.',\n MOLDEA_ID_RESERVED: 'The ID uses a reserved filesystem name.',\n MOLDEA_IMPACT_PATH_MISSING: 'The exact impact path does not exist.',\n MOLDEA_IMPACT_PATH_NOT_FILE: 'The exact impact path is not a regular file.',\n MOLDEA_MANIFEST_MISSING: 'The project manifest is missing.',\n MOLDEA_MANIFEST_PATH_INVALID: 'The manifest path is not the canonical manifest path.',\n MOLDEA_MANIFEST_PROPERTY_UNKNOWN: 'The manifest contains an unknown property.',\n MOLDEA_MANIFEST_ROOT_INVALID: 'The manifest root is not a mapping.',\n MOLDEA_MANIFEST_VALUE_INVALID: 'The manifest value is invalid.',\n MOLDEA_MANIFEST_VERSION_INVALID: 'The manifest version is not a valid integer major version.',\n MOLDEA_MANIFEST_VERSION_MISSING: 'The manifest version is missing.',\n MOLDEA_MANIFEST_VERSION_UNSUPPORTED: 'The manifest version is unsupported.',\n MOLDEA_MIRROR_PATH_DUPLICATE: 'The mirror path is assigned more than once.',\n MOLDEA_MIRROR_PATH_INSIDE_MOLDEA: 'The mirror path is inside /moldea.',\n MOLDEA_MIRROR_PATH_INVALID: 'The mirror path is invalid.',\n MOLDEA_MIRROR_MISSING: 'The declared mirror does not exist.',\n MOLDEA_MIRROR_NOT_FILE: 'The declared mirror is not a regular file.',\n MOLDEA_MIRROR_STALE: 'The declared mirror differs from its canonical instruction.',\n MOLDEA_MIRROR_SYMLINK: 'The declared mirror is a symlink.',\n MOLDEA_PATH_DUPLICATE: 'The path is duplicated.',\n MOLDEA_PATH_INVALID: 'The manifest logical path is invalid.',\n MOLDEA_PATTERN_DUPLICATE: 'The impact pattern is duplicated.',\n MOLDEA_PROJECT_FILE_EMPTY: 'The project file is empty.',\n MOLDEA_PROJECT_FILE_MISSING: 'The project file is missing.',\n MOLDEA_REFERENCE_MISSING: 'The referenced repository path does not exist.',\n MOLDEA_REFERENCE_NOT_FILE: 'The referenced repository path is not a regular file.',\n MOLDEA_REFERENCE_SYMLINK: 'The referenced repository path is a symlink.',\n MOLDEA_RUNTIME_GUIDANCE_EMPTY: 'The runtime guidance is empty.',\n MOLDEA_RUNTIME_GUIDANCE_MISSING: 'The referenced runtime guidance does not exist.',\n MOLDEA_SKILL_IMPLEMENTATION_MISSING: 'The registered skill implementation is missing.',\n MOLDEA_SYMBOL_FORBIDDEN: 'A canonical moldea reference must not include a symbol.',\n MOLDEA_SYMBOL_INVALID: 'The repository-reference symbol is invalid.',\n MOLDEA_TEXT_EMPTY: 'The required text document is empty.',\n MOLDEA_TEXT_INVALID_UNICODE:\n 'The text document contains an invalid Unicode scalar representation.',\n MOLDEA_TEXT_INVALID_UTF8: 'The text document is not valid UTF-8.',\n MOLDEA_TEXT_NUL_FORBIDDEN: 'The text document contains a forbidden NUL character.',\n MOLDEA_TOOL_IMPLEMENTATION_MISSING: 'The registered tool implementation is missing.',\n MOLDEA_VARIABLE_ID_INVALID: 'The runtime-variable ID is invalid.',\n MOLDEA_VARIABLE_PLACEHOLDER_MALFORMED:\n 'The agent instruction contains a malformed runtime-variable placeholder.',\n MOLDEA_VARIABLE_PROVIDER_UNDECLARED:\n 'A variable-provider binding exists for an undeclared variable.',\n MOLDEA_VARIABLE_UNDECLARED: 'The agent instruction references an undeclared runtime variable.',\n MOLDEA_VARIABLE_UNUSED: 'The declared runtime variable is unused by the agent instruction.',\n MOLDEA_YAML_DUPLICATE_KEY: 'The YAML document contains a duplicate mapping key.',\n MOLDEA_YAML_FEATURE_UNSUPPORTED: 'The YAML document uses an unsupported feature.',\n MOLDEA_YAML_MALFORMED: 'The YAML document is malformed.',\n MOLDEA_YAML_MULTIPLE_DOCUMENTS: 'The YAML stream contains more than one document.',\n};\n\nconst ENTITY_KEYS = [\n 'agentId',\n 'capabilityKind',\n 'capabilityId',\n 'decisionId',\n 'variableId',\n 'adapterId',\n] as const satisfies readonly (keyof IDiagnosticEntity)[];\n\n// private normalized diagnostic construction contracts\nexport interface ICoreDiagnosticInput {\n readonly code: ICoreDiagnosticCode;\n readonly details?: Readonly<Record<string, string | number | boolean | null>>;\n readonly entity?: IDiagnosticEntity | null;\n readonly path: IRepositoryPath | null;\n readonly pointer?: string | null;\n readonly range?: ISourceRange | null;\n}\n\nexport interface ICoreDiagnosticCollector {\n add(input: ICoreDiagnosticInput): void;\n merge(input: ICoreDiagnosticInput): void;\n finalize(): readonly ICoreDiagnostic[];\n readonly size: number;\n}\n\ninterface ICoreDiagnosticBudget {\n count: number;\n}\n\nconst CORE_DIAGNOSTIC_BUDGET = Symbol('core-diagnostic-budget');\n\ntype ICoreOperationResourceLimits = ICoreResourceLimits & {\n readonly [CORE_DIAGNOSTIC_BUDGET]?: ICoreDiagnosticBudget;\n};\n\n/** Creates a detached limits view with one diagnostic budget for a complete Core operation. */\nexport const createCoreOperationResourceLimits = (\n limits: ICoreResourceLimits,\n): ICoreResourceLimits => {\n const operationLimits = limits as ICoreOperationResourceLimits;\n\n if (operationLimits[CORE_DIAGNOSTIC_BUDGET] !== undefined) {\n return limits;\n }\n\n return Object.freeze({\n ...limits,\n [CORE_DIAGNOSTIC_BUDGET]: { count: 0 },\n });\n};\n\n/** Registers raw diagnostics against the shared operation budget before normalization. */\nexport const registerCoreDiagnosticCandidates = (\n limits: ICoreResourceLimits,\n amount: number,\n operation: ICoreOperation,\n fallbackCount = 0,\n adapterId?: string,\n): number => {\n const budget = (limits as ICoreOperationResourceLimits)[CORE_DIAGNOSTIC_BUDGET];\n const currentCount = budget?.count ?? fallbackCount;\n\n if (amount > limits.maxDiagnostics - currentCount) {\n throw new CoreOperationException({\n ...(adapterId === undefined ? {} : { adapterId }),\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit: 'maxDiagnostics',\n limitMaximum: limits.maxDiagnostics,\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage: currentCount + amount,\n operation,\n });\n }\n\n if (budget !== undefined) {\n budget.count += amount;\n }\n\n return fallbackCount + amount;\n};\n\nconst compareNullableStrings = (left: string | null, right: string | null): number => {\n if (left === null) {\n return right === null ? 0 : -1;\n }\n\n return right === null ? 1 : compareExactStrings(left, right);\n};\n\n/**\n * Normalizes trusted JSON-scalar diagnostic metadata.\n * @param details The optional detached metadata record.\n * @returns A frozen null-prototype record with canonical key order.\n */\nexport const normalizeDiagnosticDetails = (\n details: Readonly<Record<string, string | number | boolean | null>> | undefined,\n): IDiagnosticDetails => {\n const entries = Object.entries(details ?? {})\n .sort(([left], [right]) => compareExactStrings(left, right))\n .map(\n ([key, value]) =>\n [key, typeof value === 'number' && Object.is(value, -0) ? 0 : value] as const,\n );\n\n return freezeRecursively(createNullPrototypeRecord(entries));\n};\n\n/**\n * Normalizes a trusted diagnostic entity into canonical key order.\n * @param entity The optional diagnostic entity.\n * @returns The frozen normalized entity or `null`.\n */\nexport const normalizeDiagnosticEntity = (\n entity: IDiagnosticEntity | null | undefined,\n): IDiagnosticEntity | null => {\n if (entity === undefined || entity === null) {\n return null;\n }\n\n const entries = ENTITY_KEYS.flatMap((key) => {\n const value = entity[key];\n return value === undefined ? [] : ([[key, value]] as const);\n });\n\n return freezeRecursively(createNullPrototypeRecord(entries) as IDiagnosticEntity);\n};\n\n/** Serializes unordered diagnostic details with explicit exact-code-point key ordering. */\nexport const serializeDiagnosticDetails = (details: IDiagnosticDetails): string => {\n const entries = Object.entries(details).sort(([left], [right]) =>\n compareExactStrings(left, right),\n );\n\n return JSON.stringify(entries);\n};\n\nconst serializeDiagnostic = (diagnostic: IDiagnostic): string => {\n const entity =\n diagnostic.entity === null\n ? null\n : ENTITY_KEYS.map((key) => [key, diagnostic.entity?.[key] ?? null]);\n const range =\n diagnostic.range === null\n ? null\n : [\n diagnostic.range.start.line,\n diagnostic.range.start.column,\n diagnostic.range.start.offset,\n diagnostic.range.end.line,\n diagnostic.range.end.column,\n diagnostic.range.end.offset,\n ];\n\n return JSON.stringify([\n diagnostic.code,\n diagnostic.severity,\n serializeDiagnosticDetails(diagnostic.details),\n entity,\n diagnostic.message,\n diagnostic.path,\n diagnostic.pointer,\n range,\n diagnostic.source,\n ]);\n};\n\nconst compareRanges = (left: ISourceRange | null, right: ISourceRange | null): number => {\n if (left === null) {\n return right === null ? 0 : -1;\n }\n\n if (right === null) {\n return 1;\n }\n\n return (\n left.start.line - right.start.line ||\n left.start.column - right.start.column ||\n left.start.offset - right.start.offset ||\n left.end.line - right.end.line ||\n left.end.column - right.end.column ||\n left.end.offset - right.end.offset\n );\n};\n\nconst readEntityValue = (\n entity: IDiagnosticEntity | null,\n key: keyof IDiagnosticEntity,\n): string => {\n return entity?.[key] ?? '';\n};\n\nconst compareDiagnostics = (left: IDiagnostic, right: IDiagnostic): number => {\n return (\n compareNullableStrings(left.path, right.path) ||\n compareRanges(left.range, right.range) ||\n compareNullableStrings(left.pointer, right.pointer) ||\n compareExactStrings(left.source, right.source) ||\n compareExactStrings(left.code, right.code) ||\n compareExactStrings(left.severity, right.severity) ||\n compareExactStrings(\n readEntityValue(left.entity, 'agentId'),\n readEntityValue(right.entity, 'agentId'),\n ) ||\n compareExactStrings(\n readEntityValue(left.entity, 'capabilityKind'),\n readEntityValue(right.entity, 'capabilityKind'),\n ) ||\n compareExactStrings(\n readEntityValue(left.entity, 'capabilityId'),\n readEntityValue(right.entity, 'capabilityId'),\n ) ||\n compareExactStrings(\n readEntityValue(left.entity, 'decisionId'),\n readEntityValue(right.entity, 'decisionId'),\n ) ||\n compareExactStrings(\n readEntityValue(left.entity, 'variableId'),\n readEntityValue(right.entity, 'variableId'),\n ) ||\n compareExactStrings(\n readEntityValue(left.entity, 'adapterId'),\n readEntityValue(right.entity, 'adapterId'),\n ) ||\n compareExactStrings(\n serializeDiagnosticDetails(left.details),\n serializeDiagnosticDetails(right.details),\n ) ||\n compareExactStrings(left.message, right.message)\n );\n};\n\n/**\n * Creates one normalized, immutable Core diagnostic.\n * @param input The trusted Core-owned diagnostic fields to normalize.\n * @returns A deeply immutable public diagnostic value.\n */\nexport const createCoreDiagnostic = (input: ICoreDiagnosticInput): ICoreDiagnostic => {\n const message = CORE_DIAGNOSTIC_MESSAGES[input.code];\n\n if (message === undefined) {\n throw new TypeError('The requested Core diagnostic is not implemented.');\n }\n\n return freezeRecursively({\n code: input.code,\n details: normalizeDiagnosticDetails(input.details),\n entity: normalizeDiagnosticEntity(input.entity),\n message,\n path: input.path,\n pointer: input.pointer ?? null,\n range: input.range ?? null,\n severity: 'error' as const,\n source: 'core' as const,\n });\n};\n\n/**\n * Deduplicates and sorts already-normalized Core and adapter diagnostics.\n * @param candidates The immutable diagnostics to combine.\n * @returns A frozen deterministic diagnostic collection.\n */\nexport const normalizeDiagnostics = (\n candidates: readonly IDiagnostic[],\n): readonly IDiagnostic[] => {\n const diagnostics = new Map<string, IDiagnostic>();\n\n for (const diagnostic of candidates) {\n const key = serializeDiagnostic(diagnostic);\n\n if (diagnostics.has(key)) {\n continue;\n }\n\n diagnostics.set(key, diagnostic);\n }\n\n return freezeRecursively([...diagnostics.values()].sort(compareDiagnostics));\n};\n\n/** Counts the complete normalized diagnostic result by severity once. */\nexport const countDiagnosticsBySeverity = (\n diagnostics: readonly IDiagnostic[],\n): { readonly errorCount: number; readonly warningCount: number } => {\n let errorCount = 0;\n let warningCount = 0;\n\n for (const diagnostic of diagnostics) {\n if (diagnostic.severity === 'error') {\n errorCount += 1;\n } else {\n warningCount += 1;\n }\n }\n\n return { errorCount, warningCount };\n};\n\n/**\n * Creates a deterministic, deduplicating diagnostic collector for one operation.\n * @param limits The Core resource limits governing diagnostic output.\n * @param operation The operation reported by resource failures.\n * @returns A collector that freezes and sorts its final diagnostic array.\n */\nexport const createCoreDiagnosticCollector = (\n limits: ICoreResourceLimits,\n operation: ICoreOperation,\n): ICoreDiagnosticCollector => {\n const diagnostics = new Map<string, ICoreDiagnostic>();\n let proposalCount = 0;\n let fallbackRawCount = 0;\n\n const retain = (input: ICoreDiagnosticInput): void => {\n const diagnostic = createCoreDiagnostic(input);\n const key = serializeDiagnostic(diagnostic);\n\n proposalCount += 1;\n\n if (!diagnostics.has(key)) {\n diagnostics.set(key, diagnostic);\n }\n };\n\n return {\n add: (input): void => {\n fallbackRawCount = registerCoreDiagnosticCandidates(limits, 1, operation, fallbackRawCount);\n retain(input);\n },\n merge: retain,\n finalize: (): readonly ICoreDiagnostic[] =>\n normalizeDiagnostics([...diagnostics.values()]) as readonly ICoreDiagnostic[],\n get size(): number {\n return proposalCount;\n },\n };\n};\n\n/**\n * Escapes one JSON Pointer reference token.\n * @param value The decoded mapping key or array index token.\n * @returns The RFC 6901 escaped token.\n */\nexport const escapeJsonPointerSegment = (value: string): string => {\n return value.replaceAll('~', '~0').replaceAll('/', '~1');\n};\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport {\n escapeJsonPointerSegment,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { IDiagnosticEntity, ISourceRange } from '../diagnostics/index.js';\nimport { compareExactStrings, hasNonWhitespace } from '../format-validation/index.js';\nimport type { IDecisionStatus, IParsedDecision } from '../format/index.js';\nimport type { ISourceLocator } from '../source-location/index.js';\nimport type { IYamlNode } from '../yaml/index.js';\n\ninterface IDecisionValidationContext {\n readonly decisionId: string | null;\n readonly diagnostics: ICoreDiagnosticCollector;\n readonly path: IRepositoryPath;\n}\n\nconst DECISION_STATUSES = new Set<IDecisionStatus>([\n 'accepted',\n 'proposed',\n 'rejected',\n 'superseded',\n]);\nconst DECISION_ID_PATTERN = /^\\d{13}$/u;\nconst CREATED_AT_PATTERN =\n /^\\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;\n\nconst getEntity = (decisionId: string | null): IDiagnosticEntity | null => {\n return decisionId === null ? null : { decisionId };\n};\n\nconst addInvalidFrontmatter = (\n context: IDecisionValidationContext,\n range: ISourceRange | null,\n reason: string,\n pointer: string | null = null,\n): void => {\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_FRONTMATTER_INVALID',\n details: { reason },\n entity: getEntity(context.decisionId),\n path: context.path,\n pointer,\n range,\n });\n};\n\nconst isCanonicalCreatedAt = (value: string): boolean => {\n if (!CREATED_AT_PATTERN.test(value)) {\n return false;\n }\n\n const timestamp = Date.parse(value);\n\n return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;\n};\n\nconst readMapping = (\n node: IYamlNode,\n context: IDecisionValidationContext,\n): ReadonlyMap<string, IYamlNode> | null => {\n if (node.kind !== 'mapping') {\n addInvalidFrontmatter(context, node.range, 'mapping-required');\n return null;\n }\n\n const entries = new Map<string, IYamlNode>();\n\n for (const entry of node.entries) {\n if (entry.key.kind !== 'scalar' || typeof entry.key.value !== 'string') {\n addInvalidFrontmatter(context, entry.key.range, 'string-key-required');\n continue;\n }\n\n const key = entry.key.value;\n\n if (key !== 'status' && key !== 'createdAt' && key !== 'supersedes') {\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_PROPERTY_UNKNOWN',\n entity: getEntity(context.decisionId),\n path: context.path,\n pointer: `/${escapeJsonPointerSegment(key)}`,\n range: entry.key.range,\n });\n continue;\n }\n\n entries.set(key, entry.value);\n }\n\n return entries;\n};\n\nconst readStatus = (\n node: IYamlNode | undefined,\n context: IDecisionValidationContext,\n): IDecisionStatus | null => {\n if (\n node?.kind !== 'scalar' ||\n typeof node.value !== 'string' ||\n !DECISION_STATUSES.has(node.value as IDecisionStatus)\n ) {\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_STATUS_INVALID',\n entity: getEntity(context.decisionId),\n path: context.path,\n pointer: '/status',\n range: node?.range ?? null,\n });\n return null;\n }\n\n return node.value as IDecisionStatus;\n};\n\nconst readCreatedAt = (\n node: IYamlNode | undefined,\n context: IDecisionValidationContext,\n): string | null => {\n if (\n node?.kind !== 'scalar' ||\n typeof node.value !== 'string' ||\n !isCanonicalCreatedAt(node.value)\n ) {\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_CREATED_AT_INVALID',\n entity: getEntity(context.decisionId),\n path: context.path,\n pointer: '/createdAt',\n range: node?.range ?? null,\n });\n return null;\n }\n\n if (context.decisionId !== null && Date.parse(node.value) !== Number(context.decisionId)) {\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_TIMESTAMP_MISMATCH',\n entity: getEntity(context.decisionId),\n path: context.path,\n pointer: '/createdAt',\n range: node.range,\n });\n }\n\n return node.value;\n};\n\nconst readSupersedes = (\n node: IYamlNode | undefined,\n context: IDecisionValidationContext,\n): readonly string[] | null => {\n if (node === undefined) {\n return [];\n }\n\n if (node.kind !== 'sequence' || node.items.length === 0) {\n addInvalidFrontmatter(\n context,\n node.range,\n 'non-empty-supersedes-sequence-required',\n '/supersedes',\n );\n return null;\n }\n\n const supersedes: string[] = [];\n const seen = new Set<string>();\n\n node.items.forEach((item, index) => {\n const pointer = `/supersedes/${index}`;\n\n if (\n item.kind !== 'scalar' ||\n typeof item.value !== 'string' ||\n !DECISION_ID_PATTERN.test(item.value)\n ) {\n addInvalidFrontmatter(context, item.range, 'decision-id-string-required', pointer);\n return;\n }\n\n if (seen.has(item.value)) {\n context.diagnostics.add({\n code: 'MOLDEA_ID_DUPLICATE',\n entity: getEntity(context.decisionId),\n path: context.path,\n pointer,\n range: item.range,\n });\n return;\n }\n\n seen.add(item.value);\n supersedes.push(item.value);\n\n if (item.value === context.decisionId) {\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_SELF_SUPERSESSION',\n entity: getEntity(context.decisionId),\n path: context.path,\n pointer,\n range: item.range,\n });\n }\n });\n\n return supersedes.sort(compareExactStrings);\n};\n\n/**\n * Locates exact decision frontmatter delimiters and preserves the complete Markdown body.\n * @param value The complete normalized decision document.\n * @param locator The full-document scalar-aware source locator.\n * @param context The decision diagnostic context.\n * @returns The YAML prefix and exact body, or `null` when delimiters are unavailable.\n */\nexport const extractDecisionSections = (\n value: string,\n locator: ISourceLocator,\n context: IDecisionValidationContext,\n): { readonly body: string; readonly bodyRange: ISourceRange; readonly yaml: string } | null => {\n const firstLineEnd = value.indexOf('\\n');\n const openingLineEnd = firstLineEnd === -1 ? value.length : firstLineEnd;\n\n if (value.slice(0, openingLineEnd) !== '---') {\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_FRONTMATTER_MISSING',\n entity: getEntity(context.decisionId),\n path: context.path,\n range: locator.locateRange(0, openingLineEnd),\n });\n return null;\n }\n\n let lineStart = firstLineEnd === -1 ? value.length : firstLineEnd + 1;\n\n while (lineStart <= value.length) {\n const nextLineBreak = value.indexOf('\\n', lineStart);\n const lineEnd = nextLineBreak === -1 ? value.length : nextLineBreak;\n\n if (value.slice(lineStart, lineEnd) === '---') {\n const bodyStart = nextLineBreak === -1 ? lineEnd : nextLineBreak + 1;\n\n return {\n body: value.slice(bodyStart),\n bodyRange: locator.locateRange(bodyStart, value.length),\n yaml: value.slice(0, lineStart),\n };\n }\n\n if (nextLineBreak === -1) {\n break;\n }\n\n lineStart = nextLineBreak + 1;\n }\n\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_FRONTMATTER_MISSING',\n entity: getEntity(context.decisionId),\n path: context.path,\n range: locator.locateRange(value.length, value.length),\n });\n return null;\n};\n\n/**\n * Validates one parsed decision-frontmatter mapping without resolving other files.\n * @param node The strict parser-neutral YAML root.\n * @param context The decision diagnostic context.\n * @returns Canonical decision metadata when every document-level rule is valid.\n */\nexport const validateDecisionFrontmatter = (\n node: IYamlNode,\n context: IDecisionValidationContext,\n): Pick<IParsedDecision, 'createdAt' | 'status' | 'supersedes'> | null => {\n const initialDiagnosticCount = context.diagnostics.size;\n const entries = readMapping(node, context);\n\n if (entries === null) {\n return null;\n }\n\n const status = readStatus(entries.get('status'), context);\n const createdAt = readCreatedAt(entries.get('createdAt'), context);\n const supersedes = readSupersedes(entries.get('supersedes'), context);\n\n if (\n status === null ||\n createdAt === null ||\n supersedes === null ||\n context.diagnostics.size > initialDiagnosticCount\n ) {\n return null;\n }\n\n return { createdAt, status, supersedes };\n};\n\n/** Adds the decision-body diagnostic when the preserved Markdown has no content. */\nexport const validateDecisionBody = (\n body: string,\n range: ISourceRange,\n context: IDecisionValidationContext,\n): boolean => {\n if (hasNonWhitespace(body)) {\n return true;\n }\n\n context.diagnostics.add({\n code: 'MOLDEA_DECISION_BODY_EMPTY',\n entity: getEntity(context.decisionId),\n path: context.path,\n range,\n });\n return false;\n};\n","import type {\n IRuntimeAdapter,\n IRuntimeAdapterContext,\n IRuntimeAdapterResult,\n} from '../adapter/index.js';\nimport {\n DEFAULT_CORE_RESOURCE_LIMITS,\n RECOGNIZED_RUNTIME_ADAPTER_IDS,\n SUPPORTED_REPOSITORY_FORMAT_VERSIONS,\n} from '../constants/index.js';\nimport type { ICoreOptions, ICoreResourceLimits } from '../contracts/index.js';\nimport { createCoreOperationResourceLimits } from '../diagnostic-utilities/index.js';\nimport { CoreConfigurationException } from '../exceptions/index.js';\nimport type { IRepositoryFormatVersion } from '../format/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\n\n// detached adapter and complete Core configuration snapshots\nexport interface IRuntimeAdapterSnapshot {\n readonly id: string;\n readonly supportedRepositoryFormatVersions: readonly IRepositoryFormatVersion[];\n readonly inspect: (context: IRuntimeAdapterContext) => Promise<IRuntimeAdapterResult>;\n}\n\nexport interface ICoreOptionsSnapshot {\n readonly adapters: readonly IRuntimeAdapterSnapshot[];\n readonly limits: ICoreResourceLimits;\n}\n\n/** Creates an operation-local options view with one shared raw-diagnostic budget. */\nexport const createCoreOperationOptionsSnapshot = (\n options: ICoreOptionsSnapshot,\n): ICoreOptionsSnapshot => {\n return Object.freeze({\n adapters: options.adapters,\n limits: createCoreOperationResourceLimits(options.limits),\n });\n};\n\nconst RESOURCE_LIMIT_KEYS = [\n 'maxEntries',\n 'maxTotalBytesRead',\n 'maxFileBytes',\n 'maxManifestBytes',\n 'maxRetainedBytes',\n 'maxDiagnostics',\n 'maxEvidence',\n] as const satisfies readonly (keyof ICoreResourceLimits)[];\n\nconst STABLE_ID_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;\nconst WINDOWS_RESERVED_ID_PATTERN = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/u;\n\nconst compareStrings = (left: string, right: string): number => {\n if (left < right) {\n return -1;\n }\n\n if (left > right) {\n return 1;\n }\n\n return 0;\n};\n\nconst invalidAdapter = (adapterId?: string): never => {\n throw new CoreConfigurationException({\n ...(adapterId === undefined ? {} : { adapterId }),\n code: 'INVALID_ADAPTER_DEFINITION',\n operation: 'create-core',\n });\n};\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\nconst isStableId = (value: string): boolean => {\n return value.length >= 1 && value.length <= 64 && STABLE_ID_PATTERN.test(value);\n};\n\n/**\n * Validates, copies, fills, and freezes all configured resource limits.\n * @param candidate The untrusted optional limit overrides.\n * @returns The complete frozen resource limits.\n * @throws\n * - INVALID_RESOURCE_LIMIT: A Core resource limit is invalid.\n */\nconst normalizeLimits = (candidate: unknown): ICoreResourceLimits => {\n if (candidate === undefined) {\n return DEFAULT_CORE_RESOURCE_LIMITS;\n }\n\n if (!isRecord(candidate)) {\n throw new CoreConfigurationException({\n code: 'INVALID_RESOURCE_LIMIT',\n operation: 'create-core',\n });\n }\n\n const knownKeys = new Set<string>(RESOURCE_LIMIT_KEYS);\n\n if (Object.keys(candidate).some((key) => !knownKeys.has(key))) {\n throw new CoreConfigurationException({\n code: 'INVALID_RESOURCE_LIMIT',\n operation: 'create-core',\n });\n }\n\n const normalized: ICoreResourceLimits = {\n ...DEFAULT_CORE_RESOURCE_LIMITS,\n };\n\n for (const key of RESOURCE_LIMIT_KEYS) {\n const value = candidate[key];\n\n if (value === undefined) {\n continue;\n }\n\n if (!Number.isSafeInteger(value) || (value as number) <= 0) {\n throw new CoreConfigurationException({\n code: 'INVALID_RESOURCE_LIMIT',\n operation: 'create-core',\n });\n }\n\n (normalized as Record<keyof ICoreResourceLimits, number>)[key] = value as number;\n }\n\n return freezeRecursively(normalized);\n};\n\n/**\n * Snapshots one adapter definition without freezing caller-owned state.\n * @param candidate The untrusted adapter definition.\n * @returns A frozen detached adapter snapshot.\n * @throws\n * - RESERVED_ADAPTER_ID: A reserved runtime adapter ID was supplied.\n * - INVALID_ADAPTER_DEFINITION: A runtime adapter definition is invalid.\n */\nconst normalizeAdapter = (candidate: unknown): IRuntimeAdapterSnapshot => {\n if (!isRecord(candidate)) {\n return invalidAdapter();\n }\n\n const id = candidate['id'];\n\n if (typeof id !== 'string' || !isStableId(id) || WINDOWS_RESERVED_ID_PATTERN.test(id)) {\n return invalidAdapter();\n }\n\n if (id === 'custom') {\n throw new CoreConfigurationException({\n adapterId: id,\n code: 'RESERVED_ADAPTER_ID',\n operation: 'create-core',\n });\n }\n\n if (!(RECOGNIZED_RUNTIME_ADAPTER_IDS as readonly string[]).includes(id)) {\n return invalidAdapter(id);\n }\n\n const versions = candidate['supportedRepositoryFormatVersions'];\n const inspect = candidate['inspect'];\n\n if (!Array.isArray(versions) || versions.length === 0 || typeof inspect !== 'function') {\n return invalidAdapter(id);\n }\n\n const supportedVersions = new Set<IRepositoryFormatVersion>();\n\n for (const version of versions as readonly unknown[]) {\n if (\n !SUPPORTED_REPOSITORY_FORMAT_VERSIONS.includes(version as IRepositoryFormatVersion) ||\n supportedVersions.has(version as IRepositoryFormatVersion)\n ) {\n return invalidAdapter(id);\n }\n\n supportedVersions.add(version as IRepositoryFormatVersion);\n }\n\n const inspectReference = inspect as IRuntimeAdapter['inspect'];\n\n return freezeRecursively({\n id,\n inspect: async (context: IRuntimeAdapterContext): Promise<IRuntimeAdapterResult> =>\n inspectReference.call(candidate, context),\n supportedRepositoryFormatVersions: [...supportedVersions].sort((left, right) => left - right),\n });\n};\n\n/**\n * Validates, snapshots, and deterministically sorts the configured adapter registry.\n * @param candidate The untrusted optional adapter definitions.\n * @returns The frozen adapter snapshots in canonical ID order.\n * @throws\n * - DUPLICATE_ADAPTER_ID: A runtime adapter ID is registered more than once.\n * - RESERVED_ADAPTER_ID: A reserved runtime adapter ID was supplied.\n * - INVALID_ADAPTER_DEFINITION: A runtime adapter definition is invalid.\n */\nconst normalizeAdapters = (candidate: unknown): readonly IRuntimeAdapterSnapshot[] => {\n if (candidate === undefined) {\n return Object.freeze([]);\n }\n\n if (!Array.isArray(candidate)) {\n return invalidAdapter();\n }\n\n const adapters = Array.from(candidate as readonly unknown[], (adapter) =>\n normalizeAdapter(adapter),\n );\n const ids = new Set<string>();\n\n for (const adapter of adapters) {\n if (ids.has(adapter.id)) {\n throw new CoreConfigurationException({\n adapterId: adapter.id,\n code: 'DUPLICATE_ADAPTER_ID',\n operation: 'create-core',\n });\n }\n\n ids.add(adapter.id);\n }\n\n return freezeRecursively(adapters.sort((left, right) => compareStrings(left.id, right.id)));\n};\n\n/**\n * Validates and snapshots caller-owned Core construction options.\n * @param options The optional adapters and resource-limit overrides.\n * @returns A deeply frozen, deterministically ordered configuration snapshot.\n * @throws\n * - DUPLICATE_ADAPTER_ID: A runtime adapter ID is registered more than once.\n * - RESERVED_ADAPTER_ID: A reserved runtime adapter ID was supplied.\n * - INVALID_ADAPTER_DEFINITION: A runtime adapter definition is invalid.\n * - INVALID_RESOURCE_LIMIT: A Core resource limit is invalid.\n */\nexport const normalizeCoreOptions = (options: ICoreOptions | undefined): ICoreOptionsSnapshot => {\n if (options !== undefined && !isRecord(options)) {\n return invalidAdapter();\n }\n\n return freezeRecursively({\n adapters: normalizeAdapters(options?.['adapters']),\n limits: normalizeLimits(options?.['limits']),\n });\n};\n","import type { ISourcePosition, ISourceRange } from '../diagnostics/index.js';\n\n// scalar-aware normalized source lookup used by parsers and diagnostics\nexport interface ISourceLocator {\n locateRange(startOffset: number, endOffset: number): ISourceRange;\n}\n\nconst findLineIndex = (lineStarts: readonly number[], offset: number): number => {\n let lower = 0;\n let upper = lineStarts.length - 1;\n\n while (lower < upper) {\n const middle = Math.ceil((lower + upper) / 2);\n\n if ((lineStarts[middle] ?? 0) <= offset) {\n lower = middle;\n } else {\n upper = middle - 1;\n }\n }\n\n return lower;\n};\n\n/**\n * Creates an efficient UTF-16-offset to Unicode-scalar source locator.\n * @param value The already-normalized valid Unicode scalar text.\n * @returns A locator producing one-based lines and columns with zero-based scalar offsets.\n */\nexport const createSourceLocator = (value: string): ISourceLocator => {\n const scalarOffsets = new Uint32Array(value.length + 1);\n const lineStarts = [0];\n let scalarOffset = 0;\n\n for (let codeUnitOffset = 0; codeUnitOffset < value.length;) {\n const codePoint = value.codePointAt(codeUnitOffset);\n const width = codePoint !== undefined && codePoint > 0xffff ? 2 : 1;\n\n scalarOffsets[codeUnitOffset] = scalarOffset;\n\n for (let interiorOffset = 1; interiorOffset < width; interiorOffset += 1) {\n scalarOffsets[codeUnitOffset + interiorOffset] = scalarOffset;\n }\n\n codeUnitOffset += width;\n scalarOffset += 1;\n scalarOffsets[codeUnitOffset] = scalarOffset;\n\n if (codePoint === 0x0a) {\n lineStarts.push(codeUnitOffset);\n }\n }\n\n const locatePosition = (candidateOffset: number): ISourcePosition => {\n const codeUnitOffset = Math.max(0, Math.min(value.length, candidateOffset));\n const lineIndex = findLineIndex(lineStarts, codeUnitOffset);\n const lineStart = lineStarts[lineIndex] ?? 0;\n const positionScalarOffset = scalarOffsets[codeUnitOffset] ?? 0;\n const lineStartScalarOffset = scalarOffsets[lineStart] ?? 0;\n\n return {\n column: positionScalarOffset - lineStartScalarOffset + 1,\n line: lineIndex + 1,\n offset: positionScalarOffset,\n };\n };\n\n return Object.freeze({\n locateRange: (startOffset: number, endOffset: number): ISourceRange => ({\n end: locatePosition(endOffset),\n start: locatePosition(startOffset),\n }),\n });\n};\n","import { parseRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport type {\n IContentDigest,\n IContentDigestResult,\n ICoreResourceLimits,\n INormalizedText,\n ITextDocumentInput,\n ITextNormalizationResult,\n} from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { CoreOperationException, type ICoreOperation } from '../exceptions/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/**\n * Measures valid scalar UTF-8 bytes and stops once the operation budget is exceeded.\n * @param value The decoded string to measure without lossy replacement.\n * @param maximumByteLength The threshold after which measurement may stop early.\n * @returns The measured bytes, a value above the threshold, or `null` for invalid Unicode.\n */\nconst measureScalarUtf8ByteLength = (value: string, maximumByteLength: number): number | null => {\n let byteLength = 0;\n\n for (let index = 0; index < value.length; index += 1) {\n const codeUnit = value.charCodeAt(index);\n\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n if (index + 1 >= value.length) {\n return null;\n }\n\n const nextCodeUnit = value.charCodeAt(index + 1);\n\n if (nextCodeUnit < 0xdc00 || nextCodeUnit > 0xdfff) {\n return null;\n }\n\n byteLength += 4;\n\n if (byteLength > maximumByteLength) {\n return byteLength;\n }\n\n index += 1;\n continue;\n }\n\n if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {\n return null;\n }\n\n byteLength += codeUnit <= 0x7f ? 1 : codeUnit <= 0x7ff ? 2 : 3;\n\n if (byteLength > maximumByteLength) {\n return byteLength;\n }\n }\n\n return byteLength;\n};\n\nconst countUnicodeScalars = (value: string): number => {\n let count = 0;\n\n for (let index = 0; index < value.length; count += 1) {\n const codePoint = value.codePointAt(index);\n\n if (codePoint === undefined) {\n break;\n }\n\n index += codePoint > 0xffff ? 2 : 1;\n }\n\n return count;\n};\n\n/**\n * Collects every normalized NUL location or rejects when the diagnostic budget is exhausted.\n * @param value The normalized scalar text to inspect.\n * @param path The logical document path attached to each diagnostic.\n * @param diagnostics The operation collector receiving every NUL diagnostic.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nconst collectNulDiagnostics = (\n value: string,\n path: IRepositoryPath,\n diagnostics: ICoreDiagnosticCollector,\n): void => {\n let column = 1;\n let line = 1;\n let offset = 0;\n\n for (const scalar of value) {\n if (scalar === '\\0') {\n diagnostics.add({\n code: 'MOLDEA_TEXT_NUL_FORBIDDEN',\n path,\n range: {\n end: { column: column + 1, line, offset: offset + 1 },\n start: { column, line, offset },\n },\n });\n }\n\n if (scalar === '\\n') {\n column = 1;\n line += 1;\n } else {\n column += 1;\n }\n\n offset += 1;\n }\n};\n\nconst invalidArgument = (operation: ICoreOperation): never => {\n throw new CoreOperationException({\n code: 'INVALID_ARGUMENT',\n operation,\n });\n};\n\nconst enforceFileLimit = (\n byteLength: number,\n limits: ICoreResourceLimits,\n operation: ICoreOperation,\n limit: 'maxFileBytes' | 'maxManifestBytes',\n): void => {\n if (byteLength <= limits[limit]) {\n return;\n }\n\n throw new CoreOperationException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit,\n limitMaximum: limits[limit],\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage: byteLength,\n operation,\n });\n};\n\nconst invalidResult = (diagnostics: readonly ICoreDiagnostic[]): ITextNormalizationResult => {\n return freezeRecursively({\n diagnostics: [...diagnostics],\n text: null,\n valid: false,\n });\n};\n\n/**\n * Validates one public text input, enforces its source-byte budget, and decodes strict UTF-8.\n * @param input The untrusted public text-document input.\n * @param limits The immutable Core resource limits.\n * @param operation The public operation requesting the input.\n * @param limit The source-byte limit applied by the operation.\n * @param diagnostics The operation collector receiving text diagnostics.\n * @returns Decoded text or a frozen structural failure result.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nconst readInput = (\n input: ITextDocumentInput,\n limits: ICoreResourceLimits,\n operation: ICoreOperation,\n limit: 'maxFileBytes' | 'maxManifestBytes',\n diagnostics: ICoreDiagnosticCollector,\n): { readonly path: IRepositoryPath; readonly value: string } | ITextNormalizationResult => {\n if (!isRecord(input)) {\n return invalidArgument(operation);\n }\n\n const pathCandidate = input['path'];\n const content = input['content'];\n\n if (\n typeof pathCandidate !== 'string' ||\n (typeof content !== 'string' && !(content instanceof Uint8Array))\n ) {\n return invalidArgument(operation);\n }\n\n const path = parseRepositoryPath(pathCandidate);\n\n if (typeof content === 'string') {\n const byteLength = measureScalarUtf8ByteLength(content, limits[limit]);\n\n if (byteLength === null) {\n diagnostics.add({ code: 'MOLDEA_TEXT_INVALID_UNICODE', path });\n return invalidResult(diagnostics.finalize());\n }\n\n enforceFileLimit(byteLength, limits, operation, limit);\n return { path, value: content };\n }\n\n enforceFileLimit(content.byteLength, limits, operation, limit);\n const bytes = new Uint8Array(content);\n\n try {\n return { path, value: decoder.decode(bytes) };\n } catch {\n diagnostics.add({ code: 'MOLDEA_TEXT_INVALID_UTF8', path });\n return invalidResult(diagnostics.finalize());\n }\n};\n\n/**\n * Validates and normalizes one text document under an operation-specific resource budget.\n * @param input The logical path and decoded string or exact source bytes.\n * @param limits The immutable Core resource limits.\n * @param operation The public Core operation requesting normalization.\n * @param limit The source-byte limit applied by the operation.\n * @returns A frozen normalized result or structural text diagnostics.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nexport const normalizeTextDocument = (\n input: ITextDocumentInput,\n limits: ICoreResourceLimits,\n operation: ICoreOperation,\n limit: 'maxFileBytes' | 'maxManifestBytes' = 'maxFileBytes',\n): ITextNormalizationResult => {\n const diagnostics = createCoreDiagnosticCollector(limits, operation);\n const decoded = readInput(input, limits, operation, limit, diagnostics);\n\n if ('valid' in decoded) {\n return decoded;\n }\n\n const withoutLeadingBom = decoded.value.startsWith('\\ufeff')\n ? decoded.value.slice(1)\n : decoded.value;\n const value = withoutLeadingBom.replace(/\\r\\n?/gu, '\\n');\n collectNulDiagnostics(value, decoded.path, diagnostics);\n\n if (diagnostics.size > 0) {\n return invalidResult(diagnostics.finalize());\n }\n\n const text: INormalizedText = freezeRecursively({\n scalarLength: countUnicodeScalars(value),\n utf8ByteLength: encoder.encode(value).byteLength,\n value,\n });\n\n return freezeRecursively({\n diagnostics: [],\n text,\n valid: true,\n });\n};\n\nconst toLowercaseHex = (bytes: Uint8Array): string => {\n let value = '';\n\n for (const byte of bytes) {\n value += byte.toString(16).padStart(2, '0');\n }\n\n return value;\n};\n\n/**\n * Calculates the canonical digest for already-normalized text.\n * @param text The validated normalized text to encode and hash.\n * @returns A promise resolving to the canonical lowercase SHA-256 digest.\n */\nexport const calculateNormalizedTextDigest = async (\n text: INormalizedText,\n): Promise<IContentDigest> => {\n const bytes = encoder.encode(text.value);\n const hash = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes));\n\n return `sha256:${toLowercaseHex(hash)}` as IContentDigest;\n};\n\n/**\n * Calculates the normalized SHA-256 digest for one text document.\n * @param input The logical path and decoded string or exact source bytes.\n * @param limits The immutable Core resource limits.\n * @returns A promise resolving to a frozen digest result or structural text diagnostics.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nexport const calculateContentDigest = async (\n input: ITextDocumentInput,\n limits: ICoreResourceLimits,\n): Promise<IContentDigestResult> => {\n const normalized = normalizeTextDocument(input, limits, 'calculate-content-digest');\n\n if (!normalized.valid || normalized.text === null) {\n return freezeRecursively({\n diagnostics: normalized.diagnostics,\n digest: null,\n text: null,\n valid: false,\n });\n }\n\n const digest = await calculateNormalizedTextDigest(normalized.text);\n\n return freezeRecursively({\n diagnostics: [],\n digest,\n text: normalized.text,\n valid: true,\n });\n};\n","import { Parser, isAlias, isMap, isScalar, isSeq, parseAllDocuments, type ParsedNode } from 'yaml';\n\nimport type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { ISourceRange } from '../diagnostics/index.js';\nimport type { ISourceLocator } from '../source-location/index.js';\n\n// parser-neutral YAML nodes retained only inside Core\nexport type IYamlNode = IYamlMappingNode | IYamlSequenceNode | IYamlScalarNode;\n\nexport interface IYamlMappingEntry {\n readonly key: IYamlNode;\n readonly value: IYamlNode;\n}\n\nexport interface IYamlMappingNode {\n readonly kind: 'mapping';\n readonly entries: readonly IYamlMappingEntry[];\n readonly range: ISourceRange;\n}\n\nexport interface IYamlSequenceNode {\n readonly kind: 'sequence';\n readonly items: readonly IYamlNode[];\n readonly range: ISourceRange;\n}\n\nexport interface IYamlScalarNode {\n readonly kind: 'scalar';\n readonly range: ISourceRange;\n readonly source: string;\n readonly style: string | null;\n readonly value: string | number | bigint | boolean | null;\n}\n\nexport interface IStrictYamlParseResult {\n readonly valid: boolean;\n readonly value: IYamlNode | null;\n}\n\nconst CORE_TAGS = new Set([\n 'tag:yaml.org,2002:bool',\n 'tag:yaml.org,2002:float',\n 'tag:yaml.org,2002:int',\n 'tag:yaml.org,2002:map',\n 'tag:yaml.org,2002:null',\n 'tag:yaml.org,2002:seq',\n 'tag:yaml.org,2002:str',\n]);\n\nconst toRange = (\n range: readonly [number, number, number] | null | undefined,\n locator: ISourceLocator,\n): ISourceRange => {\n return locator.locateRange(range?.[0] ?? 0, range?.[1] ?? range?.[0] ?? 0);\n};\n\nconst addUnsupportedFeature = (\n diagnostics: ICoreDiagnosticCollector,\n path: IRepositoryPath,\n range: ISourceRange,\n reason: string,\n): void => {\n diagnostics.add({\n code: 'MOLDEA_YAML_FEATURE_UNSUPPORTED',\n details: { reason },\n path,\n range,\n });\n};\n\nconst isUnicodeScalarString = (value: string): boolean => {\n for (let index = 0; index < value.length; index += 1) {\n const codeUnit = value.charCodeAt(index);\n\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n const nextCodeUnit = value.charCodeAt(index + 1);\n\n if (!(nextCodeUnit >= 0xdc00 && nextCodeUnit <= 0xdfff)) {\n return false;\n }\n\n index += 1;\n } else if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {\n return false;\n }\n }\n\n return true;\n};\n\nconst isCoreTagCompatible = (node: ParsedNode): boolean => {\n switch (node.tag) {\n case 'tag:yaml.org,2002:bool':\n return isScalar(node) && typeof node.value === 'boolean';\n case 'tag:yaml.org,2002:float':\n return isScalar(node) && typeof node.value === 'number';\n case 'tag:yaml.org,2002:int':\n return isScalar(node) && typeof node.value === 'bigint';\n case 'tag:yaml.org,2002:map':\n return isMap(node);\n case 'tag:yaml.org,2002:null':\n return isScalar(node) && node.value === null;\n case 'tag:yaml.org,2002:seq':\n return isSeq(node);\n case 'tag:yaml.org,2002:str':\n return isScalar(node) && typeof node.value === 'string';\n default:\n return false;\n }\n};\n\nconst convertNode = (\n node: ParsedNode,\n path: IRepositoryPath,\n locator: ISourceLocator,\n diagnostics: ICoreDiagnosticCollector,\n): IYamlNode | null => {\n const range = toRange(node.range, locator);\n\n if (isAlias(node)) {\n addUnsupportedFeature(diagnostics, path, range, 'alias');\n return null;\n }\n\n if ('anchor' in node && typeof node.anchor === 'string') {\n addUnsupportedFeature(diagnostics, path, range, 'anchor');\n }\n\n if (node.tag !== undefined) {\n if (!CORE_TAGS.has(node.tag)) {\n addUnsupportedFeature(diagnostics, path, range, 'custom-tag');\n return null;\n }\n\n if (!isCoreTagCompatible(node)) {\n diagnostics.add({\n code: 'MOLDEA_YAML_MALFORMED',\n details: { reason: 'tag-value' },\n path,\n range,\n });\n return null;\n }\n }\n\n if (isScalar(node)) {\n const value = node.value;\n\n if (\n value !== null &&\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'bigint' &&\n typeof value !== 'boolean'\n ) {\n diagnostics.add({\n code: 'MOLDEA_YAML_MALFORMED',\n details: { reason: 'scalar-type' },\n path,\n range,\n });\n return null;\n }\n\n if (typeof value === 'string' && !isUnicodeScalarString(value)) {\n diagnostics.add({\n code: 'MOLDEA_YAML_MALFORMED',\n details: { reason: 'invalid-unicode' },\n path,\n range,\n });\n return null;\n }\n\n return {\n kind: 'scalar',\n range,\n source: node.source,\n style: node.type ?? null,\n value,\n };\n }\n\n if (isSeq(node)) {\n const items: IYamlNode[] = [];\n\n for (const item of node.items) {\n if (item === null) {\n items.push({ kind: 'scalar', range, source: '', style: null, value: null });\n continue;\n }\n\n const converted = convertNode(item, path, locator, diagnostics);\n\n if (converted !== null) {\n items.push(converted);\n }\n }\n\n return { items, kind: 'sequence', range };\n }\n\n if (isMap(node)) {\n const entries: IYamlMappingEntry[] = [];\n\n for (const pair of node.items) {\n const key = convertNode(pair.key, path, locator, diagnostics);\n const value =\n pair.value === null\n ? ({\n kind: 'scalar',\n range: key?.range ?? range,\n source: '',\n style: null,\n value: null,\n } satisfies IYamlScalarNode)\n : convertNode(pair.value, path, locator, diagnostics);\n\n if (key?.kind === 'scalar' && key.value === '<<' && key.style === 'PLAIN') {\n addUnsupportedFeature(diagnostics, path, key.range, 'merge-key');\n }\n\n if (key !== null && value !== null) {\n entries.push({ key, value });\n }\n }\n\n return { entries, kind: 'mapping', range };\n }\n\n diagnostics.add({\n code: 'MOLDEA_YAML_MALFORMED',\n details: { reason: 'node-type' },\n path,\n range,\n });\n return null;\n};\n\nconst addParserDiagnostic = (\n code: string,\n start: number,\n end: number,\n path: IRepositoryPath,\n locator: ISourceLocator,\n diagnostics: ICoreDiagnosticCollector,\n): void => {\n if (code === 'BAD_DIRECTIVE') {\n return;\n }\n\n if (code === 'DUPLICATE_KEY') {\n diagnostics.add({\n code: 'MOLDEA_YAML_DUPLICATE_KEY',\n path,\n range: locator.locateRange(start, end),\n });\n return;\n }\n\n if (code === 'TAG_RESOLVE_FAILED') {\n return;\n }\n\n diagnostics.add({\n code: 'MOLDEA_YAML_MALFORMED',\n details: { reason: code === 'RESOURCE_EXHAUSTION' ? 'resource-exhaustion' : 'syntax' },\n path,\n range: locator.locateRange(start, end),\n });\n};\n\n/**\n * Parses one normalized YAML 1.2 Core Schema document into parser-neutral nodes.\n * @param value The normalized manifest text.\n * @param path The logical source path used by diagnostics.\n * @param locator The scalar-aware source locator for the normalized text.\n * @param diagnostics The operation diagnostic collector.\n * @returns The private parsed tree only when the YAML substrate is trustworthy.\n */\nexport const parseStrictYaml = (\n value: string,\n path: IRepositoryPath,\n locator: ISourceLocator,\n diagnostics: ICoreDiagnosticCollector,\n): IStrictYamlParseResult => {\n const initialDiagnosticCount = diagnostics.size;\n\n for (const token of new Parser().parse(value)) {\n if (token.type === 'directive') {\n addUnsupportedFeature(\n diagnostics,\n path,\n locator.locateRange(token.offset, token.offset + token.source.length),\n 'directive',\n );\n }\n }\n\n const documents = parseAllDocuments(value, {\n intAsBigInt: true,\n keepSourceTokens: true,\n logLevel: 'silent',\n merge: false,\n prettyErrors: false,\n resolveKnownTags: false,\n schema: 'core',\n strict: true,\n uniqueKeys: true,\n version: '1.2',\n });\n\n if (documents.length > 1) {\n const secondDocument = documents[1];\n const range = secondDocument?.range;\n\n diagnostics.add({\n code: 'MOLDEA_YAML_MULTIPLE_DOCUMENTS',\n path,\n range: locator.locateRange(range?.[0] ?? 0, range?.[0] ?? 0),\n });\n }\n\n for (const document of documents) {\n for (const error of [...document.errors, ...document.warnings]) {\n addParserDiagnostic(error.code, error.pos[0], error.pos[1], path, locator, diagnostics);\n }\n }\n\n if (documents.length > 1 || diagnostics.size > initialDiagnosticCount) {\n return { valid: false, value: null };\n }\n\n const document = documents[0];\n\n if (document === undefined || document.contents === null) {\n return {\n valid: true,\n value: {\n kind: 'scalar',\n range: locator.locateRange(0, 0),\n source: '',\n style: null,\n value: null,\n },\n };\n }\n\n const parsedValue = convertNode(document.contents, path, locator, diagnostics);\n\n return {\n valid: parsedValue !== null && diagnostics.size === initialDiagnosticCount,\n value: diagnostics.size === initialDiagnosticCount ? parsedValue : null,\n };\n};\n","import { parseRepositoryPath } from '@moldea.ai/repository';\n\nimport type {\n IDecisionParseResult,\n IIndexedTextAsset,\n ITextDocumentInput,\n} from '../contracts/index.js';\nimport {\n extractDecisionSections,\n validateDecisionBody,\n validateDecisionFrontmatter,\n} from '../decision-validation/index.js';\nimport { createCoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { ICoreOperation } from '../exceptions/index.js';\nimport { parseDecisionIdFromPath } from '../format-validation/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport { createSourceLocator } from '../source-location/index.js';\nimport { calculateNormalizedTextDigest, normalizeTextDocument } from '../text/index.js';\nimport { parseStrictYaml } from '../yaml/index.js';\n\n/**\n * Parses and validates one complete decision document without resolving cross-file relationships.\n * @param input The canonical logical path and exact decision text or bytes.\n * @param options The immutable Core limits and adapter snapshots.\n * @param operation The owning public or repository-level operation for typed failures.\n * @returns A frozen all-or-nothing decision parse result.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nexport const parseDecisionDocument = async (\n input: ITextDocumentInput,\n options: ICoreOptionsSnapshot,\n operation: Extract<ICoreOperation, 'parse-decision' | 'validate-project'> = 'parse-decision',\n): Promise<IDecisionParseResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const normalized = normalizeTextDocument(input, options.limits, operation);\n const path = parseRepositoryPath(input.path);\n const diagnostics = createCoreDiagnosticCollector(options.limits, operation);\n const decisionId = parseDecisionIdFromPath(path);\n\n if (decisionId === null) {\n diagnostics.add({ code: 'MOLDEA_DECISION_FILENAME_INVALID', path });\n }\n\n for (const diagnostic of normalized.diagnostics) {\n diagnostics.merge(diagnostic);\n }\n\n if (!normalized.valid || normalized.text === null) {\n return freezeRecursively({\n decision: null,\n diagnostics: diagnostics.finalize(),\n valid: false,\n });\n }\n\n const context = { decisionId, diagnostics, path };\n const locator = createSourceLocator(normalized.text.value);\n const sections = extractDecisionSections(normalized.text.value, locator, context);\n let metadata: ReturnType<typeof validateDecisionFrontmatter> = null;\n\n if (sections !== null) {\n validateDecisionBody(sections.body, sections.bodyRange, context);\n const parsed = parseStrictYaml(sections.yaml, path, locator, diagnostics);\n\n if (parsed.valid && parsed.value !== null) {\n metadata = validateDecisionFrontmatter(parsed.value, context);\n }\n }\n\n if (decisionId === null || sections === null || metadata === null || diagnostics.size > 0) {\n return freezeRecursively({\n decision: null,\n diagnostics: diagnostics.finalize(),\n valid: false,\n });\n }\n\n const digest = await calculateNormalizedTextDigest(normalized.text);\n const asset: IIndexedTextAsset = {\n content: normalized.text.value,\n digest,\n path,\n scalarLength: normalized.text.scalarLength,\n utf8ByteLength: normalized.text.utf8ByteLength,\n };\n\n return freezeRecursively({\n decision: {\n asset,\n body: sections.body,\n createdAt: metadata.createdAt,\n id: decisionId,\n path,\n status: metadata.status,\n supersedes: metadata.supersedes,\n },\n diagnostics: diagnostics.finalize(),\n valid: true,\n });\n};\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport { RECOGNIZED_RUNTIME_ADAPTER_IDS } from '../constants/index.js';\nimport {\n escapeJsonPointerSegment,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { IDiagnosticEntity, ISourceRange } from '../diagnostics/index.js';\nimport {\n compareExactStrings,\n hasNonWhitespace,\n hasUnsupportedGlobMetacharacter,\n isCanonicalMoldeaPath,\n isCapabilityDescription,\n isContextPath,\n isDecisionPath,\n isMirrorPath,\n isNonEmptySingleLine,\n isRepositorySymbol,\n isReservedId,\n isRuntimeGuidancePath,\n isSimpleGlob,\n isStableId,\n isVariableId,\n parseManifestPath,\n sortRepositoryReferences,\n} from '../format-validation/index.js';\nimport type {\n IAgentBindingsManifestEntry,\n IAgentManifestEntry,\n IRuntimeManifestEntry,\n IMoldeaManifestV1,\n IRelationshipManifestEntry,\n IRepositoryFormatVersion,\n IRepositoryReference,\n IRuntimeVariableManifestEntry,\n ISkillManifestEntry,\n IToolManifestEntry,\n IUnresolvedRequirementEffect,\n IUnresolvedRequirementManifestEntry,\n} from '../format/index.js';\nimport { createNullPrototypeRecord } from '../immutable/index.js';\nimport type { IYamlNode, IYamlScalarNode } from '../yaml/index.js';\n\ninterface IManifestValidationContext {\n readonly diagnostics: ICoreDiagnosticCollector;\n readonly mirrorPaths: Set<string>;\n readonly path: IRepositoryPath;\n readonly runtimeLocations: IRuntimeManifestLocation[];\n}\n\n// private source location retained for repository-level adapter preflight\nexport interface IRuntimeManifestLocation {\n readonly adapterId: string;\n readonly agentId: string;\n readonly path: IRepositoryPath;\n readonly pointer: string;\n readonly range: ISourceRange;\n}\n\ninterface IMappingEntry {\n readonly key: IYamlScalarNode;\n readonly value: IYamlNode;\n}\n\nconst childPointer = (pointer: string, key: string): string => {\n return `${pointer}/${escapeJsonPointerSegment(key)}`;\n};\n\nconst addInvalidValue = (\n context: IManifestValidationContext,\n pointer: string,\n range: ISourceRange | null,\n reason: string,\n entity: IDiagnosticEntity | null = null,\n): void => {\n context.diagnostics.add({\n code: 'MOLDEA_MANIFEST_VALUE_INVALID',\n details: { reason },\n entity,\n path: context.path,\n pointer,\n range,\n });\n};\n\nconst readMapping = (\n node: IYamlNode,\n pointer: string,\n allowedProperties: ReadonlySet<string> | null,\n context: IManifestValidationContext,\n entity: IDiagnosticEntity | null = null,\n): ReadonlyMap<string, IMappingEntry> | null => {\n if (node.kind !== 'mapping') {\n addInvalidValue(context, pointer, node.range, 'mapping-required', entity);\n return null;\n }\n\n const entries = new Map<string, IMappingEntry>();\n\n for (const entry of node.entries) {\n if (entry.key.kind !== 'scalar' || typeof entry.key.value !== 'string') {\n addInvalidValue(context, pointer, entry.key.range, 'string-key-required', entity);\n continue;\n }\n\n const key = entry.key.value;\n\n if (allowedProperties !== null && !allowedProperties.has(key)) {\n context.diagnostics.add({\n code: 'MOLDEA_MANIFEST_PROPERTY_UNKNOWN',\n entity,\n path: context.path,\n pointer: childPointer(pointer, key),\n range: entry.key.range,\n });\n continue;\n }\n\n entries.set(key, { key: entry.key, value: entry.value });\n }\n\n return entries;\n};\n\nconst readString = (\n entry: IMappingEntry | undefined,\n pointer: string,\n context: IManifestValidationContext,\n options: {\n readonly entity?: IDiagnosticEntity;\n readonly required?: boolean;\n readonly singleLine?: boolean;\n } = {},\n): string | null => {\n if (entry === undefined) {\n if (options.required === true) {\n addInvalidValue(context, pointer, null, 'required', options.entity ?? null);\n }\n\n return null;\n }\n\n if (entry.value.kind !== 'scalar' || typeof entry.value.value !== 'string') {\n addInvalidValue(context, pointer, entry.value.range, 'string-required', options.entity ?? null);\n return null;\n }\n\n const value = entry.value.value;\n\n if (!hasNonWhitespace(value) || (options.singleLine === true && !isNonEmptySingleLine(value))) {\n addInvalidValue(context, pointer, entry.value.range, 'string-invalid', options.entity ?? null);\n return null;\n }\n\n return value;\n};\n\nconst validateStableId = (\n value: string,\n range: ISourceRange,\n pointer: string,\n context: IManifestValidationContext,\n entity: IDiagnosticEntity | null = null,\n): boolean => {\n if (!isStableId(value)) {\n context.diagnostics.add({\n code: 'MOLDEA_ID_INVALID',\n entity,\n path: context.path,\n pointer,\n range,\n });\n return false;\n }\n\n if (isReservedId(value)) {\n context.diagnostics.add({\n code: 'MOLDEA_ID_RESERVED',\n entity,\n path: context.path,\n pointer,\n range,\n });\n return false;\n }\n\n return true;\n};\n\nconst readReference = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n entity: IDiagnosticEntity | null = null,\n): IRepositoryReference | null => {\n const entries = readMapping(node, pointer, new Set(['path', 'symbol']), context, entity);\n\n if (entries === null) {\n return null;\n }\n\n const pathEntry = entries.get('path');\n\n if (pathEntry?.value.kind !== 'scalar' || typeof pathEntry.value.value !== 'string') {\n context.diagnostics.add({\n code: 'MOLDEA_PATH_INVALID',\n details: { reason: pathEntry === undefined ? 'missing' : 'type' },\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'path'),\n range: pathEntry?.value.range ?? null,\n });\n return null;\n }\n\n const path = parseManifestPath(pathEntry.value.value);\n\n if (path === null) {\n context.diagnostics.add({\n code: 'MOLDEA_PATH_INVALID',\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'path'),\n range: pathEntry.value.range,\n });\n return null;\n }\n\n const symbolEntry = entries.get('symbol');\n\n if (symbolEntry === undefined) {\n return { path };\n }\n\n if (\n symbolEntry.value.kind !== 'scalar' ||\n typeof symbolEntry.value.value !== 'string' ||\n !isRepositorySymbol(symbolEntry.value.value)\n ) {\n context.diagnostics.add({\n code: 'MOLDEA_SYMBOL_INVALID',\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'symbol'),\n range: symbolEntry.value.range,\n });\n return null;\n }\n\n if (isCanonicalMoldeaPath(path)) {\n context.diagnostics.add({\n code: 'MOLDEA_SYMBOL_FORBIDDEN',\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'symbol'),\n range: symbolEntry.value.range,\n });\n return null;\n }\n\n return { path, symbol: symbolEntry.value.value };\n};\n\nconst readReferenceList = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n entity: IDiagnosticEntity | null = null,\n): readonly IRepositoryReference[] => {\n if (node.kind !== 'sequence' || node.items.length === 0) {\n addInvalidValue(context, pointer, node.range, 'non-empty-sequence-required', entity);\n return [];\n }\n\n const references: IRepositoryReference[] = [];\n const seen = new Set<string>();\n\n node.items.forEach((item, index) => {\n const reference = readReference(item, childPointer(pointer, String(index)), context, entity);\n\n if (reference === null) {\n return;\n }\n\n const key = `${reference.path}\\0${reference.symbol ?? ''}`;\n\n if (seen.has(key)) {\n context.diagnostics.add({\n code: 'MOLDEA_PATH_DUPLICATE',\n entity,\n path: context.path,\n pointer: childPointer(pointer, String(index)),\n range: item.range,\n });\n return;\n }\n\n seen.add(key);\n references.push(reference);\n });\n\n return sortRepositoryReferences(references);\n};\n\nconst readAffectedBy = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n entity: IDiagnosticEntity | null = null,\n): readonly string[] => {\n if (node.kind !== 'sequence' || node.items.length === 0) {\n addInvalidValue(context, pointer, node.range, 'non-empty-sequence-required', entity);\n return [];\n }\n\n const values: string[] = [];\n const seen = new Set<string>();\n\n node.items.forEach((item, index) => {\n const itemPointer = childPointer(pointer, String(index));\n\n if (item.kind !== 'scalar' || typeof item.value !== 'string') {\n addInvalidValue(context, itemPointer, item.range, 'string-required', entity);\n return;\n }\n\n const isGlob = item.value.includes('*') || hasUnsupportedGlobMetacharacter(item.value);\n const isValid = isGlob ? isSimpleGlob(item.value) : parseManifestPath(item.value) !== null;\n\n if (!isValid) {\n context.diagnostics.add({\n code: isGlob ? 'MOLDEA_GLOB_INVALID' : 'MOLDEA_PATH_INVALID',\n entity,\n path: context.path,\n pointer: itemPointer,\n range: item.range,\n });\n return;\n }\n\n if (seen.has(item.value)) {\n context.diagnostics.add({\n code: isGlob ? 'MOLDEA_PATTERN_DUPLICATE' : 'MOLDEA_PATH_DUPLICATE',\n entity,\n path: context.path,\n pointer: itemPointer,\n range: item.range,\n });\n return;\n }\n\n seen.add(item.value);\n values.push(item.value);\n });\n\n return values.sort(compareExactStrings);\n};\n\nconst readRelationship = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n): IRelationshipManifestEntry | null => {\n const entries = readMapping(node, pointer, new Set(['affectedBy', 'bindings']), context);\n\n if (entries === null) {\n return null;\n }\n\n const bindingsEntry = entries.get('bindings');\n const affectedByEntry = entries.get('affectedBy');\n\n if (bindingsEntry === undefined && affectedByEntry === undefined) {\n context.diagnostics.add({\n code: 'MOLDEA_CONTEXT_RELATIONSHIP_EMPTY',\n path: context.path,\n pointer,\n range: node.range,\n });\n }\n\n return {\n ...(bindingsEntry === undefined\n ? {}\n : {\n bindings: readReferenceList(\n bindingsEntry.value,\n childPointer(pointer, 'bindings'),\n context,\n ),\n }),\n ...(affectedByEntry === undefined\n ? {}\n : {\n affectedBy: readAffectedBy(\n affectedByEntry.value,\n childPointer(pointer, 'affectedBy'),\n context,\n ),\n }),\n };\n};\n\nconst readRelationshipRecord = (\n node: IYamlNode,\n pointer: string,\n kind: 'context' | 'decision',\n context: IManifestValidationContext,\n): Readonly<Record<string, IRelationshipManifestEntry>> | null => {\n const entries = readMapping(node, pointer, null, context);\n\n if (entries === null) {\n return null;\n }\n\n const normalized: Array<readonly [string, IRelationshipManifestEntry]> = [];\n\n for (const [key, entry] of [...entries].sort(([left], [right]) =>\n compareExactStrings(left, right),\n )) {\n const path = parseManifestPath(key);\n const validPath =\n path !== null && (kind === 'context' ? isContextPath(path, true) : isDecisionPath(path));\n\n if (!validPath) {\n context.diagnostics.add({\n code:\n kind === 'context' ? 'MOLDEA_CONTEXT_PATH_INVALID' : 'MOLDEA_DECISION_FILENAME_INVALID',\n path: context.path,\n pointer: childPointer(pointer, key),\n range: entry.key.range,\n });\n continue;\n }\n\n const relationship = readRelationship(entry.value, childPointer(pointer, key), context);\n\n if (relationship !== null) {\n normalized.push([key, relationship]);\n }\n }\n\n return createNullPrototypeRecord(normalized);\n};\n\nconst readPathList = (\n node: IYamlNode,\n pointer: string,\n kind: 'context' | 'decision' | 'mirror',\n context: IManifestValidationContext,\n entity: IDiagnosticEntity,\n): readonly IRepositoryPath[] => {\n if (node.kind !== 'sequence') {\n addInvalidValue(context, pointer, node.range, 'sequence-required', entity);\n return [];\n }\n\n const paths: IRepositoryPath[] = [];\n const seen = new Set<string>();\n\n node.items.forEach((item, index) => {\n const itemPointer = childPointer(pointer, String(index));\n\n if (item.kind !== 'scalar' || typeof item.value !== 'string') {\n addInvalidValue(context, itemPointer, item.range, 'string-required', entity);\n return;\n }\n\n const path = parseManifestPath(item.value);\n const valid =\n path !== null &&\n (kind === 'context'\n ? isContextPath(path, false)\n : kind === 'decision'\n ? isDecisionPath(path)\n : isMirrorPath(path));\n\n if (!valid || path === null) {\n const code =\n kind === 'context'\n ? 'MOLDEA_CONTEXT_PATH_INVALID'\n : kind === 'decision'\n ? 'MOLDEA_DECISION_FILENAME_INVALID'\n : path !== null && !isMirrorPath(path)\n ? 'MOLDEA_MIRROR_PATH_INSIDE_MOLDEA'\n : 'MOLDEA_MIRROR_PATH_INVALID';\n context.diagnostics.add({\n code,\n entity,\n path: context.path,\n pointer: itemPointer,\n range: item.range,\n });\n return;\n }\n\n if (seen.has(path)) {\n context.diagnostics.add({\n code: kind === 'mirror' ? 'MOLDEA_MIRROR_PATH_DUPLICATE' : 'MOLDEA_PATH_DUPLICATE',\n entity,\n path: context.path,\n pointer: itemPointer,\n range: item.range,\n });\n return;\n }\n\n if (kind === 'mirror' && context.mirrorPaths.has(path)) {\n context.diagnostics.add({\n code: 'MOLDEA_MIRROR_PATH_DUPLICATE',\n entity,\n path: context.path,\n pointer: itemPointer,\n range: item.range,\n });\n return;\n }\n\n seen.add(path);\n if (kind === 'mirror') {\n context.mirrorPaths.add(path);\n }\n paths.push(path);\n });\n\n return paths.sort(compareExactStrings);\n};\n\nconst readRuntime = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n agentId: string,\n): IRuntimeManifestEntry | null => {\n const entity = { agentId };\n const entries = readMapping(node, pointer, new Set(['guidance', 'id']), context, entity);\n\n if (entries === null) {\n return null;\n }\n\n const idEntry = entries.get('id');\n\n if (idEntry?.value.kind !== 'scalar' || typeof idEntry.value.value !== 'string') {\n context.diagnostics.add({\n code: 'MOLDEA_RUNTIME_ID_INVALID',\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'id'),\n range: idEntry?.value.range ?? null,\n });\n return null;\n }\n\n const id = idEntry.value.value;\n\n if (\n !isStableId(id) ||\n isReservedId(id) ||\n !(RECOGNIZED_RUNTIME_ADAPTER_IDS as readonly string[]).includes(id)\n ) {\n context.diagnostics.add({\n code: 'MOLDEA_RUNTIME_ID_INVALID',\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'id'),\n range: idEntry.value.range,\n });\n } else {\n context.runtimeLocations.push({\n adapterId: id,\n agentId,\n path: context.path,\n pointer: childPointer(pointer, 'id'),\n range: idEntry.value.range,\n });\n }\n\n const guidanceEntry = entries.get('guidance');\n let guidance: IRepositoryPath | null = null;\n\n if (guidanceEntry !== undefined) {\n if (guidanceEntry.value.kind === 'scalar' && typeof guidanceEntry.value.value === 'string') {\n const candidate = parseManifestPath(guidanceEntry.value.value);\n\n if (candidate !== null && isRuntimeGuidancePath(candidate)) {\n guidance = candidate;\n } else {\n context.diagnostics.add({\n code: 'MOLDEA_PATH_INVALID',\n details: { reason: 'runtime-guidance' },\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'guidance'),\n range: guidanceEntry.value.range,\n });\n }\n } else {\n context.diagnostics.add({\n code: 'MOLDEA_PATH_INVALID',\n details: { reason: 'runtime-guidance' },\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'guidance'),\n range: guidanceEntry.value.range,\n });\n }\n }\n\n return { id, ...(guidance === null ? {} : { guidance }) };\n};\n\nconst readVariables = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n agentId: string,\n): Readonly<Record<string, IRuntimeVariableManifestEntry>> | null => {\n const entries = readMapping(node, pointer, null, context, { agentId });\n\n if (entries === null) {\n return null;\n }\n\n const normalized: Array<readonly [string, IRuntimeVariableManifestEntry]> = [];\n\n for (const [variableId, entry] of [...entries].sort(([left], [right]) =>\n compareExactStrings(left, right),\n )) {\n const entity = { agentId, variableId };\n\n if (!isVariableId(variableId)) {\n context.diagnostics.add({\n code: 'MOLDEA_VARIABLE_ID_INVALID',\n entity,\n path: context.path,\n pointer: childPointer(pointer, variableId),\n range: entry.key.range,\n });\n }\n\n const variablePointer = childPointer(pointer, variableId);\n const variableEntries = readMapping(\n entry.value,\n variablePointer,\n new Set(['description']),\n context,\n entity,\n );\n\n if (variableEntries === null) {\n continue;\n }\n\n const description = readString(\n variableEntries.get('description'),\n childPointer(variablePointer, 'description'),\n context,\n { entity, required: true },\n );\n\n if (description !== null) {\n normalized.push([variableId, { description }]);\n }\n }\n\n return createNullPrototypeRecord(normalized);\n};\n\nconst readBindings = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n agentId: string,\n declaredVariables: ReadonlySet<string>,\n): IAgentBindingsManifestEntry | null => {\n const entity = { agentId };\n const entries = readMapping(\n node,\n pointer,\n new Set([\n 'inputSchema',\n 'instructionLoader',\n 'outputSchema',\n 'runtimeAgent',\n 'variableProviders',\n ]),\n context,\n entity,\n );\n\n if (entries === null) {\n return null;\n }\n\n const referenceProperty = (\n key: 'inputSchema' | 'instructionLoader' | 'outputSchema' | 'runtimeAgent',\n ) => {\n const entry = entries.get(key);\n return entry === undefined\n ? null\n : readReference(entry.value, childPointer(pointer, key), context, entity);\n };\n const inputSchema = referenceProperty('inputSchema');\n const instructionLoader = referenceProperty('instructionLoader');\n const outputSchema = referenceProperty('outputSchema');\n const runtimeAgent = referenceProperty('runtimeAgent');\n const providersEntry = entries.get('variableProviders');\n let variableProviders: Readonly<Record<string, IRepositoryReference>> | null = null;\n\n if (providersEntry !== undefined) {\n const providers = readMapping(\n providersEntry.value,\n childPointer(pointer, 'variableProviders'),\n null,\n context,\n entity,\n );\n\n if (providers !== null) {\n const normalized: Array<readonly [string, IRepositoryReference]> = [];\n\n for (const [variableId, providerEntry] of [...providers].sort(([left], [right]) =>\n compareExactStrings(left, right),\n )) {\n const variableEntity = { agentId, variableId };\n const providerPointer = childPointer(\n childPointer(pointer, 'variableProviders'),\n variableId,\n );\n\n if (!isVariableId(variableId)) {\n context.diagnostics.add({\n code: 'MOLDEA_VARIABLE_ID_INVALID',\n entity: variableEntity,\n path: context.path,\n pointer: providerPointer,\n range: providerEntry.key.range,\n });\n } else if (!declaredVariables.has(variableId)) {\n context.diagnostics.add({\n code: 'MOLDEA_VARIABLE_PROVIDER_UNDECLARED',\n entity: variableEntity,\n path: context.path,\n pointer: providerPointer,\n range: providerEntry.key.range,\n });\n }\n\n const reference = readReference(\n providerEntry.value,\n providerPointer,\n context,\n variableEntity,\n );\n\n if (reference !== null) {\n normalized.push([variableId, reference]);\n }\n }\n\n variableProviders = createNullPrototypeRecord(normalized);\n }\n }\n\n return {\n ...(runtimeAgent === null ? {} : { runtimeAgent }),\n ...(inputSchema === null ? {} : { inputSchema }),\n ...(outputSchema === null ? {} : { outputSchema }),\n ...(instructionLoader === null ? {} : { instructionLoader }),\n ...(variableProviders === null ? {} : { variableProviders }),\n };\n};\n\nconst readCapability = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n agentId: string,\n capabilityId: string,\n kind: 'tool' | 'skill',\n): IToolManifestEntry | ISkillManifestEntry | null => {\n const entity = { agentId, capabilityId, capabilityKind: kind } as const;\n const allowed =\n kind === 'tool'\n ? new Set([\n 'affectedBy',\n 'description',\n 'implementation',\n 'inputSchema',\n 'name',\n 'outputSchema',\n 'registration',\n ])\n : new Set(['affectedBy', 'description', 'implementation', 'name', 'registration']);\n const entries = readMapping(node, pointer, allowed, context, entity);\n\n if (entries === null) {\n return null;\n }\n\n const name = readString(entries.get('name'), childPointer(pointer, 'name'), context, {\n entity,\n required: true,\n singleLine: true,\n });\n const descriptionEntry = entries.get('description');\n let description: string | null = null;\n\n if (descriptionEntry === undefined) {\n context.diagnostics.add({\n code: 'MOLDEA_CAPABILITY_DESCRIPTION_MISSING',\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'description'),\n });\n } else if (\n descriptionEntry.value.kind !== 'scalar' ||\n typeof descriptionEntry.value.value !== 'string' ||\n !isCapabilityDescription(descriptionEntry.value.value)\n ) {\n context.diagnostics.add({\n code: 'MOLDEA_CAPABILITY_DESCRIPTION_INVALID',\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'description'),\n range: descriptionEntry.value.range,\n });\n } else {\n description = descriptionEntry.value.value;\n }\n\n const implementationEntry = entries.get('implementation');\n let implementation: IRepositoryReference | null = null;\n\n if (implementationEntry === undefined) {\n context.diagnostics.add({\n code:\n kind === 'tool'\n ? 'MOLDEA_TOOL_IMPLEMENTATION_MISSING'\n : 'MOLDEA_SKILL_IMPLEMENTATION_MISSING',\n entity,\n path: context.path,\n pointer: childPointer(pointer, 'implementation'),\n });\n } else {\n implementation = readReference(\n implementationEntry.value,\n childPointer(pointer, 'implementation'),\n context,\n entity,\n );\n }\n\n const optionalReference = (key: 'inputSchema' | 'outputSchema' | 'registration') => {\n const entry = entries.get(key);\n return entry === undefined\n ? null\n : readReference(entry.value, childPointer(pointer, key), context, entity);\n };\n const registration = optionalReference('registration');\n const inputSchema = kind === 'tool' ? optionalReference('inputSchema') : null;\n const outputSchema = kind === 'tool' ? optionalReference('outputSchema') : null;\n const affectedByEntry = entries.get('affectedBy');\n const affectedBy =\n affectedByEntry === undefined\n ? null\n : readAffectedBy(affectedByEntry.value, childPointer(pointer, 'affectedBy'), context, entity);\n\n if (name === null || description === null || implementation === null) {\n return null;\n }\n\n return {\n name,\n description,\n implementation,\n ...(registration === null ? {} : { registration }),\n ...(inputSchema === null ? {} : { inputSchema }),\n ...(outputSchema === null ? {} : { outputSchema }),\n ...(affectedBy === null ? {} : { affectedBy }),\n };\n};\n\nconst readCapabilities = <Value extends IToolManifestEntry | ISkillManifestEntry>(\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n agentId: string,\n kind: 'tool' | 'skill',\n): Readonly<Record<string, Value>> | null => {\n const entries = readMapping(node, pointer, null, context, { agentId });\n\n if (entries === null) {\n return null;\n }\n\n const normalized: Array<readonly [string, Value]> = [];\n\n for (const [capabilityId, entry] of [...entries].sort(([left], [right]) =>\n compareExactStrings(left, right),\n )) {\n const entity = { agentId, capabilityId, capabilityKind: kind } as const;\n const capabilityPointer = childPointer(pointer, capabilityId);\n validateStableId(capabilityId, entry.key.range, capabilityPointer, context, entity);\n const capability = readCapability(\n entry.value,\n capabilityPointer,\n context,\n agentId,\n capabilityId,\n kind,\n );\n\n if (capability !== null) {\n normalized.push([capabilityId, capability as Value]);\n }\n }\n\n return createNullPrototypeRecord(normalized);\n};\n\nconst readUnresolved = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n agentId?: string,\n): Readonly<Record<string, IUnresolvedRequirementManifestEntry>> | null => {\n const entries = readMapping(\n node,\n pointer,\n null,\n context,\n agentId === undefined ? null : { agentId },\n );\n\n if (entries === null) {\n return null;\n }\n\n const normalized: Array<readonly [string, IUnresolvedRequirementManifestEntry]> = [];\n\n for (const [requirementId, entry] of [...entries].sort(([left], [right]) =>\n compareExactStrings(left, right),\n )) {\n const entity = agentId === undefined ? null : { agentId };\n const requirementPointer = childPointer(pointer, requirementId);\n validateStableId(requirementId, entry.key.range, requirementPointer, context, entity);\n const requirementEntries = readMapping(\n entry.value,\n requirementPointer,\n new Set(['category', 'description', 'effect', 'reference', 'related', 'resolution']),\n context,\n entity,\n );\n\n if (requirementEntries === null) {\n continue;\n }\n\n const category = readString(\n requirementEntries.get('category'),\n childPointer(requirementPointer, 'category'),\n context,\n { ...(entity === null ? {} : { entity }), required: true },\n );\n\n if (category !== null && !isStableId(category)) {\n context.diagnostics.add({\n code: 'MOLDEA_ID_INVALID',\n entity,\n path: context.path,\n pointer: childPointer(requirementPointer, 'category'),\n range: requirementEntries.get('category')?.value.range ?? null,\n });\n }\n\n const effectEntry = requirementEntries.get('effect');\n let effect: IUnresolvedRequirementEffect | null = null;\n\n if (\n effectEntry?.value.kind === 'scalar' &&\n (effectEntry.value.value === 'blocking' ||\n effectEntry.value.value === 'warning' ||\n effectEntry.value.value === 'informational')\n ) {\n effect = effectEntry.value.value;\n } else {\n addInvalidValue(\n context,\n childPointer(requirementPointer, 'effect'),\n effectEntry?.value.range ?? null,\n effectEntry === undefined ? 'required' : 'enum',\n entity,\n );\n }\n\n const description = readString(\n requirementEntries.get('description'),\n childPointer(requirementPointer, 'description'),\n context,\n { ...(entity === null ? {} : { entity }), required: true },\n );\n const resolution = readString(\n requirementEntries.get('resolution'),\n childPointer(requirementPointer, 'resolution'),\n context,\n { ...(entity === null ? {} : { entity }), required: true },\n );\n const relatedEntry = requirementEntries.get('related');\n const related =\n relatedEntry === undefined\n ? null\n : readReferenceList(\n relatedEntry.value,\n childPointer(requirementPointer, 'related'),\n context,\n entity,\n );\n const reference = readString(\n requirementEntries.get('reference'),\n childPointer(requirementPointer, 'reference'),\n context,\n { ...(entity === null ? {} : { entity }), singleLine: true },\n );\n\n if (category !== null && effect !== null && description !== null && resolution !== null) {\n normalized.push([\n requirementId,\n {\n category,\n effect,\n description,\n resolution,\n ...(related === null ? {} : { related }),\n ...(reference === null ? {} : { reference }),\n },\n ]);\n }\n }\n\n return createNullPrototypeRecord(normalized);\n};\n\nconst findMappingProperty = (node: IYamlNode, property: string): IYamlNode | null => {\n if (node.kind !== 'mapping') {\n return null;\n }\n\n for (const entry of node.entries) {\n if (entry.key.kind === 'scalar' && entry.key.value === property) {\n return entry.value;\n }\n }\n\n return null;\n};\n\n/**\n * Detects a supported repository-format version without treating the remaining manifest as valid.\n * @param node The trustworthy strict-YAML manifest root.\n * @returns The supported parsed version when its declaration is independently unambiguous.\n */\nexport const detectSupportedManifestVersion = (\n node: IYamlNode,\n): IRepositoryFormatVersion | null => {\n if (node.kind !== 'mapping') {\n return null;\n }\n\n const versionNode = findMappingProperty(node, 'version');\n\n return versionNode?.kind === 'scalar' && versionNode.value === 1n ? 1 : null;\n};\n\nconst validateAgentOwnedIdUniqueness = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n agentId: string,\n): void => {\n const seen = new Set<string>();\n\n for (const property of ['tools', 'skills', 'unresolved']) {\n const record = findMappingProperty(node, property);\n\n if (record?.kind !== 'mapping') {\n continue;\n }\n\n for (const entry of record.entries) {\n if (entry.key.kind !== 'scalar' || typeof entry.key.value !== 'string') {\n continue;\n }\n\n if (seen.has(entry.key.value)) {\n context.diagnostics.add({\n code: 'MOLDEA_ID_DUPLICATE',\n entity: { agentId },\n path: context.path,\n pointer: childPointer(childPointer(pointer, property), entry.key.value),\n range: entry.key.range,\n });\n }\n\n seen.add(entry.key.value);\n }\n }\n};\n\nconst readAgent = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n agentId: string,\n): IAgentManifestEntry | null => {\n const entity = { agentId };\n const entries = readMapping(\n node,\n pointer,\n new Set([\n 'affectedBy',\n 'bindings',\n 'context',\n 'decisions',\n 'runtime',\n 'mirrors',\n 'skills',\n 'tools',\n 'unresolved',\n 'variables',\n ]),\n context,\n entity,\n );\n\n if (entries === null) {\n return null;\n }\n\n validateAgentOwnedIdUniqueness(node, pointer, context, agentId);\n const runtimeEntry = entries.get('runtime');\n let runtime: IRuntimeManifestEntry | null = null;\n\n if (runtimeEntry === undefined) {\n addInvalidValue(context, childPointer(pointer, 'runtime'), null, 'required', entity);\n } else {\n runtime = readRuntime(runtimeEntry.value, childPointer(pointer, 'runtime'), context, agentId);\n }\n\n const variablesEntry = entries.get('variables');\n const variables =\n variablesEntry === undefined\n ? null\n : readVariables(variablesEntry.value, childPointer(pointer, 'variables'), context, agentId);\n const declaredVariables = new Set(Object.keys(variables ?? {}));\n const bindingsEntry = entries.get('bindings');\n const bindings =\n bindingsEntry === undefined\n ? null\n : readBindings(\n bindingsEntry.value,\n childPointer(pointer, 'bindings'),\n context,\n agentId,\n declaredVariables,\n );\n const contextEntry = entries.get('context');\n const contextPaths =\n contextEntry === undefined\n ? null\n : readPathList(\n contextEntry.value,\n childPointer(pointer, 'context'),\n 'context',\n context,\n entity,\n );\n const decisionsEntry = entries.get('decisions');\n const decisions =\n decisionsEntry === undefined\n ? null\n : readPathList(\n decisionsEntry.value,\n childPointer(pointer, 'decisions'),\n 'decision',\n context,\n entity,\n );\n const toolsEntry = entries.get('tools');\n const tools =\n toolsEntry === undefined\n ? null\n : readCapabilities<IToolManifestEntry>(\n toolsEntry.value,\n childPointer(pointer, 'tools'),\n context,\n agentId,\n 'tool',\n );\n const skillsEntry = entries.get('skills');\n const skills =\n skillsEntry === undefined\n ? null\n : readCapabilities<ISkillManifestEntry>(\n skillsEntry.value,\n childPointer(pointer, 'skills'),\n context,\n agentId,\n 'skill',\n );\n const affectedByEntry = entries.get('affectedBy');\n const affectedBy =\n affectedByEntry === undefined\n ? null\n : readAffectedBy(affectedByEntry.value, childPointer(pointer, 'affectedBy'), context, entity);\n const mirrorsEntry = entries.get('mirrors');\n const mirrors =\n mirrorsEntry === undefined\n ? null\n : readPathList(\n mirrorsEntry.value,\n childPointer(pointer, 'mirrors'),\n 'mirror',\n context,\n entity,\n );\n const unresolvedEntry = entries.get('unresolved');\n const unresolved =\n unresolvedEntry === undefined\n ? null\n : readUnresolved(\n unresolvedEntry.value,\n childPointer(pointer, 'unresolved'),\n context,\n agentId,\n );\n\n if (runtime === null) {\n return null;\n }\n\n return {\n runtime,\n ...(contextPaths === null ? {} : { context: contextPaths }),\n ...(decisions === null ? {} : { decisions }),\n ...(variables === null ? {} : { variables }),\n ...(bindings === null ? {} : { bindings }),\n ...(tools === null ? {} : { tools }),\n ...(skills === null ? {} : { skills }),\n ...(affectedBy === null ? {} : { affectedBy }),\n ...(mirrors === null ? {} : { mirrors }),\n ...(unresolved === null ? {} : { unresolved }),\n };\n};\n\nconst readAgents = (\n node: IYamlNode,\n pointer: string,\n context: IManifestValidationContext,\n): Readonly<Record<string, IAgentManifestEntry>> | null => {\n const entries = readMapping(node, pointer, null, context);\n\n if (entries === null) {\n return null;\n }\n\n const normalized: Array<readonly [string, IAgentManifestEntry]> = [];\n\n for (const [agentId, entry] of [...entries].sort(([left], [right]) =>\n compareExactStrings(left, right),\n )) {\n const agentPointer = childPointer(pointer, agentId);\n validateStableId(agentId, entry.key.range, agentPointer, context, { agentId });\n const agent = readAgent(entry.value, agentPointer, context, agentId);\n\n if (agent !== null) {\n normalized.push([agentId, agent]);\n }\n }\n\n return createNullPrototypeRecord(normalized);\n};\n\n/**\n * Validates and normalizes a strict YAML document as a version 1 moldea manifest.\n * @param node The parser-neutral YAML root node.\n * @param path The canonical or caller-supplied logical manifest path.\n * @param diagnostics The operation diagnostic collector.\n * @param runtimeLocations Mutable private source locations populated for repository inspection.\n * @returns The normalized manifest when its supported version can be interpreted.\n */\nexport const validateManifest = (\n node: IYamlNode,\n path: IRepositoryPath,\n diagnostics: ICoreDiagnosticCollector,\n runtimeLocations: IRuntimeManifestLocation[],\n): IMoldeaManifestV1 | null => {\n const context: IManifestValidationContext = {\n diagnostics,\n mirrorPaths: new Set(),\n path,\n runtimeLocations,\n };\n\n if (node.kind !== 'mapping') {\n diagnostics.add({ code: 'MOLDEA_MANIFEST_ROOT_INVALID', path, range: node.range });\n return null;\n }\n\n const versionNode = findMappingProperty(node, 'version');\n\n if (versionNode === null) {\n diagnostics.add({ code: 'MOLDEA_MANIFEST_VERSION_MISSING', path, pointer: '/version' });\n return null;\n }\n\n const isIntegerSyntax = versionNode.kind === 'scalar' && typeof versionNode.value === 'bigint';\n\n if (!isIntegerSyntax || versionNode.kind !== 'scalar' || versionNode.value <= 0n) {\n diagnostics.add({\n code: 'MOLDEA_MANIFEST_VERSION_INVALID',\n path,\n pointer: '/version',\n range: versionNode.range,\n });\n return null;\n }\n\n if (versionNode.value !== 1n) {\n diagnostics.add({\n code: 'MOLDEA_MANIFEST_VERSION_UNSUPPORTED',\n path,\n pointer: '/version',\n range: versionNode.range,\n });\n return null;\n }\n\n const entries = readMapping(\n node,\n '',\n new Set(['agents', 'context', 'decisions', 'unresolved', 'version']),\n context,\n );\n\n if (entries === null) {\n return null;\n }\n\n const contextEntry = entries.get('context');\n const contextRelationships =\n contextEntry === undefined\n ? null\n : readRelationshipRecord(contextEntry.value, '/context', 'context', context);\n const decisionsEntry = entries.get('decisions');\n const decisionRelationships =\n decisionsEntry === undefined\n ? null\n : readRelationshipRecord(decisionsEntry.value, '/decisions', 'decision', context);\n const unresolvedEntry = entries.get('unresolved');\n const unresolved =\n unresolvedEntry === undefined\n ? null\n : readUnresolved(unresolvedEntry.value, '/unresolved', context);\n const agentsEntry = entries.get('agents');\n const agents =\n agentsEntry === undefined ? null : readAgents(agentsEntry.value, '/agents', context);\n\n return {\n version: 1,\n ...(contextRelationships === null ? {} : { context: contextRelationships }),\n ...(decisionRelationships === null ? {} : { decisions: decisionRelationships }),\n ...(unresolved === null ? {} : { unresolved }),\n ...(agents === null ? {} : { agents }),\n };\n};\n","import { parseRepositoryPath } from '@moldea.ai/repository';\n\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport type {\n IIndexedTextAsset,\n IManifestParseResult,\n ITextDocumentInput,\n} from '../contracts/index.js';\nimport { createCoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { ICoreOperation } from '../exceptions/index.js';\nimport { isCanonicalManifestPath } from '../format-validation/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport {\n detectSupportedManifestVersion,\n validateManifest,\n type IRuntimeManifestLocation,\n} from '../manifest-validation/index.js';\nimport { createSourceLocator } from '../source-location/index.js';\nimport { calculateNormalizedTextDigest, normalizeTextDocument } from '../text/index.js';\nimport { parseStrictYaml } from '../yaml/index.js';\n\n// richer manifest parse state retained only by repository inspection\nexport interface IManifestDocumentInspectionResult extends IManifestParseResult {\n readonly formatVersion: 1 | null;\n readonly runtimeLocations: readonly IRuntimeManifestLocation[];\n}\n\n/**\n * Inspects one complete manifest while retaining an independently trustworthy supported version.\n * @param input The canonical logical path and exact manifest text or bytes.\n * @param options The immutable Core limits and adapter snapshots.\n * @param operation The owning public or repository-level operation for typed failures.\n * @returns Frozen inspection state with all-or-nothing manifest assets and values.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nexport const inspectManifestDocument = async (\n input: ITextDocumentInput,\n options: ICoreOptionsSnapshot,\n operation: Extract<\n ICoreOperation,\n 'parse-manifest' | 'match-manifest-scope' | 'validate-project'\n > = 'parse-manifest',\n): Promise<IManifestDocumentInspectionResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const normalized = normalizeTextDocument(input, options.limits, operation, 'maxManifestBytes');\n const path = parseRepositoryPath(input.path);\n const diagnostics = createCoreDiagnosticCollector(options.limits, operation);\n\n if (!isCanonicalManifestPath(path)) {\n diagnostics.add({ code: 'MOLDEA_MANIFEST_PATH_INVALID', path });\n }\n\n for (const diagnostic of normalized.diagnostics) {\n diagnostics.merge(diagnostic);\n }\n\n if (!normalized.valid || normalized.text === null) {\n return freezeRecursively({\n asset: null,\n diagnostics: diagnostics.finalize(),\n formatVersion: null,\n manifest: null,\n runtimeLocations: [],\n valid: false,\n });\n }\n\n const locator = createSourceLocator(normalized.text.value);\n const parsed = parseStrictYaml(normalized.text.value, path, locator, diagnostics);\n const formatVersion = parsed.value === null ? null : detectSupportedManifestVersion(parsed.value);\n const runtimeLocations: IRuntimeManifestLocation[] = [];\n const manifest =\n parsed.valid && parsed.value !== null\n ? validateManifest(parsed.value, path, diagnostics, runtimeLocations)\n : null;\n\n if (manifest === null || diagnostics.size > 0) {\n return freezeRecursively({\n asset: null,\n diagnostics: diagnostics.finalize(),\n formatVersion,\n manifest: null,\n runtimeLocations,\n valid: false,\n });\n }\n\n const digest = await calculateNormalizedTextDigest(normalized.text);\n const asset: IIndexedTextAsset = {\n content: normalized.text.value,\n digest,\n path,\n scalarLength: normalized.text.scalarLength,\n utf8ByteLength: normalized.text.utf8ByteLength,\n };\n\n return freezeRecursively({\n asset,\n diagnostics: diagnostics.finalize(),\n formatVersion,\n manifest,\n runtimeLocations,\n valid: true,\n });\n};\n\n/**\n * Parses and validates one complete version 1 manifest document.\n * @param input The canonical logical path and exact manifest text or bytes.\n * @param options The immutable Core limits and adapter snapshots.\n * @returns A frozen all-or-nothing manifest parse result.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nexport const parseManifestDocument = async (\n input: ITextDocumentInput,\n options: ICoreOptionsSnapshot,\n operation: Extract<ICoreOperation, 'parse-manifest' | 'match-manifest-scope'> = 'parse-manifest',\n): Promise<IManifestParseResult> => {\n const inspection = await inspectManifestDocument(input, options, operation);\n\n return freezeRecursively({\n asset: inspection.asset,\n diagnostics: inspection.diagnostics,\n manifest: inspection.manifest,\n valid: inspection.valid,\n });\n};\n","import type { IMoldeaProjectIndex, IProjectAgentAssignmentItem } from '../contracts/index.js';\n\n/** Iterates content-free agent-to-runtime assignments without retaining an intermediate array. */\nexport const iterateProjectAgentAssignments = function* (\n project: IMoldeaProjectIndex,\n): IterableIterator<IProjectAgentAssignmentItem> {\n for (const agent of project.agents) {\n yield {\n agentId: agent.id,\n runtimeId: agent.declaration.runtime.id,\n };\n }\n};\n","import type {\n IIndexedTextAsset,\n IMoldeaProjectIndex,\n IProjectMetadataItem,\n IProjectValidationSummary,\n} from '../contracts/index.js';\n\nconst createAssetItem = (\n asset: IIndexedTextAsset,\n kind: IProjectMetadataItem['kind'],\n agentId: string | null = null,\n decisionId: string | null = null,\n): IProjectMetadataItem => ({\n agentId,\n byteLength: asset.utf8ByteLength,\n canonicalDigest: null,\n decisionId,\n digest: asset.digest,\n kind,\n path: asset.path,\n scalarLength: asset.scalarLength,\n});\n\n/** Iterates content-free asset metadata without retaining a second project-sized collection. */\nexport const iterateProjectMetadata = function* (\n project: IMoldeaProjectIndex,\n): IterableIterator<IProjectMetadataItem> {\n yield createAssetItem(project.manifest.asset, 'manifest');\n yield createAssetItem(project.project, 'project');\n\n for (const context of project.context) {\n yield createAssetItem(context.asset, 'context');\n }\n\n for (const { decision } of project.decisions) {\n yield createAssetItem(decision.asset, 'decision', null, decision.id);\n }\n\n for (const runtime of project.runtimes) {\n yield createAssetItem(runtime.asset, 'runtime-guidance');\n }\n\n for (const agent of project.agents) {\n yield createAssetItem(agent.description.asset, 'agent-description', agent.id);\n yield createAssetItem(agent.instruction, 'agent-instruction', agent.id);\n\n if (agent.handoffDescription !== null) {\n yield createAssetItem(agent.handoffDescription.asset, 'agent-handoff-description', agent.id);\n }\n\n for (const mirror of agent.mirrors) {\n yield {\n agentId: agent.id,\n byteLength: mirror.byteLength,\n canonicalDigest: mirror.canonicalDigest,\n decisionId: null,\n digest: mirror.digest,\n kind: 'mirror',\n path: mirror.path,\n scalarLength: mirror.scalarLength,\n };\n }\n }\n};\n\n/** Creates the content-free summary for one validated project snapshot. */\nexport const createProjectSummary = (project: IMoldeaProjectIndex): IProjectValidationSummary =>\n ({\n counts: {\n agents: project.agents.length,\n context: project.context.length,\n decisions: project.decisions.length,\n mirrors: project.agents.reduce((count, agent) => count + agent.mirrors.length, 0),\n runtimes: project.runtimes.length,\n unresolved: project.agents.reduce(\n (count, agent) => count + Object.keys(agent.declaration.unresolved ?? {}).length,\n Object.keys(project.unresolved).length,\n ),\n },\n manifestDigest: project.manifest.asset.digest,\n manifestPath: project.manifest.asset.path,\n projectDigest: project.project.digest,\n projectPath: project.project.path,\n }) satisfies IProjectValidationSummary;\n","import type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { createCoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { IRepositoryFormatVersion } from '../format/index.js';\nimport type { IRuntimeManifestLocation } from '../manifest-validation/index.js';\nimport type { ICoreOptionsSnapshot } from '../options/index.js';\n\n/**\n * Validates adapter availability and format support before any runtime adapter runs.\n * @param locations The recognized runtime declarations retained from manifest parsing.\n * @param formatVersion The active repository-format version.\n * @param options The immutable Core adapter registry and limits.\n * @returns Frozen deterministic preflight diagnostics.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: The raw Core diagnostic limit was exceeded.\n */\nexport const validateRuntimeAdapterAvailability = (\n locations: readonly IRuntimeManifestLocation[],\n formatVersion: IRepositoryFormatVersion,\n options: ICoreOptionsSnapshot,\n): readonly ICoreDiagnostic[] => {\n const diagnostics = createCoreDiagnosticCollector(options.limits, 'validate-project');\n const adapters = new Map(options.adapters.map((adapter) => [adapter.id, adapter]));\n\n for (const location of locations) {\n if (location.adapterId === 'custom') {\n continue;\n }\n\n const adapter = adapters.get(location.adapterId);\n\n if (adapter === undefined) {\n diagnostics.add({\n code: 'MOLDEA_RUNTIME_ADAPTER_UNAVAILABLE',\n entity: { adapterId: location.adapterId, agentId: location.agentId },\n path: location.path,\n pointer: location.pointer,\n range: location.range,\n });\n continue;\n }\n\n if (!adapter.supportedRepositoryFormatVersions.includes(formatVersion)) {\n diagnostics.add({\n code: 'MOLDEA_RUNTIME_ADAPTER_FORMAT_UNSUPPORTED',\n entity: { adapterId: location.adapterId, agentId: location.agentId },\n path: location.path,\n pointer: location.pointer,\n range: location.range,\n });\n }\n }\n\n return diagnostics.finalize();\n};\n","import {\n RepositoryPathException,\n RepositorySourceException,\n isRepositoryPath,\n parseRepositoryPath,\n type IRepositoryEntry,\n type IRepositoryPath,\n} from '@moldea.ai/repository';\n\nimport type {\n IRuntimeAdapterEvidence,\n IRuntimeAdapterEvidenceKind,\n IRuntimeAdapterRepository,\n} from '../adapter/index.js';\nimport type {\n ICoreResourceLimits,\n IIndexedAgent,\n IMoldeaProjectIndex,\n} from '../contracts/index.js';\nimport {\n normalizeDiagnosticDetails,\n normalizeDiagnosticEntity,\n normalizeDiagnostics,\n registerCoreDiagnosticCandidates,\n serializeDiagnosticDetails,\n} from '../diagnostic-utilities/index.js';\nimport type {\n IAdapterDiagnostic,\n IAdapterWarningDiagnostic,\n IDiagnosticEntity,\n ISourcePosition,\n ISourceRange,\n IUnverifiedRelationship,\n} from '../diagnostics/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\nimport {\n compareExactStrings,\n isCanonicalMoldeaPath,\n isNonEmptySingleLine,\n isRepositorySymbol,\n isUnicodeScalarText,\n hasSurroundingWhitespace,\n sortRepositoryReferences,\n} from '../format-validation/index.js';\nimport type { IRepositoryReference } from '../format/index.js';\nimport { createNullPrototypeRecord, freezeRecursively } from '../immutable/index.js';\n\n// closed adapter output fields, evidence kinds, and scalar patterns\nconst EVIDENCE_KINDS = new Set<IRuntimeAdapterEvidenceKind>([\n 'runtime-package',\n 'language',\n 'agent-definition',\n 'instruction-loader',\n 'schema',\n 'tool-registration',\n 'skill-registration',\n 'handoff-registration',\n 'variable-provider',\n 'runtime-pattern',\n]);\nconst DIAGNOSTIC_ENTITY_KEYS = new Set<keyof IDiagnosticEntity>([\n 'agentId',\n 'capabilityKind',\n 'capabilityId',\n 'decisionId',\n 'variableId',\n 'adapterId',\n]);\nconst POSITION_KEYS = new Set(['line', 'column', 'offset']);\nconst RANGE_KEYS = new Set(['start', 'end']);\nconst REFERENCE_KEYS = new Set(['path', 'symbol']);\nconst EVIDENCE_KEYS = new Set([\n 'source',\n 'kind',\n 'agentId',\n 'capabilityKind',\n 'capabilityId',\n 'runtimeName',\n 'references',\n 'details',\n]);\nconst DIAGNOSTIC_KEYS = new Set([\n 'source',\n 'severity',\n 'code',\n 'message',\n 'path',\n 'pointer',\n 'range',\n 'entity',\n 'details',\n]);\nconst ADAPTER_RESULT_KEYS = new Set(['evidence', 'diagnostics']);\nconst ADAPTER_CODE_PATTERN = /^[A-Z][A-Z0-9_]*$/u;\nconst UNVERIFIED_MESSAGE = 'The declared runtime relationship could not be verified.';\nconst UNVERIFIED_RELATIONSHIPS = new Set<IUnverifiedRelationship>([\n 'runtime-agent',\n 'instruction-loader',\n 'agent-input-schema',\n 'agent-output-schema',\n 'tool-implementation',\n 'tool-registration',\n 'tool-input-schema',\n 'tool-output-schema',\n 'skill-implementation',\n 'skill-registration',\n 'handoff-registration',\n 'routing-description',\n 'variable-provider',\n]);\nconst SIMPLE_WARNING_KEYS = new Set(['relationship', 'reason']);\nconst VERSION_WARNING_KEYS = new Set([\n 'relationship',\n 'reason',\n 'packageName',\n 'declaredRange',\n 'boundaryVersion',\n]);\nconst PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*$/u;\nconst BOUNDARY_VERSION_PATTERN = /^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)$/u;\nconst VERSION_TOKEN =\n '(?:0|[1-9]\\\\d*)\\\\.(?:0|[1-9]\\\\d*)\\\\.(?:0|[1-9]\\\\d*)(?:-[0-9A-Za-z-]+(?:\\\\.[0-9A-Za-z-]+)*)?(?:\\\\+[0-9A-Za-z-]+(?:\\\\.[0-9A-Za-z-]+)*)?';\nconst RANGE_COMPARATOR_PATTERN = new RegExp(`^(?:<=|>=|<|>|=)?${VERSION_TOKEN}$`, 'u');\n\n// normalized output retained after one adapter result passes Core validation\nexport interface IValidatedRuntimeAdapterResult {\n readonly evidence: readonly IRuntimeAdapterEvidence[];\n readonly diagnostics: readonly IAdapterDiagnostic[];\n}\n\n// mutable raw output counters shared by every adapter in one inspection\nexport interface IRuntimeAdapterOutputCounts {\n diagnostics: number;\n evidence: number;\n}\n\ninterface IAdapterValidationContext {\n readonly adapterId: string;\n readonly agents: readonly IIndexedAgent[];\n readonly project: IMoldeaProjectIndex;\n readonly repository: IRuntimeAdapterRepository;\n readonly limits: ICoreResourceLimits;\n readonly signal?: AbortSignal;\n}\n\ninterface IAdapterValidationState extends IAdapterValidationContext {\n readonly agentsById: ReadonlyMap<string, IIndexedAgent>;\n readonly decisionIds: ReadonlySet<string>;\n}\n\nconst isRecord = (candidate: unknown): candidate is Readonly<Record<string, unknown>> => {\n return typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate);\n};\n\nconst invalidAdapterResult = (adapterId: string): never => {\n throw new CoreOperationException({\n adapterId,\n cause: new TypeError('The runtime adapter result is invalid.'),\n code: 'ADAPTER_EXECUTION_FAILED',\n operation: 'validate-adapter',\n });\n};\n\nconst registerRawOutput = (\n outputCounts: IRuntimeAdapterOutputCounts,\n key: keyof IRuntimeAdapterOutputCounts,\n amount: number,\n context: IAdapterValidationContext,\n): void => {\n const limit = key === 'diagnostics' ? 'maxDiagnostics' : 'maxEvidence';\n\n if (key === 'diagnostics') {\n outputCounts.diagnostics = registerCoreDiagnosticCandidates(\n context.limits,\n amount,\n 'validate-adapter',\n outputCounts.diagnostics,\n context.adapterId,\n );\n return;\n }\n\n if (amount > context.limits[limit] - outputCounts[key]) {\n throw new CoreOperationException({\n adapterId: context.adapterId,\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit,\n limitMaximum: context.limits[limit],\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage: outputCounts[key] + amount,\n operation: 'validate-adapter',\n });\n }\n\n outputCounts[key] += amount;\n};\n\nconst hasOnlyKeys = (\n candidate: Readonly<Record<string, unknown>>,\n keys: ReadonlySet<string>,\n): boolean => {\n return Reflect.ownKeys(candidate).every((key) => {\n if (typeof key !== 'string' || !keys.has(key)) {\n return false;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(candidate, key);\n\n return descriptor !== undefined && descriptor.enumerable && 'value' in descriptor;\n });\n};\n\nconst isSafeString = (candidate: unknown): candidate is string => {\n return (\n typeof candidate === 'string' && isUnicodeScalarText(candidate) && !candidate.includes('\\0')\n );\n};\n\nconst normalizeDetails = (candidate: unknown, adapterId: string) => {\n if (!isRecord(candidate)) {\n return invalidAdapterResult(adapterId);\n }\n\n const entries: [string, string | number | boolean | null][] = [];\n\n for (const key of Reflect.ownKeys(candidate)) {\n if (typeof key !== 'string' || !isUnicodeScalarText(key) || key.includes('\\0')) {\n return invalidAdapterResult(adapterId);\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(candidate, key);\n\n if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n return invalidAdapterResult(adapterId);\n }\n\n const detail = descriptor.value as unknown;\n\n if (\n detail !== null &&\n typeof detail !== 'boolean' &&\n !(typeof detail === 'string' && isUnicodeScalarText(detail) && !detail.includes('\\0')) &&\n !(typeof detail === 'number' && Number.isFinite(detail))\n ) {\n return invalidAdapterResult(adapterId);\n }\n\n entries.push([key, typeof detail === 'number' && Object.is(detail, -0) ? 0 : detail]);\n }\n\n return normalizeDiagnosticDetails(createNullPrototypeRecord(entries));\n};\n\nconst normalizePosition = (candidate: unknown, adapterId: string): ISourcePosition => {\n if (\n !isRecord(candidate) ||\n !hasOnlyKeys(candidate, POSITION_KEYS) ||\n !Number.isSafeInteger(candidate['line']) ||\n !Number.isSafeInteger(candidate['column']) ||\n !Number.isSafeInteger(candidate['offset']) ||\n (candidate['line'] as number) < 1 ||\n (candidate['column'] as number) < 1 ||\n (candidate['offset'] as number) < 0\n ) {\n return invalidAdapterResult(adapterId);\n }\n\n return freezeRecursively({\n column: candidate['column'] as number,\n line: candidate['line'] as number,\n offset: candidate['offset'] as number,\n });\n};\n\nconst normalizeRange = (candidate: unknown, adapterId: string): ISourceRange | null => {\n if (candidate === null) {\n return null;\n }\n\n if (!isRecord(candidate) || !hasOnlyKeys(candidate, RANGE_KEYS)) {\n return invalidAdapterResult(adapterId);\n }\n\n const start = normalizePosition(candidate['start'], adapterId);\n const end = normalizePosition(candidate['end'], adapterId);\n const hasOrderedLines =\n end.line > start.line || (end.line === start.line && end.column >= start.column);\n\n if (!hasOrderedLines || end.offset < start.offset) {\n return invalidAdapterResult(adapterId);\n }\n\n return freezeRecursively({ end, start });\n};\n\nconst isJsonPointer = (candidate: string): boolean => {\n return (\n isUnicodeScalarText(candidate) &&\n !candidate.includes('\\0') &&\n (candidate === '' || (candidate.startsWith('/') && !/~(?![01])/u.test(candidate)))\n );\n};\n\nconst readCapability = (\n agent: IIndexedAgent,\n capabilityKind: 'tool' | 'skill',\n capabilityId: string,\n): unknown => {\n const capabilities =\n capabilityKind === 'tool' ? agent.declaration.tools : agent.declaration.skills;\n\n return capabilities !== undefined && Object.hasOwn(capabilities, capabilityId)\n ? capabilities[capabilityId]\n : undefined;\n};\n\nconst normalizeEntity = (\n candidate: unknown,\n context: IAdapterValidationState,\n): IDiagnosticEntity | null => {\n if (candidate === null) {\n return null;\n }\n\n if (!isRecord(candidate) || !hasOnlyKeys(candidate, DIAGNOSTIC_ENTITY_KEYS)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const entity: Record<string, string> = {};\n\n for (const key of DIAGNOSTIC_ENTITY_KEYS) {\n const candidateValue = candidate[key];\n\n if (candidateValue === undefined) {\n continue;\n }\n\n if (!isSafeString(candidateValue) || candidateValue.length === 0) {\n return invalidAdapterResult(context.adapterId);\n }\n\n entity[key] = candidateValue;\n }\n\n const agentId = entity['agentId'];\n const agent = agentId === undefined ? undefined : context.agentsById.get(agentId);\n\n if (agentId !== undefined && agent === undefined) {\n return invalidAdapterResult(context.adapterId);\n }\n\n if (entity['adapterId'] !== undefined && entity['adapterId'] !== context.adapterId) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const capabilityKind = entity['capabilityKind'];\n const capabilityId = entity['capabilityId'];\n\n if (\n (capabilityKind === undefined) !== (capabilityId === undefined) ||\n (capabilityKind !== undefined && capabilityKind !== 'tool' && capabilityKind !== 'skill') ||\n (capabilityKind !== undefined &&\n capabilityId !== undefined &&\n (agent === undefined || readCapability(agent, capabilityKind, capabilityId) === undefined))\n ) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const variableId = entity['variableId'];\n\n if (\n variableId !== undefined &&\n (agent === undefined ||\n agent.declaration.variables === undefined ||\n !Object.hasOwn(agent.declaration.variables, variableId))\n ) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const decisionId = entity['decisionId'];\n\n if (decisionId !== undefined && !context.decisionIds.has(decisionId)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n return normalizeDiagnosticEntity(entity);\n};\n\n/** Checks only the safe wire grammar; adapters own SemVer meaning and normalization. */\nconst isNormalizedRangeWire = (candidate: string): boolean => {\n if (candidate === '*') {\n return true;\n }\n\n return candidate.split(' || ').every((set) => {\n const comparators = set.split(' ');\n\n return (\n comparators.length > 0 && comparators.every((part) => RANGE_COMPARATOR_PATTERN.test(part))\n );\n });\n};\n\nconst isValidWarningSubject = (\n relationship: IUnverifiedRelationship,\n entity: IDiagnosticEntity | null,\n context: IAdapterValidationState,\n): boolean => {\n if (entity?.agentId === undefined || entity.decisionId !== undefined) {\n return false;\n }\n\n const agent = context.agentsById.get(entity.agentId);\n\n if (agent === undefined) {\n return false;\n }\n\n if (relationship === 'variable-provider') {\n return (\n entity.capabilityKind === undefined &&\n entity.capabilityId === undefined &&\n entity.variableId !== undefined &&\n agent.declaration.bindings?.variableProviders?.[entity.variableId] !== undefined\n );\n }\n\n if (entity.variableId !== undefined) {\n return false;\n }\n\n if (relationship.startsWith('tool-')) {\n if (entity.capabilityKind !== 'tool' || entity.capabilityId === undefined) {\n return false;\n }\n\n const tool = agent.declaration.tools?.[entity.capabilityId];\n\n return (\n tool !== undefined &&\n (relationship !== 'tool-input-schema' || tool.inputSchema !== undefined) &&\n (relationship !== 'tool-output-schema' || tool.outputSchema !== undefined)\n );\n }\n\n if (relationship.startsWith('skill-')) {\n return (\n entity.capabilityKind === 'skill' &&\n entity.capabilityId !== undefined &&\n agent.declaration.skills?.[entity.capabilityId] !== undefined\n );\n }\n\n if (entity.capabilityKind !== undefined || entity.capabilityId !== undefined) {\n return false;\n }\n\n if (relationship === 'runtime-agent') {\n return agent.declaration.bindings?.runtimeAgent !== undefined;\n }\n\n if (relationship === 'instruction-loader') {\n return agent.declaration.bindings?.instructionLoader !== undefined;\n }\n\n if (relationship === 'agent-input-schema') {\n return agent.declaration.bindings?.inputSchema !== undefined;\n }\n\n if (relationship === 'agent-output-schema') {\n return agent.declaration.bindings?.outputSchema !== undefined;\n }\n\n return relationship === 'handoff-registration' || relationship === 'routing-description';\n};\n\nconst normalizeWarningDetails = (\n candidate: unknown,\n entity: IDiagnosticEntity | null,\n context: IAdapterValidationState,\n): IAdapterWarningDiagnostic['details'] => {\n const details = normalizeDetails(candidate, context.adapterId);\n const relationship = details['relationship'];\n const reason = details['reason'];\n\n if (\n typeof relationship !== 'string' ||\n !UNVERIFIED_RELATIONSHIPS.has(relationship as IUnverifiedRelationship) ||\n !isValidWarningSubject(relationship as IUnverifiedRelationship, entity, context)\n ) {\n return invalidAdapterResult(context.adapterId);\n }\n\n if (reason === 'unsupported-source-pattern' || reason === 'dynamic-source-pattern') {\n if (!hasOnlyKeys(details, SIMPLE_WARNING_KEYS)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n return freezeRecursively({ relationship: relationship as IUnverifiedRelationship, reason });\n }\n\n if (reason !== 'version-dependent-behavior' || !hasOnlyKeys(details, VERSION_WARNING_KEYS)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const packageName = details['packageName'];\n const declaredRange = details['declaredRange'];\n const boundaryVersion = details['boundaryVersion'];\n\n if (\n typeof packageName !== 'string' ||\n !PACKAGE_NAME_PATTERN.test(packageName) ||\n (declaredRange !== null &&\n (typeof declaredRange !== 'string' || !isNormalizedRangeWire(declaredRange))) ||\n typeof boundaryVersion !== 'string' ||\n !BOUNDARY_VERSION_PATTERN.test(boundaryVersion)\n ) {\n return invalidAdapterResult(context.adapterId);\n }\n\n return freezeRecursively({\n boundaryVersion,\n declaredRange,\n packageName,\n reason,\n relationship: relationship as IUnverifiedRelationship,\n });\n};\n\nconst normalizeReference = (candidate: unknown, adapterId: string): IRepositoryReference => {\n if (!isRecord(candidate) || !hasOnlyKeys(candidate, REFERENCE_KEYS)) {\n return invalidAdapterResult(adapterId);\n }\n\n const pathCandidate = candidate['path'];\n const symbolCandidate = candidate['symbol'];\n\n if (typeof pathCandidate !== 'string' || !isRepositoryPath(pathCandidate)) {\n return invalidAdapterResult(adapterId);\n }\n\n const path = parseRepositoryPath(pathCandidate);\n\n if (\n symbolCandidate !== undefined &&\n (typeof symbolCandidate !== 'string' ||\n !isUnicodeScalarText(symbolCandidate) ||\n !isRepositorySymbol(symbolCandidate) ||\n isCanonicalMoldeaPath(path))\n ) {\n return invalidAdapterResult(adapterId);\n }\n\n return freezeRecursively({\n path,\n ...(symbolCandidate === undefined ? {} : { symbol: symbolCandidate }),\n });\n};\n\nconst normalizeReferences = (\n candidate: unknown,\n adapterId: string,\n): readonly IRepositoryReference[] => {\n if (!Array.isArray(candidate) || candidate.length === 0) {\n return invalidAdapterResult(adapterId);\n }\n\n const references = candidate.map((reference) => normalizeReference(reference, adapterId));\n const referenceKeys = new Set<string>();\n\n for (const reference of references) {\n const key = JSON.stringify([reference.path, reference.symbol ?? null]);\n\n if (referenceKeys.has(key)) {\n return invalidAdapterResult(adapterId);\n }\n\n referenceKeys.add(key);\n }\n\n return freezeRecursively(sortRepositoryReferences(references));\n};\n\nconst normalizeEvidence = (\n candidate: unknown,\n context: IAdapterValidationState,\n): IRuntimeAdapterEvidence => {\n if (!isRecord(candidate) || !hasOnlyKeys(candidate, EVIDENCE_KEYS)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const source = candidate['source'];\n const kind = candidate['kind'];\n const agentId = candidate['agentId'];\n const capabilityKind = candidate['capabilityKind'];\n const capabilityId = candidate['capabilityId'];\n const runtimeName = candidate['runtimeName'];\n\n if (\n source !== context.adapterId ||\n typeof kind !== 'string' ||\n !EVIDENCE_KINDS.has(kind as IRuntimeAdapterEvidenceKind) ||\n (agentId !== null && !isSafeString(agentId)) ||\n (capabilityKind !== null && capabilityKind !== 'tool' && capabilityKind !== 'skill') ||\n (capabilityId !== null && !isSafeString(capabilityId)) ||\n (runtimeName !== null &&\n (!isSafeString(runtimeName) ||\n !isNonEmptySingleLine(runtimeName) ||\n hasSurroundingWhitespace(runtimeName)))\n ) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const scopedAgent = agentId === null ? undefined : context.agentsById.get(agentId);\n\n if (\n (agentId !== null && scopedAgent === undefined) ||\n (capabilityKind === null) !== (capabilityId === null) ||\n (capabilityKind !== null &&\n capabilityId !== null &&\n (scopedAgent === undefined ||\n readCapability(scopedAgent, capabilityKind, capabilityId) === undefined))\n ) {\n return invalidAdapterResult(context.adapterId);\n }\n\n return freezeRecursively({\n agentId,\n capabilityId,\n capabilityKind,\n details: normalizeDetails(candidate['details'], context.adapterId),\n kind: kind as IRuntimeAdapterEvidenceKind,\n references: normalizeReferences(candidate['references'], context.adapterId),\n runtimeName,\n source,\n });\n};\n\nconst validateEvidenceReferences = async (\n evidence: readonly IRuntimeAdapterEvidence[],\n context: IAdapterValidationState,\n): Promise<void> => {\n const entries = new Map<IRepositoryPath, IRepositoryEntry | null>();\n const operationOptions = context.signal === undefined ? undefined : { signal: context.signal };\n\n for (const item of evidence) {\n for (const reference of item.references) {\n let entry = entries.get(reference.path);\n\n if (entry === undefined && !entries.has(reference.path)) {\n entry = await context.repository.getEntry(reference.path, operationOptions);\n entries.set(reference.path, entry);\n }\n\n if (entry?.type !== 'file') {\n return invalidAdapterResult(context.adapterId);\n }\n }\n }\n};\n\nconst normalizeDiagnostic = (\n candidate: unknown,\n context: IAdapterValidationState,\n): IAdapterDiagnostic => {\n if (!isRecord(candidate) || !hasOnlyKeys(candidate, DIAGNOSTIC_KEYS)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const source = candidate['source'];\n const severity = candidate['severity'];\n const code = candidate['code'];\n const message = candidate['message'];\n const pathCandidate = candidate['path'];\n const pointer = candidate['pointer'];\n const namespace = `${context.adapterId.toUpperCase().replaceAll('-', '_')}_`;\n const isUnverified = code === `${namespace}RUNTIME_RELATIONSHIP_UNVERIFIED`;\n\n if (\n source !== context.adapterId ||\n !isSafeString(code) ||\n !ADAPTER_CODE_PATTERN.test(code) ||\n !code.startsWith(namespace) ||\n code.length === namespace.length ||\n (isUnverified\n ? severity !== 'warning' || message !== UNVERIFIED_MESSAGE\n : severity !== 'error') ||\n !isSafeString(message) ||\n message.length === 0 ||\n (pathCandidate !== null &&\n (typeof pathCandidate !== 'string' || !isRepositoryPath(pathCandidate))) ||\n (pointer !== null && (typeof pointer !== 'string' || !isJsonPointer(pointer)))\n ) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const path = pathCandidate === null ? null : parseRepositoryPath(pathCandidate);\n const range = normalizeRange(candidate['range'], context.adapterId);\n const entity = normalizeEntity(candidate['entity'], context);\n\n if (path === null && (pointer !== null || range !== null)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n if (isUnverified) {\n if (path === null) {\n return invalidAdapterResult(context.adapterId);\n }\n\n return freezeRecursively({\n code,\n details: normalizeWarningDetails(candidate['details'], entity, context),\n entity,\n message,\n path,\n pointer,\n range,\n severity: 'warning' as const,\n source,\n });\n }\n\n return freezeRecursively({\n code,\n details: normalizeDetails(candidate['details'], context.adapterId),\n entity,\n message,\n path,\n pointer,\n range,\n severity: 'error' as const,\n source,\n });\n};\n\nconst compareNullableStrings = (left: string | null, right: string | null): number => {\n return left === null\n ? right === null\n ? 0\n : -1\n : right === null\n ? 1\n : compareExactStrings(left, right);\n};\n\nconst compareEvidence = (left: IRuntimeAdapterEvidence, right: IRuntimeAdapterEvidence): number => {\n const leftReferences = JSON.stringify(\n left.references.map((reference) => [reference.path, reference.symbol ?? null]),\n );\n const rightReferences = JSON.stringify(\n right.references.map((reference) => [reference.path, reference.symbol ?? null]),\n );\n\n return (\n compareExactStrings(left.source, right.source) ||\n compareExactStrings(left.kind, right.kind) ||\n compareNullableStrings(left.agentId, right.agentId) ||\n compareNullableStrings(left.capabilityKind, right.capabilityKind) ||\n compareNullableStrings(left.capabilityId, right.capabilityId) ||\n compareNullableStrings(left.runtimeName, right.runtimeName) ||\n compareExactStrings(leftReferences, rightReferences) ||\n compareExactStrings(\n serializeDiagnosticDetails(left.details),\n serializeDiagnosticDetails(right.details),\n )\n );\n};\n\nconst serializeEvidence = (evidence: IRuntimeAdapterEvidence): string => {\n return JSON.stringify([\n evidence.source,\n evidence.kind,\n evidence.agentId,\n evidence.capabilityKind,\n evidence.capabilityId,\n evidence.runtimeName,\n evidence.references.map((reference) => [reference.path, reference.symbol ?? null]),\n serializeDiagnosticDetails(evidence.details),\n ]);\n};\n\n/**\n * Deduplicates and sorts normalized evidence from every completed adapter.\n * @param candidates The normalized evidence items to combine.\n * @returns A frozen deterministic evidence collection.\n */\nexport const normalizeRuntimeAdapterEvidence = (\n candidates: readonly IRuntimeAdapterEvidence[],\n): readonly IRuntimeAdapterEvidence[] => {\n const evidence = new Map<string, IRuntimeAdapterEvidence>();\n\n for (const item of candidates) {\n evidence.set(serializeEvidence(item), item);\n }\n\n return freezeRecursively([...evidence.values()].sort(compareEvidence));\n};\n\n/**\n * Validates and normalizes one untrusted runtime adapter result.\n * @param candidate The result returned by the adapter implementation.\n * @param context The invoking adapter scope, project, reader, limits, and signal.\n * @returns A promise resolving to frozen deterministic evidence and diagnostics.\n * @throws\n * - INVALID_REPOSITORY_PATH: An adapter repository reference path is invalid.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during validation.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Adapter validation or a repository operation was aborted.\n * - ADAPTER_EXECUTION_FAILED: The adapter result violates its public contract.\n */\nexport const validateRuntimeAdapterResult = async (\n candidate: unknown,\n context: IAdapterValidationContext,\n outputCounts: IRuntimeAdapterOutputCounts,\n): Promise<IValidatedRuntimeAdapterResult> => {\n let diagnostics: readonly IAdapterDiagnostic[];\n let evidence: readonly IRuntimeAdapterEvidence[];\n let validationState: IAdapterValidationState;\n\n try {\n if (!isRecord(candidate) || !hasOnlyKeys(candidate, ADAPTER_RESULT_KEYS)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const evidenceValue: unknown = candidate['evidence'];\n const diagnosticsValue: unknown = candidate['diagnostics'];\n\n if (!Array.isArray(evidenceValue) || !Array.isArray(diagnosticsValue)) {\n return invalidAdapterResult(context.adapterId);\n }\n\n const evidenceCandidates: readonly unknown[] = evidenceValue;\n const diagnosticCandidates: readonly unknown[] = diagnosticsValue;\n registerRawOutput(outputCounts, 'evidence', evidenceCandidates.length, context);\n registerRawOutput(outputCounts, 'diagnostics', diagnosticCandidates.length, context);\n validationState = {\n ...context,\n agentsById: new Map(context.agents.map((agent) => [agent.id, agent])),\n decisionIds: new Set(context.project.decisions.map(({ decision }) => decision.id)),\n };\n diagnostics = diagnosticCandidates.map((diagnostic) =>\n normalizeDiagnostic(diagnostic, validationState),\n );\n evidence = normalizeRuntimeAdapterEvidence(\n evidenceCandidates.map((evidenceCandidate) =>\n normalizeEvidence(evidenceCandidate, validationState),\n ),\n );\n } catch (error: unknown) {\n if (error instanceof CoreOperationException && error.code === 'RESOURCE_LIMIT_EXCEEDED') {\n throw error;\n }\n\n return invalidAdapterResult(context.adapterId);\n }\n\n try {\n await validateEvidenceReferences(evidence, validationState);\n\n return freezeRecursively({\n diagnostics: normalizeDiagnostics(diagnostics),\n evidence,\n });\n } catch (error: unknown) {\n if (\n error instanceof RepositoryPathException ||\n error instanceof RepositorySourceException ||\n error instanceof CoreOperationException\n ) {\n throw error;\n }\n\n return invalidAdapterResult(context.adapterId);\n }\n};\n","import { RepositoryPathException, RepositorySourceException } from '@moldea.ai/repository';\n\nimport type {\n IRuntimeAdapterAgentResolution,\n IRuntimeAdapterContext,\n IRuntimeAdapterEvidence,\n IRuntimeAdapterRepository,\n IRuntimeAdapterResolvedAgent,\n} from '../adapter/index.js';\nimport type { IIndexedAgent, IMoldeaProjectIndex } from '../contracts/index.js';\nimport {\n normalizeRuntimeAdapterEvidence,\n validateRuntimeAdapterResult,\n type IRuntimeAdapterOutputCounts,\n} from '../adapter-validation/index.js';\nimport { normalizeDiagnostics } from '../diagnostic-utilities/index.js';\nimport type { IAdapterDiagnostic } from '../diagnostics/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport type { ICoreOptionsSnapshot, IRuntimeAdapterSnapshot } from '../options/index.js';\nimport type { IRepositoryReference } from '../format/index.js';\nimport type { IRepositoryInspectionSession } from '../repository-inspection-session/index.js';\n\n// complete normalized output from every applicable runtime adapter\nexport interface IRuntimeAdapterInspectionResult {\n readonly evidence: readonly IRuntimeAdapterEvidence[];\n readonly diagnostics: readonly IAdapterDiagnostic[];\n}\n\nconst isInspectionBoundaryFailure = (error: unknown): boolean => {\n return (\n error instanceof RepositoryPathException ||\n error instanceof RepositorySourceException ||\n (error instanceof CoreOperationException &&\n error.operation === 'validate-project' &&\n (error.code === 'ABORTED' || error.code === 'RESOURCE_LIMIT_EXCEEDED'))\n );\n};\n\ninterface IRuntimeAgentBindingEntry {\n readonly agent: IIndexedAgent;\n readonly resolved: IRuntimeAdapterResolvedAgent;\n}\n\ntype IRuntimeAgentBindingResolution =\n | { readonly candidateCount: number; readonly kind: 'ambiguous' }\n | ({ readonly kind: 'matched' } & IRuntimeAgentBindingEntry);\n\ntype IRuntimeAgentBindingIndex = ReadonlyMap<string, IRuntimeAgentBindingResolution>;\n\nconst getRuntimeBindingKey = (reference: IRepositoryReference): string =>\n JSON.stringify([reference.path, reference.symbol ?? null]);\n\n/** Builds one compact exact-binding index for a single configured runtime. */\nconst createRuntimeAgentBindingIndex = (\n agents: readonly IIndexedAgent[],\n): IRuntimeAgentBindingIndex => {\n const candidates = new Map<string, IRuntimeAgentBindingResolution>();\n\n for (const agent of agents) {\n const runtimeAgent = agent.declaration.bindings?.runtimeAgent;\n\n if (runtimeAgent === undefined) {\n continue;\n }\n\n const key = getRuntimeBindingKey(runtimeAgent);\n const existing = candidates.get(key);\n\n if (existing !== undefined) {\n candidates.set(key, {\n candidateCount: existing.kind === 'matched' ? 2 : existing.candidateCount + 1,\n kind: 'ambiguous',\n });\n continue;\n }\n\n candidates.set(key, {\n agent,\n kind: 'matched',\n resolved: freezeRecursively({\n declaration: agent.declaration,\n description: agent.description,\n handoffDescription: agent.handoffDescription,\n id: agent.id,\n }),\n });\n }\n\n return candidates;\n};\n\nconst invokeAdapter = async (\n adapter: IRuntimeAdapterSnapshot,\n agent: IIndexedAgent,\n agentBindings: IRuntimeAgentBindingIndex,\n project: IMoldeaProjectIndex,\n session: IRepositoryInspectionSession,\n options: ICoreOptionsSnapshot,\n outputCounts: IRuntimeAdapterOutputCounts,\n signal?: AbortSignal,\n): Promise<IRuntimeAdapterInspectionResult> => {\n const scopedAgent = freezeRecursively(agent);\n const resolvedAgents = new Map<string, IIndexedAgent>([[scopedAgent.id, scopedAgent]]);\n const repository: IRuntimeAdapterRepository = session.adapterRepository;\n const resolveAgent = (reference: IRepositoryReference): IRuntimeAdapterAgentResolution => {\n const resolution = agentBindings.get(getRuntimeBindingKey(reference));\n\n if (resolution === undefined) {\n return Object.freeze({ kind: 'absent' });\n }\n\n if (resolution.kind === 'ambiguous') {\n return Object.freeze({\n candidateCount: resolution.candidateCount,\n kind: 'ambiguous',\n });\n }\n\n resolvedAgents.set(resolution.agent.id, resolution.agent);\n return Object.freeze({ agent: resolution.resolved, kind: 'matched' });\n };\n\n const context: IRuntimeAdapterContext = Object.freeze({\n agent: scopedAgent,\n repository,\n resolveAgent,\n ...(signal === undefined ? {} : { signal }),\n });\n\n let candidate: unknown;\n\n try {\n session.throwIfAborted();\n candidate = await adapter.inspect(context);\n session.throwIfAborted();\n } catch (error: unknown) {\n session.throwIfAborted();\n\n if (isInspectionBoundaryFailure(error)) {\n throw error;\n }\n\n throw new CoreOperationException({\n adapterId: adapter.id,\n cause: error,\n code: 'ADAPTER_EXECUTION_FAILED',\n operation: 'validate-project',\n });\n }\n\n return validateRuntimeAdapterResult(\n candidate,\n {\n adapterId: adapter.id,\n agents: [...resolvedAgents.values()],\n limits: options.limits,\n project,\n repository: session.adapterRepository,\n ...(signal === undefined ? {} : { signal }),\n },\n outputCounts,\n );\n};\n\n/**\n * Invokes every applicable configured adapter in canonical ID order.\n * @param project The complete frozen universal project index.\n * @param session The shared inspection reader, cache, and resource budget.\n * @param options The immutable Core adapter registry and resource limits.\n * @param signal Optional cancellation shared by the complete inspection.\n * @returns A promise resolving to normalized evidence and adapter diagnostics.\n * @throws\n * - INVALID_REPOSITORY_PATH: An adapter repository path is invalid.\n * - ENTRY_NOT_FOUND: A requested repository entry is absent.\n * - ENTRY_NOT_FILE: A requested repository entry is not a regular file.\n * - ENTRY_NOT_DIRECTORY: A requested repository entry is not a directory.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during adapter inspection.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Adapter inspection or a repository operation was aborted.\n * - ADAPTER_EXECUTION_FAILED: An adapter failed or returned an invalid result.\n */\nexport const inspectRuntimeAdapters = async (\n project: IMoldeaProjectIndex,\n session: IRepositoryInspectionSession,\n options: ICoreOptionsSnapshot,\n signal?: AbortSignal,\n): Promise<IRuntimeAdapterInspectionResult> => {\n const evidence: IRuntimeAdapterEvidence[] = [];\n const diagnostics: IAdapterDiagnostic[] = [];\n const outputCounts: IRuntimeAdapterOutputCounts = { diagnostics: 0, evidence: 0 };\n const agentsByRuntimeId = new Map<string, IIndexedAgent[]>();\n\n for (const agent of project.agents) {\n const runtimeAgents = agentsByRuntimeId.get(agent.declaration.runtime.id);\n\n if (runtimeAgents === undefined) {\n agentsByRuntimeId.set(agent.declaration.runtime.id, [agent]);\n } else {\n runtimeAgents.push(agent);\n }\n }\n\n for (const adapter of options.adapters) {\n const agents = agentsByRuntimeId.get(adapter.id) ?? [];\n const agentBindings = createRuntimeAgentBindingIndex(agents);\n\n for (const agent of agents) {\n const result = await invokeAdapter(\n adapter,\n agent,\n agentBindings,\n project,\n session,\n options,\n outputCounts,\n signal,\n );\n evidence.push(...result.evidence);\n diagnostics.push(...result.diagnostics);\n }\n }\n\n return freezeRecursively({\n diagnostics: normalizeDiagnostics(diagnostics),\n evidence: normalizeRuntimeAdapterEvidence(evidence),\n });\n};\n","import {\n REPOSITORY_ROOT,\n RepositorySourceException,\n compareRepositoryPaths,\n isRepositoryPath,\n parseRepositoryPath,\n type IRepositoryEntry,\n type IRepositoryOperation,\n type IRepositoryOperationOptions,\n type IRepositoryPath,\n type IRepositoryReader,\n} from '@moldea.ai/repository';\n\nimport type { ICoreResourceLimits } from '../contracts/index.js';\nimport type { IRuntimeAdapterRepository } from '../adapter/index.js';\nimport { registerRuntimeAdapterRetainedByteReservation } from '../adapter-retained-memory/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\n\nconst MANIFEST_PATH = parseRepositoryPath('/moldea/moldea.yaml');\nconst SOURCE_PAGE_ENTRIES = 256;\nconst SOURCE_PAGE_BYTES = 65_536;\nconst CANONICAL_BYTE_RETENTION_MULTIPLIER = 4;\nconst RETAINED_PATH_FIXED_BYTES = 64;\nconst RETAINED_PATH_BYTE_MULTIPLIER = 2;\nconst encoder = new TextEncoder();\n\ntype IInspectionFileByteLimit = 'maxFileBytes' | 'maxManifestBytes';\n\nexport interface IRepositoryInspectionListOptions extends IRepositoryOperationOptions {\n readonly prefix?: IRepositoryPath;\n}\n\n// private complete-content view used only while validating canonical documents\nexport interface IRepositoryInspectionReader {\n getEntry(\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryEntry | null>;\n iterateEntries(options?: IRepositoryInspectionListOptions): AsyncIterable<IRepositoryEntry>;\n readCompleteFile(\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<Uint8Array>;\n}\n\n// private resource state shared by every reader consumer during one validation\nexport interface IRepositoryInspectionSession {\n readonly adapterRepository: IRuntimeAdapterRepository;\n readonly reader: IRepositoryInspectionReader;\n\n /** Returns deterministic logical resource usage for the current validation state. */\n getResourceUsage(): IRepositoryInspectionResourceUsage;\n\n /**\n * Stops work at an inspection boundary when cancellation was requested.\n * @throws\n * - ABORTED: Repository inspection was aborted.\n */\n throwIfAborted(): void;\n}\n\n// private logical usage carried into prepared project inspection\nexport interface IRepositoryInspectionResourceUsage {\n readonly canonicalBytes: number;\n readonly peakRetainedBytes: number;\n readonly retainedBytes: number;\n readonly totalBytesRead: number;\n}\n\nconst invalidSourceData = (\n operation: IRepositoryOperation,\n path: IRepositoryPath | null,\n): never => {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation,\n path,\n retryable: false,\n });\n};\n\nconst copyReaderEntry = (\n candidate: unknown,\n operation: 'get-entry' | 'list-entries-page',\n fallbackPath: IRepositoryPath,\n expectedPath?: IRepositoryPath,\n): IRepositoryEntry => {\n if (typeof candidate !== 'object' || candidate === null) {\n return invalidSourceData(operation, fallbackPath);\n }\n\n const record = candidate as Readonly<Record<string, unknown>>;\n const pathCandidate = record['path'];\n const typeCandidate = record['type'];\n const byteLength = record['byteLength'];\n const contentIdentity = record['contentIdentity'];\n\n if (typeof pathCandidate !== 'string' || !isRepositoryPath(pathCandidate)) {\n return invalidSourceData(operation, fallbackPath);\n }\n\n const path = parseRepositoryPath(pathCandidate);\n\n if (expectedPath !== undefined && path !== expectedPath) {\n return invalidSourceData(operation, path);\n }\n\n if (typeCandidate !== 'file' && typeCandidate !== 'directory' && typeCandidate !== 'symlink') {\n return invalidSourceData(operation, path);\n }\n\n if (\n typeCandidate === 'file'\n ? !Number.isSafeInteger(byteLength) ||\n (byteLength as number) < 0 ||\n (contentIdentity !== null && typeof contentIdentity !== 'string')\n : byteLength !== null || contentIdentity !== null\n ) {\n return invalidSourceData(operation, path);\n }\n\n return {\n byteLength: byteLength as number | null,\n contentIdentity: contentIdentity as string | null,\n path,\n type: typeCandidate,\n };\n};\n\nconst isStrictDescendant = (path: IRepositoryPath, prefix: IRepositoryPath): boolean => {\n if (path === prefix) {\n return false;\n }\n\n const descendantPrefix = prefix === REPOSITORY_ROOT ? REPOSITORY_ROOT : `${prefix}/`;\n return path.startsWith(descendantPrefix);\n};\n\nconst throwResourceLimitExceeded = (\n limit: keyof ICoreResourceLimits,\n limitMaximum: number,\n observedUsage: number,\n): never => {\n throw new CoreOperationException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit,\n limitMaximum,\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage,\n operation: 'validate-project',\n });\n};\n\nconst createSourceOptions = (\n sessionSignal: AbortSignal | undefined,\n operationSignal: AbortSignal | undefined,\n): IRepositoryOperationOptions | undefined => {\n const signal =\n sessionSignal === undefined\n ? operationSignal\n : operationSignal === undefined || operationSignal === sessionSignal\n ? sessionSignal\n : AbortSignal.any([sessionSignal, operationSignal]);\n return signal === undefined ? undefined : { signal };\n};\n\n/**\n * Creates the isolated reader state for one repository inspection.\n * @param repository The source-neutral reader bound to one coherent snapshot.\n * @param limits The immutable resource limits for the inspection.\n * @param signal Optional cancellation shared by every inspection operation.\n * @returns A session that pages source metadata and range-reads bounded canonical files.\n * @throws\n * - ABORTED: Repository inspection was aborted before the session was created.\n */\nexport const createRepositoryInspectionSession = (\n repository: IRepositoryReader,\n limits: ICoreResourceLimits,\n signal?: AbortSignal,\n): IRepositoryInspectionSession => {\n const seenPaths = new Set<IRepositoryPath>();\n let canonicalBytes = 0;\n let peakRetainedBytes = 0;\n let retainedBytes = 0;\n let totalBytesRead = 0;\n const adapterLimits = Object.freeze({\n maxEntries: limits.maxEntries,\n maxFileBytes: limits.maxFileBytes,\n maxPageBytes: Math.min(SOURCE_PAGE_BYTES, limits.maxFileBytes),\n maxPageEntries: Math.min(SOURCE_PAGE_ENTRIES, limits.maxEntries),\n maxTotalBytesRead: limits.maxTotalBytesRead,\n });\n\n const createAbortedException = (abortedSignal: AbortSignal): CoreOperationException => {\n return new CoreOperationException({\n cause: abortedSignal.reason,\n code: 'ABORTED',\n operation: 'validate-project',\n });\n };\n\n const reserveRetainedBytes = (byteLength: number): void => {\n if (\n !Number.isSafeInteger(byteLength) ||\n byteLength < 0 ||\n byteLength > limits.maxRetainedBytes - retainedBytes\n ) {\n return throwResourceLimitExceeded(\n 'maxRetainedBytes',\n limits.maxRetainedBytes,\n retainedBytes + byteLength,\n );\n }\n\n retainedBytes += byteLength;\n peakRetainedBytes = Math.max(peakRetainedBytes, retainedBytes);\n };\n\n const observeTransientBytes = (byteLength: number): void => {\n if (\n !Number.isSafeInteger(byteLength) ||\n byteLength < 0 ||\n byteLength > limits.maxRetainedBytes - retainedBytes\n ) {\n return throwResourceLimitExceeded(\n 'maxRetainedBytes',\n limits.maxRetainedBytes,\n retainedBytes + byteLength,\n );\n }\n\n peakRetainedBytes = Math.max(peakRetainedBytes, retainedBytes + byteLength);\n };\n\n const registerPath = (path: IRepositoryPath): void => {\n if (path === REPOSITORY_ROOT || seenPaths.has(path)) {\n return;\n }\n\n if (seenPaths.size >= limits.maxEntries) {\n return throwResourceLimitExceeded('maxEntries', limits.maxEntries, seenPaths.size + 1);\n }\n\n reserveRetainedBytes(\n RETAINED_PATH_FIXED_BYTES + encoder.encode(path).byteLength * RETAINED_PATH_BYTE_MULTIPLIER,\n );\n seenPaths.add(path);\n };\n\n const throwIfSignalAborted = (operationSignal?: AbortSignal): void => {\n const abortedSignal = signal?.aborted\n ? signal\n : operationSignal?.aborted\n ? operationSignal\n : null;\n\n if (abortedSignal !== null) {\n throw createAbortedException(abortedSignal);\n }\n };\n\n throwIfSignalAborted();\n\n const reserveReadBytes = (byteLength: number): void => {\n if (byteLength > limits.maxTotalBytesRead - totalBytesRead) {\n return throwResourceLimitExceeded(\n 'maxTotalBytesRead',\n limits.maxTotalBytesRead,\n totalBytesRead + byteLength,\n );\n }\n\n totalBytesRead += byteLength;\n };\n\n const getEntry = async (\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryEntry | null> => {\n const parsedPath = parseRepositoryPath(path);\n throwIfSignalAborted(options?.signal);\n registerPath(parsedPath);\n const candidate = await repository.getEntry(\n parsedPath,\n createSourceOptions(signal, options?.signal),\n );\n throwIfSignalAborted(options?.signal);\n\n return candidate === null\n ? null\n : copyReaderEntry(candidate, 'get-entry', parsedPath, parsedPath);\n };\n\n const iterateEntries = (\n options?: IRepositoryInspectionListOptions,\n ): AsyncIterable<IRepositoryEntry> => {\n const prefix =\n options?.prefix === undefined ? REPOSITORY_ROOT : parseRepositoryPath(options.prefix);\n\n return {\n async *[Symbol.asyncIterator](): AsyncIterator<IRepositoryEntry> {\n registerPath(prefix);\n const yieldedPaths = new Set<IRepositoryPath>();\n let cursor: string | undefined;\n let previousPath: IRepositoryPath | null = null;\n\n do {\n throwIfSignalAborted(options?.signal);\n const page = await repository.listEntriesPage({\n ...(cursor === undefined ? {} : { cursor }),\n maxEntries: Math.min(SOURCE_PAGE_ENTRIES, limits.maxEntries),\n prefix,\n ...(createSourceOptions(signal, options?.signal) ?? {}),\n });\n\n if (\n page.snapshot.id !== repository.snapshot.id ||\n (page.entries.length === 0 && !page.isComplete)\n ) {\n return invalidSourceData('list-entries-page', prefix);\n }\n\n for (const candidate of page.entries) {\n throwIfSignalAborted(options?.signal);\n const entry = copyReaderEntry(candidate, 'list-entries-page', prefix);\n\n if (\n !isStrictDescendant(entry.path, prefix) ||\n yieldedPaths.has(entry.path) ||\n (previousPath !== null && compareRepositoryPaths(previousPath, entry.path) >= 0)\n ) {\n return invalidSourceData('list-entries-page', entry.path);\n }\n\n yieldedPaths.add(entry.path);\n previousPath = entry.path;\n registerPath(entry.path);\n yield entry;\n }\n\n if (page.isComplete) {\n if (page.nextCursor !== null) {\n return invalidSourceData('list-entries-page', prefix);\n }\n\n return;\n }\n\n if (page.nextCursor === null || page.nextCursor === cursor) {\n return invalidSourceData('list-entries-page', prefix);\n }\n\n cursor = page.nextCursor;\n } while (true);\n },\n };\n };\n\n const loadFile = async (\n path: IRepositoryPath,\n operationSignal?: AbortSignal,\n ): Promise<Uint8Array> => {\n const fileLimit: IInspectionFileByteLimit =\n path === MANIFEST_PATH ? 'maxManifestBytes' : 'maxFileBytes';\n const availableRetainedBytes = limits.maxRetainedBytes - retainedBytes;\n\n if (availableRetainedBytes < 1) {\n return throwResourceLimitExceeded(\n 'maxRetainedBytes',\n limits.maxRetainedBytes,\n retainedBytes + 1,\n );\n }\n\n const firstPageMaximumBytes = Math.min(\n SOURCE_PAGE_BYTES,\n Math.max(1, limits[fileLimit]),\n availableRetainedBytes,\n );\n observeTransientBytes(firstPageMaximumBytes);\n const firstPage = await repository.readFilePage(path, {\n maxBytes: firstPageMaximumBytes,\n offset: 0,\n ...(createSourceOptions(signal, operationSignal) ?? {}),\n });\n throwIfSignalAborted(operationSignal);\n\n if (\n firstPage.snapshot.id !== repository.snapshot.id ||\n firstPage.offset !== 0 ||\n !(firstPage.bytes instanceof Uint8Array) ||\n !Number.isSafeInteger(firstPage.totalBytes) ||\n firstPage.totalBytes < 0 ||\n firstPage.bytes.byteLength > SOURCE_PAGE_BYTES ||\n firstPage.bytes.byteLength > firstPage.totalBytes ||\n (firstPage.bytes.byteLength === 0 && !firstPage.isComplete)\n ) {\n return invalidSourceData('read-file-page', path);\n }\n\n if (firstPage.totalBytes > limits[fileLimit]) {\n return throwResourceLimitExceeded(fileLimit, limits[fileLimit], firstPage.totalBytes);\n }\n\n const firstPageBytes = firstPage.bytes.byteLength;\n const retainedBytesAvailableForCanonicalContent =\n limits.maxRetainedBytes - retainedBytes - firstPageBytes;\n\n if (\n retainedBytesAvailableForCanonicalContent < 0 ||\n firstPage.totalBytes >\n Math.floor(retainedBytesAvailableForCanonicalContent / CANONICAL_BYTE_RETENTION_MULTIPLIER)\n ) {\n const projectedUsage =\n retainedBytes + firstPageBytes + firstPage.totalBytes * CANONICAL_BYTE_RETENTION_MULTIPLIER;\n\n return throwResourceLimitExceeded(\n 'maxRetainedBytes',\n limits.maxRetainedBytes,\n Number.isSafeInteger(projectedUsage) ? projectedUsage : Number.MAX_SAFE_INTEGER,\n );\n }\n\n reserveReadBytes(firstPage.totalBytes);\n const canonicalRetainedBytes = firstPage.totalBytes * CANONICAL_BYTE_RETENTION_MULTIPLIER;\n observeTransientBytes(canonicalRetainedBytes + firstPageBytes);\n reserveRetainedBytes(canonicalRetainedBytes);\n canonicalBytes += firstPage.totalBytes;\n\n const content = new Uint8Array(firstPage.totalBytes);\n let offset = 0;\n let page = firstPage;\n let isFirstPage = true;\n\n while (isFirstPage || offset < content.byteLength) {\n isFirstPage = false;\n if (\n page.snapshot.id !== repository.snapshot.id ||\n page.offset !== offset ||\n page.totalBytes !== content.byteLength ||\n !(page.bytes instanceof Uint8Array) ||\n page.bytes.byteLength > SOURCE_PAGE_BYTES ||\n page.bytes.byteLength > content.byteLength - offset ||\n (page.bytes.byteLength === 0 && !page.isComplete)\n ) {\n return invalidSourceData('read-file-page', path);\n }\n\n content.set(page.bytes, offset);\n offset += page.bytes.byteLength;\n\n if (page.isComplete) {\n if (page.nextOffset !== null || offset !== content.byteLength) {\n return invalidSourceData('read-file-page', path);\n }\n\n break;\n }\n\n if (page.nextOffset !== offset) {\n return invalidSourceData('read-file-page', path);\n }\n\n page = await repository.readFilePage(path, {\n maxBytes: Math.min(SOURCE_PAGE_BYTES, Math.max(1, content.byteLength - offset)),\n offset,\n ...(createSourceOptions(signal, operationSignal) ?? {}),\n });\n throwIfSignalAborted(operationSignal);\n }\n\n return content;\n };\n\n const awaitWithCancellation = async <T>(\n promise: Promise<T>,\n operationSignal?: AbortSignal,\n ): Promise<T> => {\n const callerSignal = createSourceOptions(signal, operationSignal)?.signal;\n\n if (callerSignal === undefined) {\n return promise;\n }\n\n if (callerSignal.aborted) {\n throw createAbortedException(callerSignal);\n }\n\n return new Promise<T>((resolve, reject) => {\n const cleanup = (): void => callerSignal.removeEventListener('abort', abort);\n const abort = (): void => {\n cleanup();\n reject(createAbortedException(callerSignal));\n };\n\n callerSignal.addEventListener('abort', abort, { once: true });\n void promise.then(\n (result) => {\n cleanup();\n resolve(result);\n },\n (error: unknown) => {\n cleanup();\n reject(\n error instanceof Error\n ? error\n : new RepositorySourceException({\n cause: error,\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path: null,\n retryable: false,\n }),\n );\n },\n );\n });\n };\n\n const readCompleteFile = async (\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<Uint8Array> => {\n const parsedPath = parseRepositoryPath(path);\n throwIfSignalAborted(options?.signal);\n registerPath(parsedPath);\n const content = await awaitWithCancellation(\n loadFile(parsedPath, options?.signal),\n options?.signal,\n );\n throwIfSignalAborted(options?.signal);\n\n return content.slice();\n };\n\n const listAdapterEntriesPage: IRuntimeAdapterRepository['listEntriesPage'] = async (options) => {\n const prefix =\n options.prefix === undefined ? REPOSITORY_ROOT : parseRepositoryPath(options.prefix);\n registerPath(prefix);\n\n if (\n !Number.isSafeInteger(options.maxEntries) ||\n options.maxEntries < 1 ||\n options.maxEntries > adapterLimits.maxPageEntries\n ) {\n return throwResourceLimitExceeded(\n 'maxEntries',\n adapterLimits.maxPageEntries,\n options.maxEntries,\n );\n }\n\n throwIfSignalAborted(options.signal);\n const page = await repository.listEntriesPage({\n ...(options.cursor === undefined ? {} : { cursor: options.cursor }),\n maxEntries: options.maxEntries,\n prefix,\n ...(createSourceOptions(signal, options.signal) ?? {}),\n });\n throwIfSignalAborted(options.signal);\n\n if (\n page.snapshot.id !== repository.snapshot.id ||\n page.entries.length > options.maxEntries ||\n (page.entries.length === 0 && !page.isComplete) ||\n (page.isComplete ? page.nextCursor !== null : page.nextCursor === null)\n ) {\n return invalidSourceData('list-entries-page', prefix);\n }\n\n let previousPath: IRepositoryPath | null = null;\n const entries = page.entries.map((candidate) => {\n const entry = copyReaderEntry(candidate, 'list-entries-page', prefix);\n\n if (\n !isStrictDescendant(entry.path, prefix) ||\n (previousPath !== null && compareRepositoryPaths(previousPath, entry.path) >= 0)\n ) {\n return invalidSourceData('list-entries-page', entry.path);\n }\n\n previousPath = entry.path;\n registerPath(entry.path);\n return entry;\n });\n\n return Object.freeze({\n entries: Object.freeze(entries),\n isComplete: page.isComplete,\n nextCursor: page.nextCursor,\n snapshot: repository.snapshot,\n });\n };\n\n const readAdapterFilePage: IRuntimeAdapterRepository['readFilePage'] = async (path, options) => {\n const parsedPath = parseRepositoryPath(path);\n\n if (\n !Number.isSafeInteger(options.offset) ||\n options.offset < 0 ||\n !Number.isSafeInteger(options.maxBytes) ||\n options.maxBytes < 1 ||\n options.maxBytes > adapterLimits.maxPageBytes\n ) {\n return invalidSourceData('read-file-page', parsedPath);\n }\n\n throwIfSignalAborted(options.signal);\n registerPath(parsedPath);\n const reservedBytes = Math.min(options.maxBytes, limits.maxTotalBytesRead - totalBytesRead);\n\n if (reservedBytes < 1) {\n return throwResourceLimitExceeded(\n 'maxTotalBytesRead',\n limits.maxTotalBytesRead,\n totalBytesRead + 1,\n );\n }\n\n observeTransientBytes(reservedBytes);\n reserveReadBytes(reservedBytes);\n let page;\n\n try {\n page = await repository.readFilePage(parsedPath, {\n maxBytes: reservedBytes,\n offset: options.offset,\n ...(createSourceOptions(signal, options.signal) ?? {}),\n });\n } catch (error: unknown) {\n totalBytesRead -= reservedBytes;\n throw error;\n }\n\n throwIfSignalAborted(options.signal);\n\n if (\n page.snapshot.id !== repository.snapshot.id ||\n page.offset !== options.offset ||\n !(page.bytes instanceof Uint8Array) ||\n !Number.isSafeInteger(page.totalBytes) ||\n page.totalBytes < 0 ||\n page.totalBytes > limits.maxFileBytes ||\n page.bytes.byteLength > reservedBytes ||\n page.bytes.byteLength > page.totalBytes - page.offset ||\n (page.bytes.byteLength === 0 && !page.isComplete) ||\n (page.isComplete\n ? page.nextOffset !== null || page.offset + page.bytes.byteLength !== page.totalBytes\n : page.nextOffset !== page.offset + page.bytes.byteLength)\n ) {\n totalBytesRead -= reservedBytes;\n return invalidSourceData('read-file-page', parsedPath);\n }\n\n totalBytesRead -= reservedBytes - page.bytes.byteLength;\n\n return Object.freeze({\n bytes: page.bytes.slice(),\n isComplete: page.isComplete,\n nextOffset: page.nextOffset,\n offset: page.offset,\n snapshot: repository.snapshot,\n totalBytes: page.totalBytes,\n });\n };\n\n const adapterRepository: IRuntimeAdapterRepository = Object.freeze({\n getEntry,\n limits: adapterLimits,\n listEntriesPage: listAdapterEntriesPage,\n readFilePage: readAdapterFilePage,\n snapshot: repository.snapshot,\n });\n registerRuntimeAdapterRetainedByteReservation(adapterRepository, reserveRetainedBytes);\n\n return Object.freeze({\n adapterRepository,\n getResourceUsage: () =>\n Object.freeze({ canonicalBytes, peakRetainedBytes, retainedBytes, totalBytesRead }),\n reader: Object.freeze({ getEntry, iterateEntries, readCompleteFile }),\n throwIfAborted: throwIfSignalAborted,\n });\n};\n","import type {\n ICoreResourceLimits,\n IIndexedDescriptionAsset,\n IIndexedTextAsset,\n} from '../contracts/index.js';\nimport { createCoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport {\n countUnicodeScalars,\n hasNonWhitespace,\n trimRepositoryFormatWhitespace,\n} from '../format-validation/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\n\nconst OPENING_HEADING_PATTERN = /^#{1,6} /u;\n\n// internal description validation result retained for agent reconciliation\nexport interface IAgentDescriptionValidationResult {\n readonly valid: boolean;\n readonly description: IIndexedDescriptionAsset | null;\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\n// internal instruction validation result retained for later placeholder checks\nexport interface IAgentInstructionValidationResult {\n readonly valid: boolean;\n readonly instruction: IIndexedTextAsset | null;\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\n/** Finds the first nonblank line at or after one normalized line index. */\nconst findNonblankLine = (lines: readonly string[], startIndex: number): number | null => {\n for (let index = startIndex; index < lines.length; index += 1) {\n const line = lines[index];\n\n if (line !== undefined && hasNonWhitespace(line)) {\n return index;\n }\n }\n\n return null;\n};\n\n/**\n * Validates the effective value of one agent description asset.\n * @param asset The normalized complete description or handoff-description asset.\n * @param agentId The owning registered agent ID.\n * @param kind The description role determining its diagnostic code.\n * @param limits The Core diagnostic budget.\n * @returns The frozen effective description when every version 1 rule passes.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: The repository-level diagnostic budget was exceeded.\n */\nexport const validateAgentDescription = (\n asset: IIndexedTextAsset,\n agentId: string,\n kind: 'description' | 'handoff-description',\n limits: ICoreResourceLimits,\n): IAgentDescriptionValidationResult => {\n const diagnostics = createCoreDiagnosticCollector(limits, 'validate-project');\n const value = trimRepositoryFormatWhitespace(asset.content);\n const scalarLength = countUnicodeScalars(value);\n const code =\n kind === 'description'\n ? 'MOLDEA_AGENT_DESCRIPTION_INVALID'\n : 'MOLDEA_AGENT_HANDOFF_DESCRIPTION_INVALID';\n\n if (scalarLength === 0) {\n diagnostics.add({ code, details: { reason: 'empty' }, entity: { agentId }, path: asset.path });\n }\n\n if (scalarLength > 1_000) {\n diagnostics.add({\n code,\n details: { reason: 'too-long' },\n entity: { agentId },\n path: asset.path,\n });\n }\n\n if (value.includes('{{') || value.includes('}}')) {\n diagnostics.add({\n code,\n details: { reason: 'runtime-variable-delimiter' },\n entity: { agentId },\n path: asset.path,\n });\n }\n\n const finalizedDiagnostics = diagnostics.finalize();\n\n return freezeRecursively({\n description: finalizedDiagnostics.length === 0 ? { asset, scalarLength, value } : null,\n diagnostics: finalizedDiagnostics,\n valid: finalizedDiagnostics.length === 0,\n });\n};\n\n/**\n * Validates one canonical instruction's non-empty content and opening identity.\n * @param asset The normalized complete instruction asset.\n * @param agentId The owning registered agent ID.\n * @param limits The Core diagnostic budget.\n * @returns The frozen instruction result, retaining non-empty content for later validation.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: The repository-level diagnostic budget was exceeded.\n */\nexport const validateAgentInstruction = (\n asset: IIndexedTextAsset,\n agentId: string,\n limits: ICoreResourceLimits,\n): IAgentInstructionValidationResult => {\n const diagnostics = createCoreDiagnosticCollector(limits, 'validate-project');\n\n if (!hasNonWhitespace(asset.content)) {\n diagnostics.add({\n code: 'MOLDEA_AGENT_INSTRUCTION_EMPTY',\n entity: { agentId },\n path: asset.path,\n });\n\n return freezeRecursively({\n diagnostics: diagnostics.finalize(),\n instruction: null,\n valid: false,\n });\n }\n\n const identityToken = `\\`${agentId}\\``;\n const lines = asset.content.split('\\n');\n const openingIndex = findNonblankLine(lines, 0);\n let identityIndex = openingIndex;\n\n if (openingIndex !== null && OPENING_HEADING_PATTERN.test(lines[openingIndex] ?? '')) {\n identityIndex = findNonblankLine(lines, openingIndex + 1);\n }\n\n if (identityIndex === null || !(lines[identityIndex] ?? '').includes(identityToken)) {\n diagnostics.add({\n code: 'MOLDEA_AGENT_IDENTITY_INVALID',\n details: { reason: asset.content.includes(identityToken) ? 'misplaced' : 'missing' },\n entity: { agentId },\n path: asset.path,\n });\n }\n\n const finalizedDiagnostics = diagnostics.finalize();\n\n return freezeRecursively({\n diagnostics: finalizedDiagnostics,\n instruction: asset,\n valid: finalizedDiagnostics.length === 0,\n });\n};\n","import { RepositorySourceException, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICoreResourceLimits, IIndexedTextAsset } from '../contracts/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\nimport { calculateNormalizedTextDigest, normalizeTextDocument } from '../text/index.js';\n\n// internal result for one canonical text read during repository inspection\nexport interface IRepositoryTextResult {\n readonly valid: boolean;\n readonly asset: IIndexedTextAsset | null;\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\nconst invalidSourceData = (path: IRepositoryPath): never => {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n};\n\n/**\n * Reads and normalizes one canonical Markdown asset through a repository reader.\n * @param repository The coherent source-neutral repository reader.\n * @param path The discovered regular-file path to read exactly once.\n * @param limits The Core limits applied to the source bytes and diagnostics.\n * @param signal Optional cancellation forwarded to the repository read.\n * @returns A deeply immutable indexed asset or its deterministic text diagnostics.\n * @throws\n * - ENTRY_NOT_FOUND: The discovered file disappeared from the reader snapshot.\n * - ENTRY_NOT_FILE: The discovered entry is no longer a regular file.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during the read.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Repository inspection or the repository read was aborted.\n */\nexport const readRepositoryTextAsset = async (\n repository: IRepositoryInspectionReader,\n path: IRepositoryPath,\n limits: ICoreResourceLimits,\n signal?: AbortSignal,\n): Promise<IRepositoryTextResult> => {\n const content = await repository.readCompleteFile(\n path,\n signal === undefined ? undefined : { signal },\n );\n\n if (!(content instanceof Uint8Array)) {\n return invalidSourceData(path);\n }\n\n const normalized = normalizeTextDocument({ content, path }, limits, 'validate-project');\n\n if (!normalized.valid || normalized.text === null) {\n return freezeRecursively({\n asset: null,\n diagnostics: normalized.diagnostics,\n valid: false,\n });\n }\n\n const asset: IIndexedTextAsset = {\n content: normalized.text.value,\n digest: await calculateNormalizedTextDigest(normalized.text),\n path,\n scalarLength: normalized.text.scalarLength,\n utf8ByteLength: normalized.text.utf8ByteLength,\n };\n\n return freezeRecursively({\n asset,\n diagnostics: [],\n valid: true,\n });\n};\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICoreResourceLimits, IIndexedTextAsset } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n escapeJsonPointerSegment,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic, ISourceRange } from '../diagnostics/index.js';\nimport { compareExactStrings, isVariableId } from '../format-validation/index.js';\nimport type { IRuntimeVariableManifestEntry } from '../format/index.js';\nimport { createSourceLocator } from '../source-location/index.js';\n\n// internal malformed classifications and valid-placeholder aggregation\ntype IMalformedPlaceholderReason =\n | 'invalid-opening-delimiter'\n | 'invalid-closing-delimiter'\n | 'nested-opening'\n | 'unmatched-opening'\n | 'unmatched-closing'\n | 'invalid-variable-id';\n\ninterface IPlaceholderOccurrence {\n count: number;\n readonly firstRange: ISourceRange;\n}\n\nconst readBraceRunEnd = (content: string, startOffset: number, brace: '{' | '}'): number => {\n let endOffset = startOffset + 1;\n\n while (content[endOffset] === brace) {\n endOffset += 1;\n }\n\n return endOffset;\n};\n\n/** Finds the end of the next closing-delimiter run without rescanning prior content. */\nconst findClosingRunEnd = (content: string, startOffset: number): number => {\n let cursor = startOffset;\n\n while (cursor < content.length) {\n if (content[cursor] !== '}') {\n cursor += 1;\n continue;\n }\n\n const runEnd = readBraceRunEnd(content, cursor, '}');\n if (runEnd - cursor >= 2) {\n return runEnd;\n }\n\n cursor = runEnd;\n }\n\n return content.length;\n};\n\n/** Adds one malformed-placeholder diagnostic for an exact normalized source span. */\nconst addMalformedDiagnostic = (\n collector: ICoreDiagnosticCollector,\n instruction: IIndexedTextAsset,\n agentId: string,\n reason: IMalformedPlaceholderReason,\n range: ISourceRange,\n): void => {\n collector.add({\n code: 'MOLDEA_VARIABLE_PLACEHOLDER_MALFORMED',\n details: { reason },\n entity: { agentId },\n path: instruction.path,\n range,\n });\n};\n\n/** Records a valid placeholder occurrence and its first normalized source range. */\nconst recordOccurrence = (\n occurrences: Map<string, IPlaceholderOccurrence>,\n variableId: string,\n range: ISourceRange,\n): void => {\n const occurrence = occurrences.get(variableId);\n\n if (occurrence === undefined) {\n occurrences.set(variableId, { count: 1, firstRange: range });\n return;\n }\n\n occurrence.count += 1;\n};\n\n/**\n * Validates runtime-variable placeholders in one normalized canonical agent instruction.\n * @param manifestPath The canonical manifest path containing variable declarations.\n * @param agentId The owning agent ID.\n * @param instruction The normalized non-empty canonical instruction asset.\n * @param declaredVariables The owning agent's normalized variable declarations.\n * @param limits The resource limits applied to emitted diagnostics.\n * @returns Frozen deterministic placeholder diagnostics.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: The repository-level diagnostic budget was exceeded.\n */\nexport const validateRuntimePlaceholders = (\n manifestPath: IRepositoryPath,\n agentId: string,\n instruction: IIndexedTextAsset,\n declaredVariables: Readonly<Record<string, IRuntimeVariableManifestEntry>>,\n limits: ICoreResourceLimits,\n): readonly ICoreDiagnostic[] => {\n const collector = createCoreDiagnosticCollector(limits, 'validate-project');\n const locator = createSourceLocator(instruction.content);\n const occurrences = new Map<string, IPlaceholderOccurrence>();\n let cursor = 0;\n\n while (cursor < instruction.content.length) {\n const character = instruction.content[cursor];\n\n if (character === '}') {\n const runEnd = readBraceRunEnd(instruction.content, cursor, '}');\n const runLength = runEnd - cursor;\n\n if (runLength >= 2) {\n addMalformedDiagnostic(\n collector,\n instruction,\n agentId,\n runLength === 2 ? 'unmatched-closing' : 'invalid-closing-delimiter',\n locator.locateRange(cursor, runEnd),\n );\n }\n\n cursor = runEnd;\n continue;\n }\n\n if (character !== '{') {\n cursor += 1;\n continue;\n }\n\n const openingEnd = readBraceRunEnd(instruction.content, cursor, '{');\n const openingLength = openingEnd - cursor;\n\n if (openingLength === 1) {\n cursor = openingEnd;\n continue;\n }\n\n if (openingLength > 2) {\n addMalformedDiagnostic(\n collector,\n instruction,\n agentId,\n 'invalid-opening-delimiter',\n locator.locateRange(cursor, openingEnd),\n );\n cursor = openingEnd;\n continue;\n }\n\n let candidateCursor = openingEnd;\n let isCandidateComplete = false;\n\n while (candidateCursor < instruction.content.length) {\n const candidateCharacter = instruction.content[candidateCursor];\n\n if (candidateCharacter === '{') {\n const nestedOpeningEnd = readBraceRunEnd(instruction.content, candidateCursor, '{');\n\n if (nestedOpeningEnd - candidateCursor >= 2) {\n const malformedEnd = findClosingRunEnd(instruction.content, nestedOpeningEnd);\n addMalformedDiagnostic(\n collector,\n instruction,\n agentId,\n 'nested-opening',\n locator.locateRange(cursor, malformedEnd),\n );\n cursor = malformedEnd;\n isCandidateComplete = true;\n break;\n }\n\n candidateCursor = nestedOpeningEnd;\n continue;\n }\n\n if (candidateCharacter !== '}') {\n candidateCursor += 1;\n continue;\n }\n\n const closingEnd = readBraceRunEnd(instruction.content, candidateCursor, '}');\n const closingLength = closingEnd - candidateCursor;\n\n if (closingLength === 1) {\n candidateCursor = closingEnd;\n continue;\n }\n\n if (closingLength > 2) {\n addMalformedDiagnostic(\n collector,\n instruction,\n agentId,\n 'invalid-closing-delimiter',\n locator.locateRange(cursor, closingEnd),\n );\n cursor = closingEnd;\n isCandidateComplete = true;\n break;\n }\n\n const variableId = instruction.content.slice(openingEnd, candidateCursor);\n const placeholderRange = locator.locateRange(cursor, closingEnd);\n\n if (isVariableId(variableId)) {\n recordOccurrence(occurrences, variableId, placeholderRange);\n } else {\n addMalformedDiagnostic(\n collector,\n instruction,\n agentId,\n 'invalid-variable-id',\n placeholderRange,\n );\n }\n\n cursor = closingEnd;\n isCandidateComplete = true;\n break;\n }\n\n if (!isCandidateComplete) {\n addMalformedDiagnostic(\n collector,\n instruction,\n agentId,\n 'unmatched-opening',\n locator.locateRange(cursor, instruction.content.length),\n );\n cursor = instruction.content.length;\n }\n }\n\n for (const variableId of [...occurrences.keys()].sort(compareExactStrings)) {\n if (declaredVariables[variableId] !== undefined) {\n continue;\n }\n\n const occurrence = occurrences.get(variableId);\n if (occurrence === undefined) {\n continue;\n }\n\n collector.add({\n code: 'MOLDEA_VARIABLE_UNDECLARED',\n details: { occurrences: occurrence.count },\n entity: { agentId, variableId },\n path: instruction.path,\n range: occurrence.firstRange,\n });\n }\n\n for (const variableId of Object.keys(declaredVariables).sort(compareExactStrings)) {\n if (occurrences.has(variableId)) {\n continue;\n }\n\n collector.add({\n code: 'MOLDEA_VARIABLE_UNUSED',\n entity: { agentId, variableId },\n path: manifestPath,\n pointer: `/agents/${escapeJsonPointerSegment(agentId)}/variables/${escapeJsonPointerSegment(variableId)}`,\n });\n }\n\n return collector.finalize();\n};\n","import { parseRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport {\n validateAgentDescription,\n validateAgentInstruction,\n} from '../agent-asset-validation/index.js';\nimport type { ICanonicalDiscoveryResult } from '../canonical-discovery/index.js';\nimport type { IIndexedDescriptionAsset, IIndexedTextAsset } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { compareExactStrings } from '../format-validation/index.js';\nimport type { IAgentManifestEntry, IMoldeaManifestV1 } from '../format/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\nimport { readRepositoryTextAsset } from '../repository-text/index.js';\nimport { validateRuntimePlaceholders } from '../runtime-placeholder-validation/index.js';\n\nconst MANIFEST_PATH = parseRepositoryPath('/moldea/moldea.yaml');\n\n// internal agent assets retained even when later validation is still required\nexport interface IInspectedAgentAssets {\n readonly id: string;\n readonly declaration: IAgentManifestEntry;\n readonly description: IIndexedDescriptionAsset | null;\n readonly instruction: IIndexedTextAsset | null;\n readonly handoffDescription: IIndexedDescriptionAsset | null;\n}\n\n// internal reconciliation result retained for final project indexing\nexport interface IAgentAssetInspectionResult {\n readonly valid: boolean;\n readonly agents: readonly IInspectedAgentAssets[];\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\nconst addDiagnostics = (\n collector: ICoreDiagnosticCollector,\n diagnostics: readonly ICoreDiagnostic[],\n): void => {\n for (const diagnostic of diagnostics) {\n collector.merge(diagnostic);\n }\n};\n\nconst isBlockedPath = (path: IRepositoryPath, blockedPaths: ReadonlySet<string>): boolean => {\n let candidate: string = path;\n\n while (candidate.length > 0) {\n if (blockedPaths.has(candidate)) {\n return true;\n }\n\n const separatorIndex = candidate.lastIndexOf('/');\n if (separatorIndex <= 0) {\n return false;\n }\n\n candidate = candidate.slice(0, separatorIndex);\n }\n\n return false;\n};\n\n/** Reads and validates a required or optional description asset. */\nconst readDescription = async (\n repository: IRepositoryInspectionReader,\n path: IRepositoryPath,\n agentId: string,\n kind: 'description' | 'handoff-description',\n options: ICoreOptionsSnapshot,\n collector: ICoreDiagnosticCollector,\n signal?: AbortSignal,\n): Promise<IIndexedDescriptionAsset | null> => {\n const readResult = await readRepositoryTextAsset(repository, path, options.limits, signal);\n addDiagnostics(collector, readResult.diagnostics);\n\n if (readResult.asset === null) {\n return null;\n }\n\n const validation = validateAgentDescription(readResult.asset, agentId, kind, options.limits);\n addDiagnostics(collector, validation.diagnostics);\n\n return validation.description;\n};\n\n/** Reads and validates a mandatory instruction asset. */\nconst readInstruction = async (\n repository: IRepositoryInspectionReader,\n path: IRepositoryPath,\n agentId: string,\n declaration: IAgentManifestEntry,\n options: ICoreOptionsSnapshot,\n collector: ICoreDiagnosticCollector,\n signal?: AbortSignal,\n): Promise<IIndexedTextAsset | null> => {\n const readResult = await readRepositoryTextAsset(repository, path, options.limits, signal);\n addDiagnostics(collector, readResult.diagnostics);\n\n if (readResult.asset === null) {\n return null;\n }\n\n const validation = validateAgentInstruction(readResult.asset, agentId, options.limits);\n addDiagnostics(collector, validation.diagnostics);\n\n if (validation.instruction !== null) {\n addDiagnostics(\n collector,\n validateRuntimePlaceholders(\n MANIFEST_PATH,\n agentId,\n validation.instruction,\n declaration.variables ?? {},\n options.limits,\n ),\n );\n }\n\n return validation.instruction;\n};\n\n/**\n * Reconciles registered agents with their convention-owned directories and Markdown assets.\n * @param repository The coherent source-neutral repository reader.\n * @param manifest The normalized manifest containing registered agents.\n * @param discovery The canonical inventory and path-owned structural diagnostics.\n * @param options The immutable Core configuration snapshot.\n * @param signal Optional cancellation forwarded to every repository read.\n * @returns Deeply immutable registered-agent assets and deterministic diagnostics.\n * @throws\n * - ENTRY_NOT_FOUND: A discovered agent asset disappeared from the reader snapshot.\n * - ENTRY_NOT_FILE: A discovered agent asset is no longer a regular file.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during agent reads.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Agent inspection or a repository operation was aborted.\n */\nexport const inspectAgentAssets = async (\n repository: IRepositoryInspectionReader,\n manifest: IMoldeaManifestV1,\n discovery: ICanonicalDiscoveryResult,\n options: ICoreOptionsSnapshot,\n signal?: AbortSignal,\n): Promise<IAgentAssetInspectionResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const collector = createCoreDiagnosticCollector(options.limits, 'validate-project');\n const agents: IInspectedAgentAssets[] = [];\n const registeredAgents = manifest.agents ?? {};\n const registeredIds = new Set(Object.keys(registeredAgents));\n const discoveredById = new Map(\n discovery.inventory.agents.map((agent) => [agent.id, agent] as const),\n );\n const blockedPaths = new Set(\n discovery.diagnostics.flatMap((diagnostic) =>\n diagnostic.path === null ? [] : [diagnostic.path],\n ),\n );\n\n for (const discovered of discovery.inventory.agents) {\n if (!registeredIds.has(discovered.id)) {\n collector.add({\n code: 'MOLDEA_AGENT_DIRECTORY_UNREGISTERED',\n entity: { agentId: discovered.id },\n path: discovered.path,\n });\n }\n }\n\n for (const agentId of [...registeredIds].sort(compareExactStrings)) {\n const declaration = registeredAgents[agentId];\n\n if (declaration === undefined) {\n continue;\n }\n\n const discovered = discoveredById.get(agentId);\n\n if (discovered === undefined) {\n const directoryPath = parseRepositoryPath(`/moldea/agents/${agentId}`);\n\n if (!isBlockedPath(directoryPath, blockedPaths)) {\n collector.add({\n code: 'MOLDEA_AGENT_DIRECTORY_MISSING',\n entity: { agentId },\n path: directoryPath,\n });\n }\n\n agents.push({\n declaration,\n description: null,\n handoffDescription: null,\n id: agentId,\n instruction: null,\n });\n continue;\n }\n\n let description: IIndexedDescriptionAsset | null = null;\n let instruction: IIndexedTextAsset | null = null;\n let handoffDescription: IIndexedDescriptionAsset | null = null;\n\n if (discovered.description === null) {\n const path = parseRepositoryPath(`${discovered.path}/description.md`);\n if (!isBlockedPath(path, blockedPaths)) {\n collector.add({\n code: 'MOLDEA_AGENT_DESCRIPTION_MISSING',\n entity: { agentId },\n path,\n });\n }\n } else {\n description = await readDescription(\n repository,\n discovered.description,\n agentId,\n 'description',\n options,\n collector,\n signal,\n );\n }\n\n if (discovered.instruction === null) {\n const path = parseRepositoryPath(`${discovered.path}/instruction.md`);\n if (!isBlockedPath(path, blockedPaths)) {\n collector.add({\n code: 'MOLDEA_AGENT_INSTRUCTION_MISSING',\n entity: { agentId },\n path,\n });\n }\n } else {\n instruction = await readInstruction(\n repository,\n discovered.instruction,\n agentId,\n declaration,\n options,\n collector,\n signal,\n );\n }\n\n if (discovered.handoffDescription !== null) {\n handoffDescription = await readDescription(\n repository,\n discovered.handoffDescription,\n agentId,\n 'handoff-description',\n options,\n collector,\n signal,\n );\n }\n\n agents.push({\n declaration,\n description,\n handoffDescription,\n id: agentId,\n instruction,\n });\n }\n\n const diagnostics = collector.finalize();\n\n return freezeRecursively({\n agents,\n diagnostics,\n valid: diagnostics.length === 0,\n });\n};\n","import type { IRepositoryEntry, IRepositoryPath } from '@moldea.ai/repository';\n\nimport { isContextPath, isRuntimeGuidancePath } from '../format-validation/index.js';\n\n// canonical file categories retained by repository discovery\nexport type ICanonicalFileKind =\n | 'manifest'\n | 'project'\n | 'context'\n | 'decision'\n | 'runtime-guidance'\n | 'agent-description'\n | 'agent-instruction'\n | 'agent-handoff-description';\n\n// exhaustive internal classification for one entry below /moldea\nexport type ICanonicalEntryClassification =\n | {\n readonly kind: 'canonical-file';\n readonly fileKind: ICanonicalFileKind;\n readonly agentId: string | null;\n }\n | { readonly kind: 'agent-directory'; readonly agentId: string }\n | { readonly kind: 'structural-directory' | 'ignored-directory' }\n | { readonly kind: 'canonical-asset-symlink' }\n | { readonly kind: 'entry-type-invalid'; readonly expectedType: 'file' | 'directory' }\n | { readonly kind: 'unrecognized' };\n\nconst AGENT_ASSET_PATTERN =\n /^\\/moldea\\/agents\\/([^/]+)\\/(description|instruction|handoff-description)\\.md$/u;\nconst AGENT_DIRECTORY_PATTERN = /^\\/moldea\\/agents\\/([^/]+)$/u;\nconst DECISION_CANDIDATE_PATTERN = /^\\/moldea\\/decisions\\/[^/]+\\.md$/u;\n\nconst readCanonicalFile = (\n path: IRepositoryPath,\n): Extract<ICanonicalEntryClassification, { readonly kind: 'canonical-file' }> | null => {\n if (path === '/moldea/moldea.yaml') {\n return { agentId: null, fileKind: 'manifest', kind: 'canonical-file' };\n }\n\n if (path === '/moldea/project.md') {\n return { agentId: null, fileKind: 'project', kind: 'canonical-file' };\n }\n\n if (isContextPath(path, false)) {\n return { agentId: null, fileKind: 'context', kind: 'canonical-file' };\n }\n\n if (DECISION_CANDIDATE_PATTERN.test(path)) {\n return { agentId: null, fileKind: 'decision', kind: 'canonical-file' };\n }\n\n if (isRuntimeGuidancePath(path)) {\n return { agentId: null, fileKind: 'runtime-guidance', kind: 'canonical-file' };\n }\n\n const agentAsset = AGENT_ASSET_PATTERN.exec(path);\n\n if (agentAsset === null) {\n return null;\n }\n\n const agentId = agentAsset[1];\n const fileName = agentAsset[2];\n\n if (agentId === undefined || fileName === undefined) {\n return null;\n }\n\n const fileKind =\n fileName === 'description'\n ? 'agent-description'\n : fileName === 'instruction'\n ? 'agent-instruction'\n : 'agent-handoff-description';\n\n return { agentId, fileKind, kind: 'canonical-file' };\n};\n\nconst readAgentDirectoryId = (path: IRepositoryPath): string | null => {\n return AGENT_DIRECTORY_PATTERN.exec(path)?.[1] ?? null;\n};\n\nconst isRequiredDirectoryPath = (path: IRepositoryPath): boolean => {\n return (\n path === '/moldea' ||\n path === '/moldea/context' ||\n path === '/moldea/decisions' ||\n path === '/moldea/runtimes' ||\n path === '/moldea/agents'\n );\n};\n\nconst isPermittedStructuralDirectoryPath = (path: IRepositoryPath): boolean => {\n return (\n isRequiredDirectoryPath(path) ||\n path.startsWith('/moldea/context/') ||\n path.startsWith('/moldea/runtimes/')\n );\n};\n\n/**\n * Classifies one reader entry against the version 1 canonical layout.\n * @param entry The detached entry beneath the canonical moldea root.\n * @returns Its canonical category or the precise structural failure category.\n */\nexport const classifyCanonicalEntry = (entry: IRepositoryEntry): ICanonicalEntryClassification => {\n const canonicalFile = readCanonicalFile(entry.path);\n\n if (canonicalFile !== null) {\n if (entry.type === 'file') {\n return canonicalFile;\n }\n\n return entry.type === 'symlink'\n ? { kind: 'canonical-asset-symlink' }\n : { expectedType: 'file', kind: 'entry-type-invalid' };\n }\n\n const agentId = readAgentDirectoryId(entry.path);\n\n if (agentId !== null) {\n return entry.type === 'directory'\n ? { agentId, kind: 'agent-directory' }\n : { expectedType: 'directory', kind: 'entry-type-invalid' };\n }\n\n if (isRequiredDirectoryPath(entry.path)) {\n return entry.type === 'directory'\n ? { kind: 'structural-directory' }\n : { expectedType: 'directory', kind: 'entry-type-invalid' };\n }\n\n if (entry.type === 'directory') {\n return isPermittedStructuralDirectoryPath(entry.path)\n ? { kind: 'structural-directory' }\n : { kind: 'ignored-directory' };\n }\n\n return { kind: 'unrecognized' };\n};\n","import {\n RepositorySourceException,\n isRepositoryPath,\n parseRepositoryPath,\n type IRepositoryEntry,\n type IRepositoryPath,\n} from '@moldea.ai/repository';\n\nimport {\n classifyCanonicalEntry,\n type ICanonicalFileKind,\n} from '../canonical-discovery-validation/index.js';\nimport type { ICoreResourceLimits } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { compareExactStrings } from '../format-validation/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\n\nconst MOLDEA_ROOT = parseRepositoryPath('/moldea');\nconst MANIFEST_PATH = parseRepositoryPath('/moldea/moldea.yaml');\nconst PROJECT_PATH = parseRepositoryPath('/moldea/project.md');\n\n// immutable assets discovered for one convention-based agent directory\nexport interface IDiscoveredAgentAssets {\n readonly id: string;\n readonly path: IRepositoryPath;\n readonly description: IRepositoryPath | null;\n readonly instruction: IRepositoryPath | null;\n readonly handoffDescription: IRepositoryPath | null;\n}\n\n// immutable canonical inventory produced before cross-file validation\nexport interface ICanonicalDiscoveryInventory {\n readonly manifest: IRepositoryPath | null;\n readonly project: IRepositoryPath | null;\n readonly context: readonly IRepositoryPath[];\n readonly decisions: readonly IRepositoryPath[];\n readonly runtimeGuidance: readonly IRepositoryPath[];\n readonly agents: readonly IDiscoveredAgentAssets[];\n}\n\n// internal discovery result retained even when structural diagnostics exist\nexport interface ICanonicalDiscoveryResult {\n readonly valid: boolean;\n readonly inventory: ICanonicalDiscoveryInventory;\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\n// exact foundation entries prelocated by an owning repository inspection\nexport interface ICanonicalDiscoveryFoundationEntries {\n readonly moldeaRoot: IRepositoryEntry | null;\n readonly manifest: IRepositoryEntry | null;\n readonly project: IRepositoryEntry | null;\n}\n\ninterface IMutableDiscoveredAgentAssets {\n id: string;\n path: IRepositoryPath;\n description: IRepositoryPath | null;\n instruction: IRepositoryPath | null;\n handoffDescription: IRepositoryPath | null;\n}\n\ninterface IWorkingInventory {\n manifest: IRepositoryPath | null;\n project: IRepositoryPath | null;\n context: Set<IRepositoryPath>;\n decisions: Set<IRepositoryPath>;\n runtimeGuidance: Set<IRepositoryPath>;\n agents: Map<string, IMutableDiscoveredAgentAssets>;\n}\n\nconst createWorkingInventory = (): IWorkingInventory => ({\n agents: new Map(),\n context: new Set(),\n decisions: new Set(),\n manifest: null,\n project: null,\n runtimeGuidance: new Set(),\n});\n\nconst invalidSourceData = (\n operation: 'get-entry' | 'list-entries-page',\n path: IRepositoryPath | null,\n): never => {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation,\n path,\n retryable: false,\n });\n};\n\nconst copyReaderEntry = (\n candidate: unknown,\n operation: 'get-entry' | 'list-entries-page',\n expectedPath?: IRepositoryPath,\n): IRepositoryEntry => {\n if (typeof candidate !== 'object' || candidate === null) {\n return invalidSourceData(operation, expectedPath ?? null);\n }\n\n const record = candidate as Readonly<Record<string, unknown>>;\n const pathCandidate = record['path'];\n const typeCandidate = record['type'];\n const byteLength = record['byteLength'];\n const contentIdentity = record['contentIdentity'];\n\n if (typeof pathCandidate !== 'string' || !isRepositoryPath(pathCandidate)) {\n return invalidSourceData(operation, expectedPath ?? null);\n }\n\n const path = parseRepositoryPath(pathCandidate);\n\n if (expectedPath !== undefined && path !== expectedPath) {\n return invalidSourceData(operation, path);\n }\n\n if (typeCandidate !== 'file' && typeCandidate !== 'directory' && typeCandidate !== 'symlink') {\n return invalidSourceData(operation, path);\n }\n\n if (\n typeCandidate === 'file'\n ? !Number.isSafeInteger(byteLength) ||\n (byteLength as number) < 0 ||\n (contentIdentity !== null && typeof contentIdentity !== 'string')\n : byteLength !== null || contentIdentity !== null\n ) {\n return invalidSourceData(operation, path);\n }\n\n return {\n byteLength: byteLength as number | null,\n contentIdentity: contentIdentity as string | null,\n path,\n type: typeCandidate,\n };\n};\n\nconst readExactEntry = async (\n repository: IRepositoryInspectionReader,\n path: IRepositoryPath,\n signal: AbortSignal | undefined,\n): Promise<IRepositoryEntry | null> => {\n const candidate = await repository.getEntry(path, signal === undefined ? undefined : { signal });\n return candidate === null ? null : copyReaderEntry(candidate, 'get-entry', path);\n};\n\nconst addEntryTypeDiagnostic = (\n diagnostics: ICoreDiagnosticCollector,\n entry: IRepositoryEntry,\n expectedType: 'file' | 'directory',\n): void => {\n diagnostics.add({\n code: 'MOLDEA_ENTRY_TYPE_INVALID',\n details: { actualType: entry.type, expectedType },\n path: entry.path,\n });\n};\n\nconst getAgent = (\n agents: Map<string, IMutableDiscoveredAgentAssets>,\n agentId: string,\n): IMutableDiscoveredAgentAssets => {\n const existing = agents.get(agentId);\n\n if (existing !== undefined) {\n return existing;\n }\n\n const created: IMutableDiscoveredAgentAssets = {\n description: null,\n handoffDescription: null,\n id: agentId,\n instruction: null,\n path: parseRepositoryPath(`/moldea/agents/${agentId}`),\n };\n agents.set(agentId, created);\n\n return created;\n};\n\nconst retainCanonicalFile = (\n inventory: IWorkingInventory,\n path: IRepositoryPath,\n fileKind: ICanonicalFileKind,\n agentId: string | null,\n): void => {\n switch (fileKind) {\n case 'manifest':\n inventory.manifest = path;\n return;\n case 'project':\n inventory.project = path;\n return;\n case 'context':\n inventory.context.add(path);\n return;\n case 'decision':\n inventory.decisions.add(path);\n return;\n case 'runtime-guidance':\n inventory.runtimeGuidance.add(path);\n return;\n default:\n break;\n }\n\n if (agentId === null) {\n return invalidSourceData('list-entries-page', path);\n }\n\n const agent = getAgent(inventory.agents, agentId);\n\n if (fileKind === 'agent-description') {\n agent.description = path;\n } else if (fileKind === 'agent-instruction') {\n agent.instruction = path;\n } else {\n agent.handoffDescription = path;\n }\n};\n\nconst finalizeInventory = (working: IWorkingInventory): ICanonicalDiscoveryInventory => {\n const sortPaths = (paths: ReadonlySet<IRepositoryPath>): IRepositoryPath[] => {\n return [...paths].sort(compareExactStrings);\n };\n const agents = [...working.agents.values()]\n .sort((left, right) => compareExactStrings(left.id, right.id))\n .map((agent) => freezeRecursively({ ...agent }));\n\n return freezeRecursively({\n agents,\n context: sortPaths(working.context),\n decisions: sortPaths(working.decisions),\n manifest: working.manifest,\n project: working.project,\n runtimeGuidance: sortPaths(working.runtimeGuidance),\n });\n};\n\nconst finalizeResult = (\n working: IWorkingInventory,\n diagnostics: ICoreDiagnosticCollector,\n): ICanonicalDiscoveryResult => {\n const finalizedDiagnostics = diagnostics.finalize();\n\n return freezeRecursively({\n diagnostics: finalizedDiagnostics,\n inventory: finalizeInventory(working),\n valid: finalizedDiagnostics.length === 0,\n });\n};\n\nconst retainFoundationEntry = (\n entry: IRepositoryEntry | null,\n expectedPath: IRepositoryPath,\n missingCode: 'MOLDEA_MANIFEST_MISSING' | 'MOLDEA_PROJECT_FILE_MISSING',\n working: IWorkingInventory,\n diagnostics: ICoreDiagnosticCollector,\n): void => {\n if (entry === null) {\n diagnostics.add({ code: missingCode, path: expectedPath });\n return;\n }\n\n if (entry.type === 'file') {\n if (expectedPath === MANIFEST_PATH) {\n working.manifest = expectedPath;\n } else {\n working.project = expectedPath;\n }\n return;\n }\n\n if (entry.type === 'symlink') {\n diagnostics.add({ code: 'MOLDEA_CANONICAL_ASSET_SYMLINK', path: expectedPath });\n return;\n }\n\n addEntryTypeDiagnostic(diagnostics, entry, 'file');\n};\n\nconst checkFoundationListing = (\n listedEntry: IRepositoryEntry,\n exactEntry: IRepositoryEntry | null,\n): void => {\n if (exactEntry === null || exactEntry.type !== listedEntry.type) {\n return invalidSourceData('list-entries-page', listedEntry.path);\n }\n};\n\n/**\n * Discovers and classifies version 1 canonical assets through one repository snapshot.\n * @param repository The coherent source-neutral repository reader.\n * @param limits The immutable Core limits governing diagnostic collection.\n * @param signal Optional cancellation forwarded to every repository operation.\n * @param foundations Optional exact foundation entries already observed by this inspection.\n * @returns A deeply immutable inventory and its deterministic structural diagnostics.\n * @throws\n * - ENTRY_NOT_FOUND: The reader snapshot became inconsistent during discovery.\n * - ENTRY_NOT_DIRECTORY: The reader snapshot became inconsistent during discovery.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source was unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during discovery.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Discovery or a repository operation was aborted.\n */\nexport const discoverCanonicalAssets = async (\n repository: IRepositoryInspectionReader,\n limits: ICoreResourceLimits,\n signal?: AbortSignal,\n foundations?: ICanonicalDiscoveryFoundationEntries,\n): Promise<ICanonicalDiscoveryResult> => {\n const diagnostics = createCoreDiagnosticCollector(limits, 'validate-project');\n const working = createWorkingInventory();\n const moldeaEntry =\n foundations === undefined\n ? await readExactEntry(repository, MOLDEA_ROOT, signal)\n : foundations.moldeaRoot;\n\n if (moldeaEntry === null) {\n diagnostics.add({ code: 'MOLDEA_MANIFEST_MISSING', path: MANIFEST_PATH });\n diagnostics.add({ code: 'MOLDEA_PROJECT_FILE_MISSING', path: PROJECT_PATH });\n return finalizeResult(working, diagnostics);\n }\n\n if (moldeaEntry.type !== 'directory') {\n addEntryTypeDiagnostic(diagnostics, moldeaEntry, 'directory');\n return finalizeResult(working, diagnostics);\n }\n\n const manifestEntry =\n foundations === undefined\n ? await readExactEntry(repository, MANIFEST_PATH, signal)\n : foundations.manifest;\n const projectEntry =\n foundations === undefined\n ? await readExactEntry(repository, PROJECT_PATH, signal)\n : foundations.project;\n retainFoundationEntry(\n manifestEntry,\n MANIFEST_PATH,\n 'MOLDEA_MANIFEST_MISSING',\n working,\n diagnostics,\n );\n retainFoundationEntry(\n projectEntry,\n PROJECT_PATH,\n 'MOLDEA_PROJECT_FILE_MISSING',\n working,\n diagnostics,\n );\n\n const seenPaths = new Set<IRepositoryPath>();\n let listedManifest = false;\n let listedProject = false;\n\n const listOptions =\n signal === undefined ? { prefix: MOLDEA_ROOT } : { prefix: MOLDEA_ROOT, signal };\n\n for await (const candidate of repository.iterateEntries(listOptions)) {\n const entry = copyReaderEntry(candidate, 'list-entries-page');\n\n if (!entry.path.startsWith('/moldea/')) {\n return invalidSourceData('list-entries-page', entry.path);\n }\n\n if (seenPaths.has(entry.path)) {\n return invalidSourceData('list-entries-page', entry.path);\n }\n\n seenPaths.add(entry.path);\n\n if (entry.path === MANIFEST_PATH) {\n checkFoundationListing(entry, manifestEntry);\n listedManifest = true;\n continue;\n }\n\n if (entry.path === PROJECT_PATH) {\n checkFoundationListing(entry, projectEntry);\n listedProject = true;\n continue;\n }\n\n const classification = classifyCanonicalEntry(entry);\n\n switch (classification.kind) {\n case 'canonical-file':\n retainCanonicalFile(working, entry.path, classification.fileKind, classification.agentId);\n break;\n case 'agent-directory':\n getAgent(working.agents, classification.agentId);\n break;\n case 'canonical-asset-symlink':\n diagnostics.add({ code: 'MOLDEA_CANONICAL_ASSET_SYMLINK', path: entry.path });\n break;\n case 'entry-type-invalid':\n addEntryTypeDiagnostic(diagnostics, entry, classification.expectedType);\n break;\n case 'unrecognized':\n diagnostics.add({\n code: 'MOLDEA_CANONICAL_PATH_UNRECOGNIZED',\n details: { entryType: entry.type },\n path: entry.path,\n });\n break;\n case 'ignored-directory':\n case 'structural-directory':\n break;\n }\n }\n\n if ((manifestEntry !== null) !== listedManifest) {\n return invalidSourceData('list-entries-page', MANIFEST_PATH);\n }\n\n if ((projectEntry !== null) !== listedProject) {\n return invalidSourceData('list-entries-page', PROJECT_PATH);\n }\n\n return finalizeResult(working, diagnostics);\n};\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICoreResourceLimits } from '../contracts/index.js';\nimport { createCoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { compareExactStrings } from '../format-validation/index.js';\nimport type { IDecisionStatus } from '../format/index.js';\n\n// trustworthy document fields required by cross-file decision validation\nexport interface IDecisionGraphNode {\n readonly id: string;\n readonly path: IRepositoryPath;\n readonly status: IDecisionStatus;\n readonly supersedes: readonly string[];\n}\n\n// one discovered decision candidate, including invalid document placeholders\nexport interface IDecisionGraphCandidate {\n readonly id: string | null;\n readonly path: IRepositoryPath;\n readonly decision: IDecisionGraphNode | null;\n}\n\ninterface IDecisionGraphIndex {\n readonly candidateGroups: ReadonlyMap<string, readonly IDecisionGraphCandidate[]>;\n readonly edges: ReadonlyMap<string, readonly string[]>;\n readonly nodes: ReadonlyMap<string, IDecisionGraphNode>;\n}\n\nconst sortCandidates = (\n candidates: readonly IDecisionGraphCandidate[],\n): IDecisionGraphCandidate[] => {\n return [...candidates].sort((left, right) => compareExactStrings(left.path, right.path));\n};\n\nconst buildGraphIndex = (candidates: readonly IDecisionGraphCandidate[]): IDecisionGraphIndex => {\n const mutableGroups = new Map<string, IDecisionGraphCandidate[]>();\n\n for (const candidate of sortCandidates(candidates)) {\n if (candidate.id === null) {\n continue;\n }\n\n const group = mutableGroups.get(candidate.id) ?? [];\n group.push(candidate);\n mutableGroups.set(candidate.id, group);\n }\n\n const candidateGroups = new Map<string, readonly IDecisionGraphCandidate[]>();\n const nodes = new Map<string, IDecisionGraphNode>();\n\n for (const id of [...mutableGroups.keys()].sort(compareExactStrings)) {\n const group = mutableGroups.get(id) ?? [];\n candidateGroups.set(id, group);\n\n if (group.length === 1 && group[0]?.decision !== null) {\n const decision = group[0]?.decision;\n\n if (decision !== undefined) {\n nodes.set(id, decision);\n }\n }\n }\n\n const edges = new Map<string, readonly string[]>();\n\n for (const [id, decision] of nodes) {\n const resolvedTargets = decision.supersedes.filter((targetId) => {\n const group = candidateGroups.get(targetId);\n return group?.length === 1 && group[0]?.decision !== null;\n });\n edges.set(id, resolvedTargets);\n }\n\n return { candidateGroups, edges, nodes };\n};\n\nconst collectDuplicateDiagnostics = (\n index: IDecisionGraphIndex,\n diagnostics: ReturnType<typeof createCoreDiagnosticCollector>,\n): void => {\n for (const [id, candidates] of index.candidateGroups) {\n if (candidates.length < 2) {\n continue;\n }\n\n for (const candidate of candidates) {\n diagnostics.add({\n code: 'MOLDEA_DECISION_ID_DUPLICATE',\n details: { occurrences: candidates.length },\n entity: { decisionId: id },\n path: candidate.path,\n });\n }\n }\n};\n\nconst collectReferenceDiagnostics = (\n index: IDecisionGraphIndex,\n diagnostics: ReturnType<typeof createCoreDiagnosticCollector>,\n): void => {\n for (const decision of index.nodes.values()) {\n for (const targetId of decision.supersedes) {\n if (index.candidateGroups.has(targetId)) {\n continue;\n }\n\n diagnostics.add({\n code: 'MOLDEA_DECISION_REFERENCE_MISSING',\n details: { referencedDecisionId: targetId },\n entity: { decisionId: decision.id },\n path: decision.path,\n pointer: '/supersedes',\n });\n }\n }\n};\n\nconst collectStatusDiagnostics = (\n index: IDecisionGraphIndex,\n diagnostics: ReturnType<typeof createCoreDiagnosticCollector>,\n): Set<string> => {\n const activelySupersededIds = new Set<string>();\n\n for (const decision of index.nodes.values()) {\n if (decision.status !== 'accepted' && decision.status !== 'superseded') {\n continue;\n }\n\n for (const targetId of index.edges.get(decision.id) ?? []) {\n const target = index.nodes.get(targetId);\n\n if (target === undefined) {\n continue;\n }\n\n if (target.status === 'superseded') {\n activelySupersededIds.add(targetId);\n continue;\n }\n\n diagnostics.add({\n code: 'MOLDEA_DECISION_SUPERSESSION_STATUS_INVALID',\n details: {\n referencedDecisionId: targetId,\n sourceStatus: decision.status,\n targetStatus: target.status,\n },\n entity: { decisionId: decision.id },\n path: decision.path,\n pointer: '/supersedes',\n });\n }\n }\n\n return activelySupersededIds;\n};\n\nconst collectOrphanDiagnostics = (\n index: IDecisionGraphIndex,\n activelySupersededIds: ReadonlySet<string>,\n diagnostics: ReturnType<typeof createCoreDiagnosticCollector>,\n): void => {\n for (const decision of index.nodes.values()) {\n if (decision.status === 'superseded' && !activelySupersededIds.has(decision.id)) {\n diagnostics.add({\n code: 'MOLDEA_DECISION_SUPERSEDED_ORPHAN',\n entity: { decisionId: decision.id },\n path: decision.path,\n });\n }\n }\n};\n\nconst calculateFinishOrder = (index: IDecisionGraphIndex): readonly string[] => {\n const visited = new Set<string>();\n const finished: string[] = [];\n\n for (const startId of index.nodes.keys()) {\n if (visited.has(startId)) {\n continue;\n }\n\n const stack: { id: string; nextNeighbor: number }[] = [{ id: startId, nextNeighbor: 0 }];\n visited.add(startId);\n\n while (stack.length > 0) {\n const current = stack.at(-1);\n\n if (current === undefined) {\n break;\n }\n\n const neighbors = index.edges.get(current.id) ?? [];\n const neighbor = neighbors[current.nextNeighbor];\n\n if (neighbor === undefined) {\n finished.push(current.id);\n stack.pop();\n continue;\n }\n\n current.nextNeighbor += 1;\n\n if (!visited.has(neighbor)) {\n visited.add(neighbor);\n stack.push({ id: neighbor, nextNeighbor: 0 });\n }\n }\n }\n\n return finished;\n};\n\nconst buildReverseEdges = (index: IDecisionGraphIndex): ReadonlyMap<string, readonly string[]> => {\n const reverseEdges = new Map<string, string[]>();\n\n for (const id of index.nodes.keys()) {\n reverseEdges.set(id, []);\n }\n\n for (const [sourceId, targets] of index.edges) {\n for (const targetId of targets) {\n reverseEdges.get(targetId)?.push(sourceId);\n }\n }\n\n for (const sources of reverseEdges.values()) {\n sources.sort(compareExactStrings);\n }\n\n return reverseEdges;\n};\n\nconst findStronglyConnectedComponents = (\n index: IDecisionGraphIndex,\n): readonly (readonly string[])[] => {\n const reverseEdges = buildReverseEdges(index);\n const visited = new Set<string>();\n const components: string[][] = [];\n\n for (const startId of [...calculateFinishOrder(index)].reverse()) {\n if (visited.has(startId)) {\n continue;\n }\n\n const component: string[] = [];\n const stack = [startId];\n visited.add(startId);\n\n while (stack.length > 0) {\n const currentId = stack.pop();\n\n if (currentId === undefined) {\n break;\n }\n\n component.push(currentId);\n\n for (const sourceId of [...(reverseEdges.get(currentId) ?? [])].reverse()) {\n if (!visited.has(sourceId)) {\n visited.add(sourceId);\n stack.push(sourceId);\n }\n }\n }\n\n components.push(component.sort(compareExactStrings));\n }\n\n return components.sort((left, right) => compareExactStrings(left[0] ?? '', right[0] ?? ''));\n};\n\nconst collectCycleDiagnostics = (\n index: IDecisionGraphIndex,\n diagnostics: ReturnType<typeof createCoreDiagnosticCollector>,\n): void => {\n for (const component of findStronglyConnectedComponents(index)) {\n if (component.length < 2) {\n continue;\n }\n\n const cycleRepresentativeDecisionId = component[0];\n\n if (cycleRepresentativeDecisionId === undefined) {\n continue;\n }\n\n for (const decisionId of component) {\n const decision = index.nodes.get(decisionId);\n\n if (decision !== undefined) {\n diagnostics.add({\n code: 'MOLDEA_DECISION_SUPERSESSION_CYCLE',\n details: {\n cycleRepresentativeDecisionId,\n cycleSize: component.length,\n },\n entity: { decisionId },\n path: decision.path,\n pointer: '/supersedes',\n });\n }\n }\n }\n};\n\n/**\n * Validates every trustworthy cross-file relationship in one decision candidate set.\n * @param candidates Discovered candidates with valid parsed decisions where available.\n * @param limits The immutable Core limits governing repository-level diagnostics.\n * @returns Deterministically sorted, deeply immutable graph diagnostics.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: The repository-level diagnostic budget was exceeded.\n */\nexport const validateDecisionGraph = (\n candidates: readonly IDecisionGraphCandidate[],\n limits: ICoreResourceLimits,\n): readonly ICoreDiagnostic[] => {\n const diagnostics = createCoreDiagnosticCollector(limits, 'validate-project');\n const index = buildGraphIndex(candidates);\n\n collectDuplicateDiagnostics(index, diagnostics);\n collectReferenceDiagnostics(index, diagnostics);\n collectCycleDiagnostics(index, diagnostics);\n const activelySupersededIds = collectStatusDiagnostics(index, diagnostics);\n collectOrphanDiagnostics(index, activelySupersededIds, diagnostics);\n\n return diagnostics.finalize();\n};\n","import { RepositorySourceException, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport { parseDecisionDocument } from '../decision/index.js';\nimport {\n validateDecisionGraph,\n type IDecisionGraphCandidate,\n} from '../decision-graph-validation/index.js';\nimport { createCoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { compareExactStrings, parseDecisionIdFromPath } from '../format-validation/index.js';\nimport type { IParsedDecision } from '../format/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\n\n// internal repository-level decision result retained for later project indexing\nexport interface IDecisionGraphResult {\n readonly valid: boolean;\n readonly decisions: readonly IParsedDecision[];\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\nconst invalidSourceData = (path: IRepositoryPath): never => {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n};\n\nconst sortDecisions = (decisions: readonly IParsedDecision[]): IParsedDecision[] => {\n return [...decisions].sort((left, right) => {\n return compareExactStrings(left.id, right.id) || compareExactStrings(left.path, right.path);\n });\n};\n\n/**\n * Reads, parses, and validates every discovered decision through one repository snapshot.\n * @param repository The coherent source-neutral repository reader.\n * @param paths The decision candidates retained by canonical discovery.\n * @param options The immutable Core limits and adapter snapshots.\n * @param signal Optional cancellation forwarded to every repository read.\n * @returns A deeply immutable internal decision set and its deterministic diagnostics.\n * @throws\n * - ENTRY_NOT_FOUND: A discovered decision disappeared from the reader snapshot.\n * - ENTRY_NOT_FILE: A discovered decision is no longer a regular file.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during decision reads.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Decision inspection or a repository operation was aborted.\n */\nexport const readDecisionGraph = async (\n repository: IRepositoryInspectionReader,\n paths: readonly IRepositoryPath[],\n options: ICoreOptionsSnapshot,\n signal?: AbortSignal,\n): Promise<IDecisionGraphResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const diagnostics = createCoreDiagnosticCollector(options.limits, 'validate-project');\n const candidates: IDecisionGraphCandidate[] = [];\n const decisions: IParsedDecision[] = [];\n const readOptions = signal === undefined ? undefined : { signal };\n\n for (const path of [...paths].sort(compareExactStrings)) {\n const content = await repository.readCompleteFile(path, readOptions);\n\n if (!(content instanceof Uint8Array)) {\n return invalidSourceData(path);\n }\n\n const parsed = await parseDecisionDocument(\n { content: content.slice(), path },\n options,\n 'validate-project',\n );\n\n for (const diagnostic of parsed.diagnostics) {\n diagnostics.merge(diagnostic);\n }\n\n candidates.push({\n decision: parsed.decision,\n id: parseDecisionIdFromPath(path),\n path,\n });\n\n if (parsed.decision !== null) {\n decisions.push(parsed.decision);\n }\n }\n\n for (const diagnostic of validateDecisionGraph(candidates, options.limits)) {\n diagnostics.merge(diagnostic);\n }\n\n const finalizedDiagnostics = diagnostics.finalize();\n\n return freezeRecursively({\n decisions: sortDecisions(decisions),\n diagnostics: finalizedDiagnostics,\n valid: finalizedDiagnostics.length === 0,\n });\n};\n","import { parseRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICanonicalDiscoveryResult } from '../canonical-discovery/index.js';\nimport type { ICoreResourceLimits } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n escapeJsonPointerSegment,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic, IDiagnosticEntity } from '../diagnostics/index.js';\nimport { compareExactStrings, parseDecisionIdFromPath } from '../format-validation/index.js';\nimport type { IMoldeaManifestV1, IParsedDecision } from '../format/index.js';\n\n// trusted repository indexes shared by relationship validation helpers\ninterface IManifestRelationshipValidationContext {\n readonly blockedPaths: ReadonlySet<IRepositoryPath>;\n readonly collector: ICoreDiagnosticCollector;\n readonly discoveredDecisionPaths: ReadonlySet<IRepositoryPath>;\n readonly manifestPath: IRepositoryPath;\n readonly parsedDecisionsByPath: ReadonlyMap<\n IRepositoryPath,\n Pick<IParsedDecision, 'id' | 'path' | 'status'>\n >;\n readonly validAgentContextPaths: ReadonlySet<IRepositoryPath>;\n readonly validTopLevelContextPaths: ReadonlySet<IRepositoryPath>;\n}\n\n/** Creates diagnostic entity metadata for a decision relationship. */\nconst createDecisionEntity = (\n decisionPath: IRepositoryPath,\n agentId?: string,\n): IDiagnosticEntity => {\n const decisionId = parseDecisionIdFromPath(decisionPath);\n\n return {\n ...(agentId === undefined ? {} : { agentId }),\n ...(decisionId === null ? {} : { decisionId }),\n };\n};\n\n/** Adds a missing-context diagnostic unless discovery owns the target-path failure. */\nconst validateContextRelationship = (\n referencedPath: IRepositoryPath,\n pointer: string,\n validContextPaths: ReadonlySet<IRepositoryPath>,\n context: IManifestRelationshipValidationContext,\n agentId?: string,\n): void => {\n if (validContextPaths.has(referencedPath) || context.blockedPaths.has(referencedPath)) {\n return;\n }\n\n context.collector.add({\n code: 'MOLDEA_REFERENCE_MISSING',\n details: { referencedPath },\n entity: agentId === undefined ? null : { agentId },\n path: context.manifestPath,\n pointer,\n });\n};\n\n/** Adds missing or inactive diagnostics for a decision relationship. */\nconst validateDecisionRelationship = (\n referencedPath: IRepositoryPath,\n pointer: string,\n context: IManifestRelationshipValidationContext,\n agentId?: string,\n): void => {\n if (!context.discoveredDecisionPaths.has(referencedPath)) {\n if (context.blockedPaths.has(referencedPath)) {\n return;\n }\n\n context.collector.add({\n code: 'MOLDEA_DECISION_REFERENCE_MISSING',\n details: { referencedPath },\n entity: createDecisionEntity(referencedPath, agentId),\n path: context.manifestPath,\n pointer,\n });\n return;\n }\n\n const parsedDecision = context.parsedDecisionsByPath.get(referencedPath);\n if (parsedDecision === undefined || parsedDecision.status === 'accepted') {\n return;\n }\n\n context.collector.add({\n code: 'MOLDEA_DECISION_RELATIONSHIP_INACTIVE',\n details: {\n referencedPath,\n targetStatus: parsedDecision.status,\n },\n entity: createDecisionEntity(referencedPath, agentId),\n path: context.manifestPath,\n pointer,\n });\n};\n\n/**\n * Validates manifest and agent relationships against canonical discovery and parsed decisions.\n * @param manifestPath The canonical manifest path used for relationship diagnostics.\n * @param manifest The normalized manifest contract to validate.\n * @param discovery The canonical repository discovery result.\n * @param decisions The successfully parsed canonical decisions.\n * @param limits The resource limits applied to emitted diagnostics.\n * @returns The frozen deterministic relationship diagnostics.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: The repository-level diagnostic budget was exceeded.\n */\nexport const validateManifestRelationships = (\n manifestPath: IRepositoryPath,\n manifest: IMoldeaManifestV1,\n discovery: ICanonicalDiscoveryResult,\n decisions: readonly Pick<IParsedDecision, 'id' | 'path' | 'status'>[],\n limits: ICoreResourceLimits,\n): readonly ICoreDiagnostic[] => {\n const collector = createCoreDiagnosticCollector(limits, 'validate-project');\n const validAgentContextPaths = new Set<IRepositoryPath>(discovery.inventory.context);\n const validTopLevelContextPaths = new Set(validAgentContextPaths);\n if (discovery.inventory.project !== null) {\n validTopLevelContextPaths.add(discovery.inventory.project);\n }\n\n const validationContext: IManifestRelationshipValidationContext = {\n blockedPaths: new Set(\n discovery.diagnostics.flatMap((diagnostic) =>\n diagnostic.path === null ? [] : [diagnostic.path],\n ),\n ),\n collector,\n discoveredDecisionPaths: new Set(discovery.inventory.decisions),\n manifestPath,\n parsedDecisionsByPath: new Map(decisions.map((decision) => [decision.path, decision])),\n validAgentContextPaths,\n validTopLevelContextPaths,\n };\n\n for (const referencedPathValue of Object.keys(manifest.context ?? {}).sort(compareExactStrings)) {\n const referencedPath = parseRepositoryPath(referencedPathValue);\n validateContextRelationship(\n referencedPath,\n `/context/${escapeJsonPointerSegment(referencedPathValue)}`,\n validationContext.validTopLevelContextPaths,\n validationContext,\n );\n }\n\n for (const referencedPathValue of Object.keys(manifest.decisions ?? {}).sort(\n compareExactStrings,\n )) {\n const referencedPath = parseRepositoryPath(referencedPathValue);\n validateDecisionRelationship(\n referencedPath,\n `/decisions/${escapeJsonPointerSegment(referencedPathValue)}`,\n validationContext,\n );\n }\n\n for (const agentId of Object.keys(manifest.agents ?? {}).sort(compareExactStrings)) {\n const agent = manifest.agents?.[agentId];\n if (agent === undefined) {\n continue;\n }\n\n const escapedAgentId = escapeJsonPointerSegment(agentId);\n for (const referencedPath of [...(agent.context ?? [])].sort(compareExactStrings)) {\n validateContextRelationship(\n referencedPath,\n `/agents/${escapedAgentId}/context`,\n validationContext.validAgentContextPaths,\n validationContext,\n agentId,\n );\n }\n\n for (const referencedPath of [...(agent.decisions ?? [])].sort(compareExactStrings)) {\n validateDecisionRelationship(\n referencedPath,\n `/agents/${escapedAgentId}/decisions`,\n validationContext,\n agentId,\n );\n }\n }\n\n return collector.finalize();\n};\n","import type {\n IRepositoryEntry,\n IRepositoryOperationOptions,\n IRepositoryPath,\n} from '@moldea.ai/repository';\n\nimport type { IInspectedAgentAssets } from '../agent-assets/index.js';\nimport type { IIndexedMirror, IIndexedTextAsset } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n escapeJsonPointerSegment,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic, ICoreDiagnosticCode } from '../diagnostics/index.js';\nimport { compareExactStrings } from '../format-validation/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\nimport { readRepositoryTextAsset } from '../repository-text/index.js';\n\n// internal mirror records retained for final agent indexing\nexport interface IAgentMirrorInspection {\n readonly id: string;\n readonly mirrors: readonly IIndexedMirror[];\n}\n\nexport interface IMirrorInspectionResult {\n readonly valid: boolean;\n readonly agentMirrors: readonly IAgentMirrorInspection[];\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\nconst addDiagnostics = (\n collector: ICoreDiagnosticCollector,\n diagnostics: readonly ICoreDiagnostic[],\n): void => {\n for (const diagnostic of diagnostics) {\n collector.merge(diagnostic);\n }\n};\n\n/** Adds one declaration-owned mirror diagnostic with safe target metadata. */\nconst addMirrorDiagnostic = (\n collector: ICoreDiagnosticCollector,\n code: ICoreDiagnosticCode,\n manifestPath: IRepositoryPath,\n mirrorPath: IRepositoryPath,\n pointer: string,\n agentId: string,\n entry?: IRepositoryEntry,\n): void => {\n collector.add({\n code,\n details: {\n ...(entry === undefined ? {} : { actualType: entry.type }),\n mirrorPath,\n },\n entity: { agentId },\n path: manifestPath,\n pointer,\n });\n};\n\n/** Resolves, normalizes, and compares one declared mirror. */\nconst inspectMirror = async (\n repository: IRepositoryInspectionReader,\n manifestPath: IRepositoryPath,\n canonicalInstruction: IIndexedTextAsset,\n mirrorPath: IRepositoryPath,\n pointer: string,\n agentId: string,\n options: ICoreOptionsSnapshot,\n collector: ICoreDiagnosticCollector,\n operationOptions: IRepositoryOperationOptions | undefined,\n signal?: AbortSignal,\n): Promise<IIndexedMirror | null> => {\n const entry = await repository.getEntry(mirrorPath, operationOptions);\n\n if (entry === null) {\n addMirrorDiagnostic(\n collector,\n 'MOLDEA_MIRROR_MISSING',\n manifestPath,\n mirrorPath,\n pointer,\n agentId,\n );\n return null;\n }\n\n if (entry.type === 'symlink') {\n addMirrorDiagnostic(\n collector,\n 'MOLDEA_MIRROR_SYMLINK',\n manifestPath,\n mirrorPath,\n pointer,\n agentId,\n entry,\n );\n return null;\n }\n\n if (entry.type !== 'file') {\n addMirrorDiagnostic(\n collector,\n 'MOLDEA_MIRROR_NOT_FILE',\n manifestPath,\n mirrorPath,\n pointer,\n agentId,\n entry,\n );\n return null;\n }\n\n const mirrorResult = await readRepositoryTextAsset(\n repository,\n mirrorPath,\n options.limits,\n signal,\n );\n addDiagnostics(collector, mirrorResult.diagnostics);\n\n if (mirrorResult.asset === null) {\n return null;\n }\n\n if (mirrorResult.asset.content !== canonicalInstruction.content) {\n addMirrorDiagnostic(\n collector,\n 'MOLDEA_MIRROR_STALE',\n manifestPath,\n mirrorPath,\n pointer,\n agentId,\n );\n return null;\n }\n\n return {\n byteLength: mirrorResult.asset.utf8ByteLength,\n canonicalDigest: canonicalInstruction.digest,\n digest: mirrorResult.asset.digest,\n path: mirrorPath,\n scalarLength: mirrorResult.asset.scalarLength,\n };\n};\n\n/**\n * Compares every declared mirror with its available normalized canonical instruction.\n * @param repository The budget-aware reader for the active inspection session.\n * @param manifestPath The canonical manifest path used for declaration diagnostics.\n * @param agents The registered agent assets and normalized instruction prerequisites.\n * @param options The immutable Core configuration snapshot.\n * @param signal Optional cancellation forwarded to every mirror lookup and read.\n * @returns Deeply immutable index-ready mirrors and deterministic diagnostics.\n * @throws\n * - INVALID_REPOSITORY_PATH: A repository path is invalid.\n * - ENTRY_NOT_FOUND: A confirmed mirror file disappeared from the reader snapshot.\n * - ENTRY_NOT_FILE: A confirmed mirror file changed type during inspection.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during mirror inspection.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Mirror inspection or a repository operation was aborted.\n */\nexport const inspectMirrors = async (\n repository: IRepositoryInspectionReader,\n manifestPath: IRepositoryPath,\n agents: readonly IInspectedAgentAssets[],\n options: ICoreOptionsSnapshot,\n signal?: AbortSignal,\n): Promise<IMirrorInspectionResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const collector = createCoreDiagnosticCollector(options.limits, 'validate-project');\n const agentMirrors: IAgentMirrorInspection[] = [];\n const operationOptions: IRepositoryOperationOptions | undefined =\n signal === undefined ? undefined : { signal };\n\n for (const agent of [...agents].sort((left, right) => compareExactStrings(left.id, right.id))) {\n const mirrors: IIndexedMirror[] = [];\n\n if (agent.instruction !== null) {\n const declaredMirrors = [...(agent.declaration.mirrors ?? [])].sort(compareExactStrings);\n\n for (const [index, mirrorPath] of declaredMirrors.entries()) {\n const mirror = await inspectMirror(\n repository,\n manifestPath,\n agent.instruction,\n mirrorPath,\n `/agents/${escapeJsonPointerSegment(agent.id)}/mirrors/${index}`,\n agent.id,\n options,\n collector,\n operationOptions,\n signal,\n );\n\n if (mirror !== null) {\n mirrors.push(mirror);\n }\n }\n }\n\n agentMirrors.push({ id: agent.id, mirrors });\n }\n\n const diagnostics = collector.finalize();\n\n return freezeRecursively({\n agentMirrors,\n diagnostics,\n valid: diagnostics.length === 0,\n });\n};\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICanonicalDiscoveryResult } from '../canonical-discovery/index.js';\nimport type { IIndexedContextAsset, IIndexedTextAsset } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { compareExactStrings, hasNonWhitespace } from '../format-validation/index.js';\nimport type { IMoldeaManifestV1 } from '../format/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\nimport { readRepositoryTextAsset } from '../repository-text/index.js';\n\n// internal project and focused-context assets retained for provisional indexing\nexport interface IProjectAssetInspectionResult {\n readonly valid: boolean;\n readonly project: IIndexedTextAsset | null;\n readonly context: readonly IIndexedContextAsset[];\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\n// project foundation retained across discovery without repeating normalization or hashing\nexport interface IProjectFileInspectionResult {\n readonly valid: boolean;\n readonly project: IIndexedTextAsset | null;\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\nconst addDiagnostics = (\n collector: ICoreDiagnosticCollector,\n diagnostics: readonly ICoreDiagnostic[],\n): void => {\n for (const diagnostic of diagnostics) {\n collector.merge(diagnostic);\n }\n};\n\n/**\n * Reads and validates the project foundation before canonical enumeration.\n * @param repository The coherent source-neutral reader for the active inspection session.\n * @param path The canonical project path when its exact entry is a regular file.\n * @param options The immutable Core configuration snapshot.\n * @param signal Optional cancellation forwarded to the repository read.\n * @returns The deeply immutable project asset or deterministic content diagnostics.\n * @throws\n * - ENTRY_NOT_FOUND: The located project file disappeared from the snapshot.\n * - ENTRY_NOT_FILE: The located project entry changed type during inspection.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during the project read.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Project inspection or the repository read was aborted.\n */\nexport const readProjectFile = async (\n repository: IRepositoryInspectionReader,\n path: IRepositoryPath | null,\n options: ICoreOptionsSnapshot,\n signal?: AbortSignal,\n): Promise<IProjectFileInspectionResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const collector = createCoreDiagnosticCollector(options.limits, 'validate-project');\n let project: IIndexedTextAsset | null = null;\n\n if (path !== null) {\n const result = await readRepositoryTextAsset(repository, path, options.limits, signal);\n addDiagnostics(collector, result.diagnostics);\n\n if (result.asset !== null) {\n if (hasNonWhitespace(result.asset.content)) {\n project = result.asset;\n } else {\n collector.add({ code: 'MOLDEA_PROJECT_FILE_EMPTY', path: result.asset.path });\n }\n }\n }\n\n const diagnostics = collector.finalize();\n\n return freezeRecursively({\n diagnostics,\n project,\n valid: diagnostics.length === 0,\n });\n};\n\n/**\n * Reads the project foundation and every discovered focused-context asset.\n * @param repository The coherent source-neutral reader for the active inspection session.\n * @param manifest The normalized manifest used to attach context relationships, when valid.\n * @param discovery The canonical inventory and path-owned structural diagnostics.\n * @param options The immutable Core configuration snapshot.\n * @param signal Optional cancellation forwarded to every repository read.\n * @param projectFile Optional project foundation already read before canonical enumeration.\n * @returns Deeply immutable valid assets and deterministic content diagnostics.\n * @throws\n * - ENTRY_NOT_FOUND: A discovered project or context file disappeared from the snapshot.\n * - ENTRY_NOT_FILE: A discovered project or context entry changed type during inspection.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during asset reads.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Project asset inspection or a repository operation was aborted.\n */\nexport const readProjectAssets = async (\n repository: IRepositoryInspectionReader,\n manifest: IMoldeaManifestV1 | null,\n discovery: ICanonicalDiscoveryResult,\n options: ICoreOptionsSnapshot,\n signal?: AbortSignal,\n projectFile?: IProjectFileInspectionResult,\n): Promise<IProjectAssetInspectionResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const collector = createCoreDiagnosticCollector(options.limits, 'validate-project');\n const context: IIndexedContextAsset[] = [];\n const inspectedProject =\n projectFile ??\n (await readProjectFile(repository, discovery.inventory.project, options, signal));\n addDiagnostics(collector, inspectedProject.diagnostics);\n\n for (const path of [...discovery.inventory.context].sort(compareExactStrings)) {\n const result = await readRepositoryTextAsset(repository, path, options.limits, signal);\n addDiagnostics(collector, result.diagnostics);\n\n if (result.asset === null) {\n continue;\n }\n\n if (!hasNonWhitespace(result.asset.content)) {\n collector.add({ code: 'MOLDEA_CONTEXT_FILE_EMPTY', path });\n continue;\n }\n\n context.push({\n asset: result.asset,\n relationships: manifest?.context?.[path] ?? null,\n });\n }\n\n const diagnostics = collector.finalize();\n\n return freezeRecursively({\n context,\n diagnostics,\n project: inspectedProject.project,\n valid: diagnostics.length === 0,\n });\n};\n","import type { IInspectedAgentAssets } from '../agent-assets/index.js';\nimport type {\n IIndexedAgent,\n IIndexedContextAsset,\n IIndexedDecision,\n IIndexedManifest,\n IIndexedRuntimeGuidance,\n IIndexedTextAsset,\n IMoldeaProjectIndex,\n} from '../contracts/index.js';\nimport { compareExactStrings } from '../format-validation/index.js';\nimport type { IParsedDecision } from '../format/index.js';\nimport { createNullPrototypeRecord, freezeRecursively } from '../immutable/index.js';\nimport type { IAgentMirrorInspection } from '../mirrors/index.js';\n\n// complete universal inputs required to construct one provisional project index\nexport interface IProjectIndexInput {\n readonly manifest: IIndexedManifest;\n readonly project: IIndexedTextAsset;\n readonly context: readonly IIndexedContextAsset[];\n readonly decisions: readonly IParsedDecision[];\n readonly runtimes: readonly IIndexedRuntimeGuidance[];\n readonly agents: readonly IInspectedAgentAssets[];\n readonly agentMirrors: readonly IAgentMirrorInspection[];\n}\n\nconst createIndexedDecisions = (\n decisions: readonly IParsedDecision[],\n manifest: IIndexedManifest,\n): readonly IIndexedDecision[] => {\n return [...decisions]\n .sort(\n (left, right) =>\n compareExactStrings(left.id, right.id) || compareExactStrings(left.path, right.path),\n )\n .map((decision) => ({\n decision,\n relationships: manifest.value.decisions?.[decision.path] ?? null,\n }));\n};\n\nconst createIndexedAgents = (\n agents: readonly IInspectedAgentAssets[],\n agentMirrors: readonly IAgentMirrorInspection[],\n): readonly IIndexedAgent[] | null => {\n const mirrorsByAgent = new Map(agentMirrors.map((entry) => [entry.id, entry.mirrors] as const));\n const indexedAgents: IIndexedAgent[] = [];\n\n if (mirrorsByAgent.size !== agents.length) {\n return null;\n }\n\n for (const agent of [...agents].sort((left, right) => compareExactStrings(left.id, right.id))) {\n const mirrors = mirrorsByAgent.get(agent.id);\n\n if (agent.description === null || agent.instruction === null || mirrors === undefined) {\n return null;\n }\n\n indexedAgents.push({\n context: [...(agent.declaration.context ?? [])].sort(compareExactStrings),\n decisions: [...(agent.declaration.decisions ?? [])].sort(compareExactStrings),\n declaration: agent.declaration,\n description: agent.description,\n handoffDescription: agent.handoffDescription,\n id: agent.id,\n instruction: agent.instruction,\n mirrors: [...mirrors].sort((left, right) => compareExactStrings(left.path, right.path)),\n });\n }\n\n return indexedAgents;\n};\n\n/**\n * Constructs one deterministic provisional index from complete universal validation outputs.\n * @param input The normalized assets and relationships retained by universal inspection.\n * @returns The deeply immutable project index, or null when a required asset is unavailable.\n */\nexport const createProjectIndex = (input: IProjectIndexInput): IMoldeaProjectIndex | null => {\n const agents = createIndexedAgents(input.agents, input.agentMirrors);\n\n if (agents === null) {\n return null;\n }\n\n const unresolved = input.manifest.value.unresolved ?? createNullPrototypeRecord([]);\n\n return freezeRecursively({\n agents,\n context: [...input.context].sort((left, right) =>\n compareExactStrings(left.asset.path, right.asset.path),\n ),\n decisions: createIndexedDecisions(input.decisions, input.manifest),\n formatVersion: 1 as const,\n manifest: input.manifest,\n project: input.project,\n runtimes: [...input.runtimes].sort((left, right) =>\n compareExactStrings(left.asset.path, right.asset.path),\n ),\n unresolved,\n });\n};\n","import {\n parseRepositoryPath,\n type IRepositoryEntry,\n type IRepositoryOperationOptions,\n type IRepositoryPath,\n} from '@moldea.ai/repository';\n\nimport type { ICanonicalDiscoveryResult } from '../canonical-discovery/index.js';\nimport type { ICoreResourceLimits } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n escapeJsonPointerSegment,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type {\n ICoreDiagnostic,\n ICoreDiagnosticCode,\n IDiagnosticEntity,\n} from '../diagnostics/index.js';\nimport { compareExactStrings, parseDecisionIdFromPath } from '../format-validation/index.js';\nimport type {\n IAgentManifestEntry,\n IMoldeaManifestV1,\n IRepositoryReference,\n IRelationshipManifestEntry,\n ISkillManifestEntry,\n IToolManifestEntry,\n IUnresolvedRequirementManifestEntry,\n} from '../format/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\n\n// internal classification for one exact repository-backed declaration\ntype IRepositoryCandidateKind =\n 'reference' | 'impact' | 'tool-implementation' | 'skill-implementation';\n\ninterface IRepositoryCandidate {\n readonly entity: IDiagnosticEntity | null;\n readonly kind: IRepositoryCandidateKind;\n readonly path: IRepositoryPath;\n readonly pointer: string;\n}\n\nconst childPointer = (pointer: string, segment: string): string => {\n return `${pointer}/${escapeJsonPointerSegment(segment)}`;\n};\n\nconst compareNullableStrings = (left: string | undefined, right: string | undefined): number => {\n if (left === undefined) {\n return right === undefined ? 0 : -1;\n }\n\n return right === undefined ? 1 : compareExactStrings(left, right);\n};\n\nconst compareReferences = (left: IRepositoryReference, right: IRepositoryReference): number => {\n return (\n compareExactStrings(left.path, right.path) || compareNullableStrings(left.symbol, right.symbol)\n );\n};\n\n/** Adds sorted repository-reference array entries with their normalized indexes. */\nconst addReferenceCandidates = (\n candidates: IRepositoryCandidate[],\n references: readonly IRepositoryReference[] | undefined,\n pointer: string,\n entity: IDiagnosticEntity | null,\n): void => {\n for (const [index, reference] of [...(references ?? [])].sort(compareReferences).entries()) {\n candidates.push({\n entity,\n kind: 'reference',\n path: reference.path,\n pointer: childPointer(pointer, String(index)),\n });\n }\n};\n\n/** Adds sorted exact impact paths while retaining skipped glob indexes. */\nconst addImpactCandidates = (\n candidates: IRepositoryCandidate[],\n affectedBy: readonly string[] | undefined,\n pointer: string,\n entity: IDiagnosticEntity | null,\n): void => {\n for (const [index, pattern] of [...(affectedBy ?? [])].sort(compareExactStrings).entries()) {\n if (pattern.includes('*')) {\n continue;\n }\n\n candidates.push({\n entity,\n kind: 'impact',\n path: parseRepositoryPath(pattern),\n pointer: childPointer(pointer, String(index)),\n });\n }\n};\n\n/** Adds repository-backed declarations owned by one context or decision relationship. */\nconst addRelationshipCandidates = (\n candidates: IRepositoryCandidate[],\n relationship: IRelationshipManifestEntry,\n pointer: string,\n entity: IDiagnosticEntity | null,\n): void => {\n addReferenceCandidates(\n candidates,\n relationship.bindings,\n childPointer(pointer, 'bindings'),\n entity,\n );\n addImpactCandidates(\n candidates,\n relationship.affectedBy,\n childPointer(pointer, 'affectedBy'),\n entity,\n );\n};\n\n/** Adds related repository references from sorted unresolved requirements. */\nconst addUnresolvedCandidates = (\n candidates: IRepositoryCandidate[],\n requirements: Readonly<Record<string, IUnresolvedRequirementManifestEntry>> | undefined,\n pointer: string,\n entity: IDiagnosticEntity | null,\n): void => {\n for (const requirementId of Object.keys(requirements ?? {}).sort(compareExactStrings)) {\n const requirement = requirements?.[requirementId];\n\n if (requirement === undefined) {\n continue;\n }\n\n addReferenceCandidates(\n candidates,\n requirement.related,\n childPointer(childPointer(pointer, requirementId), 'related'),\n entity,\n );\n }\n};\n\n/** Adds one capability's implementation, optional bindings, and exact impact paths. */\nconst addCapabilityCandidates = (\n candidates: IRepositoryCandidate[],\n capability: ISkillManifestEntry | IToolManifestEntry,\n capabilityKind: 'tool' | 'skill',\n capabilityId: string,\n agentId: string,\n collectionPointer: string,\n additionalReferences: readonly (readonly [\n property: 'inputSchema' | 'outputSchema',\n reference: IRepositoryReference | undefined,\n ])[] = [],\n): void => {\n const capabilityPointer = childPointer(collectionPointer, capabilityId);\n const capabilityEntity = { agentId, capabilityId, capabilityKind };\n candidates.push({\n entity: capabilityEntity,\n kind: `${capabilityKind}-implementation`,\n path: capability.implementation.path,\n pointer: childPointer(capabilityPointer, 'implementation'),\n });\n\n for (const [property, reference] of [\n ['registration', capability.registration] as const,\n ...additionalReferences,\n ]) {\n if (reference !== undefined) {\n candidates.push({\n entity: capabilityEntity,\n kind: 'reference',\n path: reference.path,\n pointer: childPointer(capabilityPointer, property),\n });\n }\n }\n\n addImpactCandidates(\n candidates,\n capability.affectedBy,\n childPointer(capabilityPointer, 'affectedBy'),\n capabilityEntity,\n );\n};\n\n/** Adds all repository-backed declarations owned by one normalized agent. */\nconst addAgentCandidates = (\n candidates: IRepositoryCandidate[],\n agentId: string,\n agent: IAgentManifestEntry,\n): void => {\n const escapedAgentId = escapeJsonPointerSegment(agentId);\n const pointer = `/agents/${escapedAgentId}`;\n const entity = { agentId };\n const bindingsPointer = childPointer(pointer, 'bindings');\n const bindings = agent.bindings;\n\n for (const property of [\n 'runtimeAgent',\n 'inputSchema',\n 'outputSchema',\n 'instructionLoader',\n ] as const) {\n const reference = bindings?.[property];\n\n if (reference !== undefined) {\n candidates.push({\n entity,\n kind: 'reference',\n path: reference.path,\n pointer: childPointer(bindingsPointer, property),\n });\n }\n }\n\n for (const variableId of Object.keys(bindings?.variableProviders ?? {}).sort(\n compareExactStrings,\n )) {\n const reference = bindings?.variableProviders?.[variableId];\n\n if (reference !== undefined) {\n candidates.push({\n entity: { agentId, variableId },\n kind: 'reference',\n path: reference.path,\n pointer: childPointer(childPointer(bindingsPointer, 'variableProviders'), variableId),\n });\n }\n }\n\n addImpactCandidates(candidates, agent.affectedBy, childPointer(pointer, 'affectedBy'), entity);\n\n const toolsPointer = childPointer(pointer, 'tools');\n\n for (const capabilityId of Object.keys(agent.tools ?? {}).sort(compareExactStrings)) {\n const capability = agent.tools?.[capabilityId];\n\n if (capability !== undefined) {\n addCapabilityCandidates(candidates, capability, 'tool', capabilityId, agentId, toolsPointer, [\n ['inputSchema', capability.inputSchema],\n ['outputSchema', capability.outputSchema],\n ]);\n }\n }\n\n const skillsPointer = childPointer(pointer, 'skills');\n\n for (const capabilityId of Object.keys(agent.skills ?? {}).sort(compareExactStrings)) {\n const capability = agent.skills?.[capabilityId];\n\n if (capability !== undefined) {\n addCapabilityCandidates(\n candidates,\n capability,\n 'skill',\n capabilityId,\n agentId,\n skillsPointer,\n );\n }\n }\n\n addUnresolvedCandidates(\n candidates,\n agent.unresolved,\n childPointer(pointer, 'unresolved'),\n entity,\n );\n};\n\n/** Collects every repository-backed manifest declaration in deterministic pointer order. */\nconst collectCandidates = (manifest: IMoldeaManifestV1): readonly IRepositoryCandidate[] => {\n const candidates: IRepositoryCandidate[] = [];\n\n for (const property of ['context', 'decisions'] as const) {\n const relationships = manifest[property];\n\n for (const referencedPath of Object.keys(relationships ?? {}).sort(compareExactStrings)) {\n const relationship = relationships?.[referencedPath];\n\n if (relationship === undefined) {\n continue;\n }\n\n const pointer = childPointer(`/${property}`, referencedPath);\n const decisionId =\n property === 'decisions'\n ? parseDecisionIdFromPath(parseRepositoryPath(referencedPath))\n : null;\n addRelationshipCandidates(\n candidates,\n relationship,\n pointer,\n decisionId === null ? null : { decisionId },\n );\n }\n }\n\n addUnresolvedCandidates(candidates, manifest.unresolved, '/unresolved', null);\n\n for (const agentId of Object.keys(manifest.agents ?? {}).sort(compareExactStrings)) {\n const agent = manifest.agents?.[agentId];\n\n if (agent !== undefined) {\n addAgentCandidates(candidates, agentId, agent);\n }\n }\n\n return candidates.sort((left, right) => compareExactStrings(left.pointer, right.pointer));\n};\n\n/** Tests whether discovery already owns a diagnostic for a path or one of its ancestors. */\nconst isBlockedPath = (path: IRepositoryPath, blockedPaths: ReadonlySet<string>): boolean => {\n let candidate: string = path;\n\n while (candidate.length > 0) {\n if (blockedPaths.has(candidate)) {\n return true;\n }\n\n const separatorIndex = candidate.lastIndexOf('/');\n if (separatorIndex <= 0) {\n return false;\n }\n\n candidate = candidate.slice(0, separatorIndex);\n }\n\n return false;\n};\n\n/** Creates normalized diagnostic details for one failed exact lookup. */\nconst createCandidateDetails = (\n candidate: IRepositoryCandidate,\n entry: IRepositoryEntry | null,\n): Readonly<Record<string, string>> => {\n const pathProperty = candidate.kind === 'impact' ? 'impactPath' : 'referencedPath';\n const details: Record<string, string> = { [pathProperty]: candidate.path };\n\n if (entry !== null) {\n details['actualType'] = entry.type;\n }\n\n if (candidate.kind === 'tool-implementation' || candidate.kind === 'skill-implementation') {\n details['reason'] =\n entry === null ? 'missing' : entry.type === 'symlink' ? 'symlink' : 'not-file';\n }\n\n return details;\n};\n\n/** Selects the most-specific diagnostic code for one failed exact lookup. */\nconst getCandidateCode = (\n candidate: IRepositoryCandidate,\n entry: IRepositoryEntry | null,\n): ICoreDiagnosticCode | null => {\n if (entry?.type === 'file') {\n return null;\n }\n\n if (candidate.kind === 'tool-implementation') {\n return 'MOLDEA_TOOL_IMPLEMENTATION_MISSING';\n }\n\n if (candidate.kind === 'skill-implementation') {\n return 'MOLDEA_SKILL_IMPLEMENTATION_MISSING';\n }\n\n if (candidate.kind === 'impact') {\n return entry === null ? 'MOLDEA_IMPACT_PATH_MISSING' : 'MOLDEA_IMPACT_PATH_NOT_FILE';\n }\n\n if (entry === null) {\n return 'MOLDEA_REFERENCE_MISSING';\n }\n\n return entry.type === 'symlink' ? 'MOLDEA_REFERENCE_SYMLINK' : 'MOLDEA_REFERENCE_NOT_FILE';\n};\n\n/** Adds the one most-specific diagnostic for a resolved repository candidate. */\nconst validateCandidate = (\n candidate: IRepositoryCandidate,\n entry: IRepositoryEntry | null,\n manifestPath: IRepositoryPath,\n collector: ICoreDiagnosticCollector,\n): void => {\n const code = getCandidateCode(candidate, entry);\n\n if (code === null) {\n return;\n }\n\n collector.add({\n code,\n details: createCandidateDetails(candidate, entry),\n entity: candidate.entity,\n path: manifestPath,\n pointer: candidate.pointer,\n });\n};\n\n/**\n * Validates every manifest repository reference, binding, and exact impact path.\n * @param repository The budget-aware reader for the active inspection session.\n * @param manifestPath The canonical manifest path used for diagnostics.\n * @param manifest The normalized valid manifest contract to inspect.\n * @param discovery Canonical discovery state used to suppress dependent path diagnostics.\n * @param limits The resource limits applied to emitted diagnostics.\n * @param signal Optional cancellation forwarded to exact repository lookups.\n * @returns Deeply immutable deterministic repository-reference diagnostics.\n * @throws\n * - INVALID_REPOSITORY_PATH: A repository path is invalid.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during validation.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Repository inspection or a repository lookup was aborted.\n */\nexport const validateRepositoryReferences = async (\n repository: IRepositoryInspectionReader,\n manifestPath: IRepositoryPath,\n manifest: IMoldeaManifestV1,\n discovery: ICanonicalDiscoveryResult,\n limits: ICoreResourceLimits,\n signal?: AbortSignal,\n): Promise<readonly ICoreDiagnostic[]> => {\n const collector = createCoreDiagnosticCollector(limits, 'validate-project');\n const blockedPaths = new Set(\n discovery.diagnostics.flatMap((diagnostic) =>\n diagnostic.path === null ? [] : [diagnostic.path],\n ),\n );\n const entryCache = new Map<IRepositoryPath, Promise<IRepositoryEntry | null>>();\n const operationOptions: IRepositoryOperationOptions | undefined =\n signal === undefined ? undefined : { signal };\n\n for (const candidate of collectCandidates(manifest)) {\n if (isBlockedPath(candidate.path, blockedPaths)) {\n continue;\n }\n\n let entryPromise = entryCache.get(candidate.path);\n\n if (entryPromise === undefined) {\n entryPromise = repository.getEntry(candidate.path, operationOptions);\n entryCache.set(candidate.path, entryPromise);\n }\n\n validateCandidate(candidate, await entryPromise, manifestPath, collector);\n }\n\n return collector.finalize();\n};\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICanonicalDiscoveryResult } from '../canonical-discovery/index.js';\nimport type { IIndexedRuntimeGuidance } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n escapeJsonPointerSegment,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport { compareExactStrings, hasNonWhitespace } from '../format-validation/index.js';\nimport type { IMoldeaManifestV1 } from '../format/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\nimport { readRepositoryTextAsset } from '../repository-text/index.js';\n\n// internal runtime-guidance result retained for final project indexing\nexport interface IRuntimeGuidanceResult {\n readonly valid: boolean;\n readonly runtimes: readonly IIndexedRuntimeGuidance[];\n readonly diagnostics: readonly ICoreDiagnostic[];\n}\n\nconst addDiagnostics = (\n collector: ICoreDiagnosticCollector,\n diagnostics: readonly ICoreDiagnostic[],\n): void => {\n for (const diagnostic of diagnostics) {\n collector.merge(diagnostic);\n }\n};\n\nconst isBlockedPath = (path: IRepositoryPath, blockedPaths: ReadonlySet<string>): boolean => {\n let candidate: string = path;\n\n while (candidate.length > 0) {\n if (blockedPaths.has(candidate)) {\n return true;\n }\n\n const separatorIndex = candidate.lastIndexOf('/');\n if (separatorIndex <= 0) {\n return false;\n }\n\n candidate = candidate.slice(0, separatorIndex);\n }\n\n return false;\n};\n\n/**\n * Reads all discovered runtime guidance and validates every manifest guidance relationship.\n * @param repository The coherent source-neutral repository reader.\n * @param manifestPath The canonical manifest path used for relationship diagnostics.\n * @param manifest The normalized manifest declaring optional agent guidance paths, when valid.\n * @param discovery The canonical inventory and path-owned structural diagnostics.\n * @param options The immutable Core configuration snapshot.\n * @param signal Optional cancellation forwarded to every repository read.\n * @returns Deeply immutable valid guidance assets and deterministic diagnostics.\n * @throws\n * - ENTRY_NOT_FOUND: A discovered guidance file disappeared from the reader snapshot.\n * - ENTRY_NOT_FILE: A discovered guidance entry is no longer a regular file.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during guidance reads.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Guidance inspection or a repository operation was aborted.\n */\nexport const readRuntimeGuidance = async (\n repository: IRepositoryInspectionReader,\n manifestPath: IRepositoryPath,\n manifest: IMoldeaManifestV1 | null,\n discovery: ICanonicalDiscoveryResult,\n options: ICoreOptionsSnapshot,\n signal?: AbortSignal,\n): Promise<IRuntimeGuidanceResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const collector = createCoreDiagnosticCollector(options.limits, 'validate-project');\n const runtimes: IIndexedRuntimeGuidance[] = [];\n const discoveredPaths = new Set(discovery.inventory.runtimeGuidance);\n const blockedPaths = new Set(\n discovery.diagnostics.flatMap((diagnostic) =>\n diagnostic.path === null ? [] : [diagnostic.path],\n ),\n );\n\n for (const path of [...discoveredPaths].sort(compareExactStrings)) {\n const result = await readRepositoryTextAsset(repository, path, options.limits, signal);\n addDiagnostics(collector, result.diagnostics);\n\n if (result.asset === null) {\n continue;\n }\n\n if (!hasNonWhitespace(result.asset.content)) {\n collector.add({ code: 'MOLDEA_RUNTIME_GUIDANCE_EMPTY', path });\n continue;\n }\n\n runtimes.push({ asset: result.asset });\n }\n\n for (const agentId of Object.keys(manifest?.agents ?? {}).sort(compareExactStrings)) {\n const guidance = manifest?.agents?.[agentId]?.runtime.guidance;\n\n if (\n guidance === undefined ||\n discoveredPaths.has(guidance) ||\n isBlockedPath(guidance, blockedPaths)\n ) {\n continue;\n }\n\n collector.add({\n code: 'MOLDEA_RUNTIME_GUIDANCE_MISSING',\n details: { referencedPath: guidance },\n entity: { agentId },\n path: manifestPath,\n pointer: `/agents/${escapeJsonPointerSegment(agentId)}/runtime/guidance`,\n });\n }\n\n const diagnostics = collector.finalize();\n\n return freezeRecursively({\n diagnostics,\n runtimes,\n valid: diagnostics.length === 0,\n });\n};\n","import { parseRepositoryPath, type IRepositoryEntry } from '@moldea.ai/repository';\n\nimport { inspectAgentAssets, type IInspectedAgentAssets } from '../agent-assets/index.js';\nimport { discoverCanonicalAssets } from '../canonical-discovery/index.js';\nimport type { IIndexedManifest, IMoldeaProjectIndex } from '../contracts/index.js';\nimport { readDecisionGraph } from '../decision-graph/index.js';\nimport {\n createCoreDiagnosticCollector,\n type ICoreDiagnosticCollector,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport type { IRepositoryFormatVersion } from '../format/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { validateManifestRelationships } from '../manifest-relationship-validation/index.js';\nimport { inspectManifestDocument } from '../manifest/index.js';\nimport type { IRuntimeManifestLocation } from '../manifest-validation/index.js';\nimport { inspectMirrors, type IAgentMirrorInspection } from '../mirrors/index.js';\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport { readProjectAssets, readProjectFile } from '../project-assets/index.js';\nimport { createProjectIndex } from '../project-index/index.js';\nimport type { IRepositoryInspectionSession } from '../repository-inspection-session/index.js';\nimport { validateRepositoryReferences } from '../repository-reference-validation/index.js';\nimport { readRuntimeGuidance } from '../runtime-guidance/index.js';\n\nconst MOLDEA_ROOT = parseRepositoryPath('/moldea');\nconst MANIFEST_PATH = parseRepositoryPath('/moldea/moldea.yaml');\nconst PROJECT_PATH = parseRepositoryPath('/moldea/project.md');\n\n// internal all-or-nothing universal result retained for later adapter execution\nexport interface IUniversalProjectInspectionResult {\n readonly formatVersion: IRepositoryFormatVersion | null;\n readonly project: IMoldeaProjectIndex | null;\n readonly diagnostics: readonly ICoreDiagnostic[];\n readonly runtimeLocations: readonly IRuntimeManifestLocation[];\n}\n\n// shared inspection state supplied by the public repository-level orchestrator\nexport interface IUniversalProjectInspectionContext {\n readonly session: IRepositoryInspectionSession;\n readonly signal?: AbortSignal;\n}\n\nconst addDiagnostics = (\n collector: ICoreDiagnosticCollector,\n diagnostics: readonly ICoreDiagnostic[],\n): void => {\n for (const diagnostic of diagnostics) {\n collector.merge(diagnostic);\n }\n};\n\n/**\n * Executes every universal repository-format phase before runtime adapter validation.\n * @param context The shared inspection session and optional cancellation signal.\n * @param options The immutable Core configuration snapshot.\n * @returns The frozen provisional index only when no universal diagnostic remains.\n * @throws\n * - INVALID_REPOSITORY_PATH: A repository path is invalid.\n * - ENTRY_NOT_FOUND: A discovered file disappeared from the reader snapshot.\n * - ENTRY_NOT_FILE: A discovered file changed type during inspection.\n * - ENTRY_NOT_DIRECTORY: A discovered directory changed type during inspection.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during inspection.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Project inspection or a repository operation was aborted.\n */\nexport const inspectUniversalProject = async (\n context: IUniversalProjectInspectionContext,\n options: ICoreOptionsSnapshot,\n): Promise<IUniversalProjectInspectionResult> => {\n options = createCoreOperationOptionsSnapshot(options);\n const { session, signal } = context;\n const collector = createCoreDiagnosticCollector(options.limits, 'validate-project');\n const operationOptions = signal === undefined ? undefined : { signal };\n const moldeaRoot = await session.reader.getEntry(MOLDEA_ROOT, operationOptions);\n let manifestEntry: IRepositoryEntry | null = null;\n let projectEntry: IRepositoryEntry | null = null;\n\n let indexedManifest: IIndexedManifest | null = null;\n let formatVersion: IRepositoryFormatVersion | null = null;\n let runtimeLocations: readonly IRuntimeManifestLocation[] = [];\n\n if (moldeaRoot?.type === 'directory') {\n manifestEntry = await session.reader.getEntry(MANIFEST_PATH, operationOptions);\n\n if (manifestEntry?.type === 'file') {\n const content = await session.reader.readCompleteFile(MANIFEST_PATH, operationOptions);\n const parsedManifest = await inspectManifestDocument(\n { content, path: MANIFEST_PATH },\n options,\n 'validate-project',\n );\n formatVersion = parsedManifest.formatVersion;\n runtimeLocations = parsedManifest.runtimeLocations;\n addDiagnostics(collector, parsedManifest.diagnostics);\n\n if (parsedManifest.asset !== null && parsedManifest.manifest !== null) {\n indexedManifest = {\n asset: parsedManifest.asset,\n value: parsedManifest.manifest,\n };\n }\n }\n\n projectEntry = await session.reader.getEntry(PROJECT_PATH, operationOptions);\n }\n\n const projectFile = await readProjectFile(\n session.reader,\n projectEntry?.type === 'file' ? PROJECT_PATH : null,\n options,\n signal,\n );\n addDiagnostics(collector, projectFile.diagnostics);\n\n const discovery = await discoverCanonicalAssets(session.reader, options.limits, signal, {\n manifest: manifestEntry,\n moldeaRoot,\n project: projectEntry,\n });\n addDiagnostics(collector, discovery.diagnostics);\n session.throwIfAborted();\n\n const projectAssets = await readProjectAssets(\n session.reader,\n indexedManifest?.value ?? null,\n discovery,\n options,\n signal,\n projectFile,\n );\n addDiagnostics(collector, projectAssets.diagnostics);\n\n const runtimeGuidance = await readRuntimeGuidance(\n session.reader,\n discovery.inventory.manifest ?? MANIFEST_PATH,\n indexedManifest?.value ?? null,\n discovery,\n options,\n signal,\n );\n addDiagnostics(collector, runtimeGuidance.diagnostics);\n\n const decisionGraph = await readDecisionGraph(\n session.reader,\n discovery.inventory.decisions,\n options,\n signal,\n );\n addDiagnostics(collector, decisionGraph.diagnostics);\n\n let agents: readonly IInspectedAgentAssets[] = [];\n let agentMirrors: readonly IAgentMirrorInspection[] = [];\n\n if (indexedManifest !== null) {\n const manifestPath = indexedManifest.asset.path;\n const agentAssets = await inspectAgentAssets(\n session.reader,\n indexedManifest.value,\n discovery,\n options,\n signal,\n );\n agents = agentAssets.agents;\n addDiagnostics(collector, agentAssets.diagnostics);\n\n addDiagnostics(\n collector,\n validateManifestRelationships(\n manifestPath,\n indexedManifest.value,\n discovery,\n decisionGraph.decisions,\n options.limits,\n ),\n );\n\n addDiagnostics(\n collector,\n await validateRepositoryReferences(\n session.reader,\n manifestPath,\n indexedManifest.value,\n discovery,\n options.limits,\n signal,\n ),\n );\n\n const mirrorInspection = await inspectMirrors(\n session.reader,\n manifestPath,\n agents,\n options,\n signal,\n );\n agentMirrors = mirrorInspection.agentMirrors;\n addDiagnostics(collector, mirrorInspection.diagnostics);\n }\n\n session.throwIfAborted();\n const diagnostics = collector.finalize();\n const project =\n diagnostics.length === 0 && indexedManifest !== null && projectAssets.project !== null\n ? createProjectIndex({\n agentMirrors,\n agents,\n context: projectAssets.context,\n decisions: decisionGraph.decisions,\n manifest: indexedManifest,\n project: projectAssets.project,\n runtimes: runtimeGuidance.runtimes,\n })\n : null;\n\n return freezeRecursively({\n diagnostics,\n formatVersion,\n project,\n runtimeLocations,\n });\n};\n","import type { IRepositoryReader } from '@moldea.ai/repository';\n\nimport { validateRuntimeAdapterAvailability } from '../adapter-availability/index.js';\nimport { inspectRuntimeAdapters } from '../adapter-execution/index.js';\nimport type {\n IMoldeaProjectIndex,\n IProjectValidationInput,\n IProjectValidationResult,\n} from '../contracts/index.js';\nimport { countDiagnosticsBySeverity } from '../diagnostic-utilities/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { createCoreOperationOptionsSnapshot, type ICoreOptionsSnapshot } from '../options/index.js';\nimport { createProjectSummary } from '../project-metadata/index.js';\nimport { createRepositoryInspectionSession } from '../repository-inspection-session/index.js';\nimport type { IRepositoryInspectionResourceUsage } from '../repository-inspection-session/index.js';\nimport { inspectUniversalProject } from '../universal-project-inspection/index.js';\n\ninterface IValidatedProjectValidationInput {\n readonly repository: IRepositoryReader;\n readonly signal?: AbortSignal;\n}\n\nconst isRecord = (candidate: unknown): candidate is Readonly<Record<string, unknown>> => {\n return typeof candidate === 'object' && candidate !== null && !Array.isArray(candidate);\n};\n\nconst invalidArgument = (): never => {\n throw new CoreOperationException({\n code: 'INVALID_ARGUMENT',\n operation: 'validate-project',\n });\n};\n\nconst isRepositoryReader = (candidate: unknown): candidate is IRepositoryReader => {\n return (\n isRecord(candidate) &&\n isRecord(candidate['snapshot']) &&\n typeof candidate['snapshot']['id'] === 'string' &&\n typeof candidate['snapshot']['sourceKind'] === 'string' &&\n typeof candidate['compare'] === 'function' &&\n typeof candidate['getEntry'] === 'function' &&\n typeof candidate['listEntriesPage'] === 'function' &&\n typeof candidate['readFilePage'] === 'function'\n );\n};\n\nconst isAbortSignal = (candidate: unknown): candidate is AbortSignal => {\n return (\n isRecord(candidate) &&\n typeof candidate['aborted'] === 'boolean' &&\n typeof candidate['addEventListener'] === 'function' &&\n typeof candidate['removeEventListener'] === 'function'\n );\n};\n\nconst validateInput = (candidate: unknown): IValidatedProjectValidationInput => {\n try {\n if (!isRecord(candidate)) {\n return invalidArgument();\n }\n\n const repository = candidate['repository'];\n const signal = candidate['signal'];\n\n if (\n Reflect.ownKeys(candidate).some((key) => key !== 'repository' && key !== 'signal') ||\n !isRepositoryReader(repository) ||\n (signal !== undefined && !isAbortSignal(signal))\n ) {\n return invalidArgument();\n }\n\n return {\n repository,\n ...(signal === undefined ? {} : { signal }),\n };\n } catch (error: unknown) {\n if (error instanceof CoreOperationException) {\n throw error;\n }\n\n return invalidArgument();\n }\n};\n\n// private body-bearing state shared only by Core validation and page projection\nexport interface IProjectValidationState {\n readonly project: IMoldeaProjectIndex | null;\n readonly resourceUsage: IRepositoryInspectionResourceUsage;\n readonly result: IProjectValidationResult;\n}\n\n/**\n * Inspects one coherent repository snapshot through universal and adapter validation.\n * @param input The untrusted source-neutral reader and optional cancellation signal.\n * @param options The immutable Core configuration snapshot.\n * @returns A promise resolving to the frozen all-or-nothing project inspection result.\n * @throws\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - INVALID_REPOSITORY_PATH: A repository path is invalid.\n * - ENTRY_NOT_FOUND: A discovered file disappeared from the reader snapshot.\n * - ENTRY_NOT_FILE: A discovered file changed type during inspection.\n * - ENTRY_NOT_DIRECTORY: A discovered directory changed type during inspection.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during inspection.\n * - INVALID_SOURCE_DATA: The repository reader returned invalid contract data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core or repository resource limit was exceeded.\n * - ABORTED: Project inspection or a repository operation was aborted.\n * - ADAPTER_EXECUTION_FAILED: A runtime adapter failed or returned an invalid result.\n */\nexport const validateProjectState = async (\n input: IProjectValidationInput,\n options: ICoreOptionsSnapshot,\n): Promise<IProjectValidationState> => {\n const validatedInput = validateInput(input);\n const operationOptions = createCoreOperationOptionsSnapshot(options);\n const session = createRepositoryInspectionSession(\n validatedInput.repository,\n operationOptions.limits,\n validatedInput.signal,\n );\n const universal = await inspectUniversalProject(\n {\n session,\n ...(validatedInput.signal === undefined ? {} : { signal: validatedInput.signal }),\n },\n operationOptions,\n );\n\n if (universal.project === null) {\n const counts = countDiagnosticsBySeverity(universal.diagnostics);\n\n return freezeRecursively({\n project: null,\n resourceUsage: session.getResourceUsage(),\n result: {\n diagnostics: universal.diagnostics,\n ...counts,\n evidence: [],\n formatVersion: universal.formatVersion,\n source: validatedInput.repository.snapshot,\n summary: null,\n valid: false,\n },\n });\n }\n\n const projectSummary = createProjectSummary(universal.project);\n\n const availabilityDiagnostics = validateRuntimeAdapterAvailability(\n universal.runtimeLocations,\n universal.project.formatVersion,\n operationOptions,\n );\n\n if (availabilityDiagnostics.length > 0) {\n const counts = countDiagnosticsBySeverity(availabilityDiagnostics);\n\n return freezeRecursively({\n project: universal.project,\n resourceUsage: session.getResourceUsage(),\n result: {\n diagnostics: availabilityDiagnostics,\n ...counts,\n evidence: [],\n formatVersion: universal.formatVersion,\n source: validatedInput.repository.snapshot,\n summary: projectSummary,\n valid: false,\n },\n });\n }\n\n const adapterInspection = await inspectRuntimeAdapters(\n universal.project,\n session,\n operationOptions,\n validatedInput.signal,\n );\n const counts = countDiagnosticsBySeverity(adapterInspection.diagnostics);\n const valid = counts.errorCount === 0;\n\n return freezeRecursively({\n project: universal.project,\n resourceUsage: session.getResourceUsage(),\n result: {\n diagnostics: adapterInspection.diagnostics,\n ...counts,\n evidence: adapterInspection.evidence,\n formatVersion: universal.formatVersion,\n source: validatedInput.repository.snapshot,\n summary: projectSummary,\n valid,\n },\n });\n};\n\n/** Validates one project without returning canonical document bodies. */\nexport const validateProject = async (\n input: IProjectValidationInput,\n options: ICoreOptionsSnapshot,\n): Promise<IProjectValidationResult> => (await validateProjectState(input, options)).result;\n","import { createRepositoryIdentity } from '@moldea.ai/repository';\n\nimport type {\n IProjectInspection,\n IProjectInspectionInput,\n IProjectInspectionItem,\n IProjectInspectionPageInput,\n IProjectInspectionPageRecord,\n IProjectInspectionPageResult,\n IProjectInspectionResourceUsage,\n IProjectInspectionView,\n} from '../contracts/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport type { ICoreOptionsSnapshot } from '../options/index.js';\nimport { iterateProjectAgentAssignments } from '../project-agent-assignments/index.js';\nimport { iterateProjectMetadata } from '../project-metadata/index.js';\nimport { validateProjectState, type IProjectValidationState } from '../project-validation/index.js';\n\ninterface IKeyedInspectionItem {\n readonly item: IProjectInspectionItem;\n readonly key: string;\n}\n\ntype IInspectionViews = Readonly<Record<IProjectInspectionView, readonly IKeyedInspectionItem[]>>;\n\ninterface IPreparedProjectInspectionInput {\n readonly counts: IProjectInspection['counts'];\n readonly formatVersion: IProjectInspection['formatVersion'];\n readonly items: readonly IKeyedInspectionItem[];\n readonly maxEntries: number;\n readonly preparedBytes: number;\n readonly resourceUsage: {\n readonly canonicalBytes: number;\n readonly peakRetainedBytes: number;\n readonly retainedBytes: number;\n readonly totalBytesRead: number;\n };\n readonly source: IProjectInspection['source'];\n readonly summary: IProjectInspection['summary'];\n readonly valid: boolean;\n}\n\nconst CURSOR_PREFIX = 'core5';\nconst PREPARED_FIXED_BYTES = 512;\nconst PREPARED_ITEM_FIXED_BYTES = 64;\nconst PREPARED_TEXT_BYTE_MULTIPLIER = 2;\nconst PREPARED_VIEW_REFERENCE_BYTES = 8;\nconst encoder = new TextEncoder();\n\nconst invalidArgument = (): never => {\n throw new CoreOperationException({\n code: 'INVALID_ARGUMENT',\n operation: 'create-project-inspection',\n });\n};\n\nconst resourceLimitExceeded = (limitMaximum: number, observedUsage: number): never => {\n throw new CoreOperationException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit: 'maxRetainedBytes',\n limitMaximum,\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage,\n operation: 'create-project-inspection',\n });\n};\n\n/** Serializes content-free inspection state with recursively sorted object keys. */\nconst serializeDeterministically = (candidate: unknown): string => {\n if (candidate === null || typeof candidate !== 'object') {\n const serialized = JSON.stringify(candidate);\n\n return serialized === undefined ? 'null' : serialized;\n }\n\n if (Array.isArray(candidate)) {\n return `[${candidate.map((item) => serializeDeterministically(item)).join(',')}]`;\n }\n\n const entries = Object.entries(candidate as Readonly<Record<string, unknown>>)\n .filter(([, value]) => value !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n\n return `{${entries\n .map(([key, value]) => `${JSON.stringify(key)}:${serializeDeterministically(value)}`)\n .join(',')}}`;\n};\n\nconst createIdentity = (parts: Iterable<string>): string =>\n createRepositoryIdentity(\n (function* (): IterableIterator<Uint8Array> {\n for (const part of parts) {\n yield encoder.encode(part);\n }\n })(),\n );\n\nconst createItemBaseKey = (item: IProjectInspectionItem): string => {\n if (item.kind === 'agent') {\n return ['3', item.agent.agentId, item.agent.runtimeId].join('\\0');\n }\n\n if (item.kind === 'metadata') {\n return [\n '0',\n item.metadata.path,\n item.metadata.kind,\n item.metadata.agentId ?? '',\n item.metadata.decisionId ?? '',\n item.metadata.digest,\n ].join(':');\n }\n\n if (item.kind === 'diagnostic') {\n return [\n '1',\n item.diagnostic.source,\n item.diagnostic.code,\n item.diagnostic.path ?? '',\n createIdentity([serializeDeterministically(item.diagnostic)]),\n ].join(':');\n }\n\n return [\n '2',\n item.evidence.source,\n item.evidence.kind,\n item.evidence.agentId ?? '',\n createIdentity([serializeDeterministically(item.evidence)]),\n ].join(':');\n};\n\n/** Assigns stable unique keys once without relying on collection offsets. */\nconst createKeyedItems = (\n items: Iterable<IProjectInspectionItem>,\n): readonly IKeyedInspectionItem[] => {\n const sorted = Array.from(items, (item) => ({ item, key: createItemBaseKey(item) })).sort(\n (left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0),\n );\n let previousBaseKey: string | null = null;\n let occurrence = 0;\n\n for (const item of sorted) {\n const baseKey = item.key;\n occurrence = baseKey === previousBaseKey ? occurrence + 1 : 0;\n previousBaseKey = baseKey;\n item.key = `${baseKey}:${String(occurrence).padStart(10, '0')}`;\n }\n\n return sorted;\n};\n\nconst createCursorChecksum = (\n inspectionDigest: string,\n lastKey: string,\n view: IProjectInspectionView,\n): string => createIdentity([CURSOR_PREFIX, inspectionDigest, lastKey, view]);\n\nconst encodeCursor = (\n inspectionDigest: string,\n view: IProjectInspectionView,\n lastKey: string,\n): string =>\n [\n CURSOR_PREFIX,\n view,\n encodeURIComponent(lastKey),\n inspectionDigest,\n createCursorChecksum(inspectionDigest, lastKey, view),\n ].join(':');\n\nconst decodeCursor = (\n cursor: string | undefined,\n inspectionDigest: string,\n view: IProjectInspectionView,\n): string | null => {\n if (cursor === undefined) {\n return null;\n }\n\n const match =\n /^core5:(all|diagnostics|evidence|metadata):([^:]+):(sha256:[0-9a-f]{64}):(sha256:[0-9a-f]{64})$/u.exec(\n cursor,\n );\n\n if (match === null || match[1] !== view || match[3] !== inspectionDigest) {\n return invalidArgument();\n }\n\n let lastKey: string;\n\n try {\n lastKey = decodeURIComponent(match[2] as string);\n } catch {\n return invalidArgument();\n }\n\n if (lastKey.length === 0 || match[4] !== createCursorChecksum(inspectionDigest, lastKey, view)) {\n return invalidArgument();\n }\n\n return lastKey;\n};\n\nconst createViews = (items: readonly IKeyedInspectionItem[]): IInspectionViews =>\n freezeRecursively({\n all: items,\n diagnostics: items.filter(({ item }) => item.kind === 'diagnostic'),\n evidence: items.filter(({ item }) => item.kind === 'evidence'),\n metadata: items.filter(({ item }) => item.kind === 'metadata' || item.kind === 'agent'),\n });\n\nconst addRetainedBytes = (\n current: number,\n additional: number,\n retainedBeforePreparation: number,\n maximum: number,\n): number => {\n const projectedUsage = retainedBeforePreparation + current + additional;\n\n if (\n !Number.isSafeInteger(additional) ||\n additional < 0 ||\n !Number.isSafeInteger(projectedUsage) ||\n projectedUsage > maximum\n ) {\n return resourceLimitExceeded(\n maximum,\n Number.isSafeInteger(projectedUsage) ? projectedUsage : Number.MAX_SAFE_INTEGER,\n );\n }\n\n return current + additional;\n};\n\n/** Iterates every content-free inspection item without retaining preparation state. */\nconst iterateProjectInspectionItems = function* (\n state: IProjectValidationState,\n): IterableIterator<IProjectInspectionItem> {\n if (state.project !== null) {\n for (const metadata of iterateProjectMetadata(state.project)) {\n yield { kind: 'metadata', metadata };\n }\n }\n\n for (const diagnostic of state.result.diagnostics) {\n yield { diagnostic, kind: 'diagnostic' };\n }\n\n for (const evidence of state.result.evidence) {\n yield { evidence, kind: 'evidence' };\n }\n\n if (state.project !== null) {\n for (const agent of iterateProjectAgentAssignments(state.project)) {\n yield { agent, kind: 'agent' };\n }\n }\n};\n\ninterface IPreparedProjectInspectionEstimate {\n readonly counts: IProjectInspection['counts'];\n readonly preparedBytes: number;\n}\n\n/** Preflights the complete logical prepared-state cost before retaining its collections. */\nconst estimatePreparedProjectInspection = (\n state: IProjectValidationState,\n baseCounts: Omit<IProjectInspection['counts'], 'metadata'>,\n maximum: number,\n): IPreparedProjectInspectionEstimate => {\n const retainedBeforePreparation = state.resourceUsage.retainedBytes;\n let bytes = addRetainedBytes(0, PREPARED_FIXED_BYTES, retainedBeforePreparation, maximum);\n let metadataCount = 0;\n\n for (const item of iterateProjectInspectionItems(state)) {\n const key = `${createItemBaseKey(item)}:0000000000`;\n const encodedBytes =\n encoder.encode(key).byteLength + encoder.encode(serializeDeterministically(item)).byteLength;\n bytes = addRetainedBytes(\n bytes,\n PREPARED_ITEM_FIXED_BYTES +\n encodedBytes * PREPARED_TEXT_BYTE_MULTIPLIER +\n PREPARED_VIEW_REFERENCE_BYTES,\n retainedBeforePreparation,\n maximum,\n );\n\n if (item.kind === 'metadata') {\n metadataCount += 1;\n }\n }\n\n const counts = {\n agents: baseCounts.agents,\n context: baseCounts.context,\n decisions: baseCounts.decisions,\n diagnostics: baseCounts.diagnostics,\n errors: baseCounts.errors,\n evidence: baseCounts.evidence,\n metadata: metadataCount,\n mirrors: baseCounts.mirrors,\n runtimes: baseCounts.runtimes,\n unresolved: baseCounts.unresolved,\n warnings: baseCounts.warnings,\n };\n bytes = addRetainedBytes(\n bytes,\n encoder.encode(\n serializeDeterministically({\n counts,\n formatVersion: state.result.formatVersion,\n inspectionDigest: 'sha256:0000000000000000000000000000000000000000000000000000000000000000',\n source: state.result.source,\n summary: state.result.summary,\n valid: state.result.valid,\n }),\n ).byteLength * PREPARED_TEXT_BYTE_MULTIPLIER,\n retainedBeforePreparation,\n maximum,\n );\n\n return { counts, preparedBytes: bytes };\n};\n\n/** Creates the inspection digest without materializing a project-sized key projection. */\nconst createInspectionDigest = (\n counts: IProjectInspection['counts'],\n formatVersion: IProjectInspection['formatVersion'],\n items: readonly IKeyedInspectionItem[],\n summary: IProjectInspection['summary'],\n valid: boolean,\n): string =>\n createIdentity(\n (function* (): IterableIterator<string> {\n yield 'core5-prepared-inspection';\n yield serializeDeterministically({ counts, formatVersion, summary, valid });\n\n for (const { key } of items) {\n yield key;\n }\n })(),\n );\n\nconst findStartIndex = (items: readonly IKeyedInspectionItem[], lastKey: string | null): number => {\n if (lastKey === null) {\n return 0;\n }\n\n let lower = 0;\n let upper = items.length - 1;\n\n while (lower <= upper) {\n const middle = lower + Math.floor((upper - lower) / 2);\n const candidate = items[middle];\n\n if (candidate === undefined) {\n return invalidArgument();\n }\n\n if (candidate.key === lastKey) {\n return middle + 1;\n }\n\n if (candidate.key < lastKey) {\n lower = middle + 1;\n } else {\n upper = middle - 1;\n }\n }\n\n return invalidArgument();\n};\n\n/** Creates the returned inspection from content-free state only. */\nconst createPreparedProjectInspection = (\n input: IPreparedProjectInspectionInput,\n): IProjectInspection => {\n const {\n counts,\n formatVersion,\n items,\n maxEntries,\n preparedBytes,\n resourceUsage: validationUsage,\n source,\n summary,\n valid,\n } = input;\n const views = createViews(items);\n const inspectionDigest = createInspectionDigest(counts, formatVersion, items, summary, valid);\n const resourceUsage: IProjectInspectionResourceUsage = freezeRecursively({\n canonicalBytes: validationUsage.canonicalBytes,\n peakRetainedBytes: Math.max(\n validationUsage.peakRetainedBytes,\n validationUsage.retainedBytes + preparedBytes,\n ),\n preparedBytes,\n retainedBytes: preparedBytes,\n totalBytesRead: validationUsage.totalBytesRead,\n });\n\n const readPage = (pageInput: IProjectInspectionPageInput): IProjectInspectionPageResult => {\n if (\n typeof pageInput !== 'object' ||\n pageInput === null ||\n Reflect.ownKeys(pageInput).some(\n (key) => key !== 'cursor' && key !== 'maxItems' && key !== 'view',\n ) ||\n !Number.isSafeInteger(pageInput.maxItems) ||\n pageInput.maxItems < 1 ||\n pageInput.maxItems > maxEntries ||\n (pageInput.cursor !== undefined && typeof pageInput.cursor !== 'string') ||\n (pageInput.view !== 'all' &&\n pageInput.view !== 'diagnostics' &&\n pageInput.view !== 'evidence' &&\n pageInput.view !== 'metadata')\n ) {\n return invalidArgument();\n }\n\n const viewItems = views[pageInput.view];\n const lastKey = decodeCursor(pageInput.cursor, inspectionDigest, pageInput.view);\n const startIndex = findStartIndex(viewItems, lastKey);\n const selected = viewItems.slice(startIndex, startIndex + pageInput.maxItems);\n const records: IProjectInspectionPageRecord[] = selected.map(({ item, key }, index) => {\n const isLastItem = startIndex + index + 1 >= viewItems.length;\n\n return {\n item,\n nextCursor: isLastItem ? null : encodeCursor(inspectionDigest, pageInput.view, key),\n };\n });\n const nextCursor = records.at(-1)?.nextCursor ?? null;\n\n return freezeRecursively({\n counts,\n formatVersion,\n inspectionDigest,\n page: {\n isComplete: nextCursor === null,\n nextCursor,\n records,\n totalItems: viewItems.length,\n },\n source,\n summary,\n valid,\n view: pageInput.view,\n });\n };\n\n return freezeRecursively({\n counts,\n formatVersion,\n inspectionDigest,\n readPage,\n resourceUsage,\n source,\n summary,\n valid,\n });\n};\n\n/** Prepares one immutable content-free inspection for synchronous bounded page reads. */\nexport const createProjectInspection = async (\n input: IProjectInspectionInput,\n options: ICoreOptionsSnapshot,\n): Promise<IProjectInspection> => {\n const state = await validateProjectState(input, options);\n const baseCounts = {\n agents: state.result.summary?.counts.agents ?? 0,\n context: state.result.summary?.counts.context ?? 0,\n decisions: state.result.summary?.counts.decisions ?? 0,\n diagnostics: state.result.diagnostics.length,\n errors: state.result.errorCount,\n evidence: state.result.evidence.length,\n mirrors: state.result.summary?.counts.mirrors ?? 0,\n runtimes: state.result.summary?.counts.runtimes ?? 0,\n unresolved: state.result.summary?.counts.unresolved ?? 0,\n warnings: state.result.warningCount,\n };\n const estimate = estimatePreparedProjectInspection(\n state,\n baseCounts,\n options.limits.maxRetainedBytes,\n );\n const counts = freezeRecursively(estimate.counts);\n const items = freezeRecursively(createKeyedItems(iterateProjectInspectionItems(state)));\n\n return createPreparedProjectInspection({\n counts,\n formatVersion: state.result.formatVersion,\n items,\n maxEntries: options.limits.maxEntries,\n preparedBytes: estimate.preparedBytes,\n resourceUsage: state.resourceUsage,\n source: state.result.source,\n summary: state.result.summary,\n valid: state.result.valid,\n });\n};\n","import { parseRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport { compareExactStrings } from '../format-validation/index.js';\n\nimport type { ICoreResourceLimits, ITextDocumentInput } from '../contracts/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\n\nimport type { IManifestScopeInput } from './types.js';\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n};\n\n/** Throws the stable invalid-argument failure for malformed scope input. */\nconst invalidArgument = (): never => {\n throw new CoreOperationException({\n code: 'INVALID_ARGUMENT',\n operation: 'match-manifest-scope',\n });\n};\n\n/** Throws the stable resource failure for an exhausted scope-input budget. */\nconst resourceLimitExceeded = (\n limit: 'maxEntries' | 'maxTotalBytesRead',\n limitMaximum: number,\n observedUsage: number,\n): never => {\n throw new CoreOperationException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit,\n limitMaximum,\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage,\n operation: 'match-manifest-scope',\n });\n};\n\n/** Measures scalar UTF-8 bytes without allocating an encoded copy. */\nexport const measureUtf8ByteLength = (value: string): number => {\n let byteLength = 0;\n\n for (const scalar of value) {\n const codePoint = scalar.codePointAt(0) ?? 0;\n byteLength += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;\n }\n\n return byteLength;\n};\n\nexport interface INormalizedManifestScopeInput {\n readonly manifest: ITextDocumentInput;\n readonly paths: readonly IRepositoryPath[];\n}\n\n/**\n * Validates and snapshots one public manifest-scope input.\n * @param input The untrusted manifest document and changed logical paths.\n * @param limits The immutable Core resource limits.\n * @returns The detached manifest input and sorted unique repository paths.\n * @throws\n * - INVALID_REPOSITORY_PATH: A changed repository path is invalid.\n * - INVALID_ARGUMENT: The scope operation received an invalid argument.\n * - RESOURCE_LIMIT_EXCEEDED: The changed-path count or byte budget was exceeded.\n */\nexport const normalizeManifestScopeInput = (\n input: IManifestScopeInput,\n limits: ICoreResourceLimits,\n): INormalizedManifestScopeInput => {\n if (!isRecord(input)) {\n return invalidArgument();\n }\n\n const manifest = input['manifest'];\n const pathCandidates = input['paths'];\n\n if (!isRecord(manifest) || !Array.isArray(pathCandidates)) {\n return invalidArgument();\n }\n\n if (pathCandidates.length > limits.maxEntries) {\n return resourceLimitExceeded('maxEntries', limits.maxEntries, pathCandidates.length);\n }\n\n const uniquePaths = new Set<IRepositoryPath>();\n let totalBytes = 0;\n\n for (const [index, candidate] of pathCandidates.entries()) {\n if (typeof candidate !== 'string') {\n return invalidArgument();\n }\n\n const path = parseRepositoryPath(candidate);\n totalBytes += measureUtf8ByteLength(path) + (index === 0 ? 0 : 1);\n\n if (totalBytes > limits.maxTotalBytesRead) {\n return resourceLimitExceeded('maxTotalBytesRead', limits.maxTotalBytesRead, totalBytes);\n }\n\n uniquePaths.add(path);\n }\n\n return {\n manifest,\n paths: [...uniquePaths].sort(compareExactStrings),\n };\n};\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { IContentDigest, ICoreResourceLimits } from '../contracts/index.js';\nimport { escapeJsonPointerSegment } from '../diagnostic-utilities/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\nimport { compareExactStrings, countUnicodeScalars } from '../format-validation/index.js';\nimport type {\n IAgentManifestEntry,\n IMoldeaManifestV1,\n IRepositoryReference,\n ISkillManifestEntry,\n IToolManifestEntry,\n IUnresolvedRequirementManifestEntry,\n} from '../format/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { calculateNormalizedTextDigest } from '../text/index.js';\n\nimport type {\n IManifestScopeCounts,\n IManifestScopeDeclaration,\n IManifestScopeMatch,\n IManifestScopeOwner,\n IManifestScopeRelationshipField,\n} from './types.js';\nimport { measureUtf8ByteLength } from './validations.js';\n\ninterface IManifestScopeRelationshipDeclaration {\n readonly owner: IManifestScopeOwner;\n readonly field: IManifestScopeRelationshipField;\n readonly pointer: string;\n readonly declaration: IManifestScopeDeclaration;\n}\n\ninterface ICompiledGlobDeclaration {\n readonly declaration: IManifestScopeRelationshipDeclaration;\n readonly segments: readonly string[];\n}\n\ninterface ICompiledManifestScope {\n readonly declarations: readonly IManifestScopeRelationshipDeclaration[];\n readonly exact: ReadonlyMap<IRepositoryPath, readonly IManifestScopeRelationshipDeclaration[]>;\n readonly globalGlobs: readonly ICompiledGlobDeclaration[];\n readonly globsByFirstSegment: ReadonlyMap<string, readonly ICompiledGlobDeclaration[]>;\n}\n\ntype IManifestCapability =\n | { readonly kind: 'skill'; readonly value: ISkillManifestEntry }\n | { readonly kind: 'tool'; readonly value: IToolManifestEntry };\n\nconst childPointer = (pointer: string, segment: string): string => {\n return `${pointer}/${escapeJsonPointerSegment(segment)}`;\n};\n\nconst createOwner = (\n kind: IManifestScopeOwner['kind'],\n id: string,\n agentId: string | null = null,\n): IManifestScopeOwner => ({ agentId, id, kind });\n\nconst compareOwners = (left: IManifestScopeOwner, right: IManifestScopeOwner): number => {\n return (\n compareExactStrings(left.kind, right.kind) ||\n compareExactStrings(left.agentId ?? '', right.agentId ?? '') ||\n compareExactStrings(left.id, right.id)\n );\n};\n\nconst getDeclarationValue = (declaration: IManifestScopeDeclaration): string => {\n return declaration.kind === 'exact' ? declaration.path : declaration.pattern;\n};\n\nconst compareDeclarations = (\n left: IManifestScopeRelationshipDeclaration,\n right: IManifestScopeRelationshipDeclaration,\n): number => {\n return (\n compareOwners(left.owner, right.owner) ||\n compareExactStrings(left.field, right.field) ||\n compareExactStrings(\n getDeclarationValue(left.declaration),\n getDeclarationValue(right.declaration),\n ) ||\n compareExactStrings(left.pointer, right.pointer)\n );\n};\n\n/** Adds one exact repository relationship to the normalized declaration collection. */\nconst addExactDeclaration = (\n declarations: IManifestScopeRelationshipDeclaration[],\n owner: IManifestScopeOwner,\n field: IManifestScopeRelationshipField,\n pointer: string,\n reference: IRepositoryReference | IRepositoryPath,\n): void => {\n declarations.push({\n declaration:\n typeof reference === 'string'\n ? { kind: 'exact', path: reference, symbol: null }\n : { kind: 'exact', path: reference.path, symbol: reference.symbol ?? null },\n field,\n owner,\n pointer,\n });\n};\n\n/** Adds sorted repository references while preserving normalized declaration pointers. */\nconst addReferenceDeclarations = (\n declarations: IManifestScopeRelationshipDeclaration[],\n references: readonly IRepositoryReference[] | undefined,\n owner: IManifestScopeOwner,\n field: IManifestScopeRelationshipField,\n pointer: string,\n): void => {\n for (const [index, reference] of (references ?? []).entries()) {\n addExactDeclaration(\n declarations,\n owner,\n field,\n childPointer(pointer, String(index)),\n reference,\n );\n }\n};\n\n/** Adds exact and simple-glob impact relationships in normalized array order. */\nconst addAffectedByDeclarations = (\n declarations: IManifestScopeRelationshipDeclaration[],\n affectedBy: readonly string[] | undefined,\n owner: IManifestScopeOwner,\n pointer: string,\n): void => {\n for (const [index, pattern] of (affectedBy ?? []).entries()) {\n declarations.push({\n declaration: pattern.includes('*')\n ? { kind: 'glob', pattern }\n : { kind: 'exact', path: pattern as IRepositoryPath, symbol: null },\n field: 'affectedBy',\n owner,\n pointer: childPointer(pointer, String(index)),\n });\n }\n};\n\n/** Adds project-level or agent-level unresolved requirement references. */\nconst addUnresolvedDeclarations = (\n declarations: IManifestScopeRelationshipDeclaration[],\n requirements: Readonly<Record<string, IUnresolvedRequirementManifestEntry>> | undefined,\n pointer: string,\n agentId: string | null,\n): void => {\n for (const requirementId of Object.keys(requirements ?? {}).sort(compareExactStrings)) {\n const requirement = requirements?.[requirementId];\n\n if (requirement === undefined) {\n continue;\n }\n\n const owner = createOwner('unresolved', requirementId, agentId);\n addReferenceDeclarations(\n declarations,\n requirement.related,\n owner,\n 'related',\n childPointer(childPointer(pointer, requirementId), 'related'),\n );\n }\n};\n\n/** Adds exact and impact declarations owned by one tool or skill capability. */\nconst addCapabilityDeclarations = (\n declarations: IManifestScopeRelationshipDeclaration[],\n capabilityId: string,\n capability: IManifestCapability,\n agentId: string,\n pointer: string,\n): void => {\n const owner = createOwner(capability.kind, capabilityId, agentId);\n addExactDeclaration(\n declarations,\n owner,\n 'implementation',\n childPointer(pointer, 'implementation'),\n capability.value.implementation,\n );\n\n if (capability.value.registration !== undefined) {\n addExactDeclaration(\n declarations,\n owner,\n 'registration',\n childPointer(pointer, 'registration'),\n capability.value.registration,\n );\n }\n\n if (capability.kind === 'tool') {\n for (const field of ['inputSchema', 'outputSchema'] as const) {\n const reference = capability.value[field];\n\n if (reference !== undefined) {\n addExactDeclaration(declarations, owner, field, childPointer(pointer, field), reference);\n }\n }\n }\n\n addAffectedByDeclarations(\n declarations,\n capability.value.affectedBy,\n owner,\n childPointer(pointer, 'affectedBy'),\n );\n};\n\n/** Adds all exact and impact relationships owned by one registered agent. */\nconst addAgentDeclarations = (\n declarations: IManifestScopeRelationshipDeclaration[],\n agentId: string,\n agent: IAgentManifestEntry,\n): void => {\n const pointer = childPointer('/agents', agentId);\n const owner = createOwner('agent', agentId, agentId);\n const bindingsPointer = childPointer(pointer, 'bindings');\n\n for (const field of [\n 'runtimeAgent',\n 'inputSchema',\n 'outputSchema',\n 'instructionLoader',\n ] as const) {\n const reference = agent.bindings?.[field];\n\n if (reference !== undefined) {\n addExactDeclaration(\n declarations,\n owner,\n field,\n childPointer(bindingsPointer, field),\n reference,\n );\n }\n }\n\n for (const variableId of Object.keys(agent.bindings?.variableProviders ?? {}).sort(\n compareExactStrings,\n )) {\n const reference = agent.bindings?.variableProviders?.[variableId];\n\n if (reference !== undefined) {\n addExactDeclaration(\n declarations,\n owner,\n 'variableProvider',\n childPointer(childPointer(bindingsPointer, 'variableProviders'), variableId),\n reference,\n );\n }\n }\n\n addAffectedByDeclarations(\n declarations,\n agent.affectedBy,\n owner,\n childPointer(pointer, 'affectedBy'),\n );\n\n for (const capabilityId of Object.keys(agent.tools ?? {}).sort(compareExactStrings)) {\n const tool = agent.tools?.[capabilityId];\n\n if (tool !== undefined) {\n addCapabilityDeclarations(\n declarations,\n capabilityId,\n { kind: 'tool', value: tool },\n agentId,\n childPointer(childPointer(pointer, 'tools'), capabilityId),\n );\n }\n }\n\n for (const capabilityId of Object.keys(agent.skills ?? {}).sort(compareExactStrings)) {\n const skill = agent.skills?.[capabilityId];\n\n if (skill !== undefined) {\n addCapabilityDeclarations(\n declarations,\n capabilityId,\n { kind: 'skill', value: skill },\n agentId,\n childPointer(childPointer(pointer, 'skills'), capabilityId),\n );\n }\n }\n\n for (const [index, mirror] of (agent.mirrors ?? []).entries()) {\n addExactDeclaration(\n declarations,\n owner,\n 'mirrors',\n childPointer(childPointer(pointer, 'mirrors'), String(index)),\n mirror,\n );\n }\n\n addUnresolvedDeclarations(\n declarations,\n agent.unresolved,\n childPointer(pointer, 'unresolved'),\n agentId,\n );\n};\n\n/** Collects every version 1 declaration that can establish changed-path relevance. */\nconst collectDeclarations = (\n manifest: IMoldeaManifestV1,\n): readonly IManifestScopeRelationshipDeclaration[] => {\n const declarations: IManifestScopeRelationshipDeclaration[] = [];\n\n for (const kind of ['context', 'decision'] as const) {\n const relationships = kind === 'context' ? manifest.context : manifest.decisions;\n\n for (const ownerId of Object.keys(relationships ?? {}).sort(compareExactStrings)) {\n const relationship = relationships?.[ownerId];\n\n if (relationship === undefined) {\n continue;\n }\n\n const owner = createOwner(kind, ownerId);\n const pointer = childPointer(kind === 'context' ? '/context' : '/decisions', ownerId);\n addReferenceDeclarations(\n declarations,\n relationship.bindings,\n owner,\n 'bindings',\n childPointer(pointer, 'bindings'),\n );\n addAffectedByDeclarations(\n declarations,\n relationship.affectedBy,\n owner,\n childPointer(pointer, 'affectedBy'),\n );\n }\n }\n\n addUnresolvedDeclarations(declarations, manifest.unresolved, '/unresolved', null);\n\n for (const agentId of Object.keys(manifest.agents ?? {}).sort(compareExactStrings)) {\n const agent = manifest.agents?.[agentId];\n\n if (agent !== undefined) {\n addAgentDeclarations(declarations, agentId, agent);\n }\n }\n\n return declarations.sort(compareDeclarations);\n};\n\n/** Tests a single-segment wildcard without regular-expression interpretation. */\nconst matchesSegment = (pattern: string, value: string): boolean => {\n let patternIndex = 0;\n let valueIndex = 0;\n let starIndex = -1;\n let starValueIndex = -1;\n\n while (valueIndex < value.length) {\n if (pattern[patternIndex] === value[valueIndex]) {\n patternIndex += 1;\n valueIndex += 1;\n continue;\n }\n\n if (pattern[patternIndex] === '*') {\n starIndex = patternIndex;\n starValueIndex = valueIndex;\n patternIndex += 1;\n continue;\n }\n\n if (starIndex === -1) {\n return false;\n }\n\n patternIndex = starIndex + 1;\n starValueIndex += 1;\n valueIndex = starValueIndex;\n }\n\n while (pattern[patternIndex] === '*') {\n patternIndex += 1;\n }\n\n return patternIndex === pattern.length;\n};\n\n/** Matches validated simple-glob segments with zero-or-more-segment globstars. */\nconst matchesGlob = (patternSegments: readonly string[], path: IRepositoryPath): boolean => {\n const pathSegments = path.slice(1).split('/');\n let reachable = new Uint8Array(pathSegments.length + 1);\n reachable[0] = 1;\n\n for (const patternSegment of patternSegments) {\n const next = new Uint8Array(pathSegments.length + 1);\n\n if (patternSegment === '**') {\n let canReach = false;\n\n for (let index = 0; index < reachable.length; index += 1) {\n canReach ||= reachable[index] === 1;\n next[index] = canReach ? 1 : 0;\n }\n } else {\n for (let index = 0; index < pathSegments.length; index += 1) {\n if (reachable[index] === 1 && matchesSegment(patternSegment, pathSegments[index] ?? '')) {\n next[index + 1] = 1;\n }\n }\n }\n\n reachable = next;\n }\n\n return reachable[pathSegments.length] === 1;\n};\n\n/** Builds exact and first-segment glob indexes once for one parsed manifest. */\nconst compileManifestScope = (\n manifest: IMoldeaManifestV1,\n limits: ICoreResourceLimits,\n): ICompiledManifestScope => {\n const declarations = collectDeclarations(manifest);\n\n if (declarations.length > limits.maxEntries) {\n throw new CoreOperationException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit: 'maxEntries',\n limitMaximum: limits.maxEntries,\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage: declarations.length,\n operation: 'match-manifest-scope',\n });\n }\n\n const exact = new Map<IRepositoryPath, IManifestScopeRelationshipDeclaration[]>();\n const globalGlobs: ICompiledGlobDeclaration[] = [];\n const globsByFirstSegment = new Map<string, ICompiledGlobDeclaration[]>();\n\n for (const declaration of declarations) {\n if (declaration.declaration.kind === 'exact') {\n const existing = exact.get(declaration.declaration.path) ?? [];\n existing.push(declaration);\n exact.set(declaration.declaration.path, existing);\n continue;\n }\n\n const segments = declaration.declaration.pattern.slice(1).split('/');\n const compiled = { declaration, segments };\n const firstSegment = segments[0] ?? '';\n\n if (firstSegment === '**' || firstSegment.includes('*')) {\n globalGlobs.push(compiled);\n } else {\n const existing = globsByFirstSegment.get(firstSegment) ?? [];\n existing.push(compiled);\n globsByFirstSegment.set(firstSegment, existing);\n }\n }\n\n return { declarations, exact, globalGlobs, globsByFirstSegment };\n};\n\nconst compareMatches = (left: IManifestScopeMatch, right: IManifestScopeMatch): number => {\n return (\n compareOwners(left.owner, right.owner) ||\n compareExactStrings(left.field, right.field) ||\n compareExactStrings(\n getDeclarationValue(left.declaration),\n getDeclarationValue(right.declaration),\n ) ||\n compareExactStrings(left.inputPath, right.inputPath) ||\n compareExactStrings(left.pointer, right.pointer)\n );\n};\n\nconst createMatch = (\n inputPath: IRepositoryPath,\n relationship: IManifestScopeRelationshipDeclaration,\n): IManifestScopeMatch => ({\n declaration: relationship.declaration,\n field: relationship.field,\n inputPath,\n owner: relationship.owner,\n pointer: relationship.pointer,\n});\n\n/** Adds one match without ever allocating beyond the operation entry budget. */\nconst addMatch = (\n matches: IManifestScopeMatch[],\n inputPath: IRepositoryPath,\n relationship: IManifestScopeRelationshipDeclaration,\n limits: ICoreResourceLimits,\n): void => {\n if (matches.length >= limits.maxEntries) {\n throw new CoreOperationException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n limit: 'maxEntries',\n limitMaximum: limits.maxEntries,\n nextAction: 'reduce-input-or-increase-limit',\n observedUsage: matches.length + 1,\n operation: 'match-manifest-scope',\n });\n }\n\n matches.push(createMatch(inputPath, relationship));\n};\n\n/** Appends matches from one precompiled glob bucket without copying the bucket. */\nconst addGlobMatches = (\n matches: IManifestScopeMatch[],\n inputPath: IRepositoryPath,\n declarations: readonly ICompiledGlobDeclaration[],\n limits: ICoreResourceLimits,\n): void => {\n for (const compiled of declarations) {\n if (matchesGlob(compiled.segments, inputPath)) {\n addMatch(matches, inputPath, compiled.declaration, limits);\n }\n }\n};\n\n/** Creates the canonical digest of the sorted unique changed-path set. */\nexport const calculateManifestScopeInputDigest = async (\n paths: readonly IRepositoryPath[],\n): Promise<IContentDigest> => {\n const value = paths.join('\\0');\n\n return calculateNormalizedTextDigest({\n scalarLength: countUnicodeScalars(value),\n utf8ByteLength: measureUtf8ByteLength(value),\n value,\n });\n};\n\n/**\n * Matches normalized changed paths against one valid version 1 manifest.\n * @param manifest The parsed and validated manifest value.\n * @param paths Sorted unique repository-logical changed paths.\n * @param limits The immutable Core operation limits.\n * @returns Frozen content-free matches and stable aggregate counts.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: The declaration or match count exceeded `maxEntries`.\n */\nexport const matchParsedManifestScope = (\n manifest: IMoldeaManifestV1,\n paths: readonly IRepositoryPath[],\n limits: ICoreResourceLimits,\n): { readonly counts: IManifestScopeCounts; readonly matches: readonly IManifestScopeMatch[] } => {\n const compiled = compileManifestScope(manifest, limits);\n const matches: IManifestScopeMatch[] = [];\n const matchedOwners = new Set<string>();\n const matchedPaths = new Set<IRepositoryPath>();\n\n for (const path of paths) {\n const firstSegment = path.slice(1).split('/', 1)[0] ?? '';\n const exactDeclarations = compiled.exact.get(path) ?? [];\n\n for (const relationship of exactDeclarations) {\n addMatch(matches, path, relationship, limits);\n }\n\n addGlobMatches(matches, path, compiled.globalGlobs, limits);\n addGlobMatches(matches, path, compiled.globsByFirstSegment.get(firstSegment) ?? [], limits);\n }\n\n matches.sort(compareMatches);\n\n for (const match of matches) {\n matchedOwners.add(`${match.owner.kind}\\0${match.owner.agentId ?? ''}\\0${match.owner.id}`);\n matchedPaths.add(match.inputPath);\n }\n\n return freezeRecursively({\n counts: {\n declarations: compiled.declarations.length,\n inputPaths: paths.length,\n matchedOwners: matchedOwners.size,\n matchedPaths: matchedPaths.size,\n matches: matches.length,\n },\n matches,\n });\n};\n","import type { ICoreOptionsSnapshot } from '../options/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { parseManifestDocument } from '../manifest/index.js';\n\nimport { calculateManifestScopeInputDigest, matchParsedManifestScope } from './matching.js';\nimport type { IManifestScopeInput, IManifestScopeResult } from './types.js';\nimport { normalizeManifestScopeInput } from './validations.js';\n\n/**\n * Parses a manifest and matches its repository relationships against changed logical paths.\n * @param input The canonical manifest document and untrusted changed-path collection.\n * @param options The immutable Core operation options.\n * @returns A promise resolving to frozen content-free scope metadata and matches.\n * @throws\n * - INVALID_REPOSITORY_PATH: The manifest path or a changed repository path is invalid.\n * - INVALID_ARGUMENT: The scope operation received an invalid argument.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nexport const matchManifestScope = async (\n input: IManifestScopeInput,\n options: ICoreOptionsSnapshot,\n): Promise<IManifestScopeResult> => {\n const normalized = normalizeManifestScopeInput(input, options.limits);\n const inputDigest = await calculateManifestScopeInputDigest(normalized.paths);\n const parsed = await parseManifestDocument(normalized.manifest, options, 'match-manifest-scope');\n\n if (!parsed.valid || parsed.asset === null || parsed.manifest === null) {\n return freezeRecursively({\n counts: {\n declarations: 0,\n inputPaths: normalized.paths.length,\n matchedOwners: 0,\n matchedPaths: 0,\n matches: 0,\n },\n diagnostics: parsed.diagnostics,\n inputDigest,\n manifestDigest: null,\n matches: [],\n relevant: false,\n valid: false,\n });\n }\n\n const matched = matchParsedManifestScope(parsed.manifest, normalized.paths, options.limits);\n\n return freezeRecursively({\n counts: matched.counts,\n diagnostics: [],\n inputDigest,\n manifestDigest: parsed.asset.digest,\n matches: matched.matches,\n relevant: matched.matches.length > 0,\n valid: true,\n });\n};\n","import type {\n ICanonicalContentPageInput,\n ICore,\n ICoreOptions,\n IProjectInspectionInput,\n IProjectValidationInput,\n ITextDocumentInput,\n} from '../contracts/index.js';\nimport { readCanonicalContentPage } from '../canonical-content-page/index.js';\nimport { parseDecisionDocument } from '../decision/index.js';\nimport { freezeRecursively } from '../immutable/index.js';\nimport { parseManifestDocument } from '../manifest/index.js';\nimport { createCoreOperationOptionsSnapshot, normalizeCoreOptions } from '../options/index.js';\nimport { createProjectInspection } from '../project-inspection/index.js';\nimport { validateProject } from '../project-validation/index.js';\nimport { matchManifestScope } from '../scope-matching/index.js';\nimport type { IManifestScopeInput } from '../scope-matching/types.js';\nimport { calculateContentDigest, normalizeTextDocument } from '../text/index.js';\n\n/**\n * Creates one immutable Core instance from detached configuration snapshots.\n * @param options Optional runtime adapters and resource-limit overrides.\n * @returns A frozen Core instance safe for concurrent independent operations.\n * @throws\n * - DUPLICATE_ADAPTER_ID: A runtime adapter ID is registered more than once.\n * - RESERVED_ADAPTER_ID: A reserved runtime adapter ID was supplied.\n * - INVALID_ADAPTER_DEFINITION: A runtime adapter definition is invalid.\n * - INVALID_RESOURCE_LIMIT: A Core resource limit is invalid.\n */\nexport const createCore = (options?: ICoreOptions): ICore => {\n const snapshot = normalizeCoreOptions(options);\n\n return freezeRecursively({\n calculateContentDigest: (input: ITextDocumentInput) => {\n const operation = createCoreOperationOptionsSnapshot(snapshot);\n return calculateContentDigest(input, operation.limits);\n },\n createProjectInspection: (input: IProjectInspectionInput) =>\n createProjectInspection(input, createCoreOperationOptionsSnapshot(snapshot)),\n validateProject: (input: IProjectValidationInput) =>\n validateProject(input, createCoreOperationOptionsSnapshot(snapshot)),\n matchManifestScope: (input: IManifestScopeInput) =>\n matchManifestScope(input, createCoreOperationOptionsSnapshot(snapshot)),\n normalizeText: (input: ITextDocumentInput) => {\n const operation = createCoreOperationOptionsSnapshot(snapshot);\n return normalizeTextDocument(input, operation.limits, 'normalize-text');\n },\n parseDecision: (input: ITextDocumentInput) =>\n parseDecisionDocument(input, createCoreOperationOptionsSnapshot(snapshot)),\n parseManifest: (input: ITextDocumentInput) =>\n parseManifestDocument(input, createCoreOperationOptionsSnapshot(snapshot)),\n readCanonicalContentPage: (input: ICanonicalContentPageInput) =>\n readCanonicalContentPage(input, createCoreOperationOptionsSnapshot(snapshot)),\n });\n};\n"],"mappings":";;;;AAIA,IAAa,iCAAiC,OAAO,OAAO;CAC1D;CACA;CAC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