@moldea.ai/core 7.1.0 → 9.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.
Files changed (96) hide show
  1. package/README.md +4 -4
  2. package/dist/agent-asset-validation/index.d.ts.map +1 -1
  3. package/dist/agent-assets/index.d.ts.map +1 -1
  4. package/dist/analysis-worker.js +11 -23
  5. package/dist/analysis-worker.js.map +1 -1
  6. package/dist/canonical-content-page/index.d.ts.map +1 -1
  7. package/dist/canonical-discovery/index.d.ts.map +1 -1
  8. package/dist/chunks/{core-CMuQrqRI.js → core-CFmT3SRC.js} +170 -231
  9. package/dist/chunks/core-CFmT3SRC.js.map +1 -0
  10. package/dist/chunks/{errors-BhiLG9F0.js → errors-Uvb-9X1u.js} +29 -75
  11. package/dist/chunks/errors-Uvb-9X1u.js.map +1 -0
  12. package/dist/chunks/{exceptions-CYf1pCKf.js → exceptions-AT654xUL.js} +10 -15
  13. package/dist/chunks/exceptions-AT654xUL.js.map +1 -0
  14. package/dist/chunks/{lifecycle-Bdi_ydtH.js → lifecycle-DuAHgnYH.js} +2 -2
  15. package/dist/chunks/{lifecycle-Bdi_ydtH.js.map → lifecycle-DuAHgnYH.js.map} +1 -1
  16. package/dist/chunks/{options-BVF3DQHm.js → options-C5360E_N.js} +23 -174
  17. package/dist/chunks/options-C5360E_N.js.map +1 -0
  18. package/dist/chunks/repository-rpc-B9YaeLba.js +143 -0
  19. package/dist/chunks/repository-rpc-B9YaeLba.js.map +1 -0
  20. package/dist/chunks/{scope-DoNl6LhC.js → scope-CNg6Gnpi.js} +214 -151
  21. package/dist/chunks/scope-CNg6Gnpi.js.map +1 -0
  22. package/dist/constants/index.d.ts +1 -1
  23. package/dist/constants/index.d.ts.map +1 -1
  24. package/dist/contracts/index.d.ts +2 -6
  25. package/dist/contracts/index.d.ts.map +1 -1
  26. package/dist/core/index.d.ts.map +1 -1
  27. package/dist/decision/index.d.ts.map +1 -1
  28. package/dist/decision-graph/index.d.ts.map +1 -1
  29. package/dist/decision-graph-validation/index.d.ts.map +1 -1
  30. package/dist/decision-validation/index.d.ts.map +1 -1
  31. package/dist/diagnostic-utilities/index.d.ts.map +1 -1
  32. package/dist/diagnostics/index.d.ts +2 -2
  33. package/dist/diagnostics/index.d.ts.map +1 -1
  34. package/dist/exceptions/index.d.ts +1 -1
  35. package/dist/exceptions/index.d.ts.map +1 -1
  36. package/dist/format-validation/index.d.ts +0 -4
  37. package/dist/format-validation/index.d.ts.map +1 -1
  38. package/dist/immutable/index.d.ts +0 -6
  39. package/dist/immutable/index.d.ts.map +1 -1
  40. package/dist/index.d.ts +1 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +3 -3
  43. package/dist/integration-validation/agents-inspection.d.ts +3 -3
  44. package/dist/integration-validation/agents-inspection.d.ts.map +1 -1
  45. package/dist/integration-validation/claude-inspection.d.ts +3 -2
  46. package/dist/integration-validation/claude-inspection.d.ts.map +1 -1
  47. package/dist/integration-validation/inspection.d.ts +4 -2
  48. package/dist/integration-validation/inspection.d.ts.map +1 -1
  49. package/dist/integration-validation/parser.d.ts +9 -3
  50. package/dist/integration-validation/parser.d.ts.map +1 -1
  51. package/dist/integration-validation/types.d.ts +3 -8
  52. package/dist/integration-validation/types.d.ts.map +1 -1
  53. package/dist/integration-validation/utilities.d.ts +0 -8
  54. package/dist/integration-validation/utilities.d.ts.map +1 -1
  55. package/dist/manifest/index.d.ts.map +1 -1
  56. package/dist/manifest-relationship-validation/index.d.ts.map +1 -1
  57. package/dist/manifest-validation/index.d.ts.map +1 -1
  58. package/dist/mirrors/index.d.ts.map +1 -1
  59. package/dist/node-inspection/client.d.ts.map +1 -1
  60. package/dist/node-inspection/protocol.d.ts.map +1 -1
  61. package/dist/node-inspection/repository-rpc.d.ts +7 -6
  62. package/dist/node-inspection/repository-rpc.d.ts.map +1 -1
  63. package/dist/node-inspection/types.d.ts +7 -12
  64. package/dist/node-inspection/types.d.ts.map +1 -1
  65. package/dist/node-runner.js +3 -3
  66. package/dist/node.js +19 -35
  67. package/dist/node.js.map +1 -1
  68. package/dist/options/index.d.ts.map +1 -1
  69. package/dist/project-assets/index.d.ts.map +1 -1
  70. package/dist/project-index/index.d.ts.map +1 -1
  71. package/dist/project-inspection/index.d.ts.map +1 -1
  72. package/dist/project-validation/index.d.ts +1 -1
  73. package/dist/project-validation/index.d.ts.map +1 -1
  74. package/dist/repository-inspection-session/index.d.ts +5 -8
  75. package/dist/repository-inspection-session/index.d.ts.map +1 -1
  76. package/dist/repository-reference-validation/index.d.ts.map +1 -1
  77. package/dist/repository-text/index.d.ts.map +1 -1
  78. package/dist/runtime-guidance/index.d.ts.map +1 -1
  79. package/dist/runtime-placeholder-validation/index.d.ts.map +1 -1
  80. package/dist/scope-matching/matching.d.ts.map +1 -1
  81. package/dist/scope-matching/scope.d.ts.map +1 -1
  82. package/dist/scope-matching/validations.d.ts +0 -2
  83. package/dist/scope-matching/validations.d.ts.map +1 -1
  84. package/dist/scope.js +2 -2
  85. package/dist/text/index.d.ts.map +1 -1
  86. package/dist/universal-project-inspection/index.d.ts.map +1 -1
  87. package/dist/warning-acceptance/acceptance.d.ts.map +1 -1
  88. package/dist/yaml/index.d.ts.map +1 -1
  89. package/package.json +4 -3
  90. package/dist/chunks/core-CMuQrqRI.js.map +0 -1
  91. package/dist/chunks/errors-BhiLG9F0.js.map +0 -1
  92. package/dist/chunks/exceptions-CYf1pCKf.js.map +0 -1
  93. package/dist/chunks/options-BVF3DQHm.js.map +0 -1
  94. package/dist/chunks/repository-rpc-CiKFu86B.js +0 -178
  95. package/dist/chunks/repository-rpc-CiKFu86B.js.map +0 -1
  96. package/dist/chunks/scope-DoNl6LhC.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-CFmT3SRC.js","names":[],"sources":["../../src/canonical-content-page/index.ts","../../src/decision-validation/index.ts","../../src/decision/index.ts","../../src/project-agent-assignments/index.ts","../../src/project-metadata/index.ts","../../src/binding-coverage/index.ts","../../src/retained-memory/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/integration-validation/parser.ts","../../src/integration-validation/utilities.ts","../../src/integration-validation/agents-inspection.ts","../../src/integration-validation/claude-inspection.ts","../../src/integration-validation/inspection.ts","../../src/impact-pattern-validation/inspection.ts","../../src/warning-acceptance/acceptance.ts","../../src/mirrors/index.ts","../../src/project-assets/index.ts","../../src/project-index/index.ts","../../src/export-inventory/inventory.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/core/index.ts"],"sourcesContent":["import { deepFreeze } from 'jg-utilities';\n\nimport {\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 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 deepFreeze({\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 deepFreeze({\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 { compareCodePoints } from 'jg-utilities';\n\nimport 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 { 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(compareCodePoints);\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 { deepFreeze } from 'jg-utilities';\n\nimport { 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 { 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 limit snapshot.\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 deepFreeze({\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 deepFreeze({\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 deepFreeze({\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 { 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 { IDiagnosticEntity } from '../diagnostics/index.js';\n\n// declared relationships whose files Core checks\nexport type IBindingRelationship =\n | 'runtime-agent'\n | 'instruction-loader'\n | 'agent-input-schema'\n | 'agent-output-schema'\n | 'variable-provider'\n | 'tool-implementation'\n | 'tool-registration'\n | 'tool-input-schema'\n | 'tool-output-schema'\n | 'skill-implementation'\n | 'skill-registration'\n | 'context-binding'\n | 'decision-binding';\n\n// reasons an export check could not reach a conclusion\nexport type IExportNotCheckedReason =\n | 'no-symbol'\n | 'unsupported-file-type'\n | 'unresolved-exports'\n | 'unparseable-source'\n | 'resource-limit';\n\n// file existence and export checks never establish runtime wiring\nexport type IBindingCoverage = {\n entity: IDiagnosticEntity;\n relationship: IBindingRelationship;\n path: string;\n symbol: string | null;\n fileCheck: 'passed';\n} & (\n | { exportCheck: 'passed' }\n | { exportCheck: 'failed' }\n | { exportCheck: 'not-checked'; exportNotCheckedReason: IExportNotCheckedReason }\n);\n\n// complete operation totals, independent of a selected inspection page\nexport interface IBindingCoverageCounts {\n readonly bindings: number;\n readonly exportsPassed: number;\n readonly exportsFailed: number;\n readonly exportsNotChecked: number;\n}\n\n/** Counts every declared, existing binding by its actual export-check outcome. */\nexport const countBindingCoverage = (\n coverage: readonly IBindingCoverage[],\n): IBindingCoverageCounts => ({\n bindings: coverage.length,\n exportsPassed: coverage.filter((record) => record.exportCheck === 'passed').length,\n exportsFailed: coverage.filter((record) => record.exportCheck === 'failed').length,\n exportsNotChecked: coverage.filter((record) => record.exportCheck === 'not-checked').length,\n});\n","import type { IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\n\n// one complete temporary source buffer and the release of its retained-memory reservation\nexport interface IRetainedSource {\n bytes: Uint8Array;\n release: () => void;\n}\n\n// private session-owned admission and temporary source-buffer lifetime\nexport interface IRetainedMemory {\n reserve(bytes: number): void;\n tryReserve(bytes: number): boolean;\n release(bytes: number): void;\n readSourceFile(path: IRepositoryPath): Promise<IRetainedSource>;\n}\n\nconst ledgers = new WeakMap<IRepositoryInspectionReader, IRetainedMemory>();\n\n/** Registers the sole memory owner for one internal reader. */\nexport const registerRetainedMemory = (\n reader: IRepositoryInspectionReader,\n ledger: IRetainedMemory,\n): void => {\n if (ledgers.has(reader)) throw new TypeError('The inspection reader is already registered.');\n ledgers.set(reader, ledger);\n};\n\n/** Returns the ledger shared by all phases of a repository inspection. */\nexport const getRetainedMemory = (reader: IRepositoryInspectionReader): IRetainedMemory => {\n const ledger = ledgers.get(reader);\n if (ledger === undefined)\n throw new TypeError('The inspection reader has no retained-memory ledger.');\n return ledger;\n};\n\n/** Reserves retained coverage in production sessions and leaves standalone file-check readers untracked. */\nexport const reserveRetainedBytesIfTracked = (\n reader: IRepositoryInspectionReader,\n bytes: number,\n): void => {\n ledgers.get(reader)?.reserve(bytes);\n};\n","import {\n REPOSITORY_LINK_TEXT_MAX_BYTES,\n REPOSITORY_ROOT,\n RepositorySourceException,\n compareRepositoryPaths,\n isRepositoryPath,\n parseRepositoryPath,\n type IRepositoryEntry,\n type IRepositoryFilePage,\n type IRepositoryFilePageOptions,\n type IRepositoryLinkSource,\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 { registerRetainedMemory, type IRetainedSource } from '../retained-memory/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\n\nconst MANIFEST_PATH = parseRepositoryPath('/moldea/moldea.yaml');\n// the only paths an instruction reader may supply; every other read uses the repository\nconst INSTRUCTION_PATHS: ReadonlySet<IRepositoryPath> = new Set(\n ['/AGENTS.md', '/CLAUDE.md', '/.claude/CLAUDE.md', '/CLAUDE.local.md'].map((path) =>\n parseRepositoryPath(path),\n ),\n);\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/*\n * Private view used only by the integration check. The four coding-agent instruction paths read\n * the instruction reader when one was supplied, and every other path reads the repository, so a\n * link between an instruction file and a repository file resolves the same way everywhere.\n */\nexport interface IRepositoryInstructionView extends IRepositoryLinkSource {\n readSourceFile(path: IRepositoryPath): Promise<IRetainedSource>;\n}\n\n// private resource state shared by every reader consumer during one validation\nexport interface IRepositoryInspectionSession {\n readonly instructions: IRepositoryInstructionView;\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: The Core operation 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\n// bounded page reads from one snapshot-bound source\ninterface IFilePageSource {\n readonly readPage: (\n path: IRepositoryPath,\n options: IRepositoryFilePageOptions,\n ) => Promise<IRepositoryFilePage>;\n readonly snapshotId: string;\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 * @param instructions Optional reader of the four instruction paths, used only by the instruction view.\n * @returns A session that pages source metadata and range-reads bounded canonical files.\n * @throws\n * - ABORTED: The Core operation was aborted.\n */\nexport const createRepositoryInspectionSession = (\n repository: IRepositoryReader,\n limits: ICoreResourceLimits,\n signal?: AbortSignal,\n instructions?: IRepositoryReader,\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 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 repositoryPages: IFilePageSource = {\n readPage: (path, options) => repository.readFilePage(path, options),\n snapshotId: repository.snapshot.id,\n };\n\n const getEntryFrom = async (\n source: IRepositoryReader,\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 source.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 getEntry = (\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryEntry | null> => getEntryFrom(repository, path, options);\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 isSource = false,\n pages: IFilePageSource = repositoryPages,\n ): Promise<Uint8Array> => {\n const multiplier = isSource ? 1 : CANONICAL_BYTE_RETENTION_MULTIPLIER;\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 pages.readPage(path, {\n maxBytes: firstPageMaximumBytes,\n offset: 0,\n ...(createSourceOptions(signal, operationSignal) ?? {}),\n });\n throwIfSignalAborted(operationSignal);\n\n if (\n firstPage.snapshot.id !== pages.snapshotId ||\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 > Math.floor(retainedBytesAvailableForCanonicalContent / multiplier)\n ) {\n const projectedUsage = retainedBytes + firstPageBytes + firstPage.totalBytes * 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 * multiplier;\n observeTransientBytes(canonicalRetainedBytes + firstPageBytes);\n reserveRetainedBytes(canonicalRetainedBytes);\n if (!isSource) 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 !== pages.snapshotId ||\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 pages.readPage(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 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 if (callerSignal.aborted) abort();\n else 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 /** Loads one complete temporary source buffer whose reservation the caller releases. */\n const readRetainedSource = async (\n path: IRepositoryPath,\n pages: IFilePageSource,\n ): Promise<IRetainedSource> => {\n throwIfSignalAborted();\n registerPath(path);\n const bytes = await awaitWithCancellation(loadFile(path, undefined, true, pages));\n throwIfSignalAborted();\n let isReleased = false;\n return {\n bytes,\n release: (): void => {\n if (!isReleased) retainedBytes -= bytes.byteLength;\n isReleased = true;\n },\n };\n };\n\n const readerFor = (path: IRepositoryPath): IRepositoryReader =>\n instructions !== undefined && INSTRUCTION_PATHS.has(path) ? instructions : repository;\n const pagesFor = (path: IRepositoryPath): IFilePageSource => {\n const source = readerFor(path);\n\n return source === repository\n ? repositoryPages\n : {\n readPage: (pagePath, options) => source.readFilePage(pagePath, options),\n snapshotId: source.snapshot.id,\n };\n };\n\n /** Reads one link's stored text from the routed source, rejecting text past the shared limit. */\n const readLinkText = async (\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<string | null> => {\n const parsedPath = parseRepositoryPath(path);\n throwIfSignalAborted(options?.signal);\n registerPath(parsedPath);\n const text: unknown = await awaitWithCancellation(\n readerFor(parsedPath).readLinkText(parsedPath, createSourceOptions(signal, options?.signal)),\n options?.signal,\n );\n throwIfSignalAborted(options?.signal);\n\n if (\n text !== null &&\n (typeof text !== 'string' || encoder.encode(text).byteLength > REPOSITORY_LINK_TEXT_MAX_BYTES)\n ) {\n return invalidSourceData('read-link-text', parsedPath);\n }\n\n return text;\n };\n\n const instructionView: IRepositoryInstructionView = Object.freeze({\n getEntry: (path: IRepositoryPath, options?: IRepositoryOperationOptions) => {\n const parsedPath = parseRepositoryPath(path);\n\n return getEntryFrom(readerFor(parsedPath), parsedPath, options);\n },\n readLinkText,\n readSourceFile: (path: IRepositoryPath) => {\n const parsedPath = parseRepositoryPath(path);\n\n return readRetainedSource(parsedPath, pagesFor(parsedPath));\n },\n });\n\n const reader = Object.freeze({ getEntry, iterateEntries, readCompleteFile });\n registerRetainedMemory(reader, {\n reserve: reserveRetainedBytes,\n tryReserve: (bytes): boolean => {\n if (\n !Number.isSafeInteger(bytes) ||\n bytes < 0 ||\n bytes > limits.maxRetainedBytes - retainedBytes\n )\n return false;\n reserveRetainedBytes(bytes);\n return true;\n },\n release: (bytes): void => {\n if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > retainedBytes)\n throw new TypeError('The retained-memory release is invalid.');\n retainedBytes -= bytes;\n },\n readSourceFile: (path) => readRetainedSource(path, repositoryPages),\n });\n return Object.freeze({\n getResourceUsage: () =>\n Object.freeze({ canonicalBytes, peakRetainedBytes, retainedBytes, totalBytesRead }),\n instructions: instructionView,\n reader,\n throwIfAborted: throwIfSignalAborted,\n });\n};\n","import { deepFreeze } from 'jg-utilities';\n\nimport 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';\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 deepFreeze({\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 deepFreeze({\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 deepFreeze({\n diagnostics: finalizedDiagnostics,\n instruction: asset,\n valid: finalizedDiagnostics.length === 0,\n });\n};\n","import { deepFreeze } from 'jg-utilities';\n\nimport { RepositorySourceException, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICoreResourceLimits, IIndexedTextAsset } from '../contracts/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/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 deepFreeze({\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 deepFreeze({\n asset,\n diagnostics: [],\n valid: true,\n });\n};\n","import { compareCodePoints } from 'jg-utilities';\n\nimport 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 { 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(compareCodePoints)) {\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(compareCodePoints)) {\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 { compareCodePoints, deepFreeze } from 'jg-utilities';\n\nimport { 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 type { IAgentManifestEntry, IMoldeaManifestV1 } from '../format/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(compareCodePoints)) {\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 deepFreeze({\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 { compareCodePoints, deepFreeze } from 'jg-utilities';\n\nimport {\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 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(compareCodePoints);\n };\n const agents = [...working.agents.values()]\n .sort((left, right) => compareCodePoints(left.id, right.id))\n .map((agent) => deepFreeze({ ...agent }));\n\n return deepFreeze({\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 deepFreeze({\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 { compareCodePoints } from 'jg-utilities';\n\nimport 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 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) => compareCodePoints(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(compareCodePoints)) {\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(compareCodePoints);\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(compareCodePoints));\n }\n\n return components.sort((left, right) => compareCodePoints(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 { compareCodePoints, deepFreeze } from 'jg-utilities';\n\nimport { 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 { parseDecisionIdFromPath } from '../format-validation/index.js';\nimport type { IParsedDecision } from '../format/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 compareCodePoints(left.id, right.id) || compareCodePoints(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 limit snapshot.\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: The requested repository entry was not found.\n * - ENTRY_NOT_FILE: The requested repository entry is not a 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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The 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(compareCodePoints)) {\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 deepFreeze({\n decisions: sortDecisions(decisions),\n diagnostics: finalizedDiagnostics,\n valid: finalizedDiagnostics.length === 0,\n });\n};\n","import { compareCodePoints } from 'jg-utilities';\n\nimport { 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 { 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(compareCodePoints)) {\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(compareCodePoints)) {\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(compareCodePoints)) {\n const agent = manifest.agents?.[agentId];\n if (agent === undefined) {\n continue;\n }\n\n const escapedAgentId = escapeJsonPointerSegment(agentId);\n for (const [index, referencedPath] of (agent.context ?? []).entries()) {\n validateContextRelationship(\n referencedPath,\n `/agents/${escapedAgentId}/context/${index}`,\n validationContext.validAgentContextPaths,\n validationContext,\n agentId,\n );\n }\n\n for (const [index, referencedPath] of (agent.decisions ?? []).entries()) {\n validateDecisionRelationship(\n referencedPath,\n `/agents/${escapedAgentId}/decisions/${index}`,\n validationContext,\n agentId,\n );\n }\n }\n\n return collector.finalize();\n};\n","import { hasErrorCode } from 'jg-exception';\nimport { ERRORS, findMarkedRegion, type IMarkedRegion } from 'jg-utilities';\n\nimport type { IIntegrationBlockResult } from './types.js';\n\n// the marker lines the skill writer puts around the managed block\nconst MARKERS = { start: '<!-- moldea:start -->', end: '<!-- moldea:end -->' };\n\n/**\n * Finds the managed block's region with the skill writer's region semantics: one start and one end\n * marker, each on its own line, the start first.\n * @param text The instruction document.\n * @returns The region, or why the document has none.\n */\nexport const parseManagedIntegrationRegion = (\n text: string,\n): IMarkedRegion | 'block-missing' | 'block-invalid' => {\n try {\n return findMarkedRegion(text, MARKERS) ?? 'block-missing';\n } catch (error) {\n if (hasErrorCode(error, ERRORS.INVALID_MARKED_REGION)) return 'block-invalid';\n throw error;\n }\n};\n\n/**\n * Extracts the relative installation path from the fixed relevance-gate command without executing it.\n * @returns The safe installation path or the reason it could not be obtained.\n */\nexport const parseIntegrationBlock = (text: string): IIntegrationBlockResult => {\n const region = parseManagedIntegrationRegion(text);\n if (typeof region === 'string') return { kind: 'missing', reason: region };\n const matches = text\n .slice(region.start, region.end)\n .matchAll(/^node \"<repo-root>\\/([^\"\\r\\n]+)\\/scripts\\/relevance-gate\\.mjs\"(?:[ \\t\\r]|$)/gm);\n const first = matches.next().value;\n if (first === undefined || !matches.next().done)\n return { kind: 'missing', reason: 'skill-path-missing' };\n const skillPath = first[1];\n if (\n skillPath === undefined ||\n !/^[A-Za-z0-9._/-]+$/.test(skillPath) ||\n skillPath.startsWith('/') ||\n skillPath.endsWith('/') ||\n skillPath.includes('//') ||\n /(?:^|\\/)\\.{1,2}(?:\\/|$)/.test(skillPath)\n )\n return { kind: 'missing', reason: 'skill-path-invalid' };\n return { kind: 'found', skillPath };\n};\n\n// import lines Claude Code resolves to the root AGENTS.md, by the importing file's directory\nconst ROOT_AGENTS_IMPORTS: ReadonlySet<string> = new Set(['@AGENTS.md', '@./AGENTS.md']);\nconst NESTED_AGENTS_IMPORTS: ReadonlySet<string> = new Set(['@../AGENTS.md']);\n\n/**\n * Reports whether Claude Code instruction text imports the root AGENTS.md on a line of its own.\n * Lines inside fenced code blocks and imports embedded in other text do not count.\n * @param text The decoded instruction text.\n * @param isNested Whether the text belongs to `/.claude/CLAUDE.md` rather than a root file.\n * @returns `true` when one unfenced line, trimmed of spaces and tabs, is an AGENTS.md import.\n */\nexport const hasAgentsImport = (text: string, isNested: boolean): boolean => {\n const imports = isNested ? NESTED_AGENTS_IMPORTS : ROOT_AGENTS_IMPORTS;\n let fence: string | null = null;\n\n for (const rawLine of text.replace(/^\\uFEFF/u, '').split(/\\r\\n|\\n|\\r/u)) {\n const line = rawLine.replace(/^[ \\t]+|[ \\t]+$/gu, '');\n const marker = /^(`{3,}|~{3,})/u.exec(line)?.[1];\n\n if (fence !== null) {\n if (marker !== undefined && marker[0] === fence[0] && marker.length >= fence.length)\n fence = null;\n } else if (marker !== undefined) {\n fence = marker;\n } else if (imports.has(line)) {\n return true;\n }\n }\n\n return false;\n};\n","import { RepositorySourceException } from '@moldea.ai/repository';\n\nimport type { IRetainedMemory, IRetainedSource } from '../retained-memory/index.js';\n\n/**\n * Reads bounded untrusted text with a reservation for decoding and temporary string copies.\n * @param ledger The session ledger that owns the reservation.\n * @param load Loads the complete bounded source buffer.\n * @returns Decoded text or null for invalid UTF-8, with its reservation-release operation.\n * @throws\n * - ENTRY_NOT_FOUND: The requested repository entry was not found.\n * - ENTRY_NOT_FILE: The requested repository entry is not a file.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation was aborted.\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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n */\nexport const readRetainedText = async (\n ledger: IRetainedMemory,\n load: () => Promise<IRetainedSource>,\n): Promise<{ text: string | null; release: () => void }> => {\n const source = await load();\n const reservation = source.bytes.byteLength * 8;\n let isReserved = false;\n try {\n ledger.reserve(reservation);\n isReserved = true;\n let text: string | null;\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(source.bytes);\n } catch {\n text = null;\n }\n return { text, release: () => ledger.release(reservation) };\n } catch (error) {\n if (isReserved) ledger.release(reservation);\n throw error;\n } finally {\n source.release();\n }\n};\n\n/** Distinguishes missing and non-regular files without an extra entry lookup or following symlinks. */\nexport const getAbsentKind = (error: unknown): 'missing' | 'non-regular' | null =>\n error instanceof RepositorySourceException\n ? error.code === 'ENTRY_NOT_FOUND'\n ? 'missing'\n : error.code === 'ENTRY_NOT_FILE'\n ? 'non-regular'\n : null\n : null;\n","import type { IMarkedRegion } from 'jg-utilities';\n\nimport { parseRepositoryPath, resolveRepositoryLink } from '@moldea.ai/repository';\n\nimport type { IRetainedSource } from '../retained-memory/index.js';\n\nimport { parseIntegrationBlock, parseManagedIntegrationRegion } from './parser.js';\nimport type {\n IAgentsInstructionTarget,\n IIntegrationInspectionContext,\n IUnresolvedLinkState,\n} from './types.js';\nimport { getAbsentKind, readRetainedText } from './utilities.js';\n\nconst AGENTS_PATH = parseRepositoryPath('/AGENTS.md');\n\ntype IReport = (\n code: Parameters<IIntegrationInspectionContext['report']>[0],\n details: Record<string, string>,\n qualifier?: IUnresolvedLinkState,\n) => void;\n\n/** Reports an AGENTS.md link that doesn't lead to a file, with its reason as the qualifier. */\nconst reportUnresolvedLink = (report: IReport, reason: IUnresolvedLinkState): void =>\n report('MOLDEA_INTEGRATION_LINK_UNRESOLVED', { entryKind: 'symlink', reason }, reason);\n\n/**\n * Checks one readable AGENTS.md text against its referenced skill installation.\n * @returns A promise that settles after at most one integration warning was recorded.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation was aborted.\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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n */\nconst checkAgentsDocument = async (\n context: IIntegrationInspectionContext,\n report: IReport,\n load: () => Promise<IRetainedSource>,\n entryDetails: Record<string, string>,\n): Promise<void> => {\n const { ledger, reader, signal } = context;\n let document: Awaited<ReturnType<typeof readRetainedText>>;\n try {\n document = await readRetainedText(ledger, load);\n } catch (error) {\n const absentKind = getAbsentKind(error);\n if (absentKind === null) throw error;\n return entryDetails['entryKind'] === 'symlink'\n ? reportUnresolvedLink(report, absentKind === 'missing' ? 'missing' : 'not-file')\n : report('MOLDEA_INTEGRATION_BLOCK_MISSING', { entryKind: absentKind });\n }\n try {\n if (document.text === null)\n return report('MOLDEA_INTEGRATION_BLOCK_MISSING', {\n ...entryDetails,\n reason: 'invalid-utf8',\n });\n const parsed = parseIntegrationBlock(document.text);\n if (parsed.kind === 'missing')\n return report(\n parsed.reason.startsWith('block-')\n ? 'MOLDEA_INTEGRATION_BLOCK_MISSING'\n : 'MOLDEA_INTEGRATION_SKILL_MISSING',\n { ...entryDetails, reason: parsed.reason },\n );\n const { skillPath } = parsed;\n for (const file of ['SKILL.md', 'scripts/relevance-gate.mjs']) {\n const path = parseRepositoryPath(`/${skillPath}/${file}`);\n const skillEntry = await reader.getEntry(path, signal === undefined ? undefined : { signal });\n if (skillEntry?.type !== 'file')\n return report('MOLDEA_INTEGRATION_SKILL_MISSING', {\n referencedPath: `/${skillPath}`,\n missingFile: path,\n entryKind: skillEntry?.type ?? 'missing',\n });\n }\n const assetPath = parseRepositoryPath(`/${skillPath}/assets/managed-agents-block.md`);\n let asset: Awaited<ReturnType<typeof readRetainedText>>;\n try {\n asset = await readRetainedText(ledger, () => ledger.readSourceFile(assetPath));\n } catch (error) {\n const entryKind = getAbsentKind(error);\n if (entryKind !== null)\n return report('MOLDEA_INTEGRATION_SKILL_MISSING', {\n referencedPath: `/${skillPath}`,\n missingFile: assetPath,\n entryKind,\n });\n throw error;\n }\n try {\n if (asset.text === null)\n return report('MOLDEA_INTEGRATION_BLOCK_STALE', {\n referencedPath: `/${skillPath}`,\n reason: 'invalid-utf8-asset',\n });\n const region = parseManagedIntegrationRegion(document.text) as IMarkedRegion;\n let occurrences = 0;\n let offset = 0;\n while ((offset = asset.text.indexOf('{{skill-path}}', offset)) !== -1) {\n occurrences++;\n offset += '{{skill-path}}'.length;\n }\n const renderedReservation = (asset.text.length + occurrences * skillPath.length) * 8;\n ledger.reserve(renderedReservation);\n try {\n const expected = asset.text\n .replaceAll('{{skill-path}}', skillPath)\n .replace(/\\r\\n?/g, '\\n')\n .replaceAll('\\n', region.lineEnding);\n if (document.text.slice(region.start, region.end) !== expected)\n return report('MOLDEA_INTEGRATION_BLOCK_STALE', { referencedPath: `/${skillPath}` });\n } finally {\n ledger.release(renderedReservation);\n }\n } finally {\n asset.release();\n }\n } finally {\n document.release();\n }\n};\n\n/**\n * Checks root AGENTS.md against its referenced skill installation. A symlinked AGENTS.md that\n * leads to a regular file in the repository is checked on that file's text; any other link is\n * reported with its reason, without reading anything outside the repository.\n * @param context The instruction view, repository reader, ledger, and warning recorder.\n * @returns What AGENTS.md is, including its link resolution, for the Claude Code check.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation was aborted.\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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n */\nexport const inspectAgentsIntegration = async (\n context: IIntegrationInspectionContext,\n): Promise<IAgentsInstructionTarget> => {\n const { instructions } = context;\n const report: IReport = (code, details, qualifier) =>\n context.report(code, AGENTS_PATH, details, qualifier);\n const entry = await instructions.getEntry(AGENTS_PATH);\n\n if (entry === null) {\n report('MOLDEA_INTEGRATION_BLOCK_MISSING', { entryKind: 'missing' });\n return { kind: 'missing' };\n }\n\n if (entry.type === 'directory') {\n report('MOLDEA_INTEGRATION_BLOCK_MISSING', { entryKind: 'directory' });\n return { kind: 'directory' };\n }\n\n if (entry.type === 'file') {\n await checkAgentsDocument(context, report, () => instructions.readSourceFile(AGENTS_PATH), {\n entryKind: 'file',\n });\n return { kind: 'file' };\n }\n\n const resolution = await resolveRepositoryLink(instructions, AGENTS_PATH);\n\n if (resolution.state === 'file') {\n const { targetPath } = resolution;\n await checkAgentsDocument(context, report, () => instructions.readSourceFile(targetPath), {\n entryKind: 'symlink',\n });\n } else {\n reportUnresolvedLink(report, resolution.state);\n }\n\n return { kind: 'link', resolution };\n};\n","import {\n parseRepositoryPath,\n resolveRepositoryLink,\n type IRepositoryLinkResolution,\n type IRepositoryPath,\n} from '@moldea.ai/repository';\n\nimport type { IRetainedSource } from '../retained-memory/index.js';\n\nimport { hasAgentsImport } from './parser.js';\nimport type {\n IAgentsInstructionTarget,\n IIntegrationInspectionContext,\n IUnresolvedLinkState,\n} from './types.js';\nimport { getAbsentKind, readRetainedText } from './utilities.js';\n\nconst AGENTS_PATH = parseRepositoryPath('/AGENTS.md');\nconst CLAUDE_PATH = parseRepositoryPath('/CLAUDE.md');\nconst NESTED_CLAUDE_PATH = parseRepositoryPath('/.claude/CLAUDE.md');\nconst LOCAL_CLAUDE_PATH = parseRepositoryPath('/CLAUDE.local.md');\n\n// whether one Claude Code instruction file loads AGENTS.md\ntype IClaudeAssessment =\n | { readonly kind: 'absent' | 'loads' }\n | { readonly entryKind: string; readonly kind: 'not-loading' }\n | { readonly kind: 'unresolved'; readonly reason: IUnresolvedLinkState };\n\ntype IClaudePath = typeof CLAUDE_PATH;\n\n/** Returns the regular file AGENTS.md leads to, or null when it leads to none. */\nconst getAgentsTargetPath = (agents: IAgentsInstructionTarget): IRepositoryPath | null => {\n if (agents.kind === 'file') return AGENTS_PATH;\n return agents.kind === 'link' && agents.resolution.state === 'file'\n ? agents.resolution.targetPath\n : null;\n};\n\n/** Recognizes a link between a Claude file and AGENTS.md by final target path, without reading. */\nconst isLinkedToAgents = (\n path: IClaudePath,\n resolution: IRepositoryLinkResolution | null,\n agents: IAgentsInstructionTarget,\n): boolean => {\n const agentsTargetPath = getAgentsTargetPath(agents);\n\n // AGENTS.md itself links to this Claude file\n if (agents.kind === 'link' && agentsTargetPath === path) return true;\n return resolution?.state === 'file' && resolution.targetPath === agentsTargetPath;\n};\n\n/**\n * Determines whether one Claude Code file loads AGENTS.md through an import line, a link to the\n * same final target, or AGENTS.md linking to it. A linked Claude file with a regular-file target\n * is checked for an import line as if the file were at the link's own location.\n * @returns The assessment, reading at most the file or its link target once.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation was aborted.\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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n */\nconst assessClaudeFile = async (\n context: IIntegrationInspectionContext,\n path: IClaudePath,\n agents: IAgentsInstructionTarget,\n): Promise<IClaudeAssessment> => {\n const { instructions, ledger } = context;\n const entry = await instructions.getEntry(path);\n\n if (entry === null) return { kind: 'absent' };\n if (isLinkedToAgents(path, null, agents)) return { kind: 'loads' };\n if (entry.type === 'directory') return { entryKind: 'directory', kind: 'not-loading' };\n\n let load: () => Promise<IRetainedSource> = () => instructions.readSourceFile(path);\n\n if (entry.type === 'symlink') {\n const resolution = await resolveRepositoryLink(instructions, path);\n if (isLinkedToAgents(path, resolution, agents)) return { kind: 'loads' };\n if (resolution.state !== 'file') return { kind: 'unresolved', reason: resolution.state };\n const { targetPath } = resolution;\n load = () => instructions.readSourceFile(targetPath);\n }\n\n let document: Awaited<ReturnType<typeof readRetainedText>>;\n try {\n document = await readRetainedText(ledger, load);\n } catch (error) {\n const absentKind = getAbsentKind(error);\n if (absentKind === null) throw error;\n if (entry.type !== 'symlink') return { kind: 'absent' };\n return { kind: 'unresolved', reason: absentKind === 'missing' ? 'missing' : 'not-file' };\n }\n try {\n return document.text !== null && hasAgentsImport(document.text, path === NESTED_CLAUDE_PATH)\n ? { kind: 'loads' }\n : { entryKind: entry.type, kind: 'not-loading' };\n } finally {\n document.release();\n }\n};\n\n/**\n * Checks whether Claude Code loads AGENTS.md. When `/CLAUDE.md` or `/.claude/CLAUDE.md` exists,\n * only those shared files count; `/CLAUDE.local.md` counts only when neither exists. At most one\n * Claude warning is recorded: an unresolved link for the first counted file whose link doesn't\n * lead to a file in the repository when none loads AGENTS.md, otherwise a missing import for the\n * governing file.\n * @param context The instruction view, ledger, and warning recorder.\n * @param agents What root AGENTS.md is, as the AGENTS.md check observed it.\n * @returns A promise that settles after at most one Claude warning was recorded.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation was aborted.\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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n */\nexport const inspectClaudeIntegration = async (\n context: IIntegrationInspectionContext,\n agents: IAgentsInstructionTarget,\n): Promise<void> => {\n const counted: { path: IClaudePath; assessment: IClaudeAssessment }[] = [];\n\n for (const path of [CLAUDE_PATH, NESTED_CLAUDE_PATH]) {\n const assessment = await assessClaudeFile(context, path, agents);\n if (assessment.kind === 'loads') return;\n if (assessment.kind !== 'absent') counted.push({ assessment, path });\n }\n\n if (counted.length === 0) {\n const assessment = await assessClaudeFile(context, LOCAL_CLAUDE_PATH, agents);\n if (assessment.kind === 'absent' || assessment.kind === 'loads') return;\n counted.push({ assessment, path: LOCAL_CLAUDE_PATH });\n }\n\n const unresolved = counted.find(({ assessment }) => assessment.kind === 'unresolved');\n\n if (unresolved?.assessment.kind === 'unresolved') {\n const { reason } = unresolved.assessment;\n context.report(\n 'MOLDEA_INTEGRATION_LINK_UNRESOLVED',\n unresolved.path,\n { entryKind: 'symlink', reason },\n reason,\n );\n return;\n }\n\n const governing = counted[0];\n\n if (governing?.assessment.kind === 'not-loading') {\n context.report('MOLDEA_INTEGRATION_CLAUDE_IMPORT_MISSING', governing.path, {\n entryKind: governing.assessment.entryKind,\n });\n }\n};\n","import type { ICoreResourceLimits } from '../contracts/index.js';\nimport { createCoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic } from '../diagnostics/index.js';\nimport type {\n IRepositoryInspectionReader,\n IRepositoryInstructionView,\n} from '../repository-inspection-session/index.js';\nimport { getRetainedMemory } from '../retained-memory/index.js';\n\nimport { inspectAgentsIntegration } from './agents-inspection.js';\nimport { inspectClaudeIntegration } from './claude-inspection.js';\nimport type { IIntegrationInspectionContext } from './types.js';\n\n/**\n * Checks the coding-agent integration: root AGENTS.md and the Claude Code instruction files\n * through the instruction view, and the referenced skill installation through the repository\n * reader. It reads at most four instruction files, follows at most 32 links for each with one\n * lookup and one link-text read per link, and makes at most five bounded reads, all inside the\n * repository.\n * @param reader The repository inspection reader for skill files and the managed asset.\n * @param instructions The instruction view that routes the four instruction paths and links.\n * @param limits The immutable resource limits for the inspection.\n * @param signal Optional cancellation for repository lookups.\n * @returns Completed content-free integration warnings, never an execution or runtime-wiring claim.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation was aborted.\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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n */\nexport const inspectCodingAgentIntegration = async (\n reader: IRepositoryInspectionReader,\n instructions: IRepositoryInstructionView,\n limits: ICoreResourceLimits,\n signal?: AbortSignal,\n): Promise<readonly ICoreDiagnostic[]> => {\n const collector = createCoreDiagnosticCollector(limits, 'validate-project');\n const context: IIntegrationInspectionContext = {\n instructions,\n ledger: getRetainedMemory(reader),\n reader,\n report: (code, subject, details, qualifier) => {\n collector.add({\n code,\n path: subject,\n subject,\n qualifier: qualifier ?? null,\n entity: { integrationPath: subject },\n details,\n });\n },\n ...(signal === undefined ? {} : { signal }),\n };\n const agents = await inspectAgentsIntegration(context);\n await inspectClaudeIntegration(context, agents);\n return collector.finalize();\n};\n","import {\n parseRepositoryPath,\n RepositorySourceException,\n type IRepositoryPath,\n} from '@moldea.ai/repository';\n\nimport type { ICoreResourceLimits } from '../contracts/index.js';\nimport { createCoreDiagnosticCollector } from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic, IDiagnosticEntity } from '../diagnostics/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\nimport type { IMoldeaManifestV1 } from '../format/index.js';\nimport { parseDecisionIdFromPath } from '../format-validation/index.js';\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\nimport {\n collectManifestScopeDeclarations,\n matchesRepositoryGlob,\n type IManifestScopeOwner,\n} from '../scope-matching/index.js';\n\ntype IDeclaration = ReturnType<typeof collectManifestScopeDeclarations>[number];\ninterface IPattern {\n declaration: IDeclaration;\n pattern: string;\n segments: string[];\n}\n\n/** Identifies the canonical document owning an impact relationship. */\nconst getOwner = (\n owner: IManifestScopeOwner,\n): { subject: IRepositoryPath; entity: IDiagnosticEntity } => {\n if (owner.kind === 'context')\n return {\n subject: parseRepositoryPath(owner.id),\n entity: { contextPath: parseRepositoryPath(owner.id) },\n };\n if (owner.kind === 'decision')\n return {\n subject: parseRepositoryPath(owner.id),\n entity: { decisionId: parseDecisionIdFromPath(parseRepositoryPath(owner.id)) ?? owner.id },\n };\n const agentId = owner.agentId ?? owner.id;\n return {\n subject: parseRepositoryPath(`/moldea/agents/${agentId}/instruction.md`),\n entity: {\n agentId,\n ...(owner.kind === 'tool' || owner.kind === 'skill'\n ? { capabilityId: owner.id, capabilityKind: owner.kind }\n : {}),\n },\n };\n};\n\n/** Groups patterns by their complete fixed directory prefix to share source traversal. */\nconst groupPatterns = (manifest: IMoldeaManifestV1): Map<IRepositoryPath, IPattern[]> => {\n const groups = new Map<IRepositoryPath, IPattern[]>();\n for (const declaration of collectManifestScopeDeclarations(manifest)) {\n if (declaration.field !== 'affectedBy' || declaration.declaration.kind !== 'glob') continue;\n const pattern = declaration.declaration.pattern;\n const segments = pattern.slice(1).split('/');\n const wildcard = segments.findIndex((segment) => segment.includes('*'));\n const prefix = parseRepositoryPath('/' + segments.slice(0, wildcard).join('/'));\n const group = groups.get(prefix) ?? [];\n group.push({ declaration, pattern, segments });\n groups.set(prefix, group);\n }\n return groups;\n};\n\n/**\n * Checks globs only after required inspection, sharing bounded traversals and stopping on matches.\n * @returns Completed warnings, or no warnings when any traversal exhausts its resource budget.\n * @throws\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation was aborted.\n * - ENTRY_NOT_FOUND: The requested repository entry was not found.\n * - ENTRY_NOT_DIRECTORY: The requested repository entry is not a directory.\n * - PROVIDER_INCOMPLETE: The repository provider cannot expose a complete result.\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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nexport const inspectImpactPatterns = async (\n reader: IRepositoryInspectionReader,\n manifest: IMoldeaManifestV1,\n limits: ICoreResourceLimits,\n signal?: AbortSignal,\n): Promise<{ completed: boolean; diagnostics: readonly ICoreDiagnostic[] }> => {\n const unmatched: IPattern[] = [];\n try {\n for (const [prefix, patterns] of groupPatterns(manifest)) {\n const pending = new Set(patterns);\n const entry = await reader.getEntry(prefix, signal === undefined ? undefined : { signal });\n if (entry?.type === 'directory') {\n for await (const candidate of reader.iterateEntries({\n prefix,\n ...(signal === undefined ? {} : { signal }),\n })) {\n if (candidate.type !== 'file') continue;\n for (const pattern of pending)\n if (matchesRepositoryGlob(pattern.segments, candidate.path)) pending.delete(pattern);\n if (pending.size === 0) break;\n }\n }\n unmatched.push(...pending);\n }\n } catch (error) {\n if (\n (error instanceof CoreOperationException && error.code === 'RESOURCE_LIMIT_EXCEEDED') ||\n (error instanceof RepositorySourceException && error.code === 'RESOURCE_LIMIT_EXCEEDED')\n )\n return { completed: false, diagnostics: [] };\n throw error;\n }\n const collector = createCoreDiagnosticCollector(limits, 'validate-project');\n for (const { declaration, pattern } of unmatched) {\n const { subject, entity } = getOwner(declaration.owner);\n collector.add({\n code: 'MOLDEA_IMPACT_PATTERN_UNMATCHED',\n path: parseRepositoryPath('/moldea/moldea.yaml'),\n pointer: declaration.pointer,\n subject,\n qualifier: pattern,\n entity,\n details: { pattern, owner: subject },\n });\n }\n return { completed: true, diagnostics: collector.finalize() };\n};\n","import { deepFreeze } from 'jg-utilities';\n\nimport { parseRepositoryPath } from '@moldea.ai/repository';\n\nimport type { ICoreResourceLimits } from '../contracts/index.js';\nimport {\n createCoreDiagnosticCollector,\n normalizeDiagnostics,\n} from '../diagnostic-utilities/index.js';\nimport type { ICoreDiagnostic, ICoreWarningCode } from '../diagnostics/index.js';\nimport type { IAcceptedWarningManifestEntry } from '../format/index.js';\n\nconst identity = (entry: { code: string; subject: string; qualifier?: string | null }): string =>\n JSON.stringify([entry.code, entry.subject, entry.qualifier ?? null]);\n\n/**\n * Applies explicit manifest acceptances only to checks that completed, retaining all findings.\n * @returns Normalized diagnostics with acceptance flags, reasons, and obsolete-acceptance warnings.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n */\nexport const applyWarningAcceptances = (\n diagnostics: readonly ICoreDiagnostic[],\n entries: readonly IAcceptedWarningManifestEntry[],\n completed: ReadonlySet<ICoreWarningCode>,\n limits: ICoreResourceLimits,\n): readonly ICoreDiagnostic[] => {\n const acceptances = new Map(entries.map((entry, index) => [identity(entry), { entry, index }]));\n const matched = new Set<string>();\n const results = diagnostics.map((diagnostic) => {\n if (\n diagnostic.severity !== 'warning' ||\n !diagnostic.acceptable ||\n !completed.has(diagnostic.code)\n )\n return diagnostic;\n const key = identity(diagnostic);\n const acceptance = acceptances.get(key);\n if (acceptance === undefined) return diagnostic;\n matched.add(key);\n return deepFreeze({\n ...diagnostic,\n accepted: true as const,\n reason: acceptance.entry.reason,\n });\n });\n const collector = createCoreDiagnosticCollector(limits, 'validate-project');\n for (const [key, { entry, index }] of acceptances) {\n if (matched.has(key) || !completed.has(entry.code)) continue;\n const pointer = `/acceptedWarnings/${index}`;\n collector.add({\n code: 'MOLDEA_ACCEPTANCE_UNMATCHED',\n path: parseRepositoryPath('/moldea/moldea.yaml'),\n pointer,\n subject: parseRepositoryPath('/moldea/moldea.yaml'),\n qualifier: pointer,\n details: { code: entry.code, subject: entry.subject, qualifier: entry.qualifier ?? null },\n });\n }\n return normalizeDiagnostics([...results, ...collector.finalize()]);\n};\n","import { compareCodePoints, deepFreeze } from 'jg-utilities';\n\nimport 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 { 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) => compareCodePoints(left.id, right.id))) {\n const mirrors: IIndexedMirror[] = [];\n\n if (agent.instruction !== null) {\n const declaredMirrors = agent.declaration.mirrors ?? [];\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 deepFreeze({\n agentMirrors,\n diagnostics,\n valid: diagnostics.length === 0,\n });\n};\n","import { compareCodePoints, deepFreeze } from 'jg-utilities';\n\nimport 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 { hasNonWhitespace } from '../format-validation/index.js';\nimport type { IMoldeaManifestV1 } from '../format/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 deepFreeze({\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(compareCodePoints)) {\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 deepFreeze({\n context,\n diagnostics,\n project: inspectedProject.project,\n valid: diagnostics.length === 0,\n });\n};\n","import { compareCodePoints, deepFreeze } from 'jg-utilities';\n\nimport 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 type { IParsedDecision } from '../format/index.js';\nimport { createNullPrototypeRecord } 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 compareCodePoints(left.id, right.id) || compareCodePoints(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) => compareCodePoints(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(compareCodePoints),\n decisions: [...(agent.declaration.decisions ?? [])].sort(compareCodePoints),\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) => compareCodePoints(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 deepFreeze({\n agents,\n context: [...input.context].sort((left, right) =>\n compareCodePoints(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 compareCodePoints(left.asset.path, right.asset.path),\n ),\n unresolved,\n });\n};\n","import { RepositorySourceException, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport type { IRepositoryInspectionReader } from '../repository-inspection-session/index.js';\nimport { getRetainedMemory } from '../retained-memory/index.js';\n\nimport type { IExportInventory } from './types.js';\n\n// 512 bytes per potential syntax node, conservatively bounded by source byte length\nconst NODE_BYTES_PER_SOURCE_BYTE = 512;\n\n/** Identifies syntax-only source formats with explicit runtime export semantics. */\nexport const isSupportedExportSource = (path: string): boolean =>\n !/\\.d\\.(?:ts|tsx|mts|cts)$/.test(path) && /\\.(?:ts|tsx|mts|cts|js|mjs|jsx)$/.test(path);\n\n/**\n * Checks a declared source when budgets allow, retaining only its export-name set.\n * @returns A conclusive inventory or the precise reason analysis could not run.\n * @throws\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation was aborted.\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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - ENTRY_NOT_FOUND: The requested repository entry was not found.\n * - ENTRY_NOT_FILE: The requested repository entry is not a file.\n */\nexport const readExportInventory = async (\n reader: IRepositoryInspectionReader,\n path: IRepositoryPath,\n byteLength: number,\n maxFileBytes: number,\n): Promise<IExportInventory> => {\n if (!isSupportedExportSource(path))\n return { kind: 'not-checked', reason: 'unsupported-file-type' };\n const ledger = getRetainedMemory(reader);\n const reservation = 65_536 + byteLength * (8 + NODE_BYTES_PER_SOURCE_BYTE);\n // source bytes and the first page coexist with the syntax reservation during the read\n const readHeadroom = Math.max(1, byteLength + Math.min(65_536, byteLength));\n if (byteLength > maxFileBytes || !ledger.tryReserve(reservation + readHeadroom))\n return { kind: 'not-checked', reason: 'resource-limit' };\n ledger.release(readHeadroom);\n try {\n const source = await ledger.readSourceFile(path);\n try {\n if (source.bytes.byteLength !== byteLength)\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n const { inventoryExports } = await import('./syntax.js');\n const result = inventoryExports(path, source.bytes);\n if (result.kind === 'parsed') {\n let bytes = 64;\n for (const name of result.names) bytes += 64 + name.length * 2;\n // Admission includes the inventory while the syntax reservation is still live.\n ledger.reserve(bytes);\n }\n return result;\n } finally {\n source.release();\n }\n } finally {\n ledger.release(reservation);\n }\n};\n","import { compareCodePoints } from 'jg-utilities';\n\nimport {\n parseRepositoryPath,\n type IRepositoryEntry,\n type IRepositoryOperationOptions,\n type IRepositoryPath,\n} from '@moldea.ai/repository';\n\nimport type { IBindingCoverage, IBindingRelationship } from '../binding-coverage/index.js';\nimport { readExportInventory, type IExportInventory } from '../export-inventory/index.js';\nimport { CoreOperationException } from '../exceptions/index.js';\nimport { reserveRetainedBytesIfTracked } from '../retained-memory/index.js';\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 { 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 readonly symbol?: string;\n readonly relationship?: IBindingRelationship;\n}\n\nconst childPointer = (pointer: string, segment: string): string => {\n return `${pointer}/${escapeJsonPointerSegment(segment)}`;\n};\n\n/** Adds repository-reference array entries with their authored indexes. */\nconst addReferenceCandidates = (\n candidates: IRepositoryCandidate[],\n references: readonly IRepositoryReference[] | undefined,\n pointer: string,\n entity: IDiagnosticEntity | null,\n relationship?: IBindingRelationship,\n): void => {\n for (const [index, reference] of (references ?? []).entries()) {\n candidates.push({\n entity,\n kind: 'reference',\n path: reference.path,\n pointer: childPointer(pointer, String(index)),\n ...(relationship === undefined ? {} : { relationship }),\n ...(reference.symbol === undefined ? {} : { symbol: reference.symbol }),\n });\n }\n};\n\n/** Adds exact impact paths while retaining authored indexes for skipped globs. */\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 ?? []).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 pointer.startsWith('/context/') ? 'context-binding' : 'decision-binding',\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(compareCodePoints)) {\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 relationship: `${capabilityKind}-implementation`,\n ...(capability.implementation.symbol === undefined\n ? {}\n : { symbol: capability.implementation.symbol }),\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 relationship:\n `${capabilityKind}-${property === 'inputSchema' ? 'input-schema' : property === 'outputSchema' ? 'output-schema' : 'registration'}` as IBindingRelationship,\n ...(reference.symbol === undefined ? {} : { symbol: reference.symbol }),\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 relationship: (\n {\n runtimeAgent: 'runtime-agent',\n inputSchema: 'agent-input-schema',\n outputSchema: 'agent-output-schema',\n instructionLoader: 'instruction-loader',\n } as const\n )[property],\n ...(reference.symbol === undefined ? {} : { symbol: reference.symbol }),\n });\n }\n }\n\n for (const variableId of Object.keys(bindings?.variableProviders ?? {}).sort(compareCodePoints)) {\n const reference = bindings?.variableProviders?.[variableId];\n\n if (reference !== undefined) {\n candidates.push({\n entity: { agentId, variableId },\n relationship: 'variable-provider',\n ...(reference.symbol === undefined ? {} : { symbol: reference.symbol }),\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(compareCodePoints)) {\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(compareCodePoints)) {\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(compareCodePoints)) {\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 ? { contextPath: parseRepositoryPath(referencedPath) } : { decisionId },\n );\n }\n }\n\n addUnresolvedCandidates(candidates, manifest.unresolved, '/unresolved', null);\n\n for (const agentId of Object.keys(manifest.agents ?? {}).sort(compareCodePoints)) {\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) => compareCodePoints(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 * @param coverage Operation-owned binding coverage populated only for regular files.\n * @returns Deeply immutable deterministic repository-reference diagnostics.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - ENTRY_NOT_FOUND: The requested repository entry was not found.\n * - ENTRY_NOT_FILE: The requested repository entry is not a 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 operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The repository operation 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 coverage: IBindingCoverage[] = [],\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 inventories = new Map<IRepositoryPath, IExportInventory>();\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 const entry = await entryPromise;\n validateCandidate(candidate, entry, manifestPath, collector);\n if (entry?.type !== 'file' || candidate.relationship === undefined) continue;\n if (entry.byteLength === null)\n throw new TypeError('A repository file entry must declare its byte length.');\n if (coverage.length >= limits.maxCoverage)\n throw new CoreOperationException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n operation: 'validate-project',\n limit: 'maxCoverage',\n limitMaximum: limits.maxCoverage,\n observedUsage: coverage.length + 1,\n nextAction: 'reduce-input-or-increase-limit',\n });\n const base = {\n entity: candidate.entity ?? {},\n relationship: candidate.relationship,\n path: candidate.path,\n symbol: candidate.symbol ?? null,\n fileCheck: 'passed' as const,\n };\n let record: IBindingCoverage;\n if (candidate.symbol === undefined) {\n record = { ...base, exportCheck: 'not-checked', exportNotCheckedReason: 'no-symbol' };\n } else {\n let inventory = inventories.get(candidate.path);\n if (inventory === undefined) {\n inventory = await readExportInventory(\n repository,\n candidate.path,\n entry.byteLength,\n limits.maxFileBytes,\n );\n inventories.set(candidate.path, inventory);\n }\n if (inventory.kind === 'not-checked')\n record = { ...base, exportCheck: 'not-checked', exportNotCheckedReason: inventory.reason };\n else if (!inventory.complete)\n record = {\n ...base,\n exportCheck: 'not-checked',\n exportNotCheckedReason: 'unresolved-exports',\n };\n else if (inventory.names.has(candidate.symbol)) record = { ...base, exportCheck: 'passed' };\n else {\n record = { ...base, exportCheck: 'failed' };\n collector.add({\n code: 'MOLDEA_REFERENCE_EXPORT_MISSING',\n entity: candidate.entity,\n path: manifestPath,\n pointer: candidate.pointer,\n details: {\n referencedPath: candidate.path,\n symbol: candidate.symbol,\n relationship: candidate.relationship,\n },\n });\n }\n }\n // Coverage admission is bounded independently from diagnostics and source parsing.\n reserveRetainedBytesIfTracked(repository, 512 + JSON.stringify(record).length * 2);\n coverage.push(record);\n }\n\n return collector.finalize();\n};\n","import { compareCodePoints, deepFreeze } from 'jg-utilities';\n\nimport 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 { hasNonWhitespace } from '../format-validation/index.js';\nimport type { IMoldeaManifestV1 } from '../format/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(compareCodePoints)) {\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(compareCodePoints)) {\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 deepFreeze({\n diagnostics,\n runtimes,\n valid: diagnostics.length === 0,\n });\n};\n","import { deepFreeze } from 'jg-utilities';\n\nimport { 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 { IBindingCoverage } from '../binding-coverage/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 { validateManifestRelationships } from '../manifest-relationship-validation/index.js';\nimport { inspectManifestDocument } from '../manifest/index.js';\nimport { inspectCodingAgentIntegration } from '../integration-validation/index.js';\nimport { inspectImpactPatterns } from '../impact-pattern-validation/index.js';\nimport { applyWarningAcceptances } from '../warning-acceptance/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 universal validation result and checked bindings\nexport interface IUniversalProjectInspectionResult {\n readonly formatVersion: IRepositoryFormatVersion | null;\n readonly project: IMoldeaProjectIndex | null;\n readonly diagnostics: readonly ICoreDiagnostic[];\n readonly coverage: readonly IBindingCoverage[];\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 with syntax-only export checks.\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: The repository path is invalid.\n * - ENTRY_NOT_FOUND: The requested repository entry was not found.\n * - ENTRY_NOT_FILE: The requested repository entry is not a file.\n * - ENTRY_NOT_DIRECTORY: The 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 the operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - ABORTED: The Core operation was aborted.\n * - ABORTED: The 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 coverage: IBindingCoverage[] = [];\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\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 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 coverage,\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 addDiagnostics(\n collector,\n await inspectCodingAgentIntegration(\n session.reader,\n session.instructions,\n options.limits,\n signal,\n ),\n );\n const patterns =\n indexedManifest === null\n ? { completed: false, diagnostics: [] }\n : await inspectImpactPatterns(session.reader, indexedManifest.value, options.limits, signal);\n session.throwIfAborted();\n addDiagnostics(collector, patterns.diagnostics);\n const diagnostics = applyWarningAcceptances(\n collector.finalize(),\n indexedManifest?.value.acceptedWarnings ?? [],\n new Set([\n ...([\n 'MOLDEA_INTEGRATION_BLOCK_MISSING',\n 'MOLDEA_INTEGRATION_SKILL_MISSING',\n 'MOLDEA_INTEGRATION_BLOCK_STALE',\n 'MOLDEA_INTEGRATION_LINK_UNRESOLVED',\n 'MOLDEA_INTEGRATION_CLAUDE_IMPORT_MISSING',\n ] as const),\n ...(patterns.completed ? ['MOLDEA_IMPACT_PATTERN_UNMATCHED' as const] : []),\n ]),\n options.limits,\n );\n const project =\n !diagnostics.some((diagnostic) => diagnostic.severity === 'error') &&\n indexedManifest !== null &&\n 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 deepFreeze({\n diagnostics,\n coverage,\n formatVersion,\n project,\n });\n};\n","import { deepFreeze, isObjectValid } from 'jg-utilities';\n\nimport type { IRepositoryReader } from '@moldea.ai/repository';\n\nimport { countBindingCoverage } from '../binding-coverage/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 { 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 instructions?: IRepositoryReader;\n readonly repository: IRepositoryReader;\n readonly signal?: AbortSignal;\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 isObjectValid(candidate, true) &&\n isObjectValid(candidate['snapshot'], true) &&\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 typeof candidate['readLinkText'] === 'function'\n );\n};\n\nconst isAbortSignal = (candidate: unknown): candidate is AbortSignal => {\n return (\n isObjectValid(candidate, true) &&\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 (!isObjectValid(candidate, true)) {\n return invalidArgument();\n }\n\n const repository: unknown = candidate['repository'];\n const instructions: unknown = candidate['instructions'];\n const signal: unknown = candidate['signal'];\n\n if (\n Reflect.ownKeys(candidate).some(\n (key) => key !== 'repository' && key !== 'instructions' && key !== 'signal',\n ) ||\n !isRepositoryReader(repository) ||\n (instructions !== undefined && !isRepositoryReader(instructions)) ||\n (signal !== undefined && !isAbortSignal(signal))\n ) {\n return invalidArgument();\n }\n\n return {\n ...(instructions === undefined ? {} : { instructions }),\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 file and export validation.\n * @param input The untrusted source-neutral reader, optional instruction reader, and 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: The repository path is invalid.\n * - ENTRY_NOT_FOUND: The requested repository entry was not found.\n * - ENTRY_NOT_FILE: The requested repository entry is not a file.\n * - ENTRY_NOT_DIRECTORY: The 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 the operation.\n * - PROVIDER_INCOMPLETE: The repository provider cannot expose a complete result.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n * - ABORTED: The Core operation was aborted.\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 validatedInput.instructions,\n );\n const universal = await inspectUniversalProject(\n {\n session,\n ...(validatedInput.signal === undefined ? {} : { signal: validatedInput.signal }),\n },\n operationOptions,\n );\n\n session.throwIfAborted();\n const counts = countDiagnosticsBySeverity(universal.diagnostics);\n return deepFreeze({\n project: universal.project,\n resourceUsage: session.getResourceUsage(),\n result: {\n diagnostics: universal.diagnostics,\n ...counts,\n coverage: universal.coverage,\n coverageCounts: countBindingCoverage(universal.coverage),\n formatVersion: universal.formatVersion,\n source: validatedInput.repository.snapshot,\n summary: universal.project === null ? null : createProjectSummary(universal.project),\n valid: counts.errorCount === 0,\n },\n });\n};\n\n/**\n * Validates one project without returning canonical document bodies.\n * @param input The source-neutral reader and optional cancellation signal.\n * @param options The immutable operation limits.\n * @returns A promise resolving to the complete validation result.\n * @throws\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - ENTRY_NOT_FOUND: The requested repository entry was not found.\n * - ENTRY_NOT_FILE: The requested repository entry is not a file.\n * - ENTRY_NOT_DIRECTORY: The 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 the operation.\n * - PROVIDER_INCOMPLETE: The repository provider cannot expose a complete result.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n * - ABORTED: The Core operation was aborted.\n */\nexport const validateProject = async (\n input: IProjectValidationInput,\n options: ICoreOptionsSnapshot,\n): Promise<IProjectValidationResult> => (await validateProjectState(input, options)).result;\n","import { deepFreeze } from 'jg-utilities';\n\nimport { 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 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 coverageCounts: IProjectInspection['coverageCounts'];\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 = 'core7';\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.coverage.path,\n item.coverage.relationship,\n item.coverage.entity.agentId ?? '',\n createIdentity([serializeDeterministically(item.coverage)]),\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 /^core7:(all|diagnostics|coverage|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 deepFreeze({\n all: items,\n diagnostics: items.filter(({ item }) => item.kind === 'diagnostic'),\n coverage: items.filter(({ item }) => item.kind === 'coverage'),\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 coverage of state.result.coverage) {\n yield { coverage, kind: 'coverage' };\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 coverage: baseCounts.coverage,\n metadata: metadataCount,\n mirrors: baseCounts.mirrors,\n runtimes: baseCounts.runtimes,\n unresolved: baseCounts.unresolved,\n warnings: baseCounts.warnings,\n acceptedWarnings: baseCounts.acceptedWarnings,\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 coverageCounts: IProjectInspection['coverageCounts'],\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 'core7-prepared-inspection';\n yield serializeDeterministically({\n counts,\n coverageCounts,\n formatVersion,\n summary,\n valid,\n });\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 coverageCounts,\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(\n counts,\n coverageCounts,\n formatVersion,\n items,\n summary,\n valid,\n );\n const resourceUsage: IProjectInspectionResourceUsage = deepFreeze({\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 !== 'coverage' &&\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 deepFreeze({\n counts,\n coverageCounts,\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 deepFreeze({\n counts,\n coverageCounts,\n formatVersion,\n inspectionDigest,\n readPage,\n resourceUsage,\n source,\n summary,\n valid,\n });\n};\n\n/**\n * Prepares one immutable content-free inspection for synchronous bounded page reads.\n * @param input The source-neutral reader and optional cancellation signal.\n * @param options The immutable operation limits.\n * @returns A promise resolving to the complete prepared inspection.\n * @throws\n * - INVALID_ARGUMENT: The Core operation received an invalid argument.\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - ENTRY_NOT_FOUND: The requested repository entry was not found.\n * - ENTRY_NOT_FILE: The requested repository entry is not a file.\n * - ENTRY_NOT_DIRECTORY: The 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 the operation.\n * - PROVIDER_INCOMPLETE: The repository provider cannot expose a complete result.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A named repository resource limit was exceeded.\n * - RESOURCE_LIMIT_EXCEEDED: A Core resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n * - ABORTED: The Core operation was aborted.\n */\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 coverage: state.result.coverage.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 acceptedWarnings: state.result.acceptedWarningCount,\n };\n const estimate = estimatePreparedProjectInspection(\n state,\n baseCounts,\n options.limits.maxRetainedBytes,\n );\n const counts = deepFreeze(estimate.counts);\n const items = deepFreeze(createKeyedItems(iterateProjectInspectionItems(state)));\n\n return createPreparedProjectInspection({\n counts,\n coverageCounts: state.result.coverageCounts,\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 { deepFreeze } from 'jg-utilities';\n\nimport 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 { 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 resource-limit overrides.\n * @returns A frozen Core instance safe for concurrent independent operations.\n * @throws\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 deepFreeze({\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":";;;;;;;;;;;;;;;;;;;AAiBA,IAAM,UAAU,IAAI,YAAY,SAAS;CAAE,OAAO;CAAM,WAAW;AAAK,CAAC;AAEzE,IAAM,0BAA+B;CACnC,MAAM,IAAI,uBAAuB;EAC/B,MAAM;EACN,WAAW;CACb,CAAC;AACH;AAEA,IAAM,uBAA8B;CAClC,MAAM,IAAI,uBAAuB;EAC/B,MAAM;EACN,WAAW;CACb,CAAC;AACH;AAEA,IAAM,wBAAsB,cAC1B,OAAO,cAAc,YACrB,cAAc,QACd,OAAQ,UAAyC,aAAa,cAC9D,OAAQ,UAAyC,iBAAiB;AAEpE,IAAM,YAAY,OAChB,YACA,MACA,QACA,UACA,WACoF;CACpF,MAAM,SAAuB,CAAC;CAC9B,IAAI,aAAa;C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