@moldea.ai/cli 9.0.0 → 9.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"moldea.js","names":["#guardedPaths","#reader","#overlayPaths","#reader"],"sources":["../src/cli-execution/constants.ts","../src/command-line/constants.ts","../src/output-page/constants.ts","../src/output-page/exception.ts","../src/json-serialization/serializer.ts","../src/output-page/cursor.ts","../src/output-page/page.ts","../src/command-line/validations.ts","../src/command-line/parser.ts","../src/presentation/constants.ts","../src/presentation/errors.ts","../src/json-output-contract/document.ts","../src/json-output-contract/guard.ts","../src/presentation/formatters.ts","../src/presentation/transformers.ts","../src/git-working-tree/constants.ts","../src/git-working-tree/parser.ts","../src/git-working-tree/starting-directory.ts","../src/git-working-tree/discovery.ts","../src/host-path-identity/utilities.ts","../src/git-working-tree/identity/comparator.ts","../src/git-working-tree/identity/constants.ts","../src/git-working-tree/identity/inspector.ts","../src/project-content/exception.ts","../src/project-content/validations.ts","../src/project-content/executor.ts","../src/project-content/page.ts","../src/project-scope/constants.ts","../src/project-scope/exception.ts","../src/project-scope/paths.ts","../src/project-scope/executor.ts","../src/project-scope/transformers.ts","../src/repository-content-transformation-guard/exception.ts","../src/repository-content-transformation-guard/reader.ts","../src/operational-error/constants.ts","../src/operational-error/mapper.ts","../src/git-inventory/constants.ts","../src/git-inventory/content-transformation/constants.ts","../src/git-inventory/content-transformation/parser.ts","../src/git-inventory/content-transformation/classifier.ts","../src/git-inventory/entry-type/candidate-collapser.ts","../src/git-inventory/entry-type/entry-inspector.ts","../src/git-inventory/entry-type/constants.ts","../src/git-inventory/entry-type/symlink-configuration.ts","../src/git-inventory/entry-type/normalizer.ts","../src/git-inventory/logical-path/normalizer.ts","../src/git-inventory/parser.ts","../src/git-inventory/repository-ownership/boundary-inspector.ts","../src/git-inventory/repository-ownership/path-planner.ts","../src/git-inventory/repository-ownership/ownership-filter.ts","../src/git-inventory/probe.ts","../src/git-inventory/comparison/comparator.ts","../src/repository-symlink-overlay/reader.ts","../src/repository-reader/factory.ts","../src/working-tree-snapshot/executor.ts","../src/cli-execution/results.ts","../src/cli-execution/command-executor.ts","../src/cli-execution/runner.ts","../src/package-metadata/loader.ts","../src/process-signal/session.ts","../src/bin/index.ts"],"sourcesContent":["// handled process exit codes implemented by the current CLI foundation\nexport const MOLDEA_CLI_EXIT_CODES = {\n Interrupted: 130,\n OperationalError: 3,\n StructuralInvalid: 1,\n Success: 0,\n Terminated: 143,\n UsageError: 2,\n} as const;\n","// schema 5 command names accepted by the executable\nexport const MOLDEA_CLI_COMMANDS = {\n Composition: 'composition',\n Content: 'content',\n Inspect: 'inspect',\n Scope: 'scope',\n Validate: 'validate',\n} as const;\n\n// option names supported by the schema 5 command grammar\nexport const MOLDEA_CLI_OPTIONS = {\n Help: '--help',\n Json: '--json',\n Cursor: '--cursor',\n MaxDiagnostics: '--max-diagnostics',\n MaxEntries: '--max-entries',\n MaxEvidence: '--max-evidence',\n MaxFileBytes: '--max-file-bytes',\n MaxManifestBytes: '--max-manifest-bytes',\n MaxOutputBytes: '--max-output-bytes',\n MaxTotalBytes: '--max-total-bytes',\n NoColor: '--no-color',\n Path: '--path',\n PathsStdin: '--paths-stdin',\n Repository: '--repository',\n Version: '--version',\n} as const;\n\n// default resource bounds forwarded by later command-composition slices\nexport const DEFAULT_MOLDEA_CLI_RESOURCE_LIMITS = Object.freeze({\n maxDiagnostics: 10_000,\n maxEntries: 100_000,\n maxEvidence: 10_000,\n maxFileBytes: 8_388_608,\n maxManifestBytes: 2_097_152,\n maxTotalBytes: 134_217_728,\n});\n","// inclusive JSON output-page bounds and default transport budget\nexport const MOLDEA_CLI_MIN_OUTPUT_BYTES = 4_096;\nexport const MOLDEA_CLI_DEFAULT_OUTPUT_BYTES = 65_536;\nexport const MOLDEA_CLI_MAX_OUTPUT_BYTES = 1_048_576;\n\n// cursor format owned by CLI schema 5\nexport const MOLDEA_CLI_CURSOR_VERSION = 2 as const;\n","import type { IMoldeaCliOutputPageErrorCode } from './types.js';\n\n/** Represents a safe pagination or output-budget failure owned by the CLI. */\nexport class MoldeaCliOutputPageException extends Error {\n public readonly code: IMoldeaCliOutputPageErrorCode;\n\n /** Creates one output-page failure with a stable public code. */\n public constructor(code: IMoldeaCliOutputPageErrorCode) {\n super(code);\n this.code = code;\n this.name = 'MoldeaCliOutputPageException';\n }\n}\n","/** Compares strings by Unicode code point rather than UTF-16 code unit. */\nconst compareUnicodeCodePoints = (left: string, right: string): number => {\n const leftCodePoints = [...left];\n const rightCodePoints = [...right];\n const sharedLength = Math.min(leftCodePoints.length, rightCodePoints.length);\n\n for (let index = 0; index < sharedLength; index += 1) {\n const leftCodePoint = leftCodePoints[index]?.codePointAt(0);\n const rightCodePoint = rightCodePoints[index]?.codePointAt(0);\n\n if (leftCodePoint === undefined || rightCodePoint === undefined) {\n throw new TypeError('The JSON object key could not be compared.');\n }\n\n if (leftCodePoint !== rightCodePoint) {\n return leftCodePoint - rightCodePoint;\n }\n }\n\n return leftCodePoints.length - rightCodePoints.length;\n};\n\n/** Serializes one validated JSON value with recursively sorted object keys. */\nconst serializeJsonValue = (value: unknown, ancestors: Set<object>): string => {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') {\n return JSON.stringify(value);\n }\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError('The JSON number must be finite.');\n }\n\n return JSON.stringify(Object.is(value, -0) ? 0 : value);\n }\n\n if (typeof value !== 'object') {\n throw new TypeError('The value is not supported by the CLI JSON contract.');\n }\n\n if (ancestors.has(value)) {\n throw new TypeError('The CLI JSON value must not contain a cycle.');\n }\n\n ancestors.add(value);\n\n try {\n if (Array.isArray(value)) {\n const serializedEntries: string[] = [];\n\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index)) {\n throw new TypeError('The CLI JSON array must not contain empty slots.');\n }\n\n serializedEntries.push(serializeJsonValue(value[index], ancestors));\n }\n\n return `[${serializedEntries.join(',')}]`;\n }\n\n const prototype = Object.getPrototypeOf(value) as object | null;\n\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError('The CLI JSON object must be a plain record.');\n }\n\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new TypeError('The CLI JSON object must not contain symbol keys.');\n }\n\n const record = value as Readonly<Record<string, unknown>>;\n const properties = Object.keys(record)\n .sort(compareUnicodeCodePoints)\n .map((key) => `${JSON.stringify(key)}:${serializeJsonValue(record[key], ancestors)}`);\n\n return `{${properties.join(',')}}`;\n } finally {\n ancestors.delete(value);\n }\n};\n\n/**\n * Serializes one CLI JSON value with exact recursive Unicode code-point key ordering.\n * @param value The closed JSON value to serialize.\n * @returns Compact deterministic JSON without a trailing line feed.\n * @throws\n * - If the value contains unsupported, non-finite, symbolic, class-backed, or cyclic data\n */\nexport const serializeJsonDeterministically = (value: unknown): string => {\n return serializeJsonValue(value, new Set());\n};\n","import { createHash, timingSafeEqual } from 'node:crypto';\n\nimport { serializeJsonDeterministically, type IJsonValue } from '../json-serialization/index.js';\n\nimport { MOLDEA_CLI_CURSOR_VERSION } from './constants.js';\nimport { MoldeaCliOutputPageException } from './exception.js';\nimport type {\n IMoldeaCliCursorInput,\n IMoldeaCliCursorState,\n IMoldeaCliPageCommand,\n} from './types.js';\n\ninterface IMoldeaCliCursorPayload {\n readonly command: IMoldeaCliPageCommand;\n readonly filtersDigest: string;\n readonly lastKey: string;\n readonly sourceCursor: string | null;\n readonly snapshotDigest: string;\n readonly version: typeof MOLDEA_CLI_CURSOR_VERSION;\n}\n\ninterface IMoldeaCliCursorDocument extends IMoldeaCliCursorPayload {\n readonly checksum: string;\n}\n\nconst SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/u;\nconst BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;\nconst CURSOR_DOCUMENT_KEYS = Object.freeze([\n 'checksum',\n 'command',\n 'filtersDigest',\n 'lastKey',\n 'snapshotDigest',\n 'sourceCursor',\n 'version',\n]);\n\n/** Calculates one stable SHA-256 identifier for deterministic JSON text. */\nexport const calculateMoldeaCliJsonDigest = (value: IJsonValue): string => {\n return `sha256:${createHash('sha256').update(serializeJsonDeterministically(value), 'utf8').digest('hex')}`;\n};\n\n/** Calculates the checksum for one cursor payload without its checksum field. */\nconst calculateCursorChecksum = (payload: IMoldeaCliCursorPayload): string => {\n return calculateMoldeaCliJsonDigest(payload as unknown as IJsonValue);\n};\n\n/** Compares fixed-format checksums without data-dependent early termination. */\nconst areChecksumsEqual = (left: string, right: string): boolean => {\n const leftBytes = Buffer.from(left, 'utf8');\n const rightBytes = Buffer.from(right, 'utf8');\n\n return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);\n};\n\n/** Determines whether an unknown value is one strict cursor document. */\nconst isCursorDocument = (value: unknown): value is IMoldeaCliCursorDocument => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n\n const record = value as Readonly<Record<string, unknown>>;\n const keys = Object.keys(record).sort();\n\n return (\n keys.length === CURSOR_DOCUMENT_KEYS.length &&\n keys.every((key, index) => key === CURSOR_DOCUMENT_KEYS[index]) &&\n record['version'] === MOLDEA_CLI_CURSOR_VERSION &&\n (record['command'] === 'content' ||\n record['command'] === 'inspect' ||\n record['command'] === 'scope' ||\n record['command'] === 'validate') &&\n typeof record['filtersDigest'] === 'string' &&\n SHA256_PATTERN.test(record['filtersDigest']) &&\n typeof record['lastKey'] === 'string' &&\n record['lastKey'].length > 0 &&\n (record['sourceCursor'] === null || typeof record['sourceCursor'] === 'string') &&\n typeof record['snapshotDigest'] === 'string' &&\n SHA256_PATTERN.test(record['snapshotDigest']) &&\n typeof record['checksum'] === 'string' &&\n SHA256_PATTERN.test(record['checksum'])\n );\n};\n\n/** Encodes one command-, filter-, and snapshot-bound continuation cursor. */\nexport const encodeMoldeaCliCursor = (\n command: IMoldeaCliPageCommand,\n filters: IJsonValue,\n snapshotDigest: string,\n lastKey: string,\n sourceCursor: string | null = null,\n): string => {\n const payload: IMoldeaCliCursorPayload = {\n command,\n filtersDigest: calculateMoldeaCliJsonDigest(filters),\n lastKey,\n sourceCursor,\n snapshotDigest,\n version: MOLDEA_CLI_CURSOR_VERSION,\n };\n const document: IMoldeaCliCursorDocument = {\n ...payload,\n checksum: calculateCursorChecksum(payload),\n };\n\n return Buffer.from(serializeJsonDeterministically(document), 'utf8').toString('base64url');\n};\n\n/**\n * Decodes and validates one opaque continuation cursor.\n * @param input The current command state and untrusted cursor.\n * @returns The validated last composite record key.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n */\nexport const decodeMoldeaCliCursor = (input: IMoldeaCliCursorInput): IMoldeaCliCursorState => {\n let decoded: unknown;\n\n try {\n if (!BASE64URL_PATTERN.test(input.cursor)) {\n throw new TypeError('The cursor is not canonical base64url.');\n }\n\n const bytes = Buffer.from(input.cursor, 'base64url');\n\n if (bytes.toString('base64url') !== input.cursor) {\n throw new TypeError('The cursor is not canonical base64url.');\n }\n\n const text = bytes.toString('utf8');\n decoded = JSON.parse(text) as unknown;\n } catch {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n if (!isCursorDocument(decoded)) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n const { checksum, ...payload } = decoded;\n\n if (\n !areChecksumsEqual(checksum, calculateCursorChecksum(payload)) ||\n decoded.command !== input.command ||\n decoded.filtersDigest !== calculateMoldeaCliJsonDigest(input.filters)\n ) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n if (input.snapshotDigest !== undefined && decoded.snapshotDigest !== input.snapshotDigest) {\n throw new MoldeaCliOutputPageException('CURSOR_SNAPSHOT_CHANGED');\n }\n\n return Object.freeze({\n lastKey: decoded.lastKey,\n snapshotDigest: decoded.snapshotDigest,\n sourceCursor: decoded.sourceCursor,\n });\n};\n","import { serializeJsonDeterministically } from '../json-serialization/index.js';\n\nimport { decodeMoldeaCliCursor, encodeMoldeaCliCursor } from './cursor.js';\nimport { MoldeaCliOutputPageException } from './exception.js';\nimport type {\n IMoldeaCliOutputPage,\n IMoldeaCliOutputPageInput,\n IMoldeaCliOutputRecord,\n} from './types.js';\n\n/** Ensures records have unique keys in strict ascending order. */\nconst assertRecordOrder = (records: readonly IMoldeaCliOutputRecord[]): void => {\n for (let index = 0; index < records.length; index += 1) {\n const key = records[index]?.key;\n const previousKey = records[index - 1]?.key;\n\n if (\n key === undefined ||\n key.length === 0 ||\n (previousKey !== undefined && key <= previousKey)\n ) {\n throw new TypeError('Output records must have unique keys in ascending order.');\n }\n }\n};\n\n/**\n * Selects the largest exact serialized output page that fits its byte budget.\n * @param input Ordered records, continuation state, and an exact final-document measurement.\n * @returns A frozen record page with a snapshot-bound continuation cursor when needed.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliOutputPage = <TRecord extends IMoldeaCliOutputRecord>(\n input: IMoldeaCliOutputPageInput<TRecord>,\n): IMoldeaCliOutputPage<TRecord> => {\n assertRecordOrder(input.records);\n\n const cursorState =\n input.cursor === null\n ? null\n : decodeMoldeaCliCursor({\n command: input.command,\n cursor: input.cursor,\n filters: input.filters,\n snapshotDigest: input.snapshotDigest,\n });\n const startIndex =\n cursorState === null\n ? 0\n : cursorState.sourceCursor !== null\n ? 0\n : input.records.findIndex(({ key }) => key === cursorState.lastKey) + 1;\n\n if (cursorState !== null && cursorState.sourceCursor === null && startIndex === 0) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n const emptyRecords = Object.freeze([]) as readonly TRecord[];\n const emptyPage = Object.freeze({ cursor: null, records: emptyRecords });\n\n if (startIndex === input.records.length) {\n if (input.measure(emptyPage, 2) > input.maxOutputBytes) {\n throw new MoldeaCliOutputPageException('OUTPUT_BUDGET_TOO_SMALL');\n }\n\n return emptyPage;\n }\n\n const selectedRecords: TRecord[] = [];\n let selectedCursor: string | null = null;\n let serializedRecordsUtf8Bytes = 2;\n\n for (let endIndex = startIndex + 1; endIndex <= input.records.length; endIndex += 1) {\n const record = input.records[endIndex - 1];\n\n if (record === undefined) {\n throw new TypeError('An output page record is missing.');\n }\n\n const serializedRecordUtf8Bytes = Buffer.byteLength(\n serializeJsonDeterministically(record),\n 'utf8',\n );\n\n serializedRecordsUtf8Bytes += serializedRecordUtf8Bytes + (endIndex > startIndex + 1 ? 1 : 0);\n selectedRecords.push(record);\n\n const sourceCursor = input.sourceCursorForRecord?.(record) ?? null;\n const hasMore =\n input.sourceCursorForRecord === undefined\n ? endIndex < input.records.length\n : sourceCursor !== null;\n const cursor = hasMore\n ? encodeMoldeaCliCursor(\n input.command,\n input.filters,\n input.snapshotDigest,\n record.key,\n sourceCursor,\n )\n : null;\n const candidate = Object.freeze({ cursor, records: selectedRecords });\n\n if (input.measure(candidate, serializedRecordsUtf8Bytes) > input.maxOutputBytes) {\n selectedRecords.pop();\n break;\n }\n\n selectedCursor = cursor;\n }\n\n if (selectedRecords.length === 0) {\n throw new MoldeaCliOutputPageException('OUTPUT_BUDGET_TOO_SMALL');\n }\n\n return Object.freeze({\n cursor: selectedCursor,\n records: Object.freeze([...selectedRecords]),\n });\n};\n","import { MOLDEA_CLI_MAX_OUTPUT_BYTES, MOLDEA_CLI_MIN_OUTPUT_BYTES } from '../output-page/index.js';\n\nimport type { IMoldeaCliResourceLimits } from './types.js';\n\nconst POSITIVE_INTEGER_PATTERN = /^\\d+$/u;\n\n/**\n * Determines whether text contains only Unicode scalar values.\n * @param text The text to validate.\n * @returns Whether the text contains no unpaired UTF-16 surrogate.\n */\nexport const hasOnlyUnicodeScalarValues = (text: string): boolean => {\n for (let index = 0; index < text.length; index += 1) {\n const codeUnit = text.charCodeAt(index);\n\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n if (index + 1 >= text.length) {\n return false;\n }\n\n const trailingCodeUnit = text.charCodeAt(index + 1);\n\n if (trailingCodeUnit < 0xdc00 || trailingCodeUnit > 0xdfff) {\n return false;\n }\n\n index += 1;\n continue;\n }\n\n if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * Parses one strict base-10 positive safe integer option value.\n * @param input The untrusted command-line token.\n * @returns The parsed integer, or null when the token is invalid.\n */\nexport const parsePositiveSafeInteger = (input: string): number | null => {\n if (!POSITIVE_INTEGER_PATTERN.test(input)) {\n return null;\n }\n\n const parsedInteger = Number(input);\n\n return Number.isSafeInteger(parsedInteger) && parsedInteger > 0 ? parsedInteger : null;\n};\n\n/** Parses one output byte budget inside the schema 5 transport bounds. */\nexport const parseMoldeaCliOutputByteLimit = (input: string): number | null => {\n const parsed = parsePositiveSafeInteger(input);\n\n return parsed !== null &&\n parsed >= MOLDEA_CLI_MIN_OUTPUT_BYTES &&\n parsed <= MOLDEA_CLI_MAX_OUTPUT_BYTES\n ? parsed\n : null;\n};\n\n/**\n * Validates the cross-limit ordering required by the CLI composition.\n * @param limits The effective resource limits.\n * @returns Whether manifest, file, and total byte limits are consistently ordered.\n */\nexport const areMoldeaCliResourceLimitsConsistent = (limits: IMoldeaCliResourceLimits): boolean => {\n return (\n limits.maxManifestBytes <= limits.maxFileBytes && limits.maxFileBytes <= limits.maxTotalBytes\n );\n};\n\n/**\n * Determines whether one repository option is safe scalar host-path text.\n * @param input The untrusted command-line token.\n * @returns Whether the token is non-empty scalar text without NUL.\n */\nexport const isRepositoryDirectoryInputValid = (input: string): boolean => {\n return input.length > 0 && !input.includes('\\0') && hasOnlyUnicodeScalarValues(input);\n};\n\n/** Determines whether one opaque cursor token is bounded safe scalar text. */\nexport const isMoldeaCliCursorInputValid = (input: string): boolean => {\n return (\n input.length > 0 &&\n input.length <= 16_384 &&\n !input.includes('\\0') &&\n hasOnlyUnicodeScalarValues(input)\n );\n};\n","import { MOLDEA_CLI_DEFAULT_OUTPUT_BYTES } from '../output-page/index.js';\n\nimport {\n DEFAULT_MOLDEA_CLI_RESOURCE_LIMITS,\n MOLDEA_CLI_COMMANDS,\n MOLDEA_CLI_OPTIONS,\n} from './constants.js';\nimport type {\n IMoldeaCliArgumentError,\n IMoldeaCliArgumentErrorCode,\n IMoldeaCliCommand,\n IMoldeaCliCommandOptions,\n IMoldeaCliParseResult,\n IMoldeaCliResourceLimits,\n} from './types.js';\nimport {\n areMoldeaCliResourceLimitsConsistent,\n isMoldeaCliCursorInputValid,\n isRepositoryDirectoryInputValid,\n parseMoldeaCliOutputByteLimit,\n parsePositiveSafeInteger,\n} from './validations.js';\n\nconst COMMAND_NAMES = new Set<IMoldeaCliCommand>(Object.values(MOLDEA_CLI_COMMANDS));\nconst RESOURCE_OPTION_FIELDS = {\n [MOLDEA_CLI_OPTIONS.MaxDiagnostics]: 'maxDiagnostics',\n [MOLDEA_CLI_OPTIONS.MaxEntries]: 'maxEntries',\n [MOLDEA_CLI_OPTIONS.MaxEvidence]: 'maxEvidence',\n [MOLDEA_CLI_OPTIONS.MaxFileBytes]: 'maxFileBytes',\n [MOLDEA_CLI_OPTIONS.MaxManifestBytes]: 'maxManifestBytes',\n [MOLDEA_CLI_OPTIONS.MaxTotalBytes]: 'maxTotalBytes',\n} as const satisfies Readonly<Record<string, keyof IMoldeaCliResourceLimits>>;\n\n// mutable construction shape frozen before the normalized invocation is returned\ntype IMutableMoldeaCliResourceLimits = {\n -readonly [Key in keyof IMoldeaCliResourceLimits]: IMoldeaCliResourceLimits[Key];\n};\n\nconst createArgumentError = (\n code: IMoldeaCliArgumentErrorCode,\n command: IMoldeaCliCommand | null,\n isJson: boolean,\n): IMoldeaCliArgumentError => ({ code, command, isJson, kind: 'error' });\n\nconst isMoldeaCliCommand = (input: string | undefined): input is IMoldeaCliCommand => {\n return input !== undefined && COMMAND_NAMES.has(input as IMoldeaCliCommand);\n};\n\n/**\n * Parses the complete schema 5 command grammar without mutating caller arguments.\n * @param commandLineArguments The process arguments after the executable path.\n * @returns A normalized command, informational request, or safe invocation error.\n */\nexport const parseMoldeaCliArguments = (\n commandLineArguments: readonly string[],\n): IMoldeaCliParseResult => {\n const isJson = commandLineArguments.includes(MOLDEA_CLI_OPTIONS.Json);\n\n if (commandLineArguments.length === 0) {\n return { command: null, kind: 'help' };\n }\n\n const firstArgument = commandLineArguments[0];\n\n if (firstArgument === MOLDEA_CLI_OPTIONS.Help) {\n return commandLineArguments.length === 1\n ? { command: null, kind: 'help' }\n : createArgumentError('INVALID_ARGUMENT', null, isJson);\n }\n\n if (firstArgument === MOLDEA_CLI_OPTIONS.Version) {\n return commandLineArguments.length === 1\n ? { kind: 'version' }\n : createArgumentError('INVALID_ARGUMENT', null, isJson);\n }\n\n const command = isMoldeaCliCommand(firstArgument) ? firstArgument : null;\n\n if (command === null) {\n return createArgumentError('INVALID_ARGUMENT', null, isJson);\n }\n\n if (commandLineArguments.length === 2 && commandLineArguments[1] === MOLDEA_CLI_OPTIONS.Help) {\n return { command, kind: 'help' };\n }\n\n const seenOptions = new Set<string>();\n const resourceLimits: IMutableMoldeaCliResourceLimits = {\n ...DEFAULT_MOLDEA_CLI_RESOURCE_LIMITS,\n };\n let isColorDisabled = false;\n let cursor: string | null = null;\n let maxOutputBytes = MOLDEA_CLI_DEFAULT_OUTPUT_BYTES;\n let path: string | null = null;\n let pathsInput: IMoldeaCliCommandOptions['pathsInput'] = 'none';\n let repositoryDirectory: string | null = null;\n\n for (let index = 1; index < commandLineArguments.length; index += 1) {\n const option = commandLineArguments[index];\n\n if (option === undefined || seenOptions.has(option)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n seenOptions.add(option);\n\n if (option === MOLDEA_CLI_OPTIONS.Json) {\n continue;\n }\n\n if (option === MOLDEA_CLI_OPTIONS.NoColor) {\n isColorDisabled = true;\n continue;\n }\n\n if (option === MOLDEA_CLI_OPTIONS.PathsStdin) {\n pathsInput = 'stdin';\n continue;\n }\n\n if (option === MOLDEA_CLI_OPTIONS.Help || option === MOLDEA_CLI_OPTIONS.Version) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n const resourceField = RESOURCE_OPTION_FIELDS[option as keyof typeof RESOURCE_OPTION_FIELDS];\n const isRepositoryOption = option === MOLDEA_CLI_OPTIONS.Repository;\n const isCursorOption = option === MOLDEA_CLI_OPTIONS.Cursor;\n const isOutputLimitOption = option === MOLDEA_CLI_OPTIONS.MaxOutputBytes;\n const isPathOption = option === MOLDEA_CLI_OPTIONS.Path;\n\n if (\n resourceField === undefined &&\n !isRepositoryOption &&\n !isCursorOption &&\n !isOutputLimitOption &&\n !isPathOption\n ) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Composition) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n const optionValue = commandLineArguments[index + 1];\n\n if (optionValue === undefined || optionValue.startsWith('--')) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n index += 1;\n\n if (isCursorOption) {\n if (!isMoldeaCliCursorInputValid(optionValue)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n cursor = optionValue;\n continue;\n }\n\n if (isOutputLimitOption) {\n const parsedOutputLimit = parseMoldeaCliOutputByteLimit(optionValue);\n\n if (parsedOutputLimit === null) {\n return createArgumentError('RESOURCE_LIMIT_CONFIGURATION_INVALID', command, isJson);\n }\n\n maxOutputBytes = parsedOutputLimit;\n continue;\n }\n\n if (isPathOption) {\n if (!isRepositoryDirectoryInputValid(optionValue)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n path = optionValue;\n pathsInput = 'path';\n continue;\n }\n\n if (isRepositoryOption) {\n if (!isRepositoryDirectoryInputValid(optionValue)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n repositoryDirectory = optionValue;\n continue;\n }\n\n const parsedLimit = parsePositiveSafeInteger(optionValue);\n\n if (parsedLimit === null || resourceField === undefined) {\n return createArgumentError('RESOURCE_LIMIT_CONFIGURATION_INVALID', command, isJson);\n }\n\n resourceLimits[resourceField] = parsedLimit;\n }\n\n if (!areMoldeaCliResourceLimitsConsistent(resourceLimits)) {\n return createArgumentError('RESOURCE_LIMIT_CONFIGURATION_INVALID', command, isJson);\n }\n\n const isScope = command === MOLDEA_CLI_COMMANDS.Scope;\n const isContent = command === MOLDEA_CLI_COMMANDS.Content;\n const hasPathInput = path !== null;\n const hasStdinInput = seenOptions.has(MOLDEA_CLI_OPTIONS.PathsStdin);\n\n if ((hasPathInput || hasStdinInput) && !isScope && !isContent) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (isScope && hasPathInput === hasStdinInput) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (isContent && (!hasPathInput || hasStdinInput)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (isScope && seenOptions.has(MOLDEA_CLI_OPTIONS.MaxEvidence)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (\n isContent &&\n [\n MOLDEA_CLI_OPTIONS.MaxDiagnostics,\n MOLDEA_CLI_OPTIONS.MaxEvidence,\n MOLDEA_CLI_OPTIONS.MaxManifestBytes,\n ].some((option) => seenOptions.has(option))\n ) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (!isJson && (cursor !== null || seenOptions.has(MOLDEA_CLI_OPTIONS.MaxOutputBytes))) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n const options: IMoldeaCliCommandOptions = {\n cursor,\n isColorDisabled,\n isJson,\n maxOutputBytes,\n path,\n pathsInput,\n repositoryDirectory,\n resourceLimits: Object.freeze({ ...resourceLimits }),\n };\n\n return {\n invocation: Object.freeze({ command, options: Object.freeze(options) }),\n kind: 'command',\n };\n};\n","import { MOLDEA_CLI_COMMANDS } from '../command-line/index.js';\n\n// stable safe presentation contracts for errors implemented by the CLI\nexport const MOLDEA_CLI_ERROR_DEFINITIONS = Object.freeze({\n COMPOSITION_STATE_INVALID: Object.freeze({\n message: 'The installed composition state is invalid.',\n retryable: false,\n source: 'cli',\n }),\n CONTENT_INVALID: Object.freeze({\n message: 'The requested canonical asset is not valid moldea text.',\n retryable: false,\n source: 'cli',\n }),\n CONTENT_PATH_INVALID: Object.freeze({\n message: 'The content path must identify one canonical moldea text asset.',\n retryable: false,\n source: 'cli',\n }),\n CURSOR_INVALID: Object.freeze({\n message: 'The continuation cursor is invalid for this request.',\n retryable: false,\n source: 'cli',\n }),\n CURSOR_SNAPSHOT_CHANGED: Object.freeze({\n message: 'The continuation cursor belongs to a different repository snapshot.',\n retryable: true,\n source: 'cli',\n }),\n GIT_ACCESS_DENIED: Object.freeze({\n message: 'Git access was denied.',\n retryable: true,\n source: 'git',\n }),\n GIT_COMMAND_FAILED: Object.freeze({\n message: 'The Git command failed.',\n retryable: true,\n source: 'git',\n }),\n GIT_CONTENT_TRANSFORM_UNSUPPORTED: Object.freeze({\n message: 'The requested file uses an unsupported Git content transformation.',\n retryable: false,\n source: 'git',\n }),\n GIT_NOT_FOUND: Object.freeze({\n message: 'The Git executable is unavailable.',\n retryable: false,\n source: 'git',\n }),\n GIT_OPERATION_ABORTED: Object.freeze({\n message: 'The Git operation was aborted.',\n retryable: true,\n source: 'git',\n }),\n GIT_OUTPUT_INVALID: Object.freeze({\n message: 'Git returned invalid output.',\n retryable: false,\n source: 'git',\n }),\n GIT_REPOSITORY_NOT_FOUND: Object.freeze({\n message: 'The selected path is not inside a Git repository.',\n retryable: false,\n source: 'git',\n }),\n GIT_SPARSE_CHECKOUT_UNSUPPORTED: Object.freeze({\n message: 'Sparse Git checkouts are unsupported.',\n retryable: false,\n source: 'git',\n }),\n GIT_VERSION_INVALID: Object.freeze({\n message: 'The Git version output is invalid.',\n retryable: false,\n source: 'git',\n }),\n GIT_VERSION_UNSUPPORTED: Object.freeze({\n message: 'The installed Git version is unsupported.',\n retryable: false,\n source: 'git',\n }),\n GIT_WORK_TREE_REQUIRED: Object.freeze({\n message: 'A usable Git working tree is required.',\n retryable: false,\n source: 'git',\n }),\n INTERNAL_ERROR: Object.freeze({\n message: 'The command could not be completed.',\n retryable: false,\n source: 'cli',\n }),\n INVALID_ARGUMENT: Object.freeze({\n message: 'The command invocation is invalid.',\n retryable: false,\n source: 'cli',\n }),\n OUTPUT_BUDGET_TOO_SMALL: Object.freeze({\n message: 'The output byte budget cannot contain the next complete result.',\n retryable: false,\n source: 'cli',\n }),\n PATH_INPUT_INVALID: Object.freeze({\n message: 'The NUL-delimited changed-path input is invalid.',\n retryable: false,\n source: 'cli',\n }),\n RESOURCE_LIMIT_CONFIGURATION_INVALID: Object.freeze({\n message: 'The resource-limit configuration is invalid.',\n retryable: false,\n source: 'cli',\n }),\n RESOURCE_LIMIT_EXCEEDED: Object.freeze({\n message: 'A resource limit was exceeded.',\n retryable: false,\n source: 'cli',\n }),\n WORKING_TREE_UNSTABLE: Object.freeze({\n message: 'The working tree did not remain stable.',\n retryable: true,\n source: 'cli',\n }),\n} as const);\n\n// source descriptor for results derived from the selected Git working tree\nexport const MOLDEA_CLI_GIT_WORKING_TREE_SOURCE = Object.freeze({\n kind: 'git-working-tree' as const,\n});\n\n// top-level help presented without repository access\nexport const MOLDEA_CLI_TOP_LEVEL_HELP = `Usage: moldea <command> [options]\n\nCommands:\n validate Validate the current moldea project.\n inspect Inspect content-free project metadata.\n scope Match changed paths to declared moldea relationships.\n content Read one canonical moldea asset explicitly.\n composition Report the installed CLI composition state.\n\nGlobal options:\n --help Show top-level help.\n --version Show the CLI version.\n\nRun \"moldea <command> --help\" for command-specific options.\n`;\n\nconst REPOSITORY_OPTIONS_HELP = ` --repository <path> Select a Git working-tree directory.\n --json Emit one machine-readable JSON result.\n --no-color Disable ANSI styling in human output.\n`;\n\nconst BASE_RESOURCE_OPTIONS_HELP = ` --max-entries <integer> Override the repository entry limit.\n --max-file-bytes <integer> Override the per-file byte limit.\n --max-total-bytes <integer> Override the total cached-byte limit.\n`;\n\nconst INSPECTION_RESOURCE_OPTIONS_HELP = `${BASE_RESOURCE_OPTIONS_HELP} --max-manifest-bytes <integer> Override the manifest byte limit.\n --max-diagnostics <integer> Override the diagnostic count limit.\n`;\n\nconst PAGINATION_OPTIONS_HELP = ` --max-output-bytes <integer> Bound JSON output from 4096 to 1048576 bytes.\n --cursor <opaque-cursor> Continue a prior JSON result page.\n`;\n\nconst COMPLETE_INSPECTION_OPTIONS_HELP = `${REPOSITORY_OPTIONS_HELP}${INSPECTION_RESOURCE_OPTIONS_HELP} --max-evidence <integer> Override the adapter evidence count limit.\n${PAGINATION_OPTIONS_HELP}`;\n\nconst SCOPE_OPTIONS_HELP = `${REPOSITORY_OPTIONS_HELP}${INSPECTION_RESOURCE_OPTIONS_HELP}${PAGINATION_OPTIONS_HELP}`;\n\nconst CONTENT_OPTIONS_HELP = `${REPOSITORY_OPTIONS_HELP}${BASE_RESOURCE_OPTIONS_HELP}${PAGINATION_OPTIONS_HELP}`;\n\n// complete command-specific help keyed by the closed command set\nexport const MOLDEA_CLI_COMMAND_HELP = {\n [MOLDEA_CLI_COMMANDS.Composition]: `Usage: moldea composition [options]\n\nReport the installed CLI composition state.\n\nOptions:\n --json Emit one machine-readable JSON result.\n --no-color Disable ANSI styling in human output.\n --help Show this help.\n`,\n [MOLDEA_CLI_COMMANDS.Inspect]: `Usage: moldea inspect [options]\n\nInspect content-free metadata for the current moldea project.\n\nOptions:\n${COMPLETE_INSPECTION_OPTIONS_HELP} --help Show this help.\n`,\n [MOLDEA_CLI_COMMANDS.Scope]: `Usage: moldea scope (--path <logical-path> | --paths-stdin) [options]\n\nMatch changed repository paths to declared moldea relationships. The stdin form accepts NUL-delimited UTF-8 logical paths.\n\nOptions:\n${SCOPE_OPTIONS_HELP} --path <logical-path> Match one repository-logical path.\n --paths-stdin Read NUL-delimited paths from stdin.\n --help Show this help.\n`,\n [MOLDEA_CLI_COMMANDS.Content]: `Usage: moldea content --path <canonical-logical-path> [options]\n\nRead one canonical moldea text asset in bounded Unicode-safe chunks.\n\nOptions:\n${CONTENT_OPTIONS_HELP} --path <canonical-logical-path> Select exactly one canonical moldea file.\n --help Show this help.\n`,\n [MOLDEA_CLI_COMMANDS.Validate]: `Usage: moldea validate [options]\n\nValidate the current moldea project.\n\nOptions:\n${COMPLETE_INSPECTION_OPTIONS_HELP} --help Show this help.\n`,\n} as const;\n","import { MOLDEA_CLI_ERROR_DEFINITIONS } from './constants.js';\nimport type { IMoldeaCliError, IMoldeaCliOwnedErrorCode } from './types.js';\n\nconst EMPTY_ERROR_DETAILS = Object.freeze({});\n\n/**\n * Creates one immutable safe error from a CLI- or Git-owned definition.\n * @param code The stable executable-owned error code.\n * @returns The complete safe error object.\n */\nexport const createMoldeaCliOwnedError = (code: IMoldeaCliOwnedErrorCode): IMoldeaCliError => {\n const definition = MOLDEA_CLI_ERROR_DEFINITIONS[code];\n\n return Object.freeze({\n code,\n details: EMPTY_ERROR_DETAILS,\n message: definition.message,\n path: null,\n retryable: definition.retryable,\n source: definition.source,\n });\n};\n","import { serializeJsonDeterministically } from '../json-serialization/index.js';\n\nimport { MOLDEA_CLI_JSON_SCHEMA_VERSION } from './constants.js';\nimport type { IMoldeaCliJsonDocumentInput, IMoldeaCliJsonEnvelope } from './types.js';\n\n/** Creates one strict schema 5 JSON envelope. */\nexport const createMoldeaCliJsonEnvelope = <TResult>(\n input: IMoldeaCliJsonDocumentInput<TResult>,\n): IMoldeaCliJsonEnvelope<TResult> =>\n Object.freeze({\n cliVersion: input.cliVersion,\n command: input.command,\n error: input.error,\n result: input.result,\n schemaVersion: MOLDEA_CLI_JSON_SCHEMA_VERSION,\n status: input.status,\n });\n\n/** Serializes one schema 5 envelope with its required trailing line feed. */\nexport const serializeMoldeaCliJsonEnvelope = <TResult>(\n input: IMoldeaCliJsonDocumentInput<TResult>,\n): string => `${serializeJsonDeterministically(createMoldeaCliJsonEnvelope(input))}\\n`;\n\n/** Measures the exact final UTF-8 bytes of one schema 5 JSON document. */\nexport const measureMoldeaCliJsonEnvelope = <TResult>(\n input: IMoldeaCliJsonDocumentInput<TResult>,\n): number => Buffer.byteLength(serializeMoldeaCliJsonEnvelope(input), 'utf8');\n","/** Rejects canonical bodies and content fields from a non-content JSON result. */\nexport const assertMoldeaCliJsonResultIsContentFree = (\n value: unknown,\n canonicalBodies: readonly string[] = [],\n): void => {\n const pending: unknown[] = [value];\n const visited = new Set<object>();\n const bodies = new Set(canonicalBodies.filter((body) => body.length > 0));\n\n while (pending.length > 0) {\n const current = pending.pop();\n\n if (typeof current === 'string') {\n if (bodies.has(current)) {\n throw new TypeError('A non-content CLI result contains canonical document text.');\n }\n\n continue;\n }\n\n if (typeof current !== 'object' || current === null || visited.has(current)) {\n continue;\n }\n\n visited.add(current);\n\n if (Array.isArray(current)) {\n for (const item of current as readonly unknown[]) {\n pending.push(item);\n }\n\n continue;\n }\n\n const record = current as Readonly<Record<string, unknown>>;\n\n if (Object.hasOwn(record, 'content')) {\n throw new TypeError('A non-content CLI result contains a content property.');\n }\n\n pending.push(...Object.values(record));\n }\n};\n","import type { IDiagnosticEntity } from '@moldea.ai/core';\n\nimport { MOLDEA_CLI_COMMANDS, type IMoldeaCliCommand } from '../command-line/index.js';\nimport type { IMoldeaCliCompositionResult } from '../composition/index.js';\nimport {\n MOLDEA_CLI_JSON_SCHEMA_VERSION,\n serializeMoldeaCliJsonEnvelope,\n type IMoldeaCliJsonStatus,\n} from '../json-output-contract/index.js';\nimport type { IMoldeaCliContentResult } from '../project-content/index.js';\nimport type { IMoldeaCliScopeResult } from '../project-scope/index.js';\n\nimport { MOLDEA_CLI_COMMAND_HELP, MOLDEA_CLI_TOP_LEVEL_HELP } from './constants.js';\nimport type {\n IMoldeaCliDiagnosticRecord,\n IMoldeaCliError,\n IMoldeaCliInspectResult,\n IMoldeaCliValidateResult,\n} from './types.js';\n\nconst DIAGNOSTIC_ENTITY_KEYS = [\n 'agentId',\n 'capabilityKind',\n 'capabilityId',\n 'decisionId',\n 'variableId',\n 'adapterId',\n] as const satisfies readonly (keyof IDiagnosticEntity)[];\n\n/** Formats one diagnostic entity in the canonical Core field order. */\nconst formatMoldeaCliHumanDiagnosticEntity = (entity: IDiagnosticEntity): string =>\n DIAGNOSTIC_ENTITY_KEYS.flatMap((key) => {\n const identifier = entity[key];\n\n return identifier === undefined ? [] : [`${key}=${identifier}`];\n }).join(', ');\n\n/** Formats one projected diagnostic without exposing omitted arbitrary details. */\nconst formatMoldeaCliHumanDiagnostic = (diagnostic: IMoldeaCliDiagnosticRecord): string => {\n const location =\n diagnostic.path === null\n ? ''\n : diagnostic.range === null\n ? ` ${diagnostic.path}`\n : ` ${diagnostic.path}:${diagnostic.range.start.line}:${diagnostic.range.start.column}`;\n const lines = [`${diagnostic.source}:${diagnostic.code}${location} ${diagnostic.message}`];\n\n if (diagnostic.pointer !== null) {\n lines.push(` pointer: ${diagnostic.pointer}`);\n }\n\n if (diagnostic.entity !== null) {\n lines.push(` entity: ${formatMoldeaCliHumanDiagnosticEntity(diagnostic.entity)}`);\n }\n\n if (diagnostic.severity === 'warning') {\n lines.push(` unverified relationship: ${diagnostic.details.relationship}`);\n lines.push(` reason: ${diagnostic.details.reason.replaceAll('-', ' ')}`);\n\n if (diagnostic.details.reason === 'version-dependent-behavior') {\n lines.push(` package: ${diagnostic.details.packageName}`);\n lines.push(` declared range: ${diagnostic.details.declaredRange ?? 'unavailable'}`);\n lines.push(` behavior boundary: ${diagnostic.details.boundaryVersion}`);\n }\n }\n\n return lines.join('\\n');\n};\n\n/** Creates shared human status lines for one completed repository command. */\nconst createMoldeaCliHumanStatusLines = (\n isValid: boolean,\n formatVersion: number | null,\n warningCount = 0,\n): string[] => {\n const status = isValid ? (warningCount > 0 ? 'valid with warnings' : 'valid') : 'invalid';\n const lines = [`The moldea project is ${status}.`];\n\n if (formatVersion !== null) {\n lines.push(`Repository format: ${formatVersion}`);\n }\n\n return lines;\n};\n\n/** Formats one count label with correct singular or plural grammar. */\nconst formatMoldeaCliHumanCount = (\n count: number,\n singularLabel: string,\n pluralLabel: string,\n): string => `${count === 1 ? singularLabel : pluralLabel}: ${count}`;\n\n/** Formats top-level or command-specific help with its required trailing line feed. */\nexport const formatMoldeaCliHelp = (command: IMoldeaCliCommand | null): string => {\n return command === null ? MOLDEA_CLI_TOP_LEVEL_HELP : MOLDEA_CLI_COMMAND_HELP[command];\n};\n\n/** Formats one safe CLI error for human stderr output. */\nexport const formatMoldeaCliHumanError = (error: IMoldeaCliError): string =>\n `${error.source}:${error.code} ${error.message}\\n`;\n\n/** Formats any strict schema 5 JSON envelope. */\nexport const formatMoldeaCliJsonResult = <TResult>(\n command: IMoldeaCliCommand | null,\n result: TResult | null,\n error: IMoldeaCliError | null,\n status: IMoldeaCliJsonStatus,\n cliVersion: string,\n): string => serializeMoldeaCliJsonEnvelope({ cliVersion, command, error, result, status });\n\n/** Formats one safe schema 5 JSON error envelope. */\nexport const formatMoldeaCliJsonError = (\n error: IMoldeaCliError,\n command: IMoldeaCliCommand | null,\n cliVersion: string,\n): string => formatMoldeaCliJsonResult(command, null, error, 'error', cliVersion);\n\n/** Formats one valid composition result for human stdout. */\nexport const formatMoldeaCliHumanCompositionResult = (\n result: IMoldeaCliCompositionResult,\n cliVersion: string,\n): string => {\n const lines = [\n 'The installed CLI composition state is valid.',\n `CLI version: ${cliVersion}`,\n `Supported Node.js: ${result.supportedNodeRange}`,\n `JSON output schema: ${MOLDEA_CLI_JSON_SCHEMA_VERSION}`,\n `Minimum Git: ${result.minimumGitVersion}`,\n `Repository formats: ${result.repositoryFormatVersions.join(', ')}`,\n 'Packages:',\n ...result.packages.map(({ name, version }) => ` ${name}: ${version}`),\n 'Adapters:',\n ...result.adapters.map(\n ({ id, repositoryFormatVersions }) =>\n ` ${id}: repository formats ${repositoryFormatVersions.join(', ')}`,\n ),\n ];\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one composition result in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonCompositionResult = (\n result: IMoldeaCliCompositionResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(MOLDEA_CLI_COMMANDS.Composition, result, null, 'valid', cliVersion);\n\n/** Formats one completed validation result for human stdout. */\nexport const formatMoldeaCliHumanValidateResult = (result: IMoldeaCliValidateResult): string => {\n const lines = createMoldeaCliHumanStatusLines(\n result.valid,\n result.formatVersion,\n result.warningCount,\n );\n\n for (const diagnostic of result.page.records) {\n lines.push(formatMoldeaCliHumanDiagnostic(diagnostic));\n }\n\n lines.push(formatMoldeaCliHumanCount(result.diagnosticCount, 'Diagnostic', 'Diagnostics'));\n lines.push(formatMoldeaCliHumanCount(result.errorCount, 'Error', 'Errors'));\n lines.push(formatMoldeaCliHumanCount(result.warningCount, 'Warning', 'Warnings'));\n\n if (result.page.cursor !== null) {\n lines.push('Additional diagnostics are available through JSON pagination.');\n }\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one validation result in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonValidateResult = (\n result: IMoldeaCliValidateResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(\n MOLDEA_CLI_COMMANDS.Validate,\n result,\n null,\n result.valid ? 'valid' : 'invalid',\n cliVersion,\n );\n\n/** Formats one completed metadata inspection for human stdout. */\nexport const formatMoldeaCliHumanInspectResult = (result: IMoldeaCliInspectResult): string => {\n const lines = createMoldeaCliHumanStatusLines(\n result.valid,\n result.formatVersion,\n result.counts.warnings,\n );\n\n for (const [label, count] of Object.entries(result.counts)) {\n lines.push(`${label}: ${count}`);\n }\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one metadata inspection in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonInspectResult = (\n result: IMoldeaCliInspectResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(\n MOLDEA_CLI_COMMANDS.Inspect,\n result,\n null,\n result.valid ? 'valid' : 'invalid',\n cliVersion,\n );\n\n/** Formats one changed-path scope result for human stdout. */\nexport const formatMoldeaCliHumanScopeResult = (result: IMoldeaCliScopeResult): string => {\n const lines = [\n `The moldea scope result is ${result.valid ? 'valid' : 'invalid'}.`,\n `Relevant: ${result.relevant ? 'yes' : 'no'}`,\n ...Object.entries(result.counts).map(([label, count]) => `${label}: ${count}`),\n ];\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one changed-path scope result in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonScopeResult = (\n result: IMoldeaCliScopeResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(\n MOLDEA_CLI_COMMANDS.Scope,\n result,\n null,\n result.valid ? 'valid' : 'invalid',\n cliVersion,\n );\n\n/** Formats one explicit canonical content chunk for human stdout. */\nexport const formatMoldeaCliHumanContentResult = (result: IMoldeaCliContentResult): string => {\n const lines = [\n `Path: ${result.asset.path}`,\n `Content identity: ${result.asset.contentIdentity ?? 'unavailable'}`,\n `Bytes: ${result.chunk.byteStart}-${result.chunk.byteEnd} of ${result.asset.totalBytes}`,\n result.cursor === null ? 'Cursor: none' : `Cursor: ${result.cursor}`,\n ...(result.cursor === null\n ? []\n : ['Continue this asset by passing the cursor to a JSON content request.']),\n '',\n result.chunk.content,\n ];\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one explicit canonical content chunk in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonContentResult = (\n result: IMoldeaCliContentResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(MOLDEA_CLI_COMMANDS.Content, result, null, 'valid', cliVersion);\n","import type {\n IDiagnostic,\n IProjectInspectionItem,\n IProjectInspectionPageResult,\n IProjectValidationResult,\n} from '@moldea.ai/core';\n\nimport type { IJsonValue } from '../json-serialization/index.js';\nimport { calculateMoldeaCliJsonDigest } from '../output-page/index.js';\n\nimport { MOLDEA_CLI_GIT_WORKING_TREE_SOURCE } from './constants.js';\nimport type {\n IMoldeaCliAgentRecord,\n IMoldeaCliDiagnosticRecord,\n IMoldeaCliEvidenceRecord,\n IMoldeaCliInspectProjection,\n IMoldeaCliInspectProjectMetadata,\n IMoldeaCliInspectRecord,\n IMoldeaCliMetadataRecord,\n IMoldeaCliValidateProjection,\n} from './types.js';\n\n/** Rejects a Core validation result whose completion fields contradict its validity. */\nconst assertProjectValidationInvariant = (validation: IProjectValidationResult): void => {\n const observedErrorCount = validation.diagnostics.filter(\n (diagnostic) => diagnostic.severity === 'error',\n ).length;\n const isConsistent =\n Number.isSafeInteger(validation.errorCount) &&\n Number.isSafeInteger(validation.warningCount) &&\n validation.errorCount === observedErrorCount &&\n validation.warningCount === validation.diagnostics.length - observedErrorCount &&\n validation.valid === (validation.summary !== null && validation.errorCount === 0) &&\n (validation.valid || validation.errorCount > 0);\n\n if (!isConsistent) {\n throw new TypeError('The Core validation result is internally inconsistent.');\n }\n};\n\n/** Creates one stable composite record key. */\nconst createRecordKey = (kind: string, ...parts: readonly unknown[]): string =>\n JSON.stringify([kind, ...parts]);\n\n/** Projects one diagnostic without retaining arbitrary detail payloads. */\nexport const createMoldeaCliDiagnosticRecord = (\n diagnostic: IDiagnostic,\n occurrence = 0,\n): IMoldeaCliDiagnosticRecord => {\n const record = {\n code: diagnostic.code,\n entity: diagnostic.entity,\n key: createRecordKey(\n 'diagnostic',\n diagnostic.source,\n diagnostic.severity,\n diagnostic.code,\n diagnostic.path,\n diagnostic.pointer,\n diagnostic.severity === 'warning' ? diagnostic.details : null,\n occurrence,\n ),\n kind: 'diagnostic' as const,\n message: diagnostic.message,\n path: diagnostic.path,\n pointer: diagnostic.pointer,\n range: diagnostic.range,\n source: diagnostic.source,\n };\n\n if (diagnostic.severity === 'warning') {\n const details =\n diagnostic.details.reason === 'version-dependent-behavior'\n ? Object.freeze({\n boundaryVersion: diagnostic.details.boundaryVersion,\n declaredRange: diagnostic.details.declaredRange,\n packageName: diagnostic.details.packageName,\n reason: diagnostic.details.reason,\n relationship: diagnostic.details.relationship,\n })\n : Object.freeze({\n reason: diagnostic.details.reason,\n relationship: diagnostic.details.relationship,\n });\n\n return Object.freeze({ ...record, details, severity: 'warning' as const });\n }\n\n return Object.freeze({ ...record, severity: 'error' as const });\n};\n\n/** Projects one bounded Core inspection item through the schema 5 allowlist. */\nconst createInspectRecord = (\n item: IProjectInspectionItem,\n index: number,\n): IMoldeaCliInspectRecord => {\n const order = index.toString().padStart(6, '0');\n\n if (item.kind === 'agent') {\n const record: IMoldeaCliAgentRecord = {\n agentId: item.agent.agentId,\n key: createRecordKey(order, 'agent', item.agent.agentId, item.agent.runtimeId),\n kind: 'agent',\n runtimeId: item.agent.runtimeId,\n };\n\n return Object.freeze(record);\n }\n\n if (item.kind === 'diagnostic') {\n return Object.freeze({\n ...createMoldeaCliDiagnosticRecord(item.diagnostic, index),\n key: createRecordKey(\n order,\n 'diagnostic',\n item.diagnostic.source,\n item.diagnostic.severity,\n item.diagnostic.code,\n item.diagnostic.severity === 'warning' ? item.diagnostic.details : null,\n ),\n });\n }\n\n if (item.kind === 'evidence') {\n const evidence = item.evidence;\n const record: IMoldeaCliEvidenceRecord = {\n agentId: evidence.agentId,\n capabilityId: evidence.capabilityId,\n capabilityKind: evidence.capabilityKind,\n evidenceKind: evidence.kind,\n key: createRecordKey(\n order,\n 'evidence',\n evidence.source,\n evidence.kind,\n evidence.agentId,\n evidence.capabilityKind,\n evidence.capabilityId,\n evidence.runtimeName,\n ),\n kind: 'evidence',\n references: Object.freeze(\n evidence.references.map((reference) =>\n Object.freeze({ path: reference.path, symbol: reference.symbol ?? null }),\n ),\n ),\n runtimeName: evidence.runtimeName,\n source: evidence.source,\n };\n\n return Object.freeze(record);\n }\n\n const metadata = item.metadata;\n const record: IMoldeaCliMetadataRecord = {\n agentId: metadata.agentId,\n byteLength: metadata.byteLength,\n canonicalDigest: metadata.canonicalDigest,\n decisionId: metadata.decisionId,\n digest: metadata.digest,\n key: createRecordKey(order, 'metadata', metadata.path, metadata.kind, metadata.agentId),\n kind: 'metadata',\n metadataKind: metadata.kind,\n path: metadata.path,\n scalarLength: metadata.scalarLength,\n };\n\n return Object.freeze(record);\n};\n\n/** Creates content-free validation metadata and ordered diagnostic records. */\nexport const createMoldeaCliValidateProjection = (\n validation: IProjectValidationResult,\n): IMoldeaCliValidateProjection => {\n assertProjectValidationInvariant(validation);\n const diagnostics = Object.freeze(\n validation.diagnostics\n .map((diagnostic, index) => createMoldeaCliDiagnosticRecord(diagnostic, index))\n .sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0)),\n );\n const snapshotDigest = calculateMoldeaCliJsonDigest({\n diagnostics,\n errorCount: validation.errorCount,\n formatVersion: validation.formatVersion,\n summary: validation.summary,\n valid: validation.valid,\n warningCount: validation.warningCount,\n } as unknown as IJsonValue);\n\n return Object.freeze({\n diagnostics,\n errorCount: validation.errorCount,\n formatVersion: validation.formatVersion,\n snapshotDigest,\n source: MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,\n valid: validation.valid,\n warningCount: validation.warningCount,\n });\n};\n\n/** Projects one bounded Core page through the content-free schema 5 allowlist. */\nexport const createMoldeaCliInspectProjection = (\n inspection: IProjectInspectionPageResult,\n): IMoldeaCliInspectProjection => {\n const project: IMoldeaCliInspectProjectMetadata | null =\n inspection.summary === null\n ? null\n : Object.freeze({\n manifest: Object.freeze({\n digest: inspection.summary.manifestDigest,\n path: inspection.summary.manifestPath,\n }),\n project: Object.freeze({\n digest: inspection.summary.projectDigest,\n path: inspection.summary.projectPath,\n }),\n });\n const records = Object.freeze(\n inspection.page.records.map(({ item }, index) => createInspectRecord(item, index)),\n );\n const sourceCursors = new Map(\n inspection.page.records.map((record, index) => {\n const projected = records[index];\n\n if (projected === undefined) {\n throw new TypeError('A projected inspection record is missing.');\n }\n\n return [projected.key, record.nextCursor] as const;\n }),\n );\n const snapshotDigest = inspection.inspectionDigest;\n\n return Object.freeze({\n counts: inspection.counts,\n formatVersion: inspection.formatVersion,\n getSourceCursor: (record: IMoldeaCliInspectRecord): string | null =>\n sourceCursors.get(record.key) ?? null,\n project,\n records,\n snapshotDigest,\n source: MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,\n valid: inspection.valid,\n view: inspection.view,\n });\n};\n","// maximum bytes accepted from each Git discovery output stream\nexport const MAX_GIT_DISCOVERY_OUTPUT_BYTES = 262_144;\n","import path from 'node:path';\nimport process from 'node:process';\n\nimport { hasOnlyUnicodeScalarValues } from '../command-line/index.js';\n\nimport { MAX_GIT_DISCOVERY_OUTPUT_BYTES } from './constants.js';\n\nconst UTF8_BYTE_ORDER_MARK = [0xef, 0xbb, 0xbf] as const;\n\n/**\n * Decodes one bounded Git output value as strict UTF-8.\n * @param output The raw Git output bytes.\n * @returns The exact decoded value, or null when invalid.\n */\nconst decodeGitOutput = (output: Uint8Array): string | null => {\n if (\n output.byteLength === 0 ||\n output.byteLength > MAX_GIT_DISCOVERY_OUTPUT_BYTES ||\n UTF8_BYTE_ORDER_MARK.every((byte, index) => output[index] === byte)\n ) {\n return null;\n }\n\n let decodedOutput: string;\n\n try {\n decodedOutput = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(output);\n } catch {\n return null;\n }\n\n if (decodedOutput.includes('\\0') || !hasOnlyUnicodeScalarValues(decodedOutput)) {\n return null;\n }\n\n return decodedOutput;\n};\n\n/**\n * Parses Git's canonical boolean output.\n * @param output The raw bounded Git stdout bytes.\n * @returns The parsed boolean, or null when the output is not canonical.\n */\nexport const parseGitBooleanOutput = (output: Uint8Array): boolean | null => {\n const decodedOutput = decodeGitOutput(output);\n\n if (decodedOutput === 'true\\n' || decodedOutput === 'true\\r\\n') {\n return true;\n }\n\n if (decodedOutput === 'false\\n' || decodedOutput === 'false\\r\\n') {\n return false;\n }\n\n return null;\n};\n\n/**\n * Parses one nonempty path returned by Git.\n * @param output The raw bounded Git stdout bytes.\n * @returns The exact relative or absolute path, or null when the output is invalid.\n */\nexport const parseGitPathOutput = (output: Uint8Array): string | null => {\n const decodedOutput = decodeGitOutput(output);\n\n if (decodedOutput === null || !decodedOutput.endsWith('\\n')) {\n return null;\n }\n\n const gitPath =\n process.platform === 'win32' && decodedOutput.endsWith('\\r\\n')\n ? decodedOutput.slice(0, -2)\n : decodedOutput.slice(0, -1);\n\n return gitPath.length === 0 ? null : gitPath;\n};\n\n/**\n * Parses one absolute path returned by Git.\n * @param output The raw bounded Git stdout bytes.\n * @returns The exact absolute path, or null when the output is invalid.\n */\nexport const parseGitAbsolutePathOutput = (output: Uint8Array): string | null => {\n const gitPath = parseGitPathOutput(output);\n\n if (gitPath === null || !path.isAbsolute(gitPath)) {\n return null;\n }\n\n return gitPath;\n};\n","import { stat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {\n hasOnlyUnicodeScalarValues,\n isRepositoryDirectoryInputValid,\n} from '../command-line/index.js';\n\nimport type {\n IGitStartingDirectoryInspectionResult,\n IGitStartingDirectoryInspector,\n IGitStartingDirectoryStat,\n} from './types.js';\n\n/**\n * Maps a filesystem failure without retaining host diagnostics or paths.\n * @param error The unknown filesystem failure.\n * @returns An immutable safe discovery failure.\n */\nconst mapFilesystemFailure = (error: unknown): IGitStartingDirectoryInspectionResult => {\n const errorCode = (error as NodeJS.ErrnoException | null)?.code?.toUpperCase();\n\n if (errorCode === 'ENOENT' || errorCode === 'ENOTDIR') {\n return Object.freeze({ errorCode: 'GIT_REPOSITORY_NOT_FOUND', kind: 'failed' });\n }\n\n if (errorCode === 'EACCES' || errorCode === 'EPERM') {\n return Object.freeze({ errorCode: 'GIT_ACCESS_DENIED', kind: 'failed' });\n }\n\n return Object.freeze({ errorCode: 'GIT_COMMAND_FAILED', kind: 'failed' });\n};\n\n/**\n * Creates a starting-directory inspector around an injectable filesystem boundary.\n * @param inspectPath The filesystem stat operation.\n * @returns A safe inspector that resolves and verifies the selected directory.\n */\nexport const createGitStartingDirectoryInspector =\n (inspectPath: IGitStartingDirectoryStat = stat): IGitStartingDirectoryInspector =>\n async (input): Promise<IGitStartingDirectoryInspectionResult> => {\n if (\n !path.isAbsolute(input.invocationDirectory) ||\n input.invocationDirectory.includes('\\0') ||\n !hasOnlyUnicodeScalarValues(input.invocationDirectory) ||\n (input.repositoryDirectory !== null &&\n !isRepositoryDirectoryInputValid(input.repositoryDirectory))\n ) {\n return Object.freeze({ errorCode: 'GIT_REPOSITORY_NOT_FOUND', kind: 'failed' });\n }\n\n const selectedDirectory =\n input.repositoryDirectory === null\n ? input.invocationDirectory\n : path.isAbsolute(input.repositoryDirectory)\n ? input.repositoryDirectory\n : path.resolve(input.invocationDirectory, input.repositoryDirectory);\n\n try {\n const directoryStats = await inspectPath(selectedDirectory);\n\n if (!directoryStats.isDirectory()) {\n return Object.freeze({ errorCode: 'GIT_REPOSITORY_NOT_FOUND', kind: 'failed' });\n }\n } catch (error) {\n return mapFilesystemFailure(error);\n }\n\n return Object.freeze({ directory: selectedDirectory, kind: 'found' });\n };\n\n// default starting-directory inspection boundary\nexport const inspectGitStartingDirectory = createGitStartingDirectoryInspector();\n","import {\n executeGitProcess,\n type IGitProcessExecutor,\n type IGitProcessFailureReason,\n} from '../git-process/index.js';\nimport { createGitVersionPreflight, type IGitVersionPreflight } from '../git-version/index.js';\nimport type { IMoldeaCliGitErrorCode } from '../presentation/index.js';\n\nimport { MAX_GIT_DISCOVERY_OUTPUT_BYTES } from './constants.js';\nimport { parseGitAbsolutePathOutput, parseGitBooleanOutput } from './parser.js';\nimport { inspectGitStartingDirectory } from './starting-directory.js';\nimport type {\n IGitStartingDirectoryInspector,\n IGitWorkingTreeDiscovery,\n IGitWorkingTreeDiscoveryFailedResult,\n IGitWorkingTreeDiscoveryResult,\n} from './types.js';\n\n/** Maps a normalized Git process failure to a safe discovery error. */\nconst mapGitProcessFailure = (reason: IGitProcessFailureReason): IMoldeaCliGitErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'repository-not-found':\n return 'GIT_REPOSITORY_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'output-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Creates one immutable discovery failure. */\nconst createDiscoveryFailure = (\n errorCode: IMoldeaCliGitErrorCode,\n): IGitWorkingTreeDiscoveryFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/**\n * Creates Git working-tree discovery around injectable process and filesystem boundaries.\n * @param processExecutor The normalized Git subprocess executor.\n * @param startingDirectoryInspector The safe directory inspection boundary.\n * @param gitVersionPreflight The Git version prerequisite check.\n * @returns A working-tree discovery operation.\n */\nexport const createGitWorkingTreeDiscovery =\n (\n processExecutor: IGitProcessExecutor = executeGitProcess,\n startingDirectoryInspector: IGitStartingDirectoryInspector = inspectGitStartingDirectory,\n gitVersionPreflight: IGitVersionPreflight = createGitVersionPreflight(processExecutor),\n ): IGitWorkingTreeDiscovery =>\n async (input): Promise<IGitWorkingTreeDiscoveryResult> => {\n const startingDirectoryResult = await startingDirectoryInspector(input);\n\n if (startingDirectoryResult.kind === 'failed') {\n return createDiscoveryFailure(startingDirectoryResult.errorCode);\n }\n\n const workTreeResult = await processExecutor({\n arguments: ['-C', startingDirectoryResult.directory, 'rev-parse', '--is-inside-work-tree'],\n maxBufferBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (workTreeResult.kind === 'failed') {\n return createDiscoveryFailure(mapGitProcessFailure(workTreeResult.reason));\n }\n\n if (workTreeResult.stderr.byteLength > 0) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n const isInsideWorkTree = parseGitBooleanOutput(workTreeResult.stdout);\n\n if (isInsideWorkTree === null) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n if (!isInsideWorkTree) {\n return createDiscoveryFailure('GIT_WORK_TREE_REQUIRED');\n }\n\n const rootResult = await processExecutor({\n arguments: ['-C', startingDirectoryResult.directory, 'rev-parse', '--show-toplevel'],\n maxBufferBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (rootResult.kind === 'failed') {\n return createDiscoveryFailure(mapGitProcessFailure(rootResult.reason));\n }\n\n if (rootResult.stderr.byteLength > 0) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n const repositoryRoot = parseGitAbsolutePathOutput(rootResult.stdout);\n\n if (repositoryRoot === null) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n const rootDirectoryResult = await startingDirectoryInspector({\n invocationDirectory: startingDirectoryResult.directory,\n repositoryDirectory: repositoryRoot,\n });\n\n if (rootDirectoryResult.kind === 'failed') {\n return createDiscoveryFailure(rootDirectoryResult.errorCode);\n }\n\n const versionResult = await gitVersionPreflight(input.signal);\n\n if (versionResult.kind === 'failed') {\n return createDiscoveryFailure(versionResult.errorCode);\n }\n\n const sparseCheckoutResult = await processExecutor({\n arguments: [\n '-C',\n rootDirectoryResult.directory,\n 'config',\n '--type=bool',\n '--default=false',\n '--get',\n 'core.sparseCheckout',\n ],\n maxBufferBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (sparseCheckoutResult.kind === 'failed') {\n return createDiscoveryFailure(mapGitProcessFailure(sparseCheckoutResult.reason));\n }\n\n if (sparseCheckoutResult.stderr.byteLength > 0) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n const isSparseCheckout = parseGitBooleanOutput(sparseCheckoutResult.stdout);\n\n if (isSparseCheckout === null) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n if (isSparseCheckout) {\n return createDiscoveryFailure('GIT_SPARSE_CHECKOUT_UNSUPPORTED');\n }\n\n return Object.freeze({ kind: 'discovered', repositoryRoot });\n };\n\n// default Git working-tree discovery used by command execution\nexport const discoverGitWorkingTree = createGitWorkingTreeDiscovery();\n","import path from 'node:path';\n\nimport type { IHostPathIdentity, IHostPathOperations } from './types.js';\n\n/**\n * Determines whether two absolute path spellings identify the same host path.\n * @param left The first host path.\n * @param right The second host path.\n * @param hostPathOperations The platform path operations used for comparison.\n * @returns Whether the paths are equivalent under the selected host semantics.\n */\nexport const areHostPathsEquivalent = (\n left: string,\n right: string,\n hostPathOperations: IHostPathOperations = path,\n): boolean =>\n hostPathOperations.relative(\n hostPathOperations.resolve(left),\n hostPathOperations.resolve(right),\n ) === '';\n\n/**\n * Determines whether two observations identify the same filesystem entry.\n * @param left The first filesystem observation.\n * @param right The second filesystem observation.\n * @returns Whether both observations have the same nonzero device and inode identity.\n */\nexport const haveSameHostPathIdentity = (\n left: IHostPathIdentity,\n right: IHostPathIdentity,\n): boolean => left.ino !== 0n && left.dev === right.dev && left.ino === right.ino;\n","import { haveSameHostPathIdentity } from '../../host-path-identity/index.js';\n\nimport type { IGitWorkingTreeIdentity, IGitWorkingTreeIdentityLocation } from './types.js';\n\n/** Determines whether two locations denote the same directory despite host-path aliases. */\nconst areLocationsEqual = (\n left: IGitWorkingTreeIdentityLocation,\n right: IGitWorkingTreeIdentityLocation,\n): boolean => haveSameHostPathIdentity(left, right);\n\n/**\n * Determines whether two observations identify the same working tree and Git repository.\n * @param left The pinned working-tree identity.\n * @param right The identity observed before a snapshot attempt.\n * @returns Whether the root, worktree Git directory, and common directory all match.\n */\nexport const areGitWorkingTreeIdentitiesEqual = (\n left: IGitWorkingTreeIdentity,\n right: IGitWorkingTreeIdentity,\n): boolean =>\n areLocationsEqual(left.repositoryRoot, right.repositoryRoot) &&\n areLocationsEqual(left.gitDirectory, right.gitDirectory) &&\n areLocationsEqual(left.commonDirectory, right.commonDirectory);\n","// fixed Git queries used to establish one working-tree identity\nexport const GIT_WORKING_TREE_IDENTITY_ARGUMENTS = Object.freeze({\n CommonDirectory: Object.freeze(['rev-parse', '--git-common-dir']),\n GitDirectory: Object.freeze(['rev-parse', '--absolute-git-dir']),\n RepositoryRoot: Object.freeze(['rev-parse', '--show-toplevel']),\n});\n","import { stat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { hasOnlyUnicodeScalarValues } from '../../command-line/index.js';\nimport {\n executeGitProcess,\n type IGitProcessExecutor,\n type IGitProcessFailureReason,\n} from '../../git-process/index.js';\nimport {\n areHostPathsEquivalent,\n haveSameHostPathIdentity,\n} from '../../host-path-identity/index.js';\nimport type { IMoldeaCliGitErrorCode } from '../../presentation/index.js';\nimport { MAX_GIT_DISCOVERY_OUTPUT_BYTES } from '../constants.js';\nimport { parseGitAbsolutePathOutput, parseGitPathOutput } from '../parser.js';\n\nimport { GIT_WORKING_TREE_IDENTITY_ARGUMENTS } from './constants.js';\nimport type {\n IGitWorkingTreeIdentityInspectionFailedResult,\n IGitWorkingTreeIdentityInspectionResult,\n IGitWorkingTreeIdentityInspector,\n IGitWorkingTreeIdentityLocation,\n IGitWorkingTreeIdentityStat,\n} from './types.js';\n\n/** Reads one followed directory identity with bigint filesystem fields. */\nconst inspectDirectoryIdentity: IGitWorkingTreeIdentityStat = async (hostPath) =>\n stat(hostPath, { bigint: true });\n\n/** Creates one immutable identity-inspection failure. */\nconst createInspectionFailure = (\n errorCode: IMoldeaCliGitErrorCode,\n): IGitWorkingTreeIdentityInspectionFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps one normalized Git process failure to the discovery error contract. */\nconst mapGitProcessFailure = (reason: IGitProcessFailureReason): IMoldeaCliGitErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'repository-not-found':\n return 'GIT_REPOSITORY_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'output-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Maps one private filesystem failure without exposing its host diagnostics. */\nconst mapFilesystemFailure = (error: unknown): IMoldeaCliGitErrorCode => {\n let errorCode: string | undefined;\n\n try {\n if (typeof error === 'object' && error !== null && 'code' in error) {\n const unknownCode: unknown = error.code;\n\n errorCode = typeof unknownCode === 'string' ? unknownCode.toUpperCase() : undefined;\n }\n } catch {\n return 'GIT_COMMAND_FAILED';\n }\n\n if (errorCode === 'ENOENT' || errorCode === 'ENOTDIR') {\n return 'GIT_REPOSITORY_NOT_FOUND';\n }\n\n if (errorCode === 'EACCES' || errorCode === 'EPERM') {\n return 'GIT_ACCESS_DENIED';\n }\n\n return 'GIT_COMMAND_FAILED';\n};\n\n/** Executes one bounded Git identity-path query. */\nconst queryGitPath = async (\n processExecutor: IGitProcessExecutor,\n repositoryRoot: string,\n arguments_: readonly string[],\n isAbsoluteRequired: boolean,\n signal?: AbortSignal,\n): Promise<string | IGitWorkingTreeIdentityInspectionFailedResult> => {\n const result = await processExecutor({\n arguments: ['-C', repositoryRoot, ...arguments_],\n maxBufferBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,\n ...(signal === undefined ? {} : { signal }),\n });\n\n if (result.kind === 'failed') {\n return createInspectionFailure(mapGitProcessFailure(result.reason));\n }\n\n if (result.stderr.byteLength > 0) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const gitPath = isAbsoluteRequired\n ? parseGitAbsolutePathOutput(result.stdout)\n : parseGitPathOutput(result.stdout);\n\n return gitPath ?? createInspectionFailure('GIT_OUTPUT_INVALID');\n};\n\n/** Captures one directory path and stable filesystem identity. */\nconst captureLocation = async (\n inspectPath: IGitWorkingTreeIdentityStat,\n hostPath: string,\n invalidTypeCode: IMoldeaCliGitErrorCode,\n): Promise<IGitWorkingTreeIdentityLocation | IGitWorkingTreeIdentityInspectionFailedResult> => {\n try {\n const statistics = await inspectPath(hostPath);\n\n if (!statistics.isDirectory() || statistics.ino === 0n) {\n return createInspectionFailure(invalidTypeCode);\n }\n\n return Object.freeze({ dev: statistics.dev, ino: statistics.ino, path: hostPath });\n } catch (error) {\n return createInspectionFailure(mapFilesystemFailure(error));\n }\n};\n\n/** Determines whether an identity helper returned a safe failure. */\nconst isInspectionFailure = (\n result: string | IGitWorkingTreeIdentityLocation | IGitWorkingTreeIdentityInspectionFailedResult,\n): result is IGitWorkingTreeIdentityInspectionFailedResult =>\n typeof result === 'object' && 'kind' in result && result.kind === 'failed';\n\n/**\n * Creates a bounded working-tree identity inspector around Git and filesystem boundaries.\n * @param processExecutor The sanitized bounded Git process executor.\n * @param inspectPath The followed directory identity operation.\n * @returns An inspector that captures one private immutable identity.\n */\nexport const createGitWorkingTreeIdentityInspector = (\n processExecutor: IGitProcessExecutor = executeGitProcess,\n inspectPath: IGitWorkingTreeIdentityStat = inspectDirectoryIdentity,\n): IGitWorkingTreeIdentityInspector => {\n return async (input): Promise<IGitWorkingTreeIdentityInspectionResult> => {\n if (\n !path.isAbsolute(input.repositoryRoot) ||\n input.repositoryRoot.includes('\\0') ||\n !hasOnlyUnicodeScalarValues(input.repositoryRoot)\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const discoveredRoot = await queryGitPath(\n processExecutor,\n input.repositoryRoot,\n GIT_WORKING_TREE_IDENTITY_ARGUMENTS.RepositoryRoot,\n true,\n input.signal,\n );\n\n if (isInspectionFailure(discoveredRoot)) {\n return discoveredRoot;\n }\n\n const repositoryRoot = await captureLocation(\n inspectPath,\n discoveredRoot,\n 'GIT_WORK_TREE_REQUIRED',\n );\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isInspectionFailure(repositoryRoot)) {\n return repositoryRoot;\n }\n\n if (!areHostPathsEquivalent(discoveredRoot, input.repositoryRoot)) {\n const selectedRepositoryRoot = await captureLocation(\n inspectPath,\n input.repositoryRoot,\n 'GIT_WORK_TREE_REQUIRED',\n );\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isInspectionFailure(selectedRepositoryRoot)) {\n return selectedRepositoryRoot;\n }\n\n if (!haveSameHostPathIdentity(repositoryRoot, selectedRepositoryRoot)) {\n return Object.freeze({ kind: 'mismatched' });\n }\n }\n\n const gitDirectoryPath = await queryGitPath(\n processExecutor,\n input.repositoryRoot,\n GIT_WORKING_TREE_IDENTITY_ARGUMENTS.GitDirectory,\n true,\n input.signal,\n );\n\n if (isInspectionFailure(gitDirectoryPath)) {\n return gitDirectoryPath;\n }\n\n const commonDirectoryOutput = await queryGitPath(\n processExecutor,\n input.repositoryRoot,\n GIT_WORKING_TREE_IDENTITY_ARGUMENTS.CommonDirectory,\n false,\n input.signal,\n );\n\n if (isInspectionFailure(commonDirectoryOutput)) {\n return commonDirectoryOutput;\n }\n\n const commonDirectoryPath = path.isAbsolute(commonDirectoryOutput)\n ? commonDirectoryOutput\n : path.resolve(input.repositoryRoot, commonDirectoryOutput);\n const gitDirectory = await captureLocation(inspectPath, gitDirectoryPath, 'GIT_OUTPUT_INVALID');\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isInspectionFailure(gitDirectory)) {\n return gitDirectory;\n }\n\n const commonDirectory = await captureLocation(\n inspectPath,\n commonDirectoryPath,\n 'GIT_OUTPUT_INVALID',\n );\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isInspectionFailure(commonDirectory)) {\n return commonDirectory;\n }\n\n return Object.freeze({\n identity: Object.freeze({ commonDirectory, gitDirectory, repositoryRoot }),\n kind: 'inspected',\n });\n };\n};\n\n// default identity inspector used by snapshot execution\nexport const inspectGitWorkingTreeIdentity = createGitWorkingTreeIdentityInspector();\n","import type { IMoldeaCliProjectContentErrorCode } from './types.js';\n\n/** Represents an invalid explicit canonical content request. */\nexport class MoldeaCliProjectContentException extends Error {\n public readonly code: IMoldeaCliProjectContentErrorCode;\n\n /** Creates one content request failure with a stable public code. */\n public constructor(code: IMoldeaCliProjectContentErrorCode) {\n super(code);\n this.code = code;\n this.name = 'MoldeaCliProjectContentException';\n }\n}\n","import { parseRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport { MoldeaCliProjectContentException } from './exception.js';\n\nconst CONTEXT_PATH_PATTERN = /^\\/moldea\\/context\\/(?:[^/]+\\/)*[^/]+\\.md$/u;\nconst DECISION_PATH_PATTERN = /^\\/moldea\\/decisions\\/[^/]+\\.md$/u;\nconst RUNTIME_PATH_PATTERN = /^\\/moldea\\/runtimes\\/(?:[^/]+\\/)*[^/]+\\.md$/u;\nconst AGENT_PATH_PATTERN =\n /^\\/moldea\\/agents\\/[^/]+\\/(?:description|instruction|handoff-description)\\.md$/u;\n\n/** Determines whether a logical path names one canonical moldea text asset. */\nexport const isMoldeaCliCanonicalContentPath = (path: IRepositoryPath): boolean => {\n if (/[?*[\\]{}]/u.test(path)) {\n return false;\n }\n\n return (\n path === '/moldea/moldea.yaml' ||\n path === '/moldea/project.md' ||\n CONTEXT_PATH_PATTERN.test(path) ||\n DECISION_PATH_PATTERN.test(path) ||\n RUNTIME_PATH_PATTERN.test(path) ||\n AGENT_PATH_PATTERN.test(path)\n );\n};\n\n/**\n * Parses one untrusted path and restricts it to the canonical text layout.\n * @param input The command-line logical path.\n * @returns The validated canonical repository path.\n * @throws\n * - CONTENT_PATH_INVALID: The content path must identify one canonical moldea text asset.\n */\nexport const parseMoldeaCliCanonicalContentPath = (input: string): IRepositoryPath => {\n let path: IRepositoryPath;\n\n try {\n path = parseRepositoryPath(input);\n } catch {\n throw new MoldeaCliProjectContentException('CONTENT_PATH_INVALID');\n }\n\n if (!isMoldeaCliCanonicalContentPath(path)) {\n throw new MoldeaCliProjectContentException('CONTENT_PATH_INVALID');\n }\n\n return path;\n};\n","import { createCore } from '@moldea.ai/core';\n\nimport type {\n IMoldeaCliProjectContentCoreFactory,\n IMoldeaCliProjectContentExecutor,\n} from './types.js';\n\n/** Creates an adapter-free executor for one bounded canonical content range. */\nexport const createMoldeaCliProjectContentExecutor = (\n coreFactory: IMoldeaCliProjectContentCoreFactory = createCore,\n): IMoldeaCliProjectContentExecutor => {\n return async (input) => {\n const core = coreFactory({\n limits: Object.freeze({\n maxDiagnostics: input.resourceLimits.maxDiagnostics,\n maxEntries: input.resourceLimits.maxEntries,\n maxEvidence: input.resourceLimits.maxEvidence,\n maxFileBytes: input.resourceLimits.maxFileBytes,\n maxManifestBytes: input.resourceLimits.maxManifestBytes,\n maxTotalBytesRead: input.resourceLimits.maxTotalBytes,\n }),\n });\n\n return core.readCanonicalContentPage({\n maxBytes: input.maxBytes,\n offset: input.offset,\n path: input.path,\n repository: input.repository,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n };\n};\n\n/** Executes one adapter-free explicit canonical content range read. */\nexport const executeMoldeaCliProjectContent = createMoldeaCliProjectContentExecutor();\n","import type { IJsonValue } from '../json-serialization/index.js';\nimport {\n calculateMoldeaCliJsonDigest,\n decodeMoldeaCliCursor,\n encodeMoldeaCliCursor,\n MoldeaCliOutputPageException,\n} from '../output-page/index.js';\n\nimport type { IMoldeaCliContentPageInput, IMoldeaCliContentResult } from './types.js';\n\n/** Creates one candidate content result ending at a Unicode scalar boundary. */\nconst createCandidate = (\n input: IMoldeaCliContentPageInput,\n scalars: readonly string[],\n scalarEnd: number,\n snapshotDigest: string,\n): IMoldeaCliContentResult => {\n const content = scalars.slice(0, scalarEnd).join('');\n const byteEnd = input.page.byteStart + Buffer.byteLength(content, 'utf8');\n const isComplete = byteEnd === input.page.totalBytes;\n\n return {\n asset: {\n contentIdentity: input.page.contentIdentity,\n path: input.page.path,\n totalBytes: input.page.totalBytes,\n },\n chunk: {\n byteEnd,\n byteStart: input.page.byteStart,\n content,\n },\n cursor: isComplete\n ? null\n : encodeMoldeaCliCursor(\n 'content',\n { path: input.page.path },\n snapshotDigest,\n `byte:${byteEnd}`,\n `byte:${byteEnd}`,\n ),\n snapshotDigest,\n };\n};\n\n/** Creates the stable identity shared by every page of one canonical file snapshot. */\nconst createSnapshotDigest = (input: IMoldeaCliContentPageInput): string =>\n calculateMoldeaCliJsonDigest({\n contentIdentity: input.page.contentIdentity,\n path: input.page.path,\n totalBytes: input.page.totalBytes,\n } satisfies IJsonValue);\n\n/** Selects the largest Unicode-safe content prefix within the exact output budget. */\nexport const createMoldeaCliContentPage = (\n input: IMoldeaCliContentPageInput,\n): IMoldeaCliContentResult => {\n const snapshotDigest = createSnapshotDigest(input);\n const cursorState =\n input.cursor === null\n ? null\n : decodeMoldeaCliCursor({\n command: 'content',\n cursor: input.cursor,\n filters: { path: input.page.path },\n snapshotDigest,\n });\n const expectedSourceCursor = `byte:${input.page.byteStart}`;\n\n if (\n (cursorState === null && input.page.byteStart !== 0) ||\n (cursorState !== null && cursorState.sourceCursor !== expectedSourceCursor)\n ) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n const scalars = Array.from(input.page.content);\n const emptyResult = createCandidate(input, scalars, 0, snapshotDigest);\n\n if (scalars.length === 0) {\n if (!input.page.isComplete || input.measure(emptyResult) > input.maxOutputBytes) {\n throw new MoldeaCliOutputPageException('OUTPUT_BUDGET_TOO_SMALL');\n }\n\n return Object.freeze({\n ...emptyResult,\n asset: Object.freeze(emptyResult.asset),\n chunk: Object.freeze(emptyResult.chunk),\n });\n }\n\n let lower = 1;\n let upper = scalars.length;\n let selected: IMoldeaCliContentResult | null = null;\n\n while (lower <= upper) {\n const scalarEnd = lower + Math.floor((upper - lower) / 2);\n const candidate = createCandidate(input, scalars, scalarEnd, snapshotDigest);\n\n if (input.measure(candidate) <= input.maxOutputBytes) {\n selected = candidate;\n lower = scalarEnd + 1;\n } else {\n upper = scalarEnd - 1;\n }\n }\n\n if (selected === null) {\n throw new MoldeaCliOutputPageException('OUTPUT_BUDGET_TOO_SMALL');\n }\n\n return Object.freeze({\n ...selected,\n asset: Object.freeze(selected.asset),\n chunk: Object.freeze(selected.chunk),\n });\n};\n","import { parseRepositoryPath } from '@moldea.ai/repository';\n\n// only canonical asset required for changed-path relationship matching\nexport const MOLDEA_MANIFEST_PATH = parseRepositoryPath('/moldea/moldea.yaml');\n","import type { IMoldeaCliProjectScopeErrorCode } from './types.js';\n\n/** Represents invalid NUL-delimited changed-path input owned by the CLI. */\nexport class MoldeaCliProjectScopeException extends Error {\n public readonly code: IMoldeaCliProjectScopeErrorCode;\n\n /** Creates one scope-input failure with a stable public code. */\n public constructor(code: IMoldeaCliProjectScopeErrorCode) {\n super(code);\n this.code = code;\n this.name = 'MoldeaCliProjectScopeException';\n }\n}\n","import { MoldeaCliProjectScopeException } from './exception.js';\n\n/**\n * Parses bounded NUL-delimited UTF-8 changed paths without shell interpretation.\n * @param input Exact stdin bytes supplied to the scope command.\n * @param maxEntries Maximum changed-path records accepted by the operation.\n * @returns Detached path strings in supplied order for Core validation and normalization.\n * @throws\n * - PATH_INPUT_INVALID: The NUL-delimited changed-path input is invalid.\n */\nexport const parseMoldeaCliScopePathBytes = (\n input: Uint8Array,\n maxEntries: number,\n): readonly string[] => {\n if (input.byteLength === 0) {\n return Object.freeze([]);\n }\n\n let text: string;\n\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(input);\n } catch {\n throw new MoldeaCliProjectScopeException('PATH_INPUT_INVALID');\n }\n\n if (!text.endsWith('\\0')) {\n throw new MoldeaCliProjectScopeException('PATH_INPUT_INVALID');\n }\n\n const paths = text.slice(0, -1).split('\\0');\n\n if (paths.length > maxEntries || paths.some((path) => path.length === 0)) {\n throw new MoldeaCliProjectScopeException('PATH_INPUT_INVALID');\n }\n\n return Object.freeze(paths);\n};\n","import { createCore } from '@moldea.ai/core';\nimport { RepositorySourceException } from '@moldea.ai/repository';\n\nimport { MOLDEA_MANIFEST_PATH } from './constants.js';\nimport type {\n IMoldeaCliProjectScopeCoreFactory,\n IMoldeaCliProjectScopeExecutor,\n IMoldeaCliProjectScopeInput,\n} from './types.js';\n\n/** Reads the complete manifest within its explicit small-file resource bound. */\nconst readBoundedManifest = async (input: IMoldeaCliProjectScopeInput): Promise<Uint8Array> => {\n const operationOptions = input.signal === undefined ? undefined : { signal: input.signal };\n const entry = await input.repository.getEntry(MOLDEA_MANIFEST_PATH, operationOptions);\n\n if (entry === null) {\n throw new RepositorySourceException({\n code: 'ENTRY_NOT_FOUND',\n operation: 'read-file-page',\n path: MOLDEA_MANIFEST_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: MOLDEA_MANIFEST_PATH,\n retryable: false,\n });\n }\n\n const maxBytes = Math.min(\n input.resourceLimits.maxManifestBytes,\n input.resourceLimits.maxTotalBytes,\n );\n\n if (entry.byteLength > maxBytes) {\n throw new RepositorySourceException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n operation: 'read-file-page',\n path: MOLDEA_MANIFEST_PATH,\n retryable: false,\n });\n }\n\n const chunks: Uint8Array[] = [];\n let byteLength = 0;\n let nextOffset = 0;\n let isComplete = false;\n\n while (!isComplete) {\n const page = await input.repository.readFilePage(MOLDEA_MANIFEST_PATH, {\n maxBytes: Math.max(1, entry.byteLength - byteLength),\n offset: nextOffset,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (\n page.snapshot.id !== input.repository.snapshot.id ||\n page.offset !== nextOffset ||\n page.totalBytes !== entry.byteLength ||\n page.bytes.byteLength > entry.byteLength - byteLength ||\n (page.bytes.byteLength === 0 && !page.isComplete) ||\n (!page.isComplete && page.nextOffset !== page.offset + page.bytes.byteLength)\n ) {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path: MOLDEA_MANIFEST_PATH,\n retryable: false,\n });\n }\n\n chunks.push(page.bytes);\n byteLength += page.bytes.byteLength;\n nextOffset = page.nextOffset ?? byteLength;\n isComplete = page.isComplete;\n }\n\n if (byteLength !== entry.byteLength) {\n throw new RepositorySourceException({\n code: 'PROVIDER_INCOMPLETE',\n operation: 'read-file-page',\n path: MOLDEA_MANIFEST_PATH,\n retryable: false,\n });\n }\n\n const manifestBytes = new Uint8Array(byteLength);\n let writeOffset = 0;\n\n for (const chunk of chunks) {\n manifestBytes.set(chunk, writeOffset);\n writeOffset += chunk.byteLength;\n }\n\n return manifestBytes;\n};\n\n/** Creates an adapter-free manifest-only Core scope executor. */\nexport const createMoldeaCliProjectScopeExecutor = (\n coreFactory: IMoldeaCliProjectScopeCoreFactory = createCore,\n): IMoldeaCliProjectScopeExecutor => {\n return async (input) => {\n const manifestBytes = await readBoundedManifest(input);\n const core = coreFactory({\n limits: Object.freeze({\n maxDiagnostics: input.resourceLimits.maxDiagnostics,\n maxEntries: input.resourceLimits.maxEntries,\n maxEvidence: input.resourceLimits.maxEvidence,\n maxFileBytes: input.resourceLimits.maxFileBytes,\n maxManifestBytes: input.resourceLimits.maxManifestBytes,\n maxTotalBytesRead: input.resourceLimits.maxTotalBytes,\n }),\n });\n const scope = await core.matchManifestScope({\n manifest: { content: manifestBytes, path: MOLDEA_MANIFEST_PATH },\n paths: input.paths,\n });\n\n return Object.freeze({\n manifestContent: new TextDecoder('utf-8').decode(manifestBytes),\n scope,\n });\n };\n};\n\n/** Executes one adapter-free manifest-only changed-path scope match. */\nexport const executeMoldeaCliProjectScope = createMoldeaCliProjectScopeExecutor();\n","import type { IManifestScopeMatch } from '@moldea.ai/core';\n\nimport { calculateMoldeaCliJsonDigest } from '../output-page/index.js';\nimport { createMoldeaCliDiagnosticRecord } from '../presentation/index.js';\nimport type { IJsonValue } from '../json-serialization/index.js';\n\nimport type {\n IMoldeaCliScopeProjection,\n IMoldeaCliScopeRecord,\n IMoldeaCliProjectScopeExecutionResult,\n} from './types.js';\n\nconst compareKeys = (left: IMoldeaCliScopeRecord, right: IMoldeaCliScopeRecord): number =>\n left.key < right.key ? -1 : left.key > right.key ? 1 : 0;\n\n/** Creates one stable key for a relationship-match projection. */\nconst createMatchKey = (match: IManifestScopeMatch): string =>\n JSON.stringify([\n 'match',\n match.owner.kind,\n match.owner.agentId,\n match.owner.id,\n match.field,\n match.declaration.kind === 'exact' ? match.declaration.path : match.declaration.pattern,\n match.inputPath,\n match.pointer,\n ]);\n\n/** Projects complete Core scope output into ordered content-free CLI records. */\nexport const createMoldeaCliScopeProjection = (\n execution: IMoldeaCliProjectScopeExecutionResult,\n): IMoldeaCliScopeProjection => {\n const records: IMoldeaCliScopeRecord[] = [\n ...execution.scope.diagnostics.map((diagnostic, index) =>\n createMoldeaCliDiagnosticRecord(diagnostic, index),\n ),\n ...execution.scope.matches.map((match): IMoldeaCliScopeRecord => ({\n key: createMatchKey(match),\n kind: 'match',\n match,\n })),\n ].sort(compareKeys);\n const snapshotDigest = calculateMoldeaCliJsonDigest({\n inputDigest: execution.scope.inputDigest,\n manifestDigest: execution.scope.manifestDigest,\n records,\n valid: execution.scope.valid,\n } as unknown as IJsonValue);\n\n return Object.freeze({\n canonicalBodies: Object.freeze([execution.manifestContent]),\n counts: Object.freeze({\n ...execution.scope.counts,\n diagnostics: execution.scope.diagnostics.length,\n }),\n inputDigest: execution.scope.inputDigest,\n manifestDigest: execution.scope.manifestDigest,\n records: Object.freeze(records),\n relevant: execution.scope.relevant,\n snapshotDigest,\n valid: execution.scope.valid,\n });\n};\n","import { RepositorySourceException, type IRepositoryPath } from '@moldea.ai/repository';\n\n/** Identifies a guarded logical file whose working-tree bytes are unsafe to inspect. */\nexport class GitContentTransformUnsupportedException extends RepositorySourceException {\n /** Creates the CLI-owned marker on the common repository-source failure boundary. */\n public constructor(path: IRepositoryPath) {\n super({\n code: 'SOURCE_UNAVAILABLE',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n this.name = 'GitContentTransformUnsupportedException';\n }\n}\n","import {\n REPOSITORY_ROOT,\n RepositorySourceException,\n createRepositoryComparison,\n parseRepositoryPath,\n type IRepositoryComparison,\n type IRepositoryEntry,\n type IRepositoryEntryPage,\n type IRepositoryEntryPageOptions,\n type IRepositoryFilePage,\n type IRepositoryFilePageOptions,\n type IRepositoryOperationOptions,\n type IRepositoryPath,\n type IRepositoryReader,\n type IRepositorySnapshot,\n} from '@moldea.ai/repository';\n\nimport { GitContentTransformUnsupportedException } from './exception.js';\n\n/** Throws the common cancellation contract for one guard-owned read step. */\nconst throwIfAborted = (signal: AbortSignal | undefined, path: IRepositoryPath): void => {\n if (!signal?.aborted) {\n return;\n }\n\n throw new RepositorySourceException({\n cause: signal.reason,\n code: 'ABORTED',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n};\n\n/** Creates the common failure for contradictory underlying lookup data. */\nconst createInvalidSourceException = (path: IRepositoryPath): RepositorySourceException =>\n new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n\n// immutable guarded-read view over one coherent logical repository reader\nclass GitContentTransformationGuardRepositoryReader implements IRepositoryReader {\n public readonly snapshot: IRepositorySnapshot;\n\n readonly #guardedPaths: ReadonlySet<IRepositoryPath>;\n\n readonly #reader: IRepositoryReader;\n\n public constructor(reader: IRepositoryReader, guardedPaths: ReadonlySet<IRepositoryPath>) {\n this.#reader = reader;\n this.#guardedPaths = guardedPaths;\n this.snapshot = reader.snapshot;\n }\n\n /** Creates a bounded comparison from this guarded logical snapshot. */\n public compare(\n candidate: IRepositoryReader,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryComparison> {\n return createRepositoryComparison(this, candidate, options);\n }\n\n /**\n * Looks up an entry without changing the underlying logical inventory.\n * @param path The validated repository path to inspect.\n * @param options Optional cancellation controls.\n * @returns A promise resolving to the underlying detached entry or confirmed absence.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during the operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public getEntry(\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryEntry | null> {\n return this.#reader.getEntry(path, options);\n }\n\n /**\n * Reads ordinary files while refusing guarded logical regular-file bytes.\n * @param path The validated repository file path to read.\n * @param options Optional cancellation controls.\n * @returns A promise resolving to fresh bytes for an unguarded regular file.\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 or its regular file uses an unsupported Git content transformation.\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 repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public async readFilePage(\n path: IRepositoryPath,\n options: IRepositoryFilePageOptions,\n ): Promise<IRepositoryFilePage> {\n const parsedPath = parseRepositoryPath(path);\n\n if (!this.#guardedPaths.has(parsedPath)) {\n return this.#reader.readFilePage(parsedPath, options);\n }\n\n throwIfAborted(options?.signal, parsedPath);\n\n const entry = await this.#reader.getEntry(parsedPath, options);\n\n throwIfAborted(options?.signal, parsedPath);\n\n if (\n entry !== null &&\n (entry.path !== parsedPath ||\n (entry.type !== 'file' && entry.type !== 'directory' && entry.type !== 'symlink'))\n ) {\n throw createInvalidSourceException(parsedPath);\n }\n\n if (entry?.type !== 'file') {\n return this.#reader.readFilePage(parsedPath, options);\n }\n\n throw new GitContentTransformUnsupportedException(parsedPath);\n }\n\n /**\n * Recursively lists entries without changing the underlying logical inventory.\n * @param options Optional prefix and cancellation controls.\n * @returns The underlying async iterable of detached repository entries.\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_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 repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public listEntriesPage(options: IRepositoryEntryPageOptions): Promise<IRepositoryEntryPage> {\n return this.#reader.listEntriesPage(options);\n }\n}\n\n/**\n * Creates an immutable reader that blocks bytes for Git transform-guarded logical files.\n * @param reader The coherent reader after logical Git entry-type overlays are applied.\n * @param guardedPaths The paths whose working-tree bytes may differ from Git content.\n * @returns A reader preserving inventory semantics while refusing guarded regular-file reads.\n * @throws\n * - INVALID_REPOSITORY_PATH: A guarded repository path is invalid.\n * - INVALID_SOURCE_DATA: The repository root was supplied as a guarded file path.\n */\nexport const createGitContentTransformationGuardRepositoryReader = (\n reader: IRepositoryReader,\n guardedPaths: readonly IRepositoryPath[],\n): IRepositoryReader => {\n const parsedGuardedPaths = new Set<IRepositoryPath>();\n\n for (const guardedPath of guardedPaths) {\n const parsedPath = parseRepositoryPath(guardedPath);\n\n if (parsedPath === REPOSITORY_ROOT) {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'create-reader',\n path: parsedPath,\n retryable: false,\n });\n }\n\n parsedGuardedPaths.add(parsedPath);\n }\n\n return Object.freeze(\n new GitContentTransformationGuardRepositoryReader(reader, parsedGuardedPaths),\n );\n};\n","import type { ICoreConfigurationErrorCode, ICoreOperationErrorCode } from '@moldea.ai/core';\nimport type { IRepositorySourceErrorCode } from '@moldea.ai/repository';\n\n// safe messages for common repository-source failures\nexport const REPOSITORY_SOURCE_ERROR_MESSAGES = Object.freeze({\n ABORTED: 'The repository operation was aborted.',\n ACCESS_DENIED: 'Access to the repository source was denied.',\n ENTRY_NOT_DIRECTORY: 'The requested repository entry is not a directory.',\n ENTRY_NOT_FILE: 'The requested repository entry is not a file.',\n ENTRY_NOT_FOUND: 'The requested repository entry was not found.',\n INVALID_PAGE_REQUEST: 'The repository page request is invalid.',\n INVALID_SOURCE_DATA: 'The repository source returned invalid data.',\n PROVIDER_INCOMPLETE: 'The repository provider could not expose a complete result.',\n RESOURCE_LIMIT_EXCEEDED: 'A repository reading resource limit was exceeded.',\n SNAPSHOT_CHANGED: 'The repository snapshot changed during the operation.',\n SOURCE_UNAVAILABLE: 'The repository source is unavailable.',\n} as const satisfies Readonly<Record<IRepositorySourceErrorCode, string>>);\n\n// safe messages for Core configuration failures\nexport const CORE_CONFIGURATION_ERROR_MESSAGES = Object.freeze({\n DUPLICATE_ADAPTER_ID: 'A runtime adapter ID is registered more than once.',\n INVALID_ADAPTER_DEFINITION: 'A runtime adapter definition is invalid.',\n INVALID_RESOURCE_LIMIT: 'A Core resource limit is invalid.',\n RESERVED_ADAPTER_ID: 'A reserved runtime adapter ID was supplied.',\n} as const satisfies Readonly<Record<ICoreConfigurationErrorCode, string>>);\n\n// safe messages for Core operation failures\nexport const CORE_OPERATION_ERROR_MESSAGES = Object.freeze({\n ABORTED: 'The Core operation was aborted.',\n ADAPTER_EXECUTION_FAILED: 'A runtime adapter failed during inspection.',\n CONTENT_INVALID: 'The requested canonical content is invalid.',\n INVALID_ARGUMENT: 'The Core operation received an invalid argument.',\n RESOURCE_LIMIT_EXCEEDED: 'A Core resource limit was exceeded.',\n} as const satisfies Readonly<Record<ICoreOperationErrorCode, string>>);\n","import { CoreConfigurationException, CoreOperationException } from '@moldea.ai/core';\nimport { isRepositoryPath, RepositorySourceException } from '@moldea.ai/repository';\n\nimport { MoldeaCliOutputPageException } from '../output-page/index.js';\nimport { MoldeaCliProjectContentException } from '../project-content/index.js';\nimport { MoldeaCliProjectScopeException } from '../project-scope/index.js';\nimport { GitContentTransformUnsupportedException } from '../repository-content-transformation-guard/index.js';\nimport { createMoldeaCliOwnedError, type IMoldeaCliError } from '../presentation/index.js';\n\nimport {\n CORE_CONFIGURATION_ERROR_MESSAGES,\n CORE_OPERATION_ERROR_MESSAGES,\n REPOSITORY_SOURCE_ERROR_MESSAGES,\n} from './constants.js';\n\nconst EMPTY_ERROR_DETAILS = Object.freeze({});\n\n/** Creates frozen safe Core metadata without retaining null fields. */\nconst createCoreErrorDetails = (\n error: CoreConfigurationException | CoreOperationException,\n): Readonly<Record<string, string | number>> => {\n const details: Record<string, string | number> = { operation: error.operation };\n\n if (error.adapterId !== null) {\n details['adapterId'] = error.adapterId;\n }\n\n if (error instanceof CoreOperationException) {\n if (error.agentId !== null) {\n details['agentId'] = error.agentId;\n }\n\n if (error.limit !== null) {\n details['limit'] = error.limit;\n }\n\n if (error.limitMaximum !== null) {\n details['limitMaximum'] = error.limitMaximum;\n }\n\n if (error.nextAction !== null) {\n details['nextAction'] = error.nextAction;\n }\n\n if (error.observedUsage !== null) {\n details['observedUsage'] = error.observedUsage;\n }\n }\n\n return Object.freeze(details);\n};\n\n/**\n * Maps a known package exception or unknown failure to one safe CLI error object.\n * @param error The failure that escaped command composition.\n * @returns A complete immutable operational error without causes or private host data.\n */\nexport const mapMoldeaCliOperationalError = (error: unknown): IMoldeaCliError => {\n if (\n error instanceof MoldeaCliOutputPageException ||\n error instanceof MoldeaCliProjectContentException ||\n error instanceof MoldeaCliProjectScopeException\n ) {\n return createMoldeaCliOwnedError(error.code);\n }\n\n if (error instanceof GitContentTransformUnsupportedException) {\n return Object.freeze({\n ...createMoldeaCliOwnedError('GIT_CONTENT_TRANSFORM_UNSUPPORTED'),\n path: isRepositoryPath(error.path) ? error.path : null,\n });\n }\n\n if (error instanceof RepositorySourceException) {\n return Object.freeze({\n code: error.code,\n details: EMPTY_ERROR_DETAILS,\n message: REPOSITORY_SOURCE_ERROR_MESSAGES[error.code],\n path: error.path !== null && isRepositoryPath(error.path) ? error.path : null,\n retryable: error.retryable,\n source: 'repository',\n });\n }\n\n if (error instanceof CoreConfigurationException) {\n return Object.freeze({\n code: error.code,\n details: createCoreErrorDetails(error),\n message: CORE_CONFIGURATION_ERROR_MESSAGES[error.code],\n path: null,\n retryable: false,\n source: 'core',\n });\n }\n\n if (error instanceof CoreOperationException) {\n return Object.freeze({\n code: error.code,\n details: createCoreErrorDetails(error),\n message: CORE_OPERATION_ERROR_MESSAGES[error.code],\n path: null,\n retryable: error.retryable,\n source: 'core',\n });\n }\n\n return createMoldeaCliOwnedError('INTERNAL_ERROR');\n};\n","// fixed read-only Git commands used to enumerate raw working-tree candidates\nexport const GIT_TRACKED_INVENTORY_ARGUMENTS = [\n 'ls-files',\n '--cached',\n '--stage',\n '--full-name',\n '--no-abbrev',\n '--no-recurse-submodules',\n '-z',\n '--',\n] as const;\n\nexport const GIT_UNTRACKED_INVENTORY_ARGUMENTS = [\n 'ls-files',\n '--others',\n '--exclude-standard',\n '--full-name',\n '--no-recurse-submodules',\n '-z',\n '--',\n] as const;\n\n// Git index modes accepted by the version 1 inventory grammar\nexport const GIT_TRACKED_ENTRY_MODES = ['100644', '100755', '120000', '160000'] as const;\n","// Git attributes required to classify working-tree content transformations\nexport const GIT_CONTENT_TRANSFORMATION_ATTRIBUTES = [\n 'filter',\n 'working-tree-encoding',\n 'ident',\n] as const;\n\n// fixed read-only Git command used for NUL-delimited attribute inspection\nexport const GIT_CONTENT_TRANSFORMATION_ARGUMENTS = [\n 'check-attr',\n '--stdin',\n '-z',\n ...GIT_CONTENT_TRANSFORMATION_ATTRIBUTES,\n] as const;\n","import { GIT_CONTENT_TRANSFORMATION_ATTRIBUTES } from './constants.js';\nimport type {\n IGitContentTransformationAttribute,\n IGitContentTransformationAttributeValues,\n IGitContentTransformationParsedAttributes,\n IGitContentTransformationParser,\n IGitContentTransformationParserInput,\n IGitContentTransformationParserResult,\n} from './types.js';\n\ninterface IMutableAttributeValues {\n filter?: string;\n ident?: string;\n workingTreeEncoding?: string;\n}\n\n/** Concatenates one complete NUL-delimited field assembled across process chunks. */\nconst concatenateField = (fragments: readonly Uint8Array[], byteLength: number): Uint8Array => {\n const field = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const fragment of fragments) {\n field.set(fragment, offset);\n offset += fragment.byteLength;\n }\n\n return field;\n};\n\n/** Decodes one Git attribute field as strict UTF-8 while preserving an initial BOM scalar. */\nconst decodeField = (field: Uint8Array): string | null => {\n try {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(field);\n } catch {\n return null;\n }\n};\n\n/** Resolves one exact supported attribute name without accepting aliases. */\nconst resolveAttribute = (candidate: string): IGitContentTransformationAttribute | null => {\n return GIT_CONTENT_TRANSFORMATION_ATTRIBUTES.find((attribute) => attribute === candidate) ?? null;\n};\n\n/** Stores one exact Git value while rejecting duplicate attribute records. */\nconst storeAttribute = (\n values: IMutableAttributeValues,\n attribute: IGitContentTransformationAttribute,\n value: string,\n): boolean => {\n const property = attribute === 'working-tree-encoding' ? 'workingTreeEncoding' : attribute;\n\n if (Object.hasOwn(values, property)) {\n return false;\n }\n\n values[property] = value;\n return true;\n};\n\n/** Confirms that all three required effective attribute values were received. */\nconst hasCompleteValues = (\n values: IMutableAttributeValues,\n): values is IGitContentTransformationAttributeValues =>\n Object.hasOwn(values, 'filter') &&\n Object.hasOwn(values, 'ident') &&\n Object.hasOwn(values, 'workingTreeEncoding');\n\n/**\n * Creates a strict parser for NUL-delimited `git check-attr` triples.\n * @param input The exact paths whose three effective attributes must be present.\n * @returns An incremental all-or-nothing parser.\n */\nexport const createGitContentTransformationParser = (\n input: IGitContentTransformationParserInput,\n): IGitContentTransformationParser => {\n const paths = [...input.paths];\n const valuesByPath = new Map<string, IMutableAttributeValues>();\n let fields: Uint8Array[] = [];\n let isFailed = false;\n let pendingByteLength = 0;\n let pendingFragments: Uint8Array[] = [];\n\n for (const path of paths) {\n if (path.length === 0 || path.includes('\\u0000') || valuesByPath.has(path)) {\n isFailed = true;\n continue;\n }\n\n valuesByPath.set(path, {});\n }\n\n const consumeRecord = (): void => {\n if (isFailed || fields.length !== 3) {\n return;\n }\n\n const path = decodeField(fields[0] ?? new Uint8Array());\n const attributeCandidate = decodeField(fields[1] ?? new Uint8Array());\n const value = decodeField(fields[2] ?? new Uint8Array());\n\n fields = [];\n\n if (path === null || attributeCandidate === null || value === null) {\n isFailed = true;\n return;\n }\n\n const attribute = resolveAttribute(attributeCandidate);\n const values = valuesByPath.get(path);\n\n if (attribute === null || values === undefined || !storeAttribute(values, attribute, value)) {\n isFailed = true;\n }\n };\n\n const consumeField = (): void => {\n if (isFailed) {\n return;\n }\n\n fields.push(concatenateField(pendingFragments, pendingByteLength));\n pendingByteLength = 0;\n pendingFragments = [];\n\n if (fields.length === 3) {\n consumeRecord();\n }\n };\n\n return {\n consume: (chunk): void => {\n if (isFailed) {\n return;\n }\n\n let fragmentStart = 0;\n\n for (let index = 0; index < chunk.byteLength; index += 1) {\n if (chunk[index] !== 0x00) {\n continue;\n }\n\n const fragment = chunk.subarray(fragmentStart, index);\n\n pendingFragments.push(Uint8Array.from(fragment));\n pendingByteLength += fragment.byteLength;\n consumeField();\n\n if (isFailed) {\n return;\n }\n\n fragmentStart = index + 1;\n }\n\n const trailingFragment = chunk.subarray(fragmentStart);\n\n if (trailingFragment.byteLength > 0) {\n pendingFragments.push(Uint8Array.from(trailingFragment));\n pendingByteLength += trailingFragment.byteLength;\n }\n },\n finish: (): IGitContentTransformationParserResult => {\n if (isFailed || pendingByteLength > 0 || fields.length > 0) {\n return Object.freeze({ kind: 'failed' });\n }\n\n const attributes: IGitContentTransformationParsedAttributes[] = [];\n\n for (const path of paths) {\n const values = valuesByPath.get(path);\n\n if (values === undefined || !hasCompleteValues(values)) {\n return Object.freeze({ kind: 'failed' });\n }\n\n attributes.push(\n Object.freeze({\n filter: values.filter,\n ident: values.ident,\n path,\n workingTreeEncoding: values.workingTreeEncoding,\n }),\n );\n }\n\n return Object.freeze({ attributes: Object.freeze(attributes), kind: 'completed' });\n },\n };\n};\n","import {\n executeGitStreamingProcess,\n MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n type IGitStreamingProcessExecutor,\n type IGitStreamingProcessFailureReason,\n} from '../../git-process/index.js';\nimport type { IGitInventoryProbeErrorCode } from '../types.js';\n\nimport { GIT_CONTENT_TRANSFORMATION_ARGUMENTS } from './constants.js';\nimport { createGitContentTransformationParser } from './parser.js';\nimport type {\n IGitContentTransformationClassification,\n IGitContentTransformationClassificationFailedResult,\n IGitContentTransformationClassificationResult,\n IGitContentTransformationClassifier,\n} from './types.js';\n\n/** Creates one immutable content-transformation classification failure. */\nconst createClassificationFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitContentTransformationClassificationFailedResult =>\n Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps one bounded Git attribute failure to the existing safe inventory contract. */\nconst mapGitProcessFailure = (\n reason: IGitStreamingProcessFailureReason,\n): IGitInventoryProbeErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'repository-not-found':\n return 'GIT_REPOSITORY_NOT_FOUND';\n case 'output-limit-exceeded':\n case 'stdout-limit-exceeded':\n return 'RESOURCE_LIMIT_EXCEEDED';\n case 'stderr-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Determines whether one effective attribute value requires guarded reads. */\nconst isGuardedAttributeValue = (attributeValue: string): boolean =>\n attributeValue !== 'unset' && attributeValue !== 'unspecified';\n\n/** Encodes exact Git-relative paths as NUL-delimited stdin without shell interpretation. */\nconst encodePaths = (paths: readonly string[]): Uint8Array | null => {\n const encoder = new TextEncoder();\n const encodedPaths: Uint8Array[] = [];\n let byteLength = 0;\n\n for (const path of paths) {\n if (path.length === 0 || path.includes('\\u0000')) {\n return null;\n }\n\n const encodedPath = encoder.encode(path);\n\n if (!Number.isSafeInteger(byteLength + encodedPath.byteLength + 1)) {\n return null;\n }\n\n encodedPaths.push(encodedPath);\n byteLength += encodedPath.byteLength + 1;\n }\n\n const stdin = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const encodedPath of encodedPaths) {\n stdin.set(encodedPath, offset);\n offset += encodedPath.byteLength + 1;\n }\n\n return stdin;\n};\n\n/** Builds the exact retained classification and its conservative read guard. */\nconst createClassification = (\n filter: string,\n ident: string,\n workingTreeEncoding: string,\n): IGitContentTransformationClassification =>\n Object.freeze({\n filter,\n ident,\n isGuarded:\n isGuardedAttributeValue(filter) ||\n isGuardedAttributeValue(ident) ||\n isGuardedAttributeValue(workingTreeEncoding),\n workingTreeEncoding,\n });\n\n/**\n * Creates the effective Git content-transformation classifier around a process boundary.\n * @param processExecutor The sanitized streamed Git process executor.\n * @returns An all-or-nothing bounded classifier for effective inventory entries.\n */\nexport const createGitContentTransformationClassifier = (\n processExecutor: IGitStreamingProcessExecutor = executeGitStreamingProcess,\n): IGitContentTransformationClassifier => {\n return async (input): Promise<IGitContentTransformationClassificationResult> => {\n if (input.signal?.aborted) {\n return createClassificationFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) {\n return createClassificationFailure('RESOURCE_LIMIT_EXCEEDED');\n }\n\n if (input.entries.length === 0) {\n return Object.freeze({ entries: Object.freeze([]), gitMetadataBytes: 0, kind: 'classified' });\n }\n\n const paths = input.entries.map((entry) => entry.path);\n const stdin = encodePaths(paths);\n\n if (stdin === null) {\n return createClassificationFailure('GIT_OUTPUT_INVALID');\n }\n\n const parser = createGitContentTransformationParser({ paths });\n let consumedStdoutBytes = 0;\n const processResult = await processExecutor({\n arguments: ['-C', input.repositoryRoot, ...GIT_CONTENT_TRANSFORMATION_ARGUMENTS],\n consumeStdout: (chunk): void => {\n consumedStdoutBytes += chunk.byteLength;\n parser.consume(chunk);\n },\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: input.maxMetadataBytes,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n stdin,\n });\n\n if (processResult.kind === 'failed') {\n return createClassificationFailure(mapGitProcessFailure(processResult.reason));\n }\n\n if (\n processResult.stderr.byteLength > 0 ||\n processResult.stdoutBytes !== consumedStdoutBytes ||\n processResult.stdoutBytes > input.maxMetadataBytes\n ) {\n return createClassificationFailure('GIT_OUTPUT_INVALID');\n }\n\n const parserResult = parser.finish();\n\n if (parserResult.kind === 'failed' || parserResult.attributes.length !== input.entries.length) {\n return createClassificationFailure('GIT_OUTPUT_INVALID');\n }\n\n const entries = input.entries.map((entry, index) => {\n const attributes = parserResult.attributes[index];\n\n if (attributes === undefined || attributes.path !== entry.path) {\n return null;\n }\n\n return Object.freeze({\n ...entry,\n contentTransformation: createClassification(\n attributes.filter,\n attributes.ident,\n attributes.workingTreeEncoding,\n ),\n });\n });\n\n if (entries.some((entry) => entry === null)) {\n return createClassificationFailure('GIT_OUTPUT_INVALID');\n }\n\n return Object.freeze({\n entries: Object.freeze(entries.filter((entry) => entry !== null)),\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'classified',\n });\n };\n};\n\n// default effective Git content-transformation classifier used by inventory probing\nexport const classifyGitContentTransformations = createGitContentTransformationClassifier();\n","import type { IGitInventoryCandidate } from '../types.js';\n\nimport type {\n ICollapsedGitInventoryCandidate,\n IGitInventoryCandidateCollapseResult,\n IGitInventoryIndexEntry,\n} from './types.js';\n\ninterface IMutableTrackedCandidate {\n readonly indexEntriesByStage: Map<number, IGitInventoryIndexEntry>;\n readonly kind: 'tracked';\n readonly path: string;\n}\n\ninterface IMutableUntrackedCandidate {\n readonly kind: 'untracked';\n readonly path: string;\n}\n\ntype IMutableCollapsedCandidate = IMutableTrackedCandidate | IMutableUntrackedCandidate;\n\n/** Creates one immutable invalid candidate-collapse result. */\nconst createCollapseFailure = (): IGitInventoryCandidateCollapseResult =>\n Object.freeze({ kind: 'failed' });\n\n/**\n * Collapses raw stage records into one deterministic candidate per exact Git path.\n * @param candidates The ownership-filtered raw candidates to collapse.\n * @returns An immutable candidate set, or failure for duplicate or contradictory state.\n */\nexport const collapseGitInventoryCandidates = (\n candidates: readonly IGitInventoryCandidate[],\n): IGitInventoryCandidateCollapseResult => {\n const candidatesByPath = new Map<string, IMutableCollapsedCandidate>();\n\n for (const candidate of candidates) {\n const existingCandidate = candidatesByPath.get(candidate.path);\n\n if (candidate.kind === 'untracked') {\n if (existingCandidate !== undefined) {\n return createCollapseFailure();\n }\n\n candidatesByPath.set(candidate.path, { kind: 'untracked', path: candidate.path });\n continue;\n }\n\n if (candidate.mode === '160000' || existingCandidate?.kind === 'untracked') {\n return createCollapseFailure();\n }\n\n const trackedCandidate = existingCandidate ?? {\n indexEntriesByStage: new Map<number, IGitInventoryIndexEntry>(),\n kind: 'tracked' as const,\n path: candidate.path,\n };\n\n if (trackedCandidate.indexEntriesByStage.has(candidate.stage)) {\n return createCollapseFailure();\n }\n\n trackedCandidate.indexEntriesByStage.set(\n candidate.stage,\n Object.freeze({ mode: candidate.mode, stage: candidate.stage }),\n );\n candidatesByPath.set(candidate.path, trackedCandidate);\n }\n\n const collapsedCandidates: ICollapsedGitInventoryCandidate[] = [];\n\n for (const candidate of candidatesByPath.values()) {\n if (candidate.kind === 'untracked') {\n collapsedCandidates.push(Object.freeze(candidate));\n continue;\n }\n\n const hasStageZero = candidate.indexEntriesByStage.has(0);\n\n if (hasStageZero && candidate.indexEntriesByStage.size !== 1) {\n return createCollapseFailure();\n }\n\n const indexEntries = [...candidate.indexEntriesByStage.values()].sort(\n (left, right) => left.stage - right.stage,\n );\n\n if (indexEntries.length === 0) {\n return createCollapseFailure();\n }\n\n collapsedCandidates.push(\n Object.freeze({\n indexEntries: Object.freeze(indexEntries),\n kind: 'tracked',\n path: candidate.path,\n }),\n );\n }\n\n return Object.freeze({ candidates: Object.freeze(collapsedCandidates), kind: 'collapsed' });\n};\n","import { lstat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { IGitInventoryProbeErrorCode } from '../types.js';\n\nimport type {\n IGitInventoryEntryInspector,\n IGitInventoryEntryLstat,\n IGitInventoryHostEntryInspectionFailedResult,\n IGitInventoryHostEntryInspectionResult,\n} from './types.js';\n\n/** Creates one immutable host entry inspection failure. */\nconst createInspectionFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitInventoryHostEntryInspectionFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps an unknown no-follow filesystem failure without retaining host diagnostics. */\nconst mapFilesystemFailure = (\n error: unknown,\n): IGitInventoryHostEntryInspectionFailedResult | null => {\n const errorCode = (error as NodeJS.ErrnoException | null)?.code?.toUpperCase();\n\n if (errorCode === 'ENOENT' || errorCode === 'ENOTDIR') {\n return null;\n }\n\n if (errorCode === 'EACCES' || errorCode === 'EPERM') {\n return createInspectionFailure('GIT_ACCESS_DENIED');\n }\n\n if (errorCode === 'ELOOP') {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n return createInspectionFailure('GIT_COMMAND_FAILED');\n};\n\n/** Default no-follow stat boundary for current inventory entries. */\nconst inspectHostEntry: IGitInventoryEntryLstat = async (hostPath) => lstat(hostPath);\n\n/**\n * Creates current host entry inspection around an injectable no-follow stat boundary.\n * @param inspectEntry The no-follow filesystem stat operation.\n * @returns An inspector for one ownership-filtered candidate path.\n */\nexport const createGitInventoryEntryInspector = (\n inspectEntry: IGitInventoryEntryLstat = inspectHostEntry,\n): IGitInventoryEntryInspector => {\n return async (repositoryRoot, candidatePath): Promise<IGitInventoryHostEntryInspectionResult> => {\n let statistics: Awaited<ReturnType<IGitInventoryEntryLstat>>;\n\n try {\n statistics = await inspectEntry(path.join(repositoryRoot, candidatePath));\n } catch (error) {\n const failure = mapFilesystemFailure(error);\n\n return failure ?? Object.freeze({ kind: 'missing' });\n }\n\n if (statistics.isSymbolicLink()) {\n return Object.freeze({ entryType: 'symlink', kind: 'inspected' });\n }\n\n if (statistics.isFile()) {\n return Object.freeze({ entryType: 'file', kind: 'inspected' });\n }\n\n return Object.freeze({ entryType: 'unsupported', kind: 'inspected' });\n };\n};\n\n// default no-follow current host entry inspector\nexport const inspectGitInventoryEntry = createGitInventoryEntryInspector();\n","// fixed read-only query for the effective selected-repository symlink behavior\nexport const GIT_SYMLINK_CONFIGURATION_ARGUMENTS = [\n 'config',\n '--type=bool',\n '--default=true',\n '--get',\n 'core.symlinks',\n] as const;\n","import {\n executeGitStreamingProcess,\n MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n type IGitStreamingProcessExecutor,\n type IGitStreamingProcessFailureReason,\n} from '../../git-process/index.js';\nimport { parseGitBooleanOutput } from '../../git-working-tree/index.js';\nimport type { IGitInventoryProbeErrorCode } from '../types.js';\n\nimport { GIT_SYMLINK_CONFIGURATION_ARGUMENTS } from './constants.js';\nimport type {\n IGitSymlinkConfigurationFailedResult,\n IGitSymlinkConfigurationResolver,\n IGitSymlinkConfigurationResult,\n} from './types.js';\n\n/** Creates one immutable effective symlink configuration failure. */\nconst createConfigurationFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitSymlinkConfigurationFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps one bounded Git configuration failure to the existing safe CLI contract. */\nconst mapGitProcessFailure = (\n reason: IGitStreamingProcessFailureReason,\n): IGitInventoryProbeErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'output-limit-exceeded':\n case 'stdout-limit-exceeded':\n return 'RESOURCE_LIMIT_EXCEEDED';\n case 'repository-not-found':\n case 'stderr-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Concatenates already bounded Git stdout chunks for strict boolean parsing. */\nconst concatenateChunks = (chunks: readonly Uint8Array[], byteLength: number): Uint8Array => {\n const output = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const chunk of chunks) {\n output.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return output;\n};\n\n/**\n * Creates the bounded effective core.symlinks resolver around a Git process boundary.\n * @param processExecutor The sanitized streamed Git process executor.\n * @returns A resolver for the selected repository's effective symlink behavior.\n */\nexport const createGitSymlinkConfigurationResolver = (\n processExecutor: IGitStreamingProcessExecutor = executeGitStreamingProcess,\n): IGitSymlinkConfigurationResolver => {\n return async (input): Promise<IGitSymlinkConfigurationResult> => {\n if (input.signal?.aborted) {\n return createConfigurationFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) {\n return createConfigurationFailure('RESOURCE_LIMIT_EXCEEDED');\n }\n\n const stdoutChunks: Uint8Array[] = [];\n let consumedStdoutBytes = 0;\n const processResult = await processExecutor({\n arguments: ['-C', input.repositoryRoot, ...GIT_SYMLINK_CONFIGURATION_ARGUMENTS],\n consumeStdout: (chunk): void => {\n stdoutChunks.push(Uint8Array.from(chunk));\n consumedStdoutBytes += chunk.byteLength;\n },\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: input.maxMetadataBytes,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (processResult.kind === 'failed') {\n return createConfigurationFailure(mapGitProcessFailure(processResult.reason));\n }\n\n if (\n processResult.stderr.byteLength > 0 ||\n processResult.stdoutBytes !== consumedStdoutBytes ||\n processResult.stdoutBytes > input.maxMetadataBytes\n ) {\n return createConfigurationFailure('GIT_OUTPUT_INVALID');\n }\n\n const isEnabled = parseGitBooleanOutput(concatenateChunks(stdoutChunks, consumedStdoutBytes));\n\n if (isEnabled === null) {\n return createConfigurationFailure('GIT_OUTPUT_INVALID');\n }\n\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n isEnabled,\n kind: 'resolved',\n });\n };\n};\n\n// default bounded effective core.symlinks resolver\nexport const resolveGitSymlinkConfiguration = createGitSymlinkConfigurationResolver();\n","import { collapseGitInventoryCandidates } from './candidate-collapser.js';\nimport { inspectGitInventoryEntry } from './entry-inspector.js';\nimport { resolveGitSymlinkConfiguration } from './symlink-configuration.js';\nimport type {\n ICollapsedGitTrackedInventoryCandidate,\n IGitEntryTypeNormalizedEntry,\n IGitInventoryEntryInspector,\n IGitInventoryEntryTypeNormalizationFailedResult,\n IGitInventoryEntryTypeNormalizationResult,\n IGitInventoryEntryTypeNormalizer,\n IGitSymlinkConfigurationResolver,\n} from './types.js';\n\n/** Creates one immutable entry-type normalization failure. */\nconst createNormalizationFailure = (\n errorCode: IGitInventoryEntryTypeNormalizationFailedResult['errorCode'],\n): IGitInventoryEntryTypeNormalizationFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Determines whether retained index metadata contains a Git symlink mode. */\nconst hasSymlinkMode = (candidate: ICollapsedGitTrackedInventoryCandidate): boolean =>\n candidate.indexEntries.some(({ mode }) => mode === '120000');\n\n/** Determines whether retained index metadata contains a Git regular-file mode. */\nconst hasRegularFileMode = (candidate: ICollapsedGitTrackedInventoryCandidate): boolean =>\n candidate.indexEntries.some(({ mode }) => mode === '100644' || mode === '100755');\n\n/**\n * Creates entry-type normalization around injectable filesystem and Git configuration boundaries.\n * @param entryInspector The no-follow current host entry inspector.\n * @param symlinkConfigurationResolver The bounded effective core.symlinks resolver.\n * @returns An all-or-nothing effective working-tree entry normalizer.\n */\nexport const createGitInventoryEntryTypeNormalizer = (\n entryInspector: IGitInventoryEntryInspector = inspectGitInventoryEntry,\n symlinkConfigurationResolver: IGitSymlinkConfigurationResolver = resolveGitSymlinkConfiguration,\n): IGitInventoryEntryTypeNormalizer => {\n return async (input): Promise<IGitInventoryEntryTypeNormalizationResult> => {\n if (input.signal?.aborted) {\n return createNormalizationFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) {\n return createNormalizationFailure('RESOURCE_LIMIT_EXCEEDED');\n }\n\n const collapseResult = collapseGitInventoryCandidates(input.candidates);\n\n if (collapseResult.kind === 'failed') {\n return createNormalizationFailure('GIT_OUTPUT_INVALID');\n }\n\n const entries: IGitEntryTypeNormalizedEntry[] = [];\n let symlinkConfiguration: Awaited<ReturnType<IGitSymlinkConfigurationResolver>> | null = null;\n\n for (const candidate of collapseResult.candidates) {\n if (input.signal?.aborted) {\n return createNormalizationFailure('GIT_OPERATION_ABORTED');\n }\n\n const inspectionResult = await entryInspector(input.repositoryRoot, candidate.path);\n\n if (input.signal?.aborted) {\n return createNormalizationFailure('GIT_OPERATION_ABORTED');\n }\n\n if (inspectionResult.kind === 'failed') {\n return inspectionResult;\n }\n\n if (inspectionResult.kind === 'missing') {\n continue;\n }\n\n if (inspectionResult.entryType === 'unsupported') {\n return createNormalizationFailure('GIT_OUTPUT_INVALID');\n }\n\n if (candidate.kind === 'untracked') {\n entries.push(\n Object.freeze({\n entryType: inspectionResult.entryType,\n kind: 'untracked',\n path: candidate.path,\n requiresSymlinkOverlay: false,\n }),\n );\n continue;\n }\n\n if (inspectionResult.entryType === 'symlink' || !hasSymlinkMode(candidate)) {\n entries.push(\n Object.freeze({\n entryType: inspectionResult.entryType,\n indexEntries: candidate.indexEntries,\n kind: 'tracked',\n path: candidate.path,\n requiresSymlinkOverlay: false,\n }),\n );\n continue;\n }\n\n symlinkConfiguration ??= await symlinkConfigurationResolver({\n maxMetadataBytes: input.maxMetadataBytes,\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (symlinkConfiguration.kind === 'failed') {\n return symlinkConfiguration;\n }\n\n if (\n !Number.isSafeInteger(symlinkConfiguration.gitMetadataBytes) ||\n symlinkConfiguration.gitMetadataBytes < 0 ||\n symlinkConfiguration.gitMetadataBytes > input.maxMetadataBytes\n ) {\n return createNormalizationFailure('GIT_OUTPUT_INVALID');\n }\n\n if (!symlinkConfiguration.isEnabled && hasRegularFileMode(candidate)) {\n return createNormalizationFailure('GIT_OUTPUT_INVALID');\n }\n\n const requiresSymlinkOverlay = !symlinkConfiguration.isEnabled;\n\n entries.push(\n Object.freeze({\n entryType: requiresSymlinkOverlay ? 'symlink' : 'file',\n indexEntries: candidate.indexEntries,\n kind: 'tracked',\n path: candidate.path,\n requiresSymlinkOverlay,\n }),\n );\n }\n\n return Object.freeze({\n entries: Object.freeze(entries),\n gitMetadataBytes:\n symlinkConfiguration?.kind === 'resolved' ? symlinkConfiguration.gitMetadataBytes : 0,\n kind: 'normalized',\n });\n };\n};\n\n// default effective working-tree entry-type normalizer\nexport const normalizeGitInventoryEntryTypes = createGitInventoryEntryTypeNormalizer();\n","import { isRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport type {\n IGitInventoryCandidateLogicalPathValidationResult,\n IGitInventoryCandidateLogicalPathValidatorInput,\n IGitInventoryEntry,\n IGitInventoryLogicalPathFailedResult,\n IGitInventoryLogicalPathCandidate,\n IGitInventoryLogicalPathNormalizationResult,\n IGitInventoryLogicalPathNormalizer,\n} from './types.js';\n\n/** Creates one immutable invalid logical-path result. */\nconst createLogicalPathFailure = (): IGitInventoryLogicalPathFailedResult =>\n Object.freeze({ errorCode: 'GIT_OUTPUT_INVALID', kind: 'failed' });\n\n/** Converts one Git-relative path into a validated repository logical path. */\nconst resolveRepositoryPath = (gitPath: string): IRepositoryPath | null => {\n const logicalPath = `/${gitPath}`;\n\n return logicalPath !== '/' && isRepositoryPath(logicalPath) ? logicalPath : null;\n};\n\n/** Resolves the logical path represented by one Git candidate record. */\nconst resolveCandidateRepositoryPath = (\n candidate: IGitInventoryLogicalPathCandidate,\n): IRepositoryPath | null => {\n const gitPath =\n candidate.kind === 'untracked' && candidate.path.endsWith('/')\n ? candidate.path.slice(0, -1)\n : candidate.path;\n\n return resolveRepositoryPath(gitPath);\n};\n\n/** Compares repository paths by exact Unicode code-point order. */\nconst compareRepositoryPaths = (left: IRepositoryPath, right: IRepositoryPath): number => {\n const leftScalars = left[Symbol.iterator]();\n const rightScalars = right[Symbol.iterator]();\n\n while (true) {\n const leftScalar = leftScalars.next();\n const rightScalar = rightScalars.next();\n\n if (leftScalar.done === true) {\n return rightScalar.done === true ? 0 : -1;\n }\n\n if (rightScalar.done === true) {\n return 1;\n }\n\n const leftCodePoint = leftScalar.value.codePointAt(0) ?? 0;\n const rightCodePoint = rightScalar.value.codePointAt(0) ?? 0;\n\n if (leftCodePoint !== rightCodePoint) {\n return leftCodePoint < rightCodePoint ? -1 : 1;\n }\n }\n};\n\n/**\n * Validates every decoded Git candidate before ownership or filesystem exclusions.\n * @param input The complete decoded tracked and untracked candidate set.\n * @returns A validated result, or failure when any candidate is not portable.\n */\nexport const validateGitInventoryCandidateLogicalPaths = (\n input: IGitInventoryCandidateLogicalPathValidatorInput,\n): IGitInventoryCandidateLogicalPathValidationResult => {\n for (const candidate of input.candidates) {\n if (resolveCandidateRepositoryPath(candidate) === null) {\n return createLogicalPathFailure();\n }\n }\n\n return Object.freeze({ kind: 'validated' });\n};\n\n/**\n * Converts Git-relative inventory entries into exact repository logical paths.\n * @param input The entry-type-normalized Git-relative inventory.\n * @returns An immutable code-point-sorted inventory, or failure for invalid path state.\n */\nexport const normalizeGitInventoryLogicalPaths: IGitInventoryLogicalPathNormalizer = (\n input,\n): IGitInventoryLogicalPathNormalizationResult => {\n const entries: IGitInventoryEntry[] = [];\n const logicalPaths = new Set<IRepositoryPath>();\n\n for (const entry of input.entries) {\n const logicalPath = resolveRepositoryPath(entry.path);\n\n if (logicalPath === null || logicalPaths.has(logicalPath)) {\n return createLogicalPathFailure();\n }\n\n logicalPaths.add(logicalPath);\n entries.push(Object.freeze({ ...entry, path: logicalPath }));\n }\n\n entries.sort((left, right) => compareRepositoryPaths(left.path, right.path));\n\n return Object.freeze({ entries: Object.freeze(entries), kind: 'normalized' });\n};\n","import type {\n IGitInventoryCandidate,\n IGitInventoryParser,\n IGitInventoryParserFailureReason,\n IGitInventoryParserResult,\n IGitTrackedEntryMode,\n IGitTrackedEntryStage,\n IGitTrackedInventoryCandidate,\n IGitUntrackedInventoryCandidate,\n} from './types.js';\n\nconst TRACKED_ENTRY_HEADER_PATTERN =\n /^(100644|100755|120000|160000) (?:[0-9a-f]{40}|[0-9a-f]{64}) ([0-3])$/u;\n\n/** Decodes one complete Git path as strict UTF-8 while preserving an initial BOM scalar. */\nconst decodeGitPath = (pathBytes: Uint8Array): string | null => {\n if (pathBytes.byteLength === 0) {\n return null;\n }\n\n try {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(pathBytes);\n } catch {\n return null;\n }\n};\n\n/** Confirms that one decoded path contains only complete Unicode scalar values. */\nconst hasOnlyUnicodeScalarValues = (path: string): boolean => {\n for (let index = 0; index < path.length; index += 1) {\n const codeUnit = path.charCodeAt(index);\n\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n const trailingCodeUnit = path.charCodeAt(index + 1);\n\n if (trailingCodeUnit < 0xdc00 || trailingCodeUnit > 0xdfff) {\n return false;\n }\n\n index += 1;\n continue;\n }\n\n if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {\n return false;\n }\n }\n\n return true;\n};\n\n/** Concatenates one complete record assembled across arbitrary process chunks. */\nconst concatenateRecord = (fragments: readonly Uint8Array[], byteLength: number): Uint8Array => {\n const record = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const fragment of fragments) {\n record.set(fragment, offset);\n offset += fragment.byteLength;\n }\n\n return record;\n};\n\n/** Parses one tracked `ls-files --stage` record without normalizing its path. */\nconst parseTrackedCandidate = (record: Uint8Array): IGitTrackedInventoryCandidate | null => {\n const separatorIndex = record.indexOf(0x09);\n\n if (separatorIndex <= 0 || separatorIndex === record.byteLength - 1) {\n return null;\n }\n\n let header: string;\n\n try {\n header = new TextDecoder('utf-8', { fatal: true }).decode(record.subarray(0, separatorIndex));\n } catch {\n return null;\n }\n\n const headerMatch = TRACKED_ENTRY_HEADER_PATTERN.exec(header);\n const path = decodeGitPath(record.subarray(separatorIndex + 1));\n\n if (headerMatch === null || path === null || !hasOnlyUnicodeScalarValues(path)) {\n return null;\n }\n\n return Object.freeze({\n kind: 'tracked',\n mode: headerMatch[1] as IGitTrackedEntryMode,\n path,\n stage: Number(headerMatch[2]) as IGitTrackedEntryStage,\n });\n};\n\n/** Parses one untracked `ls-files --others` record without normalizing its path. */\nconst parseUntrackedCandidate = (record: Uint8Array): IGitUntrackedInventoryCandidate | null => {\n const path = decodeGitPath(record);\n\n if (path === null || !hasOnlyUnicodeScalarValues(path)) {\n return null;\n }\n\n return Object.freeze({ kind: 'untracked', path });\n};\n\n/** Creates a strict incremental parser for one NUL-delimited Git record grammar. */\nconst createGitInventoryParser = <TCandidate extends IGitInventoryCandidate>(\n maxEntries: number,\n parseCandidate: (record: Uint8Array) => TCandidate | null,\n): IGitInventoryParser<TCandidate> => {\n const candidates: TCandidate[] = [];\n let failureReason: IGitInventoryParserFailureReason | null = null;\n let pendingByteLength = 0;\n let pendingFragments: Uint8Array[] = [];\n\n const consumeRecord = (): void => {\n if (failureReason !== null) {\n return;\n }\n\n if (candidates.length >= maxEntries) {\n failureReason = 'entry-limit-exceeded';\n pendingByteLength = 0;\n pendingFragments = [];\n return;\n }\n\n const candidate = parseCandidate(concatenateRecord(pendingFragments, pendingByteLength));\n\n pendingByteLength = 0;\n pendingFragments = [];\n\n if (candidate === null) {\n failureReason = 'invalid';\n return;\n }\n\n candidates.push(candidate);\n };\n\n return {\n consume: (chunk): void => {\n if (failureReason !== null) {\n return;\n }\n\n let fragmentStart = 0;\n\n for (let index = 0; index < chunk.byteLength; index += 1) {\n if (chunk[index] !== 0x00) {\n continue;\n }\n\n const fragment = chunk.subarray(fragmentStart, index);\n\n pendingFragments.push(fragment);\n pendingByteLength += fragment.byteLength;\n consumeRecord();\n\n if (failureReason !== null) {\n return;\n }\n\n fragmentStart = index + 1;\n }\n\n const trailingFragment = chunk.subarray(fragmentStart);\n\n if (trailingFragment.byteLength > 0) {\n pendingFragments.push(trailingFragment);\n pendingByteLength += trailingFragment.byteLength;\n }\n },\n finish: (): IGitInventoryParserResult<TCandidate> => {\n if (failureReason === null && pendingByteLength > 0) {\n failureReason = 'invalid';\n }\n\n if (failureReason !== null) {\n return Object.freeze({ kind: 'failed', reason: failureReason });\n }\n\n return Object.freeze({ candidates: Object.freeze([...candidates]), kind: 'completed' });\n },\n };\n};\n\n/** Creates a strict incremental parser for tracked Git inventory output. */\nexport const createTrackedGitInventoryParser = (\n maxEntries: number,\n): IGitInventoryParser<IGitTrackedInventoryCandidate> =>\n createGitInventoryParser(maxEntries, parseTrackedCandidate);\n\n/** Creates a strict incremental parser for untracked Git inventory output. */\nexport const createUntrackedGitInventoryParser = (\n maxEntries: number,\n): IGitInventoryParser<IGitUntrackedInventoryCandidate> =>\n createGitInventoryParser(maxEntries, parseUntrackedCandidate);\n","import { Buffer } from 'node:buffer';\nimport { lstat, readdir } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {\n executeGitStreamingProcess,\n MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n type IGitStreamingProcessExecutor,\n type IGitStreamingProcessFailureReason,\n} from '../../git-process/index.js';\nimport { parseGitAbsolutePathOutput } from '../../git-working-tree/index.js';\nimport {\n areHostPathsEquivalent,\n haveSameHostPathIdentity,\n} from '../../host-path-identity/index.js';\nimport type { IGitInventoryProbeErrorCode } from '../types.js';\n\nimport type {\n IGitInventoryBoundaryInspectedResult,\n IGitInventoryBoundaryInspectionFailedResult,\n IGitInventoryBoundaryInspectionResult,\n IGitInventoryBoundaryInspector,\n IGitInventoryBoundaryOwnership,\n IGitInventoryOwnershipLstat,\n IGitInventoryOwnershipReadDirectory,\n IGitInventoryOwnershipStatistics,\n} from './types.js';\n\nconst GIT_CONTROL_SEGMENT = '.git';\nconst GIT_REPOSITORY_ROOT_ARGUMENTS = ['rev-parse', '--show-toplevel'] as const;\n\ninterface IGitInventoryDirectoryObservation {\n readonly encodedNameKeys: ReadonlySet<string>;\n readonly hostPath: string;\n readonly ownership: IGitInventoryBoundaryOwnership;\n}\n\ninterface IGitInventoryDirectoryReadResult {\n readonly encodedNameKeys: ReadonlySet<string>;\n readonly kind: 'read';\n}\n\ninterface IGitInventoryPathInspectedResult {\n readonly kind: 'inspected';\n readonly statistics: IGitInventoryOwnershipStatistics;\n}\n\ntype IGitInventoryDirectoryReadAttempt =\n IGitInventoryBoundaryInspectionFailedResult | IGitInventoryDirectoryReadResult;\n\ntype IGitInventoryPathInspectionAttempt =\n IGitInventoryBoundaryInspectionFailedResult | IGitInventoryPathInspectedResult;\n\ninterface IGitInventoryBoundaryValidationResult {\n readonly gitMetadataBytes: number;\n readonly kind: 'validated';\n readonly ownership: IGitInventoryBoundaryOwnership;\n}\n\ntype IGitInventoryBoundaryValidationAttempt =\n IGitInventoryBoundaryInspectionFailedResult | IGitInventoryBoundaryValidationResult;\n\n/** Identifies one safe inspection failure in a filesystem result union. */\nconst isInspectionFailure = (\n result: IGitInventoryBoundaryInspectionFailedResult | IGitInventoryDirectoryObservation,\n): result is IGitInventoryBoundaryInspectionFailedResult => 'kind' in result;\n\n/** Creates one immutable ownership-inspection failure. */\nconst createInspectionFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitInventoryBoundaryInspectionFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps an unknown filesystem failure without retaining host diagnostics. */\nconst mapFilesystemFailure = (error: unknown): IGitInventoryProbeErrorCode => {\n const errorCode = (error as NodeJS.ErrnoException | null)?.code?.toUpperCase();\n\n if (errorCode === 'EACCES' || errorCode === 'EPERM') {\n return 'GIT_ACCESS_DENIED';\n }\n\n if (errorCode === 'ENOENT' || errorCode === 'ENOTDIR' || errorCode === 'ELOOP') {\n return 'GIT_OUTPUT_INVALID';\n }\n\n return 'GIT_COMMAND_FAILED';\n};\n\n/** Maps a streamed nested-root check failure into the existing safe CLI contract. */\nconst mapGitProcessFailure = (\n reason: IGitStreamingProcessFailureReason,\n): IGitInventoryProbeErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'output-limit-exceeded':\n case 'stdout-limit-exceeded':\n return 'RESOURCE_LIMIT_EXCEEDED';\n case 'repository-not-found':\n case 'stderr-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Reads one directory as native names without decoding unrelated entries. */\nconst readDirectoryNames = async (\n hostPath: string,\n readDirectory: IGitInventoryOwnershipReadDirectory,\n): Promise<IGitInventoryDirectoryReadAttempt> => {\n try {\n const encodedNames = await readDirectory(hostPath);\n\n return Object.freeze({\n encodedNameKeys: new Set(encodedNames.map((encodedName) => encodedName.toString('hex'))),\n kind: 'read',\n });\n } catch (error) {\n return createInspectionFailure(mapFilesystemFailure(error));\n }\n};\n\n/** Captures one path without following its final filesystem entry. */\nconst inspectPath = async (\n hostPath: string,\n inspectHostPath: IGitInventoryOwnershipLstat,\n): Promise<IGitInventoryPathInspectionAttempt> => {\n try {\n return Object.freeze({\n kind: 'inspected',\n statistics: await inspectHostPath(hostPath),\n });\n } catch (error) {\n return createInspectionFailure(mapFilesystemFailure(error));\n }\n};\n\n/** Determines whether native names contain one exact UTF-8 segment spelling. */\nconst hasExactDirectoryName = (encodedNameKeys: ReadonlySet<string>, segment: string): boolean =>\n encodedNameKeys.has(Buffer.from(segment, 'utf8').toString('hex'));\n\n/** Confirms that one directory observation retained its no-follow identity. */\nconst hasStableDirectoryIdentity = (\n initialStatistics: IGitInventoryOwnershipStatistics,\n revalidatedStatistics: IGitInventoryOwnershipStatistics,\n): boolean =>\n initialStatistics.isDirectory() &&\n !initialStatistics.isSymbolicLink() &&\n revalidatedStatistics.isDirectory() &&\n !revalidatedStatistics.isSymbolicLink() &&\n initialStatistics.dev === revalidatedStatistics.dev &&\n initialStatistics.ino === revalidatedStatistics.ino;\n\n/** Concatenates already bounded Git stdout chunks for strict root parsing. */\nconst concatenateChunks = (chunks: readonly Uint8Array[], byteLength: number): Uint8Array => {\n const output = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const chunk of chunks) {\n output.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return output;\n};\n\n/**\n * Confirms whether a directory with an exact `.git` marker owns another working tree.\n * @param directory The exact no-follow directory being classified.\n * @param repositoryRoot The selected repository root.\n * @param directoryStatistics The stable no-follow boundary observation.\n * @param maxMetadataBytes The remaining bounded Git stdout budget.\n * @param processExecutor The sanitized streamed Git boundary.\n * @param inspectHostPath The no-follow filesystem stat operation.\n * @returns A safe ownership classification and the consumed Git metadata bytes.\n */\nconst validateGitBoundary = async (\n directory: string,\n repositoryRoot: string,\n directoryStatistics: IGitInventoryOwnershipStatistics,\n maxMetadataBytes: number,\n processExecutor: IGitStreamingProcessExecutor,\n inspectHostPath: IGitInventoryOwnershipLstat,\n signal?: AbortSignal,\n): Promise<IGitInventoryBoundaryValidationAttempt> => {\n if (signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!Number.isSafeInteger(maxMetadataBytes) || maxMetadataBytes < 0) {\n return createInspectionFailure('RESOURCE_LIMIT_EXCEEDED');\n }\n\n const stdoutChunks: Uint8Array[] = [];\n let consumedStdoutBytes = 0;\n const processResult = await processExecutor({\n arguments: ['-C', directory, ...GIT_REPOSITORY_ROOT_ARGUMENTS],\n consumeStdout: (chunk): void => {\n stdoutChunks.push(Uint8Array.from(chunk));\n consumedStdoutBytes += chunk.byteLength;\n },\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: maxMetadataBytes,\n ...(signal === undefined ? {} : { signal }),\n });\n\n if (processResult.kind === 'failed') {\n return createInspectionFailure(mapGitProcessFailure(processResult.reason));\n }\n\n if (processResult.stderr.byteLength > 0 || processResult.stdoutBytes !== consumedStdoutBytes) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const discoveredRoot = parseGitAbsolutePathOutput(\n concatenateChunks(stdoutChunks, consumedStdoutBytes),\n );\n\n if (discoveredRoot === null) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n if (areHostPathsEquivalent(discoveredRoot, directory)) {\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'validated',\n ownership: 'nested-repository',\n });\n }\n\n if (areHostPathsEquivalent(discoveredRoot, repositoryRoot)) {\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'validated',\n ownership: 'selected-repository',\n });\n }\n\n const discoveredRootInspection = await inspectPath(discoveredRoot, inspectHostPath);\n\n if (signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (discoveredRootInspection.kind === 'failed') {\n return discoveredRootInspection;\n }\n\n if (\n !discoveredRootInspection.statistics.isDirectory() ||\n discoveredRootInspection.statistics.isSymbolicLink()\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n if (haveSameHostPathIdentity(discoveredRootInspection.statistics, directoryStatistics)) {\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'validated',\n ownership: 'nested-repository',\n });\n }\n\n const repositoryRootInspection = await inspectPath(repositoryRoot, inspectHostPath);\n\n if (signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (repositoryRootInspection.kind === 'failed') {\n return repositoryRootInspection;\n }\n\n if (\n repositoryRootInspection.statistics.isDirectory() &&\n !repositoryRootInspection.statistics.isSymbolicLink() &&\n haveSameHostPathIdentity(\n discoveredRootInspection.statistics,\n repositoryRootInspection.statistics,\n )\n ) {\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'validated',\n ownership: 'selected-repository',\n });\n }\n\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n};\n\n/** Default no-follow stat boundary for ownership inspection. */\nconst inspectOwnershipPath: IGitInventoryOwnershipLstat = async (hostPath) =>\n lstat(hostPath, { bigint: true });\n\n/** Default raw directory-name boundary for ownership inspection. */\nconst readOwnershipDirectory: IGitInventoryOwnershipReadDirectory = async (hostPath) =>\n readdir(hostPath, { encoding: 'buffer' });\n\n/**\n * Creates nested-repository inspection around injectable filesystem and Git boundaries.\n * @param processExecutor The sanitized bounded Git process executor.\n * @param inspectHostPath The no-follow filesystem stat operation.\n * @param readDirectory The raw native-name directory operation.\n * @returns An all-or-nothing ownership inspector for untracked candidate paths.\n */\nexport const createGitInventoryBoundaryInspector = (\n processExecutor: IGitStreamingProcessExecutor = executeGitStreamingProcess,\n inspectHostPath: IGitInventoryOwnershipLstat = inspectOwnershipPath,\n readDirectory: IGitInventoryOwnershipReadDirectory = readOwnershipDirectory,\n): IGitInventoryBoundaryInspector => {\n return async (input): Promise<IGitInventoryBoundaryInspectionResult> => {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n const directoryObservations = new Map<string, IGitInventoryDirectoryObservation>();\n const ownership: IGitInventoryBoundaryOwnership[] = [];\n let gitMetadataBytes = 0;\n let rootEncodedNameKeys: ReadonlySet<string> | null = null;\n\n const getRootEncodedNames = async (): Promise<IGitInventoryDirectoryReadAttempt> => {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (rootEncodedNameKeys !== null) {\n return Object.freeze({ encodedNameKeys: rootEncodedNameKeys, kind: 'read' });\n }\n\n const readResult = await readDirectoryNames(input.repositoryRoot, readDirectory);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (readResult.kind === 'read') {\n rootEncodedNameKeys = readResult.encodedNameKeys;\n }\n\n return readResult;\n };\n\n const inspectDirectory = async (\n parentObservation: IGitInventoryDirectoryObservation | null,\n parentPrefix: string,\n segment: string,\n ): Promise<IGitInventoryBoundaryInspectionFailedResult | IGitInventoryDirectoryObservation> => {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n const prefix = parentPrefix.length === 0 ? segment : `${parentPrefix}/${segment}`;\n const cachedObservation = directoryObservations.get(prefix);\n\n if (cachedObservation !== undefined) {\n return cachedObservation;\n }\n\n const parentNamesResult =\n parentObservation === null\n ? await getRootEncodedNames()\n : Object.freeze({\n encodedNameKeys: parentObservation.encodedNameKeys,\n kind: 'read' as const,\n });\n\n if (parentNamesResult.kind === 'failed') {\n return parentNamesResult;\n }\n\n if (!hasExactDirectoryName(parentNamesResult.encodedNameKeys, segment)) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const parentHostPath = parentObservation?.hostPath ?? input.repositoryRoot;\n const hostPath = path.join(parentHostPath, segment);\n const initialInspection = await inspectPath(hostPath, inspectHostPath);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (initialInspection.kind === 'failed') {\n return initialInspection;\n }\n\n if (\n !initialInspection.statistics.isDirectory() ||\n initialInspection.statistics.isSymbolicLink()\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const directoryNamesResult = await readDirectoryNames(hostPath, readDirectory);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (directoryNamesResult.kind === 'failed') {\n return directoryNamesResult;\n }\n\n const revalidatedInspection = await inspectPath(hostPath, inspectHostPath);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (revalidatedInspection.kind === 'failed') {\n return revalidatedInspection;\n }\n\n if (\n !hasStableDirectoryIdentity(initialInspection.statistics, revalidatedInspection.statistics)\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const gitControlPath = path.join(hostPath, GIT_CONTROL_SEGMENT);\n const hasExactGitControlSegment = hasExactDirectoryName(\n directoryNamesResult.encodedNameKeys,\n GIT_CONTROL_SEGMENT,\n );\n let directoryOwnership: IGitInventoryBoundaryOwnership = 'selected-repository';\n\n if (!hasExactGitControlSegment) {\n try {\n await inspectHostPath(gitControlPath);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException | null)?.code?.toUpperCase();\n\n if (errorCode !== 'ENOENT' && errorCode !== 'ENOTDIR') {\n return createInspectionFailure(mapFilesystemFailure(error));\n }\n }\n } else {\n const gitControlInspection = await inspectPath(gitControlPath, inspectHostPath);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (gitControlInspection.kind === 'failed') {\n return gitControlInspection;\n }\n\n if (\n gitControlInspection.statistics.isSymbolicLink() ||\n (!gitControlInspection.statistics.isDirectory() &&\n !gitControlInspection.statistics.isFile())\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const boundaryValidation = await validateGitBoundary(\n hostPath,\n input.repositoryRoot,\n revalidatedInspection.statistics,\n input.maxMetadataBytes - gitMetadataBytes,\n processExecutor,\n inspectHostPath,\n input.signal,\n );\n\n if (boundaryValidation.kind === 'failed') {\n return boundaryValidation;\n }\n\n gitMetadataBytes += boundaryValidation.gitMetadataBytes;\n directoryOwnership = boundaryValidation.ownership;\n }\n\n const observation = Object.freeze({\n encodedNameKeys: directoryNamesResult.encodedNameKeys,\n hostPath,\n ownership: directoryOwnership,\n });\n\n directoryObservations.set(prefix, observation);\n\n return observation;\n };\n\n for (const plan of input.plans) {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n let candidateOwnership: IGitInventoryBoundaryOwnership = 'selected-repository';\n let parentObservation: IGitInventoryDirectoryObservation | null = null;\n let parentPrefix = '';\n\n for (const segment of plan.directorySegments) {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n const observation = await inspectDirectory(parentObservation, parentPrefix, segment);\n\n if (isInspectionFailure(observation)) {\n return observation;\n }\n\n parentObservation = observation;\n parentPrefix = parentPrefix.length === 0 ? segment : `${parentPrefix}/${segment}`;\n\n if (observation.ownership === 'nested-repository') {\n candidateOwnership = 'nested-repository';\n break;\n }\n }\n\n if (plan.isDirectoryRecord && candidateOwnership !== 'nested-repository') {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n ownership.push(candidateOwnership);\n }\n\n const result: IGitInventoryBoundaryInspectedResult = Object.freeze({\n gitMetadataBytes,\n kind: 'inspected',\n ownership: Object.freeze([...ownership]),\n });\n\n return result;\n };\n};\n\n// default nested-repository ownership boundary used by inventory filtering\nexport const inspectGitInventoryBoundaries = createGitInventoryBoundaryInspector();\n","import type { IGitInventoryCandidate } from '../types.js';\n\nimport type { IGitInventoryOwnershipPathPlanResult } from './types.js';\n\n/**\n * Prepares one raw Git path for ownership inspection without logical-path normalization.\n * @param candidate The strictly decoded tracked or untracked candidate.\n * @returns An immutable segment plan, or a failure for an unsafe raw path shape.\n */\nexport const planGitInventoryOwnershipPath = (\n candidate: IGitInventoryCandidate,\n): IGitInventoryOwnershipPathPlanResult => {\n const isDirectoryRecord = candidate.path.endsWith('/');\n\n if (\n candidate.path.length === 0 ||\n candidate.path.startsWith('/') ||\n candidate.path.includes('\\\\') ||\n (candidate.kind === 'tracked' && isDirectoryRecord)\n ) {\n return Object.freeze({ kind: 'failed' });\n }\n\n const pathWithoutDirectoryTerminator = isDirectoryRecord\n ? candidate.path.slice(0, -1)\n : candidate.path;\n const segments = pathWithoutDirectoryTerminator.split('/');\n\n if (\n segments.length === 0 ||\n segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')\n ) {\n return Object.freeze({ kind: 'failed' });\n }\n\n const frozenSegments = Object.freeze([...segments]);\n const directorySegments = Object.freeze(\n isDirectoryRecord ? [...segments] : segments.slice(0, -1),\n );\n\n return Object.freeze({\n kind: 'planned',\n plan: Object.freeze({\n candidate,\n directorySegments,\n hasGitControlSegment: segments.includes('.git'),\n isDirectoryRecord,\n segments: frozenSegments,\n }),\n });\n};\n","import type { IGitInventoryCandidate, IGitInventoryProbeErrorCode } from '../types.js';\n\nimport { inspectGitInventoryBoundaries } from './boundary-inspector.js';\nimport { planGitInventoryOwnershipPath } from './path-planner.js';\nimport type {\n IGitInventoryBoundaryInspector,\n IGitInventoryOwnershipFilter,\n IGitInventoryOwnershipFilterFailedResult,\n IGitInventoryOwnershipFilterResult,\n IGitInventoryOwnershipPathPlan,\n IGitInventoryUntrackedOwnershipPlan,\n} from './types.js';\n\ninterface IGitInventoryIndexedOwnershipPlan {\n readonly candidateIndex: number;\n readonly plan: IGitInventoryOwnershipPathPlan;\n}\n\ninterface IGitInventoryGitlinkTrieNode {\n readonly children: Map<string, IGitInventoryGitlinkTrieNode>;\n isRoot: boolean;\n}\n\n/** Creates one immutable ownership-filtering failure. */\nconst createOwnershipFailure = (\n errorCode: IGitInventoryProbeErrorCode = 'GIT_OUTPUT_INVALID',\n): IGitInventoryOwnershipFilterFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Builds one segment trie for deterministic submodule-root lookup. */\nconst createGitlinkTrie = (\n rootSegments: readonly (readonly string[])[],\n): IGitInventoryGitlinkTrieNode => {\n const trie: IGitInventoryGitlinkTrieNode = { children: new Map(), isRoot: false };\n\n for (const segments of rootSegments) {\n let node = trie;\n\n for (const segment of segments) {\n let childNode = node.children.get(segment);\n\n if (childNode === undefined) {\n childNode = { children: new Map(), isRoot: false };\n node.children.set(segment, childNode);\n }\n\n node = childNode;\n }\n\n node.isRoot = true;\n }\n\n return trie;\n};\n\n/** Determines whether one candidate is a submodule root or segment descendant. */\nconst isAtOrBelowGitlink = (\n candidateSegments: readonly string[],\n gitlinkTrie: IGitInventoryGitlinkTrieNode,\n): boolean => {\n let node = gitlinkTrie;\n\n for (const segment of candidateSegments) {\n const childNode = node.children.get(segment);\n\n if (childNode === undefined) {\n return false;\n }\n\n if (childNode.isRoot) {\n return true;\n }\n\n node = childNode;\n }\n\n return false;\n};\n\n/**\n * Creates selected-repository ownership filtering around an injectable boundary inspector.\n * @param boundaryInspector The no-follow nested-repository ownership operation.\n * @returns An all-or-nothing raw candidate ownership filter.\n */\nexport const createGitInventoryOwnershipFilter = (\n boundaryInspector: IGitInventoryBoundaryInspector = inspectGitInventoryBoundaries,\n): IGitInventoryOwnershipFilter => {\n return async (input): Promise<IGitInventoryOwnershipFilterResult> => {\n const plannedCandidates: IGitInventoryIndexedOwnershipPlan[] = [];\n\n for (const [candidateIndex, candidate] of input.candidates.entries()) {\n if (input.signal?.aborted) {\n return createOwnershipFailure('GIT_OPERATION_ABORTED');\n }\n\n const planResult = planGitInventoryOwnershipPath(candidate);\n\n if (planResult.kind === 'failed') {\n return createOwnershipFailure();\n }\n\n plannedCandidates.push({ candidateIndex, plan: planResult.plan });\n }\n\n const gitlinkTrie = createGitlinkTrie(\n plannedCandidates\n .filter(\n ({ plan }) =>\n !plan.hasGitControlSegment &&\n plan.candidate.kind === 'tracked' &&\n plan.candidate.mode === '160000',\n )\n .map(({ plan }) => plan.segments),\n );\n const includedCandidates = Array.from({ length: input.candidates.length }, () => false);\n const untrackedPlans: IGitInventoryUntrackedOwnershipPlan[] = [];\n\n for (const { candidateIndex, plan } of plannedCandidates) {\n const isExcludedByGitPolicy =\n plan.hasGitControlSegment || isAtOrBelowGitlink(plan.segments, gitlinkTrie);\n\n if (isExcludedByGitPolicy) {\n continue;\n }\n\n if (plan.candidate.kind === 'tracked') {\n includedCandidates[candidateIndex] = true;\n continue;\n }\n\n untrackedPlans.push({ candidate: plan.candidate, candidateIndex, plan });\n }\n\n const boundaryResult = await boundaryInspector({\n maxMetadataBytes: input.maxMetadataBytes,\n plans: untrackedPlans.map(({ plan }) => plan),\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (boundaryResult.kind === 'failed') {\n return boundaryResult;\n }\n\n if (boundaryResult.ownership.length !== untrackedPlans.length) {\n return createOwnershipFailure();\n }\n\n for (const [ownershipIndex, ownership] of boundaryResult.ownership.entries()) {\n if (input.signal?.aborted) {\n return createOwnershipFailure('GIT_OPERATION_ABORTED');\n }\n\n const untrackedPlan = untrackedPlans[ownershipIndex];\n\n if (untrackedPlan === undefined) {\n return createOwnershipFailure();\n }\n\n if (ownership === 'selected-repository') {\n includedCandidates[untrackedPlan.candidateIndex] = true;\n }\n }\n\n const candidates = input.candidates.filter(\n (_candidate: IGitInventoryCandidate, candidateIndex) =>\n includedCandidates[candidateIndex] === true,\n );\n\n return Object.freeze({\n candidates: Object.freeze(candidates),\n gitMetadataBytes: boundaryResult.gitMetadataBytes,\n kind: 'filtered',\n });\n };\n};\n","import {\n executeGitStreamingProcess,\n MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n type IGitStreamingProcessExecutor,\n type IGitStreamingProcessFailureReason,\n} from '../git-process/index.js';\nimport { GIT_TRACKED_INVENTORY_ARGUMENTS, GIT_UNTRACKED_INVENTORY_ARGUMENTS } from './constants.js';\nimport {\n createGitContentTransformationClassifier,\n type IGitContentTransformationClassifier,\n} from './content-transformation/index.js';\nimport {\n createGitInventoryEntryTypeNormalizer,\n createGitSymlinkConfigurationResolver,\n inspectGitInventoryEntry,\n type IGitInventoryEntryTypeNormalizer,\n} from './entry-type/index.js';\nimport {\n normalizeGitInventoryLogicalPaths,\n type IGitInventoryLogicalPathNormalizer,\n validateGitInventoryCandidateLogicalPaths,\n} from './logical-path/index.js';\nimport { createTrackedGitInventoryParser, createUntrackedGitInventoryParser } from './parser.js';\nimport {\n createGitInventoryBoundaryInspector,\n createGitInventoryOwnershipFilter,\n type IGitInventoryOwnershipFilter,\n} from './repository-ownership/index.js';\nimport type {\n IGitInventoryCandidate,\n IGitInventoryParserResult,\n IGitInventoryProbe,\n IGitInventoryProbeErrorCode,\n IGitInventoryProbeFailedResult,\n IGitInventoryProbeResult,\n} from './types.js';\n\n/** Maps one normalized streamed Git failure to a safe inventory error. */\nconst mapGitProcessFailure = (\n reason: IGitStreamingProcessFailureReason,\n): IGitInventoryProbeErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'repository-not-found':\n return 'GIT_REPOSITORY_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'stderr-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'output-limit-exceeded':\n case 'stdout-limit-exceeded':\n return 'RESOURCE_LIMIT_EXCEEDED';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Creates one immutable inventory-probe failure. */\nconst createProbeFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitInventoryProbeFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps one completed parser result into immutable candidates or a safe failure. */\nconst resolveParserResult = <TCandidate extends IGitInventoryCandidate>(\n parserResult: IGitInventoryParserResult<TCandidate>,\n): readonly TCandidate[] | IGitInventoryProbeFailedResult => {\n if (parserResult.kind === 'completed') {\n return parserResult.candidates;\n }\n\n return createProbeFailure(\n parserResult.reason === 'entry-limit-exceeded'\n ? 'RESOURCE_LIMIT_EXCEEDED'\n : 'GIT_OUTPUT_INVALID',\n );\n};\n\n/** Identifies a parser resolution failure without relying on array contents. */\nconst isProbeFailure = (\n result: readonly IGitInventoryCandidate[] | IGitInventoryProbeFailedResult,\n): result is IGitInventoryProbeFailedResult => !Array.isArray(result);\n\n/**\n * Creates the strict normalized Git inventory probe around injectable boundaries.\n * @param processExecutor The bounded incremental Git process executor.\n * @param ownershipFilter The submodule and nested-repository ownership filter.\n * @param entryTypeNormalizer The current filesystem and Git mode entry-type normalizer.\n * @param contentTransformationClassifier The bounded effective Git attribute classifier.\n * @param logicalPathNormalizer The portable repository logical-path normalizer.\n * @returns An all-or-nothing selected-repository entry probe.\n */\nexport const createGitInventoryProbe =\n (\n processExecutor: IGitStreamingProcessExecutor = executeGitStreamingProcess,\n ownershipFilter: IGitInventoryOwnershipFilter = createGitInventoryOwnershipFilter(\n createGitInventoryBoundaryInspector(processExecutor),\n ),\n entryTypeNormalizer: IGitInventoryEntryTypeNormalizer = createGitInventoryEntryTypeNormalizer(\n inspectGitInventoryEntry,\n createGitSymlinkConfigurationResolver(processExecutor),\n ),\n contentTransformationClassifier: IGitContentTransformationClassifier = createGitContentTransformationClassifier(\n processExecutor,\n ),\n logicalPathNormalizer: IGitInventoryLogicalPathNormalizer = normalizeGitInventoryLogicalPaths,\n ): IGitInventoryProbe =>\n async (input): Promise<IGitInventoryProbeResult> => {\n if (input.signal?.aborted) {\n return createProbeFailure('GIT_OPERATION_ABORTED');\n }\n\n const selectionPathspecs = (input.selectionPaths ?? []).map(\n (selectionPath) => `:(top,literal)${selectionPath.slice(1)}`,\n );\n const trackedParser = createTrackedGitInventoryParser(input.maxEntries);\n const trackedProcessResult = await processExecutor({\n arguments: [\n '-C',\n input.repositoryRoot,\n ...GIT_TRACKED_INVENTORY_ARGUMENTS,\n ...selectionPathspecs,\n ],\n consumeStdout: (chunk) => trackedParser.consume(chunk),\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: input.maxMetadataBytes,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (trackedProcessResult.kind === 'failed') {\n return createProbeFailure(mapGitProcessFailure(trackedProcessResult.reason));\n }\n\n if (trackedProcessResult.stderr.byteLength > 0) {\n return createProbeFailure('GIT_OUTPUT_INVALID');\n }\n\n const trackedCandidates = resolveParserResult(trackedParser.finish());\n\n if (isProbeFailure(trackedCandidates)) {\n return trackedCandidates;\n }\n\n const untrackedParser = createUntrackedGitInventoryParser(\n input.maxEntries - trackedCandidates.length,\n );\n const untrackedProcessResult = await processExecutor({\n arguments: [\n '-C',\n input.repositoryRoot,\n ...GIT_UNTRACKED_INVENTORY_ARGUMENTS,\n ...selectionPathspecs,\n ],\n consumeStdout: (chunk) => untrackedParser.consume(chunk),\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: input.maxMetadataBytes - trackedProcessResult.stdoutBytes,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (untrackedProcessResult.kind === 'failed') {\n return createProbeFailure(mapGitProcessFailure(untrackedProcessResult.reason));\n }\n\n if (untrackedProcessResult.stderr.byteLength > 0) {\n return createProbeFailure('GIT_OUTPUT_INVALID');\n }\n\n const untrackedCandidates = resolveParserResult(untrackedParser.finish());\n\n if (isProbeFailure(untrackedCandidates)) {\n return untrackedCandidates;\n }\n\n const candidates = Object.freeze([...trackedCandidates, ...untrackedCandidates]);\n const logicalPathValidationResult = validateGitInventoryCandidateLogicalPaths({ candidates });\n\n if (logicalPathValidationResult.kind === 'failed') {\n return logicalPathValidationResult;\n }\n\n const ownershipResult = await ownershipFilter({\n candidates,\n maxMetadataBytes:\n input.maxMetadataBytes -\n trackedProcessResult.stdoutBytes -\n untrackedProcessResult.stdoutBytes,\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (ownershipResult.kind === 'failed') {\n return ownershipResult;\n }\n\n const entryTypeResult = await entryTypeNormalizer({\n candidates: ownershipResult.candidates,\n maxMetadataBytes:\n input.maxMetadataBytes -\n trackedProcessResult.stdoutBytes -\n untrackedProcessResult.stdoutBytes -\n ownershipResult.gitMetadataBytes,\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (entryTypeResult.kind === 'failed') {\n return entryTypeResult;\n }\n\n const contentTransformationResult = await contentTransformationClassifier({\n entries: entryTypeResult.entries,\n maxMetadataBytes:\n input.maxMetadataBytes -\n trackedProcessResult.stdoutBytes -\n untrackedProcessResult.stdoutBytes -\n ownershipResult.gitMetadataBytes -\n entryTypeResult.gitMetadataBytes,\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (contentTransformationResult.kind === 'failed') {\n return contentTransformationResult;\n }\n\n const logicalPathResult = logicalPathNormalizer({\n entries: contentTransformationResult.entries,\n });\n\n if (logicalPathResult.kind === 'failed') {\n return logicalPathResult;\n }\n\n return Object.freeze({ entries: logicalPathResult.entries, kind: 'probed' });\n };\n\n// default normalized Git inventory probe used by command execution\nexport const probeGitInventory = createGitInventoryProbe();\n","import type { IGitContentTransformationClassification } from '../content-transformation/index.js';\nimport type { IGitInventoryIndexEntry } from '../entry-type/index.js';\nimport type { IGitInventoryEntry } from '../logical-path/index.js';\n\n/** Determines whether two exact transform classifications are equal. */\nconst areContentTransformationsEqual = (\n left: IGitContentTransformationClassification,\n right: IGitContentTransformationClassification,\n): boolean =>\n left.filter === right.filter &&\n left.ident === right.ident &&\n left.isGuarded === right.isGuarded &&\n left.workingTreeEncoding === right.workingTreeEncoding;\n\n/** Determines whether two retained Git mode-and-stage sequences are equal. */\nconst areIndexEntriesEqual = (\n left: readonly IGitInventoryIndexEntry[],\n right: readonly IGitInventoryIndexEntry[],\n): boolean =>\n left.length === right.length &&\n left.every(\n (leftEntry, index) =>\n leftEntry.mode === right[index]?.mode && leftEntry.stage === right[index]?.stage,\n );\n\n/** Determines whether two normalized inventory entries are exactly equal. */\nconst areInventoryEntriesEqual = (left: IGitInventoryEntry, right: IGitInventoryEntry): boolean => {\n if (\n left.kind !== right.kind ||\n left.path !== right.path ||\n left.entryType !== right.entryType ||\n left.requiresSymlinkOverlay !== right.requiresSymlinkOverlay ||\n !areContentTransformationsEqual(left.contentTransformation, right.contentTransformation)\n ) {\n return false;\n }\n\n if (left.kind === 'untracked' || right.kind === 'untracked') {\n return left.kind === right.kind;\n }\n\n return areIndexEntriesEqual(left.indexEntries, right.indexEntries);\n};\n\n/**\n * Determines whether two complete normalized Git inventories describe the same snapshot inputs.\n * @param left The first deterministic inventory.\n * @param right The second deterministic inventory.\n * @returns Whether ordering and every retained record field are equal.\n */\nexport const areGitInventoriesEqual = (\n left: readonly IGitInventoryEntry[],\n right: readonly IGitInventoryEntry[],\n): boolean =>\n left.length === right.length &&\n left.every((leftEntry, index) => {\n const rightEntry = right[index];\n\n return rightEntry !== undefined && areInventoryEntriesEqual(leftEntry, rightEntry);\n });\n","import {\n REPOSITORY_ROOT,\n RepositorySourceException,\n createRepositoryComparison,\n parseRepositoryPath,\n type IRepositoryComparison,\n type IRepositoryEntry,\n type IRepositoryEntryPage,\n type IRepositoryEntryPageOptions,\n type IRepositoryFilePage,\n type IRepositoryFilePageOptions,\n type IRepositoryOperation,\n type IRepositoryOperationOptions,\n type IRepositoryPath,\n type IRepositoryReader,\n type IRepositorySnapshot,\n} from '@moldea.ai/repository';\n\n/** Throws the common cancellation contract for wrapper-owned operations. */\nconst throwIfAborted = (\n signal: AbortSignal | undefined,\n operation: IRepositoryOperation,\n path: IRepositoryPath,\n): void => {\n if (!signal?.aborted) {\n return;\n }\n\n throw new RepositorySourceException({\n cause: signal.reason,\n code: 'ABORTED',\n operation,\n path,\n retryable: false,\n });\n};\n\n/** Creates the common failure for an overlay that contradicts its underlying snapshot. */\nconst createInvalidOverlayException = (\n operation: IRepositoryOperation,\n path: IRepositoryPath,\n): RepositorySourceException =>\n new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation,\n path,\n retryable: false,\n });\n\n/** Confirms that one overlay path remains a regular file in the underlying snapshot. */\nconst validateOverlayEntry = (\n entry: IRepositoryEntry | null,\n operation: Exclude<IRepositoryOperation, 'create-reader'>,\n path: IRepositoryPath,\n): void => {\n if (entry?.type !== 'file' || entry.path !== path) {\n throw createInvalidOverlayException(operation, path);\n }\n};\n\n/** Maps one expected underlying regular file to an immutable logical symlink entry. */\nconst overlayEntry = (\n entry: IRepositoryEntry | null,\n operation: 'get-entry' | 'list-entries-page',\n path: IRepositoryPath,\n): IRepositoryEntry => {\n validateOverlayEntry(entry, operation, path);\n\n return Object.freeze({ byteLength: null, contentIdentity: null, path, type: 'symlink' });\n};\n\n// immutable logical symlink view over one coherent repository reader\nclass GitSymlinkOverlayRepositoryReader implements IRepositoryReader {\n public readonly snapshot: IRepositorySnapshot;\n\n readonly #overlayPaths: ReadonlySet<IRepositoryPath>;\n\n readonly #reader: IRepositoryReader;\n\n public constructor(reader: IRepositoryReader, overlayPaths: ReadonlySet<IRepositoryPath>) {\n this.#reader = reader;\n this.#overlayPaths = overlayPaths;\n this.snapshot = reader.snapshot;\n }\n\n /** Creates a bounded comparison from this logical overlay snapshot. */\n public compare(\n candidate: IRepositoryReader,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryComparison> {\n return createRepositoryComparison(this, candidate, options);\n }\n\n /**\n * Looks up an entry while replacing configured host files with logical symlinks.\n * @param path The validated repository path to inspect.\n * @param options Optional cancellation controls.\n * @returns A promise resolving to the detached logical entry or confirmed absence.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during the operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public async getEntry(\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryEntry | null> {\n const entry = await this.#reader.getEntry(path, options);\n\n if (!this.#overlayPaths.has(path)) {\n return entry;\n }\n\n return overlayEntry(entry, 'get-entry', path);\n }\n\n /**\n * Reads ordinary files while refusing access to configured logical symlink bytes.\n * @param path The validated repository file path to read.\n * @param options Optional cancellation controls.\n * @returns A promise resolving to fresh bytes for a non-overlaid regular file.\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 repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public async readFilePage(\n path: IRepositoryPath,\n options: IRepositoryFilePageOptions,\n ): Promise<IRepositoryFilePage> {\n const parsedPath = parseRepositoryPath(path);\n\n if (!this.#overlayPaths.has(parsedPath)) {\n return this.#reader.readFilePage(parsedPath, options);\n }\n\n throwIfAborted(options.signal, 'read-file-page', parsedPath);\n\n const entry = await this.#reader.getEntry(parsedPath, options);\n\n validateOverlayEntry(entry, 'read-file-page', parsedPath);\n throwIfAborted(options.signal, 'read-file-page', parsedPath);\n\n throw new RepositorySourceException({\n code: 'ENTRY_NOT_FILE',\n operation: 'read-file-page',\n path: parsedPath,\n retryable: false,\n });\n }\n\n /**\n * Recursively lists descendants while replacing configured host files with logical symlinks.\n * @param options Optional prefix and cancellation controls.\n * @returns An async iterable of detached logical entries.\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_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 repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public async listEntriesPage(\n options: IRepositoryEntryPageOptions,\n ): Promise<IRepositoryEntryPage> {\n const prefix =\n options.prefix === undefined ? REPOSITORY_ROOT : parseRepositoryPath(options.prefix);\n\n if (this.#overlayPaths.has(prefix)) {\n throwIfAborted(options.signal, 'list-entries-page', prefix);\n\n const operationOptions =\n options.signal === undefined ? undefined : { signal: options.signal };\n const entry = await this.#reader.getEntry(prefix, operationOptions);\n\n validateOverlayEntry(entry, 'list-entries-page', prefix);\n throwIfAborted(options.signal, 'list-entries-page', prefix);\n throw new RepositorySourceException({\n code: 'ENTRY_NOT_DIRECTORY',\n operation: 'list-entries-page',\n path: prefix,\n retryable: false,\n });\n }\n\n const page = await this.#reader.listEntriesPage(options);\n const entries = page.entries.map((entry) =>\n this.#overlayPaths.has(entry.path)\n ? overlayEntry(entry, 'list-entries-page', entry.path)\n : entry,\n );\n\n return Object.freeze({\n entries: Object.freeze(entries),\n isComplete: page.isComplete,\n nextCursor: page.nextCursor,\n snapshot: this.snapshot,\n });\n }\n}\n\n/**\n * Creates an immutable reader overlay for Git symlinks materialized as host files.\n * @param reader The coherent underlying repository reader.\n * @param symlinkPaths The logical paths whose host files represent Git symlinks.\n * @returns A reader that exposes the configured paths only as logical symlinks.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n */\nexport const createGitSymlinkOverlayRepositoryReader = (\n reader: IRepositoryReader,\n symlinkPaths: readonly IRepositoryPath[],\n): IRepositoryReader => {\n const overlayPaths = new Set<IRepositoryPath>();\n\n for (const symlinkPath of symlinkPaths) {\n const parsedPath = parseRepositoryPath(symlinkPath);\n\n if (parsedPath === REPOSITORY_ROOT) {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'create-reader',\n path: parsedPath,\n retryable: false,\n });\n }\n\n overlayPaths.add(parsedPath);\n }\n\n return Object.freeze(new GitSymlinkOverlayRepositoryReader(reader, overlayPaths));\n};\n","import type { IRepositoryPath, IRepositoryReader } from '@moldea.ai/repository';\nimport { createFilesystemRepositoryReader } from '@moldea.ai/repository-fs';\n\nimport { createGitContentTransformationGuardRepositoryReader } from '../repository-content-transformation-guard/index.js';\nimport { createGitSymlinkOverlayRepositoryReader } from '../repository-symlink-overlay/index.js';\n\nimport type { IWorkingTreeRepositoryReaderFactory } from './types.js';\n\n// injectable package and overlay factories used by the composition boundary\ntype IFilesystemRepositoryReaderFactory = typeof createFilesystemRepositoryReader;\ntype IGitContentTransformationGuardRepositoryReaderFactory =\n typeof createGitContentTransformationGuardRepositoryReader;\ntype IGitSymlinkOverlayRepositoryReaderFactory = typeof createGitSymlinkOverlayRepositoryReader;\n\n/**\n * Creates the private working-tree reader factory around injectable composition boundaries.\n * @param filesystemReaderFactory The exact-path filesystem snapshot factory.\n * @param symlinkOverlayFactory The logical Git symlink overlay factory.\n * @param contentTransformationGuardFactory The guarded logical regular-file reader factory.\n * @returns A factory that composes one coherent selected working-tree reader.\n */\nexport const createWorkingTreeRepositoryReaderFactory =\n (\n filesystemReaderFactory: IFilesystemRepositoryReaderFactory = createFilesystemRepositoryReader,\n symlinkOverlayFactory: IGitSymlinkOverlayRepositoryReaderFactory = createGitSymlinkOverlayRepositoryReader,\n contentTransformationGuardFactory: IGitContentTransformationGuardRepositoryReaderFactory = createGitContentTransformationGuardRepositoryReader,\n ): IWorkingTreeRepositoryReaderFactory =>\n async (input): Promise<IRepositoryReader> => {\n const selectedPaths = Object.freeze(input.entries.map((entry) => entry.path));\n const symlinkOverlayPaths = Object.freeze(\n input.entries.reduce<IRepositoryPath[]>((paths, entry) => {\n if (entry.requiresSymlinkOverlay) {\n paths.push(entry.path);\n }\n\n return paths;\n }, []),\n );\n const guardedPaths = Object.freeze(\n input.entries.reduce<IRepositoryPath[]>((paths, entry) => {\n if (entry.contentTransformation.isGuarded) {\n paths.push(entry.path);\n }\n\n return paths;\n }, []),\n );\n const filesystemReader = await filesystemReaderFactory({\n limits: Object.freeze({\n maxCachedBytes: input.resourceLimits.maxTotalBytes,\n maxDirectoryEntries: input.resourceLimits.maxEntries,\n maxEntries: input.resourceLimits.maxEntries,\n maxPageEntries: Math.min(4096, input.resourceLimits.maxEntries),\n maxReadBytes: input.resourceLimits.maxFileBytes,\n }),\n rootDirectory: input.repositoryRoot,\n selection: Object.freeze({ kind: 'paths', paths: selectedPaths }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n const overlaidReader = symlinkOverlayFactory(filesystemReader, symlinkOverlayPaths);\n\n return contentTransformationGuardFactory(overlaidReader, guardedPaths);\n };\n\n// default exact-path working-tree reader composition used by command execution\nexport const createWorkingTreeRepositoryReader = createWorkingTreeRepositoryReaderFactory();\n","import { RepositorySourceException, type IRepositoryReader } from '@moldea.ai/repository';\n\nimport {\n areGitInventoriesEqual,\n probeGitInventory,\n type IGitInventoryProbe,\n type IGitInventoryProbedResult,\n} from '../git-inventory/index.js';\nimport {\n areGitWorkingTreeIdentitiesEqual,\n inspectGitWorkingTreeIdentity,\n type IGitWorkingTreeIdentity,\n type IGitWorkingTreeIdentityInspector,\n} from '../git-working-tree/index.js';\nimport type { IMoldeaCliOwnedErrorCode } from '../presentation/index.js';\nimport {\n createWorkingTreeRepositoryReader,\n type IWorkingTreeRepositoryReaderFactory,\n} from '../repository-reader/index.js';\n\nimport { MAX_WORKING_TREE_SNAPSHOT_ATTEMPTS } from './constants.js';\nimport type {\n IWorkingTreeSnapshotExecutionInput,\n IWorkingTreeSnapshotExecutionResult,\n IWorkingTreeSnapshotExecutor,\n IWorkingTreeSnapshotFailedResult,\n IWorkingTreeSnapshotInventoryComparator,\n} from './types.js';\n\n/** Creates one immutable terminal snapshot failure. */\nconst createSnapshotFailure = (\n errorCode: IMoldeaCliOwnedErrorCode,\n): IWorkingTreeSnapshotFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Determines whether a source exception proves that the current reader is unusable. */\nconst isSnapshotChanged = (error: unknown): boolean =>\n error instanceof RepositorySourceException && error.code === 'SNAPSHOT_CHANGED';\n\n/** Determines whether reader creation may have raced with an inventory change. */\nconst isCreationInventoryRace = (error: unknown): boolean =>\n error instanceof RepositorySourceException &&\n error.operation === 'create-reader' &&\n (error.code === 'ENTRY_NOT_FOUND' || error.code === 'ENTRY_NOT_DIRECTORY');\n\n/** Determines whether identity inspection failed because the pinned source disappeared. */\nconst isPinnedIdentityUnavailable = (errorCode: IMoldeaCliOwnedErrorCode): boolean =>\n errorCode === 'GIT_REPOSITORY_NOT_FOUND' || errorCode === 'GIT_WORK_TREE_REQUIRED';\n\n/**\n * Creates the bounded whole-operation working-tree snapshot executor.\n * @param identityInspector The selected working-tree identity observation boundary.\n * @param inventoryProbe The complete normalized Git inventory probe.\n * @param repositoryReaderFactory The exact-path guarded reader factory.\n * @param compareInventories The exact normalized inventory comparator.\n * @returns An executor that discards and retries complete provisional attempts.\n */\nexport const createWorkingTreeSnapshotExecutor = (\n identityInspector: IGitWorkingTreeIdentityInspector = inspectGitWorkingTreeIdentity,\n inventoryProbe: IGitInventoryProbe = probeGitInventory,\n repositoryReaderFactory: IWorkingTreeRepositoryReaderFactory = createWorkingTreeRepositoryReader,\n compareInventories: IWorkingTreeSnapshotInventoryComparator = areGitInventoriesEqual,\n): IWorkingTreeSnapshotExecutor => {\n const executeSnapshot = async <TResult>(\n input: IWorkingTreeSnapshotExecutionInput<TResult>,\n ): Promise<IWorkingTreeSnapshotExecutionResult<TResult>> => {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n const repositoryRoot = input.repositoryRoot;\n const resourceLimits = Object.freeze({ ...input.resourceLimits });\n const pinnedIdentityResult = await identityInspector({\n repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (pinnedIdentityResult.kind === 'failed') {\n return createSnapshotFailure(pinnedIdentityResult.errorCode);\n }\n\n if (pinnedIdentityResult.kind === 'mismatched') {\n return createSnapshotFailure('GIT_OUTPUT_INVALID');\n }\n\n const pinnedIdentity: IGitWorkingTreeIdentity = pinnedIdentityResult.identity;\n\n const probeInventory = async (): Promise<\n IGitInventoryProbedResult | IWorkingTreeSnapshotFailedResult\n > => {\n const result = await inventoryProbe({\n maxEntries: resourceLimits.maxEntries,\n maxMetadataBytes: resourceLimits.maxTotalBytes,\n repositoryRoot,\n ...(input.selectionPaths === undefined ? {} : { selectionPaths: input.selectionPaths }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n return result.kind === 'failed' ? createSnapshotFailure(result.errorCode) : result;\n };\n\n for (let attempt = 0; attempt < MAX_WORKING_TREE_SNAPSHOT_ATTEMPTS; attempt += 1) {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n const currentIdentityResult = await identityInspector({\n repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (currentIdentityResult.kind === 'failed') {\n return createSnapshotFailure(\n isPinnedIdentityUnavailable(currentIdentityResult.errorCode)\n ? 'WORKING_TREE_UNSTABLE'\n : currentIdentityResult.errorCode,\n );\n }\n\n if (\n currentIdentityResult.kind === 'mismatched' ||\n !areGitWorkingTreeIdentitiesEqual(pinnedIdentity, currentIdentityResult.identity)\n ) {\n return createSnapshotFailure('WORKING_TREE_UNSTABLE');\n }\n\n const firstInventoryResult = await probeInventory();\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (firstInventoryResult.kind === 'failed') {\n return firstInventoryResult;\n }\n\n let reader: IRepositoryReader;\n\n try {\n reader = await repositoryReaderFactory({\n entries: firstInventoryResult.entries,\n repositoryRoot,\n resourceLimits,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n } catch (error) {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isSnapshotChanged(error)) {\n continue;\n }\n\n if (!isCreationInventoryRace(error)) {\n throw error;\n }\n\n const freshInventoryResult = await probeInventory();\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (freshInventoryResult.kind === 'failed') {\n return freshInventoryResult;\n }\n\n if (!compareInventories(firstInventoryResult.entries, freshInventoryResult.entries)) {\n continue;\n }\n\n throw error;\n }\n\n const secondInventoryResult = await probeInventory();\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (secondInventoryResult.kind === 'failed') {\n return secondInventoryResult;\n }\n\n if (!compareInventories(firstInventoryResult.entries, secondInventoryResult.entries)) {\n continue;\n }\n\n try {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n const result =\n input.signal === undefined\n ? await input.operation(reader)\n : await input.operation(reader, input.signal);\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n return Object.freeze({ kind: 'completed', result });\n } catch (error) {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!isSnapshotChanged(error)) {\n throw error;\n }\n }\n }\n\n return createSnapshotFailure('WORKING_TREE_UNSTABLE');\n };\n\n return executeSnapshot;\n};\n\n// default bounded snapshot executor used by command execution\nexport const executeWorkingTreeSnapshot = createWorkingTreeSnapshotExecutor();\n","import type { IProjectInspectionPageResult, IProjectValidationResult } from '@moldea.ai/core';\n\nimport type { IMoldeaCliCommand } from '../command-line/index.js';\nimport type { IMoldeaCliCompositionResult } from '../composition/index.js';\nimport { assertMoldeaCliJsonResultIsContentFree } from '../json-output-contract/index.js';\nimport {\n createMoldeaCliOutputPage,\n type IMoldeaCliOutputPage,\n type IMoldeaCliOutputRecord,\n} from '../output-page/index.js';\nimport {\n createMoldeaCliContentPage,\n type IMoldeaCliContentResult,\n type IMoldeaCliProjectContentExecutor,\n} from '../project-content/index.js';\nimport {\n createMoldeaCliScopeProjection,\n type IMoldeaCliProjectScopeExecutionResult,\n type IMoldeaCliScopeResult,\n} from '../project-scope/index.js';\nimport {\n createMoldeaCliInspectProjection,\n createMoldeaCliValidateProjection,\n formatMoldeaCliHumanCompositionResult,\n formatMoldeaCliHumanContentResult,\n formatMoldeaCliHumanError,\n formatMoldeaCliHumanInspectResult,\n formatMoldeaCliHumanScopeResult,\n formatMoldeaCliHumanValidateResult,\n formatMoldeaCliJsonCompositionResult,\n formatMoldeaCliJsonContentResult,\n formatMoldeaCliJsonError,\n formatMoldeaCliJsonInspectResult,\n formatMoldeaCliJsonScopeResult,\n formatMoldeaCliJsonValidateResult,\n MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,\n type IMoldeaCliError,\n type IMoldeaCliInspectResult,\n type IMoldeaCliValidateResult,\n} from '../presentation/index.js';\n\nimport { MOLDEA_CLI_EXIT_CODES } from './constants.js';\nimport type { IMoldeaCliExecutionResult } from './types.js';\n\nconst measureOutput = (output: string): number => Buffer.byteLength(output, 'utf8');\n\n/** Measures a paged result without repeatedly serializing its accumulated JSON records. */\nconst measurePagedOutput = <TRecord extends IMoldeaCliOutputRecord>(\n page: IMoldeaCliOutputPage<TRecord>,\n serializedRecordsUtf8Bytes: number,\n isJson: boolean,\n formatJson: (candidate: IMoldeaCliOutputPage<TRecord>) => string,\n formatHuman: (candidate: IMoldeaCliOutputPage<TRecord>) => string,\n): number => {\n if (!isJson) {\n return measureOutput(formatHuman(page));\n }\n\n const emptyPage = Object.freeze({\n cursor: page.cursor,\n records: Object.freeze([]),\n });\n\n return measureOutput(formatJson(emptyPage)) - 2 + serializedRecordsUtf8Bytes;\n};\n\n/** Creates one process-neutral result for a valid installed composition. */\nexport const createMoldeaCliCompositionExecutionResult = (\n result: IMoldeaCliCompositionResult,\n cliVersion: string,\n isJson: boolean,\n): IMoldeaCliExecutionResult =>\n Object.freeze({\n exitCode: MOLDEA_CLI_EXIT_CODES.Success,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonCompositionResult(result, cliVersion)\n : formatMoldeaCliHumanCompositionResult(result, cliVersion),\n });\n\n/** Creates one safe process-neutral error result in the requested output mode. */\nexport const createMoldeaCliErrorResult = (\n error: IMoldeaCliError,\n command: IMoldeaCliCommand | null,\n cliVersion: string,\n isJson: boolean,\n exitCode: number,\n): IMoldeaCliExecutionResult =>\n Object.freeze(\n isJson\n ? {\n exitCode,\n stderr: '',\n stdout: formatMoldeaCliJsonError(error, command, cliVersion),\n }\n : {\n exitCode,\n stderr: formatMoldeaCliHumanError(error),\n stdout: '',\n },\n );\n\n/**\n * Creates one bounded process-neutral result for a completed validate command.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliValidateExecutionResult = (\n inspection: IProjectValidationResult,\n cliVersion: string,\n isJson: boolean,\n cursor: string | null,\n maxOutputBytes: number,\n): IMoldeaCliExecutionResult => {\n const projection = createMoldeaCliValidateProjection(inspection);\n const createResult = (page: IMoldeaCliValidateResult['page']): IMoldeaCliValidateResult => ({\n diagnosticCount: projection.diagnostics.length,\n errorCount: projection.errorCount,\n formatVersion: projection.formatVersion,\n page,\n snapshotDigest: projection.snapshotDigest,\n source: projection.source,\n valid: projection.valid,\n warningCount: projection.warningCount,\n });\n const page = createMoldeaCliOutputPage({\n command: 'validate',\n cursor,\n filters: {},\n maxOutputBytes,\n measure: (candidate, serializedRecordsUtf8Bytes) =>\n measurePagedOutput(\n candidate,\n serializedRecordsUtf8Bytes,\n isJson,\n (page) => formatMoldeaCliJsonValidateResult(createResult(page), cliVersion),\n (page) => formatMoldeaCliHumanValidateResult(createResult(page)),\n ),\n records: projection.diagnostics,\n snapshotDigest: projection.snapshotDigest,\n });\n const result = Object.freeze(createResult(page));\n\n assertMoldeaCliJsonResultIsContentFree(result);\n\n return Object.freeze({\n exitCode: result.valid\n ? MOLDEA_CLI_EXIT_CODES.Success\n : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonValidateResult(result, cliVersion)\n : formatMoldeaCliHumanValidateResult(result),\n });\n};\n\n/**\n * Creates one bounded content-free result for a completed inspect command.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliInspectExecutionResult = (\n inspection: IProjectInspectionPageResult,\n cliVersion: string,\n isJson: boolean,\n cursor: string | null,\n maxOutputBytes: number,\n): IMoldeaCliExecutionResult => {\n const projection = createMoldeaCliInspectProjection(inspection);\n const createResult = (page: IMoldeaCliInspectResult['page']): IMoldeaCliInspectResult => ({\n counts: projection.counts,\n formatVersion: projection.formatVersion,\n page,\n project: projection.project,\n snapshotDigest: projection.snapshotDigest,\n source: projection.source,\n valid: projection.valid,\n view: projection.view,\n });\n const page = createMoldeaCliOutputPage({\n command: 'inspect',\n cursor,\n filters: {},\n maxOutputBytes,\n measure: (candidate, serializedRecordsUtf8Bytes) =>\n measurePagedOutput(\n candidate,\n serializedRecordsUtf8Bytes,\n isJson,\n (page) => formatMoldeaCliJsonInspectResult(createResult(page), cliVersion),\n (page) => formatMoldeaCliHumanInspectResult(createResult(page)),\n ),\n records: projection.records,\n sourceCursorForRecord: projection.getSourceCursor,\n snapshotDigest: projection.snapshotDigest,\n });\n const result = Object.freeze(createResult(page));\n\n assertMoldeaCliJsonResultIsContentFree(result);\n\n return Object.freeze({\n exitCode: inspection.valid\n ? MOLDEA_CLI_EXIT_CODES.Success\n : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonInspectResult(result, cliVersion)\n : formatMoldeaCliHumanInspectResult(result),\n });\n};\n\n/**\n * Creates one bounded content-free result for changed-path relationship scope.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliScopeExecutionResult = (\n execution: IMoldeaCliProjectScopeExecutionResult,\n cliVersion: string,\n isJson: boolean,\n cursor: string | null,\n maxOutputBytes: number,\n): IMoldeaCliExecutionResult => {\n const projection = createMoldeaCliScopeProjection(execution);\n const createResult = (page: IMoldeaCliScopeResult['page']): IMoldeaCliScopeResult => ({\n counts: projection.counts,\n inputDigest: projection.inputDigest,\n manifestDigest: projection.manifestDigest,\n page,\n relevant: projection.relevant,\n snapshotDigest: projection.snapshotDigest,\n source: MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,\n valid: projection.valid,\n });\n const page = createMoldeaCliOutputPage({\n command: 'scope',\n cursor,\n filters: { inputDigest: projection.inputDigest },\n maxOutputBytes,\n measure: (candidate, serializedRecordsUtf8Bytes) =>\n measurePagedOutput(\n candidate,\n serializedRecordsUtf8Bytes,\n isJson,\n (page) => formatMoldeaCliJsonScopeResult(createResult(page), cliVersion),\n (page) => formatMoldeaCliHumanScopeResult(createResult(page)),\n ),\n records: projection.records,\n snapshotDigest: projection.snapshotDigest,\n });\n const result = Object.freeze(createResult(page));\n\n assertMoldeaCliJsonResultIsContentFree(result, projection.canonicalBodies);\n\n return Object.freeze({\n exitCode: projection.valid\n ? MOLDEA_CLI_EXIT_CODES.Success\n : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonScopeResult(result, cliVersion)\n : formatMoldeaCliHumanScopeResult(result),\n });\n};\n\n/**\n * Creates one bounded Unicode-safe explicit canonical content result.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliContentExecutionResult = (\n pageResult: Awaited<ReturnType<IMoldeaCliProjectContentExecutor>>,\n cliVersion: string,\n isJson: boolean,\n cursor: string | null,\n maxOutputBytes: number,\n): IMoldeaCliExecutionResult => {\n const result: IMoldeaCliContentResult = createMoldeaCliContentPage({\n cursor,\n maxOutputBytes,\n measure: (candidate) =>\n measureOutput(\n isJson\n ? formatMoldeaCliJsonContentResult(candidate, cliVersion)\n : formatMoldeaCliHumanContentResult(candidate),\n ),\n page: pageResult,\n });\n\n return Object.freeze({\n exitCode: MOLDEA_CLI_EXIT_CODES.Success,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonContentResult(result, cliVersion)\n : formatMoldeaCliHumanContentResult(result),\n });\n};\n","import type { IProjectInspectionPageResult, IProjectValidationResult } from '@moldea.ai/core';\n\nimport { MOLDEA_CLI_COMMANDS } from '../command-line/index.js';\nimport type { IMoldeaCliCompositionResolver } from '../composition/index.js';\nimport type { IMoldeaCliCoreInspectionExecutor } from '../core-composition/index.js';\nimport {\n discoverGitWorkingTree,\n type IGitWorkingTreeDiscovery,\n} from '../git-working-tree/index.js';\nimport { mapMoldeaCliOperationalError } from '../operational-error/index.js';\nimport { decodeMoldeaCliCursor, MoldeaCliOutputPageException } from '../output-page/index.js';\nimport {\n executeMoldeaCliProjectContent,\n parseMoldeaCliCanonicalContentPath,\n type IMoldeaCliProjectContentExecutor,\n} from '../project-content/index.js';\nimport {\n executeMoldeaCliProjectScope,\n MOLDEA_MANIFEST_PATH,\n parseMoldeaCliScopePathBytes,\n type IMoldeaCliProjectScopeExecutor,\n} from '../project-scope/index.js';\nimport { createMoldeaCliOwnedError } from '../presentation/index.js';\nimport {\n executeWorkingTreeSnapshot,\n type IWorkingTreeSnapshotExecutor,\n} from '../working-tree-snapshot/index.js';\n\nimport { MOLDEA_CLI_EXIT_CODES } from './constants.js';\nimport {\n createMoldeaCliCompositionExecutionResult,\n createMoldeaCliContentExecutionResult,\n createMoldeaCliErrorResult,\n createMoldeaCliInspectExecutionResult,\n createMoldeaCliScopeExecutionResult,\n createMoldeaCliValidateExecutionResult,\n} from './results.js';\nimport type { IMoldeaCliCommandExecutor, IMoldeaCliExecutionResult } from './types.js';\n\n/** Loads adapter-backed Core inspection only for commands that need it. */\nconst executeLazyCoreInspection: IMoldeaCliCoreInspectionExecutor = async (input) => {\n const { executeMoldeaCliCoreInspection } = await import('../core-composition/index.js');\n\n return executeMoldeaCliCoreInspection(input);\n};\n\ntype IMoldeaCliCompositionLoader = (\n input: Parameters<IMoldeaCliCompositionResolver>[0],\n) => ReturnType<IMoldeaCliCompositionResolver> | Promise<ReturnType<IMoldeaCliCompositionResolver>>;\n\nconst loadInstalledComposition: IMoldeaCliCompositionLoader = async (input) => {\n const { resolveInstalledMoldeaCliComposition } = await import('../composition/index.js');\n\n return resolveInstalledMoldeaCliComposition(input);\n};\n\n/** Creates one operational error result without exposing caught failure details. */\nconst createOperationalErrorResult = (\n code: Parameters<typeof createMoldeaCliOwnedError>[0],\n input: Parameters<IMoldeaCliCommandExecutor>[0],\n): IMoldeaCliExecutionResult =>\n createMoldeaCliErrorResult(\n createMoldeaCliOwnedError(code),\n input.invocation.command,\n input.packageMetadata.version,\n input.invocation.options.isJson,\n MOLDEA_CLI_EXIT_CODES.OperationalError,\n );\n\n/**\n * Creates command dispatch with lazy adapter composition and bounded working-tree snapshots.\n * @param workingTreeDiscovery The Git working-tree discovery operation.\n * @param workingTreeSnapshotExecutor The complete working-tree snapshot operation.\n * @param coreInspectionExecutor The adapter-backed Core inspection operation.\n * @param compositionLoader The installed executable-integrity composition boundary.\n * @param projectScopeExecutor The adapter-free manifest scope operation.\n * @param projectContentExecutor The adapter-free canonical content operation.\n * @returns A command executor for the schema 5 CLI.\n */\nexport const createMoldeaCliCommandExecutor = (\n workingTreeDiscovery: IGitWorkingTreeDiscovery = discoverGitWorkingTree,\n workingTreeSnapshotExecutor: IWorkingTreeSnapshotExecutor = executeWorkingTreeSnapshot,\n coreInspectionExecutor: IMoldeaCliCoreInspectionExecutor = executeLazyCoreInspection,\n compositionLoader: IMoldeaCliCompositionLoader = loadInstalledComposition,\n projectScopeExecutor: IMoldeaCliProjectScopeExecutor = executeMoldeaCliProjectScope,\n projectContentExecutor: IMoldeaCliProjectContentExecutor = executeMoldeaCliProjectContent,\n): IMoldeaCliCommandExecutor => {\n return async (input): Promise<IMoldeaCliExecutionResult> => {\n const command = input.invocation.command;\n const options = input.invocation.options;\n\n try {\n if (\n command === MOLDEA_CLI_COMMANDS.Composition ||\n command === MOLDEA_CLI_COMMANDS.Inspect ||\n command === MOLDEA_CLI_COMMANDS.Validate\n ) {\n const compositionResolution = await compositionLoader({\n packageMetadata: input.packageMetadata,\n });\n\n if (compositionResolution.kind === 'invalid') {\n return createOperationalErrorResult('COMPOSITION_STATE_INVALID', input);\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Composition) {\n return createMoldeaCliCompositionExecutionResult(\n compositionResolution.result,\n input.packageMetadata.version,\n options.isJson,\n );\n }\n }\n\n let scopePaths: readonly string[] | null = null;\n let contentPath: ReturnType<typeof parseMoldeaCliCanonicalContentPath> | null = null;\n let contentOffset = 0;\n const inspectionCursor =\n command === MOLDEA_CLI_COMMANDS.Inspect && options.cursor !== null\n ? decodeMoldeaCliCursor({\n command: 'inspect',\n cursor: options.cursor,\n filters: {},\n }).sourceCursor\n : null;\n\n if (command === MOLDEA_CLI_COMMANDS.Scope) {\n if (options.pathsInput === 'path' && options.path !== null) {\n scopePaths = Object.freeze([options.path]);\n } else if (options.pathsInput === 'stdin' && input.stdin !== undefined) {\n if (input.stdin.byteLength > options.resourceLimits.maxTotalBytes) {\n return createOperationalErrorResult('RESOURCE_LIMIT_EXCEEDED', input);\n }\n\n scopePaths = parseMoldeaCliScopePathBytes(input.stdin, options.resourceLimits.maxEntries);\n } else {\n return createOperationalErrorResult('PATH_INPUT_INVALID', input);\n }\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Content) {\n if (options.path === null) {\n return createOperationalErrorResult('CONTENT_PATH_INVALID', input);\n }\n\n contentPath = parseMoldeaCliCanonicalContentPath(options.path);\n\n if (options.cursor !== null) {\n const sourceCursor = decodeMoldeaCliCursor({\n command: 'content',\n cursor: options.cursor,\n filters: { path: contentPath },\n }).sourceCursor;\n const match = sourceCursor === null ? null : /^byte:(0|[1-9][0-9]*)$/u.exec(sourceCursor);\n\n if (match === null) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n contentOffset = Number(match[1]);\n\n if (!Number.isSafeInteger(contentOffset)) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n }\n }\n\n const discoveryResult = await workingTreeDiscovery({\n invocationDirectory: input.invocationDirectory,\n repositoryDirectory: options.repositoryDirectory,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (discoveryResult.kind === 'failed') {\n return createOperationalErrorResult(discoveryResult.errorCode, input);\n }\n\n const resourceLimits = options.resourceLimits;\n const snapshotResult = await workingTreeSnapshotExecutor({\n operation: async (repository, signal) => {\n if (command === MOLDEA_CLI_COMMANDS.Scope && scopePaths !== null) {\n return projectScopeExecutor({\n paths: scopePaths,\n repository,\n resourceLimits,\n ...(signal === undefined ? {} : { signal }),\n });\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Content && contentPath !== null) {\n return projectContentExecutor({\n maxBytes: Math.min(\n resourceLimits.maxFileBytes,\n resourceLimits.maxTotalBytes,\n Math.max(1, Math.floor(options.maxOutputBytes / 2)),\n ),\n offset: contentOffset,\n path: contentPath,\n repository,\n resourceLimits,\n ...(signal === undefined ? {} : { signal }),\n });\n }\n\n return coreInspectionExecutor({\n command: command === MOLDEA_CLI_COMMANDS.Inspect ? 'inspect' : 'validate',\n ...(inspectionCursor === null ? {} : { cursor: inspectionCursor }),\n repository,\n resourceLimits,\n ...(signal === undefined ? {} : { signal }),\n });\n },\n repositoryRoot: discoveryResult.repositoryRoot,\n resourceLimits,\n ...(command === MOLDEA_CLI_COMMANDS.Scope\n ? { selectionPaths: [MOLDEA_MANIFEST_PATH] }\n : contentPath === null\n ? {}\n : { selectionPaths: [contentPath] }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (snapshotResult.kind === 'failed') {\n return createOperationalErrorResult(snapshotResult.errorCode, input);\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Validate) {\n return createMoldeaCliValidateExecutionResult(\n snapshotResult.result as IProjectValidationResult,\n input.packageMetadata.version,\n options.isJson,\n options.cursor,\n options.maxOutputBytes,\n );\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Inspect) {\n return createMoldeaCliInspectExecutionResult(\n snapshotResult.result as IProjectInspectionPageResult,\n input.packageMetadata.version,\n options.isJson,\n options.cursor,\n options.maxOutputBytes,\n );\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Scope) {\n return createMoldeaCliScopeExecutionResult(\n snapshotResult.result as Awaited<ReturnType<IMoldeaCliProjectScopeExecutor>>,\n input.packageMetadata.version,\n options.isJson,\n options.cursor,\n options.maxOutputBytes,\n );\n }\n\n return createMoldeaCliContentExecutionResult(\n snapshotResult.result as Awaited<ReturnType<IMoldeaCliProjectContentExecutor>>,\n input.packageMetadata.version,\n options.isJson,\n options.cursor,\n options.maxOutputBytes,\n );\n } catch (error) {\n return createMoldeaCliErrorResult(\n mapMoldeaCliOperationalError(error),\n command,\n input.packageMetadata.version,\n options.isJson,\n MOLDEA_CLI_EXIT_CODES.OperationalError,\n );\n }\n };\n};\n\n// default private command dispatcher used by the executable runner\nexport const executeMoldeaCliCommand = createMoldeaCliCommandExecutor();\n","import { parseMoldeaCliArguments } from '../command-line/index.js';\nimport { createMoldeaCliOwnedError, formatMoldeaCliHelp } from '../presentation/index.js';\n\nimport { executeMoldeaCliCommand } from './command-executor.js';\nimport { MOLDEA_CLI_EXIT_CODES } from './constants.js';\nimport { createMoldeaCliErrorResult } from './results.js';\nimport type { IMoldeaCliExecutionResult, IRunMoldeaCliOptions } from './types.js';\n\n/**\n * Runs one process-neutral CLI invocation through parsing and private command dispatch.\n * @param options The arguments, installed metadata, optional cancellation, and executor seam.\n * @returns A promise resolving to exact process output and the handled exit code.\n */\nexport const runMoldeaCli = async (\n options: IRunMoldeaCliOptions,\n): Promise<IMoldeaCliExecutionResult> => {\n const parseResult = parseMoldeaCliArguments(options.commandLineArguments);\n\n if (parseResult.kind === 'help') {\n return {\n exitCode: MOLDEA_CLI_EXIT_CODES.Success,\n stderr: '',\n stdout: formatMoldeaCliHelp(parseResult.command),\n };\n }\n\n if (parseResult.kind === 'version') {\n return {\n exitCode: MOLDEA_CLI_EXIT_CODES.Success,\n stderr: '',\n stdout: `${options.packageMetadata.version}\\n`,\n };\n }\n\n if (parseResult.kind === 'error') {\n return createMoldeaCliErrorResult(\n createMoldeaCliOwnedError(parseResult.code),\n parseResult.command,\n options.packageMetadata.version,\n parseResult.isJson,\n MOLDEA_CLI_EXIT_CODES.UsageError,\n );\n }\n\n const executeCommand = options.executeCommand ?? executeMoldeaCliCommand;\n\n try {\n let stdin: Uint8Array | undefined;\n\n if (parseResult.invocation.options.pathsInput === 'stdin') {\n if (options.readStdin === undefined) {\n return createMoldeaCliErrorResult(\n createMoldeaCliOwnedError('PATH_INPUT_INVALID'),\n parseResult.invocation.command,\n options.packageMetadata.version,\n parseResult.invocation.options.isJson,\n MOLDEA_CLI_EXIT_CODES.UsageError,\n );\n }\n\n const stdinResult = await options.readStdin(\n parseResult.invocation.options.resourceLimits.maxTotalBytes,\n options.signal,\n );\n\n if (stdinResult.kind === 'limit-exceeded') {\n return createMoldeaCliErrorResult(\n createMoldeaCliOwnedError('RESOURCE_LIMIT_EXCEEDED'),\n parseResult.invocation.command,\n options.packageMetadata.version,\n parseResult.invocation.options.isJson,\n MOLDEA_CLI_EXIT_CODES.OperationalError,\n );\n }\n\n stdin = stdinResult.bytes;\n }\n\n return await executeCommand({\n invocationDirectory: options.invocationDirectory,\n invocation: parseResult.invocation,\n packageMetadata: options.packageMetadata,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(stdin === undefined ? {} : { stdin }),\n });\n } catch {\n return createMoldeaCliErrorResult(\n createMoldeaCliOwnedError('INTERNAL_ERROR'),\n parseResult.invocation.command,\n options.packageMetadata.version,\n parseResult.invocation.options.isJson,\n MOLDEA_CLI_EXIT_CODES.OperationalError,\n );\n }\n};\n","import { readFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { valid as isValidVersion } from 'semver';\n\nimport type { IMoldeaCliPackageEntryResolver, IMoldeaCliPackageMetadata } from './types.js';\n\nconst MOLDEA_CLI_PACKAGE_NAME = '@moldea.ai/cli';\n\n/** Checks exact SemVer syntax without accepting normalized prefixes or surrounding whitespace. */\nconst isExactSemanticVersion = (version: string): boolean =>\n version === version.trim() && /^[0-9]/u.test(version) && isValidVersion(version) !== null;\n\nconst isPlainRecord = (value: unknown): value is Readonly<Record<string, unknown>> => {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value) as object | null;\n\n return prototype === Object.prototype || prototype === null;\n};\n\n/** Returns a frozen string record, or null when a package composition field is malformed. */\nconst readStringRecord = (value: unknown): Readonly<Record<string, string>> | null => {\n if (!isPlainRecord(value)) {\n return null;\n }\n\n const entries = Object.entries(value);\n\n if (entries.some(([, entryValue]) => typeof entryValue !== 'string')) {\n return null;\n }\n\n return Object.freeze(Object.fromEntries(entries) as Record<string, string>);\n};\n\n/** Resolves one package entry through the executable's own module-resolution context. */\nconst resolvePackageEntry: IMoldeaCliPackageEntryResolver = (packageName) =>\n import.meta.resolve(packageName);\n\n/** Narrows a resolved package entry after the complete resolution pass succeeds. */\nconst isInstalledPackageEntry = (\n entry: readonly [string, string] | null,\n): entry is readonly [string, string] => entry !== null;\n\n/** Reads one resolved package's exact identity without executing package code. */\nconst readInstalledPackageVersion = async (\n packageName: string,\n packageEntry: string,\n): Promise<string | null> => {\n let packageDirectory: string;\n\n try {\n const packageEntryUrl = new URL(packageEntry);\n\n if (packageEntryUrl.protocol !== 'file:') {\n return null;\n }\n\n packageDirectory = path.dirname(fileURLToPath(packageEntryUrl));\n } catch {\n return null;\n }\n\n while (true) {\n try {\n const parsedManifest = JSON.parse(\n await readFile(path.join(packageDirectory, 'package.json'), 'utf8'),\n ) as unknown;\n\n if (isPlainRecord(parsedManifest) && parsedManifest['name'] === packageName) {\n const version = parsedManifest['version'];\n\n return typeof version === 'string' && isExactSemanticVersion(version) ? version : null;\n }\n } catch {\n // continue toward the package root when this directory has no readable manifest\n }\n\n const parentDirectory = path.dirname(packageDirectory);\n\n if (parentDirectory === packageDirectory) {\n return null;\n }\n\n packageDirectory = parentDirectory;\n }\n};\n\n/** Resolves the actual versions of every declared first-class package dependency. */\nconst readInstalledPackageVersions = async (\n dependencies: Readonly<Record<string, string>> | null,\n packageEntryResolver: IMoldeaCliPackageEntryResolver,\n): Promise<Readonly<Record<string, string>> | null> => {\n if (dependencies === null) {\n return null;\n }\n\n const packageNames = Object.keys(dependencies).filter((packageName) =>\n packageName.startsWith('@moldea.ai/'),\n );\n const installedPackageEntries = await Promise.all(\n packageNames.map(async (packageName) => {\n try {\n const version = await readInstalledPackageVersion(\n packageName,\n packageEntryResolver(packageName),\n );\n\n return version === null ? null : ([packageName, version] as const);\n } catch {\n return null;\n }\n }),\n );\n\n if (!installedPackageEntries.every(isInstalledPackageEntry)) {\n return null;\n }\n\n return Object.freeze(Object.fromEntries(installedPackageEntries));\n};\n\n/**\n * Loads the installed CLI identity and composition used by executable output and integrity checks.\n * @param packageManifestPath The package manifest adjacent to the distribution directory.\n * @param packageEntryResolver The module-resolution boundary for declared first-class packages.\n * @returns A promise resolving to validated package metadata.\n * @throws\n * - If the manifest cannot be read, parsed, or identified as the installed CLI package\n */\nexport const loadMoldeaCliPackageMetadata = async (\n packageManifestPath: string,\n packageEntryResolver: IMoldeaCliPackageEntryResolver = resolvePackageEntry,\n): Promise<IMoldeaCliPackageMetadata> => {\n const parsedManifest = JSON.parse(await readFile(packageManifestPath, 'utf8')) as unknown;\n\n if (\n !isPlainRecord(parsedManifest) ||\n parsedManifest['name'] !== MOLDEA_CLI_PACKAGE_NAME ||\n typeof parsedManifest['version'] !== 'string' ||\n !isExactSemanticVersion(parsedManifest['version'])\n ) {\n throw new TypeError('The installed CLI package metadata is invalid.');\n }\n\n const engines = readStringRecord(parsedManifest['engines']);\n const dependencies = readStringRecord(parsedManifest['dependencies']);\n\n return Object.freeze({\n dependencies,\n installedPackageVersions: await readInstalledPackageVersions(\n dependencies,\n packageEntryResolver,\n ),\n supportedNodeRange: engines?.['node'] ?? null,\n version: parsedManifest['version'],\n });\n};\n","import process from 'node:process';\n\nimport { MOLDEA_CLI_EXIT_CODES } from '../cli-execution/constants.js';\n\nimport type {\n IMoldeaCliProcessSignalSession,\n IMoldeaCliProcessSignalSource,\n IMoldeaCliSignalExitCode,\n IMoldeaCliTerminationSignal,\n} from './types.js';\n\nconst SIGNAL_EXIT_CODES = Object.freeze({\n SIGINT: MOLDEA_CLI_EXIT_CODES.Interrupted,\n SIGTERM: MOLDEA_CLI_EXIT_CODES.Terminated,\n} as const satisfies Readonly<Record<IMoldeaCliTerminationSignal, IMoldeaCliSignalExitCode>>);\n\nconst PROCESS_SIGNAL_SOURCE: IMoldeaCliProcessSignalSource = Object.freeze({\n addListener: (signal: IMoldeaCliTerminationSignal, listener: () => void): void => {\n process.on(signal, listener);\n },\n removeListener: (signal: IMoldeaCliTerminationSignal, listener: () => void): void => {\n process.off(signal, listener);\n },\n});\n\n/**\n * Creates one process-signal session around an operation-scoped abort controller.\n * @param signalSource The process-listener boundary.\n * @returns A session that records the first signal until output completes.\n */\nexport const createMoldeaCliProcessSignalSession = (\n signalSource: IMoldeaCliProcessSignalSource = PROCESS_SIGNAL_SOURCE,\n): IMoldeaCliProcessSignalSession => {\n const controller = new AbortController();\n let exitCode: IMoldeaCliSignalExitCode | null = null;\n let isDisposed = false;\n let isOutputComplete = false;\n\n const handleSignal = (signal: IMoldeaCliTerminationSignal): void => {\n if (exitCode !== null || isDisposed || isOutputComplete) {\n return;\n }\n\n exitCode = SIGNAL_EXIT_CODES[signal];\n controller.abort();\n };\n const handleSigint = (): void => handleSignal('SIGINT');\n const handleSigterm = (): void => handleSignal('SIGTERM');\n\n signalSource.addListener('SIGINT', handleSigint);\n signalSource.addListener('SIGTERM', handleSigterm);\n\n return Object.freeze({\n completeOutput: (): void => {\n isOutputComplete = true;\n },\n dispose: (): void => {\n if (isDisposed) {\n return;\n }\n\n isDisposed = true;\n signalSource.removeListener('SIGINT', handleSigint);\n signalSource.removeListener('SIGTERM', handleSigterm);\n },\n get exitCode(): IMoldeaCliSignalExitCode | null {\n return exitCode;\n },\n get hasReceivedSignal(): boolean {\n return exitCode !== null;\n },\n signal: controller.signal,\n });\n};\n","import path from 'node:path';\nimport process from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\nimport { runMoldeaCli } from '../cli-execution/index.js';\nimport type { IMoldeaCliStdinReader } from '../cli-execution/index.js';\nimport { loadMoldeaCliPackageMetadata } from '../package-metadata/index.js';\nimport { createMoldeaCliOwnedError, formatMoldeaCliHumanError } from '../presentation/index.js';\nimport { createMoldeaCliProcessSignalSession } from '../process-signal/index.js';\n\nconst executableDirectory = path.dirname(fileURLToPath(import.meta.url));\nconst packageManifestPath = path.resolve(executableDirectory, '..', 'package.json');\nconst signalSession = createMoldeaCliProcessSignalSession();\n\n/** Reads process stdin incrementally without retaining bytes above the requested limit. */\nconst readProcessStdin: IMoldeaCliStdinReader = async (maxBytes, signal) => {\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n\n for await (const chunk of process.stdin) {\n if (signal?.aborted) {\n return { bytes: new Uint8Array(), kind: 'completed' };\n }\n\n const bytes = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : new Uint8Array(chunk);\n totalBytes += bytes.byteLength;\n\n if (totalBytes > maxBytes) {\n process.stdin.pause();\n return { kind: 'limit-exceeded' };\n }\n\n chunks.push(bytes);\n }\n\n return { bytes: Buffer.concat(chunks, totalBytes), kind: 'completed' };\n};\n\n/**\n * Writes one complete process output string.\n * @param outputStream The destination process stream.\n * @param output The complete output to write.\n * @returns A promise resolving after the stream accepts the output.\n */\nconst writeProcessOutput = async (\n outputStream: NodeJS.WriteStream,\n output: string,\n): Promise<void> => {\n if (output.length === 0) {\n return;\n }\n\n await new Promise<void>((resolve, reject) => {\n outputStream.write(output, (error) => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve();\n });\n });\n};\n\ntry {\n const invocationDirectory = process.cwd();\n const packageMetadata = await loadMoldeaCliPackageMetadata(packageManifestPath);\n const executionResult = await runMoldeaCli({\n commandLineArguments: process.argv.slice(2),\n invocationDirectory,\n packageMetadata,\n readStdin: readProcessStdin,\n signal: signalSession.signal,\n });\n\n if (signalSession.hasReceivedSignal) {\n process.exitCode = signalSession.exitCode;\n } else {\n await writeProcessOutput(process.stdout, executionResult.stdout);\n\n if (!signalSession.hasReceivedSignal) {\n await writeProcessOutput(process.stderr, executionResult.stderr);\n }\n\n if (!signalSession.hasReceivedSignal) {\n signalSession.completeOutput();\n }\n\n process.exitCode = signalSession.exitCode ?? executionResult.exitCode;\n }\n} catch {\n if (signalSession.hasReceivedSignal) {\n process.exitCode = signalSession.exitCode;\n } else {\n await writeProcessOutput(\n process.stderr,\n formatMoldeaCliHumanError(createMoldeaCliOwnedError('INTERNAL_ERROR')),\n ).catch(() => undefined);\n signalSession.completeOutput();\n process.exitCode = 3;\n }\n} finally {\n signalSession.dispose();\n}\n"],"mappings":";;;;;;;;;;;;AACA,IAAa,wBAAwB;CACnC,aAAa;CACb,kBAAkB;CAClB,mBAAmB;CACnB,SAAS;CACT,YAAY;CACZ,YAAY;AACd;;;ACPA,IAAa,sBAAsB;CACjC,aAAa;CACb,SAAS;CACT,SAAS;CACT,OAAO;CACP,UAAU;AACZ;AAGA,IAAa,qBAAqB;CAChC,MAAM;CACN,MAAM;CACN,QAAQ;CACR,gBAAgB;CAChB,YAAY;CACZ,aAAa;CACb,cAAc;CACd,kBAAkB;CAClB,gBAAgB;CAChB,eAAe;CACf,SAAS;CACT,MAAM;CACN,YAAY;CACZ,YAAY;CACZ,SAAS;AACX;AAGA,IAAa,qCAAqC,OAAO,OAAO;CAC9D,gBAAgB;CAChB,YAAY;CACZ,aAAa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C5B;EACL,MAAM,mBAAmB,QAAQ,QAAQ,gBAAgB,MAAM;EAE/D,IAAI,CAAC,cAAc,mBACjB,MAAM,mBAAmB,QAAQ,QAAQ,gBAAgB,MAAM;EAGjE,IAAI,CAAC,cAAc,mBACjB,cAAc,eAAe;EAG/B,QAAQ,WAAW,cAAc,YAAY,gBAAgB;CAC/D;AACF,QAAQ;CACN,IAAI,cAAc,mBAChB,QAAQ,WAAW,cAAc;MAC5B;EACL,MAAM,mBACJ,QAAQ,QACR,0BAA0B,0BAA0B,gBAAgB,CAAC,CACvE,CAAC,CAAC,YAAY,KAAA,CAAS;EACvB,cAAc,eAAe;EAC7B,QAAQ,WAAW;CACrB;AACF,UAAU;CACR,cAAc,QAAQ;AACxB"}
1
+ {"version":3,"file":"moldea.js","names":["#guardedPaths","#reader","#overlayPaths","#reader"],"sources":["../src/cli-execution/constants.ts","../src/command-line/constants.ts","../src/output-page/constants.ts","../src/output-page/exception.ts","../src/json-serialization/serializer.ts","../src/output-page/cursor.ts","../src/output-page/page.ts","../src/command-line/validations.ts","../src/command-line/parser.ts","../src/presentation/constants.ts","../src/presentation/errors.ts","../src/json-output-contract/document.ts","../src/json-output-contract/guard.ts","../src/presentation/formatters.ts","../src/presentation/transformers.ts","../src/git-working-tree/constants.ts","../src/git-working-tree/parser.ts","../src/git-working-tree/starting-directory.ts","../src/git-working-tree/discovery.ts","../src/host-path-identity/utilities.ts","../src/git-working-tree/identity/comparator.ts","../src/git-working-tree/identity/constants.ts","../src/git-working-tree/identity/inspector.ts","../src/project-content/exception.ts","../src/project-content/validations.ts","../src/project-content/executor.ts","../src/project-content/page.ts","../src/project-scope/constants.ts","../src/project-scope/exception.ts","../src/project-scope/paths.ts","../src/project-scope/executor.ts","../src/project-scope/transformers.ts","../src/repository-content-transformation-guard/exception.ts","../src/repository-content-transformation-guard/reader.ts","../src/operational-error/constants.ts","../src/operational-error/mapper.ts","../src/git-inventory/constants.ts","../src/git-inventory/content-transformation/constants.ts","../src/git-inventory/content-transformation/parser.ts","../src/git-inventory/content-transformation/classifier.ts","../src/git-inventory/entry-type/candidate-collapser.ts","../src/git-inventory/entry-type/entry-inspector.ts","../src/git-inventory/entry-type/constants.ts","../src/git-inventory/entry-type/symlink-configuration.ts","../src/git-inventory/entry-type/normalizer.ts","../src/git-inventory/logical-path/normalizer.ts","../src/git-inventory/parser.ts","../src/git-inventory/repository-ownership/boundary-inspector.ts","../src/git-inventory/repository-ownership/path-planner.ts","../src/git-inventory/repository-ownership/ownership-filter.ts","../src/git-inventory/probe.ts","../src/git-inventory/comparison/comparator.ts","../src/repository-symlink-overlay/reader.ts","../src/repository-reader/factory.ts","../src/working-tree-snapshot/executor.ts","../src/cli-execution/results.ts","../src/cli-execution/command-executor.ts","../src/cli-execution/runner.ts","../src/package-metadata/loader.ts","../src/process-signal/session.ts","../src/bin/index.ts"],"sourcesContent":["// handled process exit codes implemented by the current CLI foundation\nexport const MOLDEA_CLI_EXIT_CODES = {\n Interrupted: 130,\n OperationalError: 3,\n StructuralInvalid: 1,\n Success: 0,\n Terminated: 143,\n UsageError: 2,\n} as const;\n","// schema 5 command names accepted by the executable\nexport const MOLDEA_CLI_COMMANDS = {\n Composition: 'composition',\n Content: 'content',\n Inspect: 'inspect',\n Scope: 'scope',\n Validate: 'validate',\n} as const;\n\n// option names supported by the schema 5 command grammar\nexport const MOLDEA_CLI_OPTIONS = {\n Help: '--help',\n Json: '--json',\n Cursor: '--cursor',\n MaxDiagnostics: '--max-diagnostics',\n MaxEntries: '--max-entries',\n MaxEvidence: '--max-evidence',\n MaxFileBytes: '--max-file-bytes',\n MaxManifestBytes: '--max-manifest-bytes',\n MaxOutputBytes: '--max-output-bytes',\n MaxTotalBytes: '--max-total-bytes',\n NoColor: '--no-color',\n Path: '--path',\n PathsStdin: '--paths-stdin',\n Repository: '--repository',\n Version: '--version',\n} as const;\n\n// default resource bounds forwarded by later command-composition slices\nexport const DEFAULT_MOLDEA_CLI_RESOURCE_LIMITS = Object.freeze({\n maxDiagnostics: 10_000,\n maxEntries: 100_000,\n maxEvidence: 10_000,\n maxFileBytes: 8_388_608,\n maxManifestBytes: 2_097_152,\n maxTotalBytes: 134_217_728,\n});\n","// inclusive JSON output-page bounds and default transport budget\nexport const MOLDEA_CLI_MIN_OUTPUT_BYTES = 4_096;\nexport const MOLDEA_CLI_DEFAULT_OUTPUT_BYTES = 65_536;\nexport const MOLDEA_CLI_MAX_OUTPUT_BYTES = 1_048_576;\n\n// cursor format owned by CLI schema 5\nexport const MOLDEA_CLI_CURSOR_VERSION = 2 as const;\n","import type { IMoldeaCliOutputPageErrorCode } from './types.js';\n\n/** Represents a safe pagination or output-budget failure owned by the CLI. */\nexport class MoldeaCliOutputPageException extends Error {\n public readonly code: IMoldeaCliOutputPageErrorCode;\n\n /** Creates one output-page failure with a stable public code. */\n public constructor(code: IMoldeaCliOutputPageErrorCode) {\n super(code);\n this.code = code;\n this.name = 'MoldeaCliOutputPageException';\n }\n}\n","/** Compares strings by Unicode code point rather than UTF-16 code unit. */\nconst compareUnicodeCodePoints = (left: string, right: string): number => {\n const leftCodePoints = [...left];\n const rightCodePoints = [...right];\n const sharedLength = Math.min(leftCodePoints.length, rightCodePoints.length);\n\n for (let index = 0; index < sharedLength; index += 1) {\n const leftCodePoint = leftCodePoints[index]?.codePointAt(0);\n const rightCodePoint = rightCodePoints[index]?.codePointAt(0);\n\n if (leftCodePoint === undefined || rightCodePoint === undefined) {\n throw new TypeError('The JSON object key could not be compared.');\n }\n\n if (leftCodePoint !== rightCodePoint) {\n return leftCodePoint - rightCodePoint;\n }\n }\n\n return leftCodePoints.length - rightCodePoints.length;\n};\n\n/** Serializes one validated JSON value with recursively sorted object keys. */\nconst serializeJsonValue = (value: unknown, ancestors: Set<object>): string => {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') {\n return JSON.stringify(value);\n }\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw new TypeError('The JSON number must be finite.');\n }\n\n return JSON.stringify(Object.is(value, -0) ? 0 : value);\n }\n\n if (typeof value !== 'object') {\n throw new TypeError('The value is not supported by the CLI JSON contract.');\n }\n\n if (ancestors.has(value)) {\n throw new TypeError('The CLI JSON value must not contain a cycle.');\n }\n\n ancestors.add(value);\n\n try {\n if (Array.isArray(value)) {\n const serializedEntries: string[] = [];\n\n for (let index = 0; index < value.length; index += 1) {\n if (!Object.hasOwn(value, index)) {\n throw new TypeError('The CLI JSON array must not contain empty slots.');\n }\n\n serializedEntries.push(serializeJsonValue(value[index], ancestors));\n }\n\n return `[${serializedEntries.join(',')}]`;\n }\n\n const prototype = Object.getPrototypeOf(value) as object | null;\n\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError('The CLI JSON object must be a plain record.');\n }\n\n if (Object.getOwnPropertySymbols(value).length > 0) {\n throw new TypeError('The CLI JSON object must not contain symbol keys.');\n }\n\n const record = value as Readonly<Record<string, unknown>>;\n const properties = Object.keys(record)\n .sort(compareUnicodeCodePoints)\n .map((key) => `${JSON.stringify(key)}:${serializeJsonValue(record[key], ancestors)}`);\n\n return `{${properties.join(',')}}`;\n } finally {\n ancestors.delete(value);\n }\n};\n\n/**\n * Serializes one CLI JSON value with exact recursive Unicode code-point key ordering.\n * @param value The closed JSON value to serialize.\n * @returns Compact deterministic JSON without a trailing line feed.\n * @throws\n * - If the value contains unsupported, non-finite, symbolic, class-backed, or cyclic data\n */\nexport const serializeJsonDeterministically = (value: unknown): string => {\n return serializeJsonValue(value, new Set());\n};\n","import { createHash, timingSafeEqual } from 'node:crypto';\n\nimport { serializeJsonDeterministically, type IJsonValue } from '../json-serialization/index.js';\n\nimport { MOLDEA_CLI_CURSOR_VERSION } from './constants.js';\nimport { MoldeaCliOutputPageException } from './exception.js';\nimport type {\n IMoldeaCliCursorInput,\n IMoldeaCliCursorState,\n IMoldeaCliPageCommand,\n} from './types.js';\n\ninterface IMoldeaCliCursorPayload {\n readonly command: IMoldeaCliPageCommand;\n readonly filtersDigest: string;\n readonly lastKey: string;\n readonly sourceCursor: string | null;\n readonly snapshotDigest: string;\n readonly version: typeof MOLDEA_CLI_CURSOR_VERSION;\n}\n\ninterface IMoldeaCliCursorDocument extends IMoldeaCliCursorPayload {\n readonly checksum: string;\n}\n\nconst SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/u;\nconst BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/u;\nconst CURSOR_DOCUMENT_KEYS = Object.freeze([\n 'checksum',\n 'command',\n 'filtersDigest',\n 'lastKey',\n 'snapshotDigest',\n 'sourceCursor',\n 'version',\n]);\n\n/** Calculates one stable SHA-256 identifier for deterministic JSON text. */\nexport const calculateMoldeaCliJsonDigest = (value: IJsonValue): string => {\n return `sha256:${createHash('sha256').update(serializeJsonDeterministically(value), 'utf8').digest('hex')}`;\n};\n\n/** Calculates the checksum for one cursor payload without its checksum field. */\nconst calculateCursorChecksum = (payload: IMoldeaCliCursorPayload): string => {\n return calculateMoldeaCliJsonDigest(payload as unknown as IJsonValue);\n};\n\n/** Compares fixed-format checksums without data-dependent early termination. */\nconst areChecksumsEqual = (left: string, right: string): boolean => {\n const leftBytes = Buffer.from(left, 'utf8');\n const rightBytes = Buffer.from(right, 'utf8');\n\n return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);\n};\n\n/** Determines whether an unknown value is one strict cursor document. */\nconst isCursorDocument = (value: unknown): value is IMoldeaCliCursorDocument => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n\n const record = value as Readonly<Record<string, unknown>>;\n const keys = Object.keys(record).sort();\n\n return (\n keys.length === CURSOR_DOCUMENT_KEYS.length &&\n keys.every((key, index) => key === CURSOR_DOCUMENT_KEYS[index]) &&\n record['version'] === MOLDEA_CLI_CURSOR_VERSION &&\n (record['command'] === 'content' ||\n record['command'] === 'inspect' ||\n record['command'] === 'scope' ||\n record['command'] === 'validate') &&\n typeof record['filtersDigest'] === 'string' &&\n SHA256_PATTERN.test(record['filtersDigest']) &&\n typeof record['lastKey'] === 'string' &&\n record['lastKey'].length > 0 &&\n (record['sourceCursor'] === null || typeof record['sourceCursor'] === 'string') &&\n typeof record['snapshotDigest'] === 'string' &&\n SHA256_PATTERN.test(record['snapshotDigest']) &&\n typeof record['checksum'] === 'string' &&\n SHA256_PATTERN.test(record['checksum'])\n );\n};\n\n/** Encodes one command-, filter-, and snapshot-bound continuation cursor. */\nexport const encodeMoldeaCliCursor = (\n command: IMoldeaCliPageCommand,\n filters: IJsonValue,\n snapshotDigest: string,\n lastKey: string,\n sourceCursor: string | null = null,\n): string => {\n const payload: IMoldeaCliCursorPayload = {\n command,\n filtersDigest: calculateMoldeaCliJsonDigest(filters),\n lastKey,\n sourceCursor,\n snapshotDigest,\n version: MOLDEA_CLI_CURSOR_VERSION,\n };\n const document: IMoldeaCliCursorDocument = {\n ...payload,\n checksum: calculateCursorChecksum(payload),\n };\n\n return Buffer.from(serializeJsonDeterministically(document), 'utf8').toString('base64url');\n};\n\n/**\n * Decodes and validates one opaque continuation cursor.\n * @param input The current command state and untrusted cursor.\n * @returns The validated last composite record key.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n */\nexport const decodeMoldeaCliCursor = (input: IMoldeaCliCursorInput): IMoldeaCliCursorState => {\n let decoded: unknown;\n\n try {\n if (!BASE64URL_PATTERN.test(input.cursor)) {\n throw new TypeError('The cursor is not canonical base64url.');\n }\n\n const bytes = Buffer.from(input.cursor, 'base64url');\n\n if (bytes.toString('base64url') !== input.cursor) {\n throw new TypeError('The cursor is not canonical base64url.');\n }\n\n const text = bytes.toString('utf8');\n decoded = JSON.parse(text) as unknown;\n } catch {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n if (!isCursorDocument(decoded)) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n const { checksum, ...payload } = decoded;\n\n if (\n !areChecksumsEqual(checksum, calculateCursorChecksum(payload)) ||\n decoded.command !== input.command ||\n decoded.filtersDigest !== calculateMoldeaCliJsonDigest(input.filters)\n ) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n if (input.snapshotDigest !== undefined && decoded.snapshotDigest !== input.snapshotDigest) {\n throw new MoldeaCliOutputPageException('CURSOR_SNAPSHOT_CHANGED');\n }\n\n return Object.freeze({\n lastKey: decoded.lastKey,\n snapshotDigest: decoded.snapshotDigest,\n sourceCursor: decoded.sourceCursor,\n });\n};\n","import { serializeJsonDeterministically } from '../json-serialization/index.js';\n\nimport { decodeMoldeaCliCursor, encodeMoldeaCliCursor } from './cursor.js';\nimport { MoldeaCliOutputPageException } from './exception.js';\nimport type {\n IMoldeaCliOutputPage,\n IMoldeaCliOutputPageInput,\n IMoldeaCliOutputRecord,\n} from './types.js';\n\n/** Ensures records have unique keys in strict ascending order. */\nconst assertRecordOrder = (records: readonly IMoldeaCliOutputRecord[]): void => {\n for (let index = 0; index < records.length; index += 1) {\n const key = records[index]?.key;\n const previousKey = records[index - 1]?.key;\n\n if (\n key === undefined ||\n key.length === 0 ||\n (previousKey !== undefined && key <= previousKey)\n ) {\n throw new TypeError('Output records must have unique keys in ascending order.');\n }\n }\n};\n\n/**\n * Selects the largest exact serialized output page that fits its byte budget.\n * @param input Ordered records, continuation state, and an exact final-document measurement.\n * @returns A frozen record page with a snapshot-bound continuation cursor when needed.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliOutputPage = <TRecord extends IMoldeaCliOutputRecord>(\n input: IMoldeaCliOutputPageInput<TRecord>,\n): IMoldeaCliOutputPage<TRecord> => {\n assertRecordOrder(input.records);\n\n const cursorState =\n input.cursor === null\n ? null\n : decodeMoldeaCliCursor({\n command: input.command,\n cursor: input.cursor,\n filters: input.filters,\n snapshotDigest: input.snapshotDigest,\n });\n const startIndex =\n cursorState === null\n ? 0\n : cursorState.sourceCursor !== null\n ? 0\n : input.records.findIndex(({ key }) => key === cursorState.lastKey) + 1;\n\n if (cursorState !== null && cursorState.sourceCursor === null && startIndex === 0) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n const emptyRecords = Object.freeze([]) as readonly TRecord[];\n const emptyPage = Object.freeze({ cursor: null, records: emptyRecords });\n\n if (startIndex === input.records.length) {\n if (input.measure(emptyPage, 2) > input.maxOutputBytes) {\n throw new MoldeaCliOutputPageException('OUTPUT_BUDGET_TOO_SMALL');\n }\n\n return emptyPage;\n }\n\n const selectedRecords: TRecord[] = [];\n let selectedCursor: string | null = null;\n let serializedRecordsUtf8Bytes = 2;\n\n for (let endIndex = startIndex + 1; endIndex <= input.records.length; endIndex += 1) {\n const record = input.records[endIndex - 1];\n\n if (record === undefined) {\n throw new TypeError('An output page record is missing.');\n }\n\n const serializedRecordUtf8Bytes = Buffer.byteLength(\n serializeJsonDeterministically(record),\n 'utf8',\n );\n\n serializedRecordsUtf8Bytes += serializedRecordUtf8Bytes + (endIndex > startIndex + 1 ? 1 : 0);\n selectedRecords.push(record);\n\n const sourceCursor = input.sourceCursorForRecord?.(record) ?? null;\n const hasMore =\n input.sourceCursorForRecord === undefined\n ? endIndex < input.records.length\n : sourceCursor !== null;\n const cursor = hasMore\n ? encodeMoldeaCliCursor(\n input.command,\n input.filters,\n input.snapshotDigest,\n record.key,\n sourceCursor,\n )\n : null;\n const candidate = Object.freeze({ cursor, records: selectedRecords });\n\n if (input.measure(candidate, serializedRecordsUtf8Bytes) > input.maxOutputBytes) {\n selectedRecords.pop();\n break;\n }\n\n selectedCursor = cursor;\n }\n\n if (selectedRecords.length === 0) {\n throw new MoldeaCliOutputPageException('OUTPUT_BUDGET_TOO_SMALL');\n }\n\n return Object.freeze({\n cursor: selectedCursor,\n records: Object.freeze([...selectedRecords]),\n });\n};\n","import { MOLDEA_CLI_MAX_OUTPUT_BYTES, MOLDEA_CLI_MIN_OUTPUT_BYTES } from '../output-page/index.js';\n\nimport type { IMoldeaCliResourceLimits } from './types.js';\n\nconst POSITIVE_INTEGER_PATTERN = /^\\d+$/u;\n\n/**\n * Determines whether text contains only Unicode scalar values.\n * @param text The text to validate.\n * @returns Whether the text contains no unpaired UTF-16 surrogate.\n */\nexport const hasOnlyUnicodeScalarValues = (text: string): boolean => {\n for (let index = 0; index < text.length; index += 1) {\n const codeUnit = text.charCodeAt(index);\n\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n if (index + 1 >= text.length) {\n return false;\n }\n\n const trailingCodeUnit = text.charCodeAt(index + 1);\n\n if (trailingCodeUnit < 0xdc00 || trailingCodeUnit > 0xdfff) {\n return false;\n }\n\n index += 1;\n continue;\n }\n\n if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {\n return false;\n }\n }\n\n return true;\n};\n\n/**\n * Parses one strict base-10 positive safe integer option value.\n * @param input The untrusted command-line token.\n * @returns The parsed integer, or null when the token is invalid.\n */\nexport const parsePositiveSafeInteger = (input: string): number | null => {\n if (!POSITIVE_INTEGER_PATTERN.test(input)) {\n return null;\n }\n\n const parsedInteger = Number(input);\n\n return Number.isSafeInteger(parsedInteger) && parsedInteger > 0 ? parsedInteger : null;\n};\n\n/** Parses one output byte budget inside the schema 5 transport bounds. */\nexport const parseMoldeaCliOutputByteLimit = (input: string): number | null => {\n const parsed = parsePositiveSafeInteger(input);\n\n return parsed !== null &&\n parsed >= MOLDEA_CLI_MIN_OUTPUT_BYTES &&\n parsed <= MOLDEA_CLI_MAX_OUTPUT_BYTES\n ? parsed\n : null;\n};\n\n/**\n * Validates the cross-limit ordering required by the CLI composition.\n * @param limits The effective resource limits.\n * @returns Whether manifest, file, and total byte limits are consistently ordered.\n */\nexport const areMoldeaCliResourceLimitsConsistent = (limits: IMoldeaCliResourceLimits): boolean => {\n return (\n limits.maxManifestBytes <= limits.maxFileBytes && limits.maxFileBytes <= limits.maxTotalBytes\n );\n};\n\n/**\n * Determines whether one repository option is safe scalar host-path text.\n * @param input The untrusted command-line token.\n * @returns Whether the token is non-empty scalar text without NUL.\n */\nexport const isRepositoryDirectoryInputValid = (input: string): boolean => {\n return input.length > 0 && !input.includes('\\0') && hasOnlyUnicodeScalarValues(input);\n};\n\n/** Determines whether one opaque cursor token is bounded safe scalar text. */\nexport const isMoldeaCliCursorInputValid = (input: string): boolean => {\n return (\n input.length > 0 &&\n input.length <= 16_384 &&\n !input.includes('\\0') &&\n hasOnlyUnicodeScalarValues(input)\n );\n};\n","import { MOLDEA_CLI_DEFAULT_OUTPUT_BYTES } from '../output-page/index.js';\n\nimport {\n DEFAULT_MOLDEA_CLI_RESOURCE_LIMITS,\n MOLDEA_CLI_COMMANDS,\n MOLDEA_CLI_OPTIONS,\n} from './constants.js';\nimport type {\n IMoldeaCliArgumentError,\n IMoldeaCliArgumentErrorCode,\n IMoldeaCliCommand,\n IMoldeaCliCommandOptions,\n IMoldeaCliParseResult,\n IMoldeaCliResourceLimits,\n} from './types.js';\nimport {\n areMoldeaCliResourceLimitsConsistent,\n isMoldeaCliCursorInputValid,\n isRepositoryDirectoryInputValid,\n parseMoldeaCliOutputByteLimit,\n parsePositiveSafeInteger,\n} from './validations.js';\n\nconst COMMAND_NAMES = new Set<IMoldeaCliCommand>(Object.values(MOLDEA_CLI_COMMANDS));\nconst RESOURCE_OPTION_FIELDS = {\n [MOLDEA_CLI_OPTIONS.MaxDiagnostics]: 'maxDiagnostics',\n [MOLDEA_CLI_OPTIONS.MaxEntries]: 'maxEntries',\n [MOLDEA_CLI_OPTIONS.MaxEvidence]: 'maxEvidence',\n [MOLDEA_CLI_OPTIONS.MaxFileBytes]: 'maxFileBytes',\n [MOLDEA_CLI_OPTIONS.MaxManifestBytes]: 'maxManifestBytes',\n [MOLDEA_CLI_OPTIONS.MaxTotalBytes]: 'maxTotalBytes',\n} as const satisfies Readonly<Record<string, keyof IMoldeaCliResourceLimits>>;\n\n// mutable construction shape frozen before the normalized invocation is returned\ntype IMutableMoldeaCliResourceLimits = {\n -readonly [Key in keyof IMoldeaCliResourceLimits]: IMoldeaCliResourceLimits[Key];\n};\n\nconst createArgumentError = (\n code: IMoldeaCliArgumentErrorCode,\n command: IMoldeaCliCommand | null,\n isJson: boolean,\n): IMoldeaCliArgumentError => ({ code, command, isJson, kind: 'error' });\n\nconst isMoldeaCliCommand = (input: string | undefined): input is IMoldeaCliCommand => {\n return input !== undefined && COMMAND_NAMES.has(input as IMoldeaCliCommand);\n};\n\n/**\n * Parses the complete schema 5 command grammar without mutating caller arguments.\n * @param commandLineArguments The process arguments after the executable path.\n * @returns A normalized command, informational request, or safe invocation error.\n */\nexport const parseMoldeaCliArguments = (\n commandLineArguments: readonly string[],\n): IMoldeaCliParseResult => {\n const isJson = commandLineArguments.includes(MOLDEA_CLI_OPTIONS.Json);\n\n if (commandLineArguments.length === 0) {\n return { command: null, kind: 'help' };\n }\n\n const firstArgument = commandLineArguments[0];\n\n if (firstArgument === MOLDEA_CLI_OPTIONS.Help) {\n return commandLineArguments.length === 1\n ? { command: null, kind: 'help' }\n : createArgumentError('INVALID_ARGUMENT', null, isJson);\n }\n\n if (firstArgument === MOLDEA_CLI_OPTIONS.Version) {\n return commandLineArguments.length === 1\n ? { kind: 'version' }\n : createArgumentError('INVALID_ARGUMENT', null, isJson);\n }\n\n const command = isMoldeaCliCommand(firstArgument) ? firstArgument : null;\n\n if (command === null) {\n return createArgumentError('INVALID_ARGUMENT', null, isJson);\n }\n\n if (commandLineArguments.length === 2 && commandLineArguments[1] === MOLDEA_CLI_OPTIONS.Help) {\n return { command, kind: 'help' };\n }\n\n const seenOptions = new Set<string>();\n const resourceLimits: IMutableMoldeaCliResourceLimits = {\n ...DEFAULT_MOLDEA_CLI_RESOURCE_LIMITS,\n };\n let isColorDisabled = false;\n let cursor: string | null = null;\n let maxOutputBytes = MOLDEA_CLI_DEFAULT_OUTPUT_BYTES;\n let path: string | null = null;\n let pathsInput: IMoldeaCliCommandOptions['pathsInput'] = 'none';\n let repositoryDirectory: string | null = null;\n\n for (let index = 1; index < commandLineArguments.length; index += 1) {\n const option = commandLineArguments[index];\n\n if (option === undefined || seenOptions.has(option)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n seenOptions.add(option);\n\n if (option === MOLDEA_CLI_OPTIONS.Json) {\n continue;\n }\n\n if (option === MOLDEA_CLI_OPTIONS.NoColor) {\n isColorDisabled = true;\n continue;\n }\n\n if (option === MOLDEA_CLI_OPTIONS.PathsStdin) {\n pathsInput = 'stdin';\n continue;\n }\n\n if (option === MOLDEA_CLI_OPTIONS.Help || option === MOLDEA_CLI_OPTIONS.Version) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n const resourceField = RESOURCE_OPTION_FIELDS[option as keyof typeof RESOURCE_OPTION_FIELDS];\n const isRepositoryOption = option === MOLDEA_CLI_OPTIONS.Repository;\n const isCursorOption = option === MOLDEA_CLI_OPTIONS.Cursor;\n const isOutputLimitOption = option === MOLDEA_CLI_OPTIONS.MaxOutputBytes;\n const isPathOption = option === MOLDEA_CLI_OPTIONS.Path;\n\n if (\n resourceField === undefined &&\n !isRepositoryOption &&\n !isCursorOption &&\n !isOutputLimitOption &&\n !isPathOption\n ) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Composition) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n const optionValue = commandLineArguments[index + 1];\n\n if (optionValue === undefined || optionValue.startsWith('--')) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n index += 1;\n\n if (isCursorOption) {\n if (!isMoldeaCliCursorInputValid(optionValue)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n cursor = optionValue;\n continue;\n }\n\n if (isOutputLimitOption) {\n const parsedOutputLimit = parseMoldeaCliOutputByteLimit(optionValue);\n\n if (parsedOutputLimit === null) {\n return createArgumentError('RESOURCE_LIMIT_CONFIGURATION_INVALID', command, isJson);\n }\n\n maxOutputBytes = parsedOutputLimit;\n continue;\n }\n\n if (isPathOption) {\n if (!isRepositoryDirectoryInputValid(optionValue)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n path = optionValue;\n pathsInput = 'path';\n continue;\n }\n\n if (isRepositoryOption) {\n if (!isRepositoryDirectoryInputValid(optionValue)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n repositoryDirectory = optionValue;\n continue;\n }\n\n const parsedLimit = parsePositiveSafeInteger(optionValue);\n\n if (parsedLimit === null || resourceField === undefined) {\n return createArgumentError('RESOURCE_LIMIT_CONFIGURATION_INVALID', command, isJson);\n }\n\n resourceLimits[resourceField] = parsedLimit;\n }\n\n if (!areMoldeaCliResourceLimitsConsistent(resourceLimits)) {\n return createArgumentError('RESOURCE_LIMIT_CONFIGURATION_INVALID', command, isJson);\n }\n\n const isScope = command === MOLDEA_CLI_COMMANDS.Scope;\n const isContent = command === MOLDEA_CLI_COMMANDS.Content;\n const hasPathInput = path !== null;\n const hasStdinInput = seenOptions.has(MOLDEA_CLI_OPTIONS.PathsStdin);\n\n if ((hasPathInput || hasStdinInput) && !isScope && !isContent) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (isScope && hasPathInput === hasStdinInput) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (isContent && (!hasPathInput || hasStdinInput)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (isScope && seenOptions.has(MOLDEA_CLI_OPTIONS.MaxEvidence)) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (\n isContent &&\n [\n MOLDEA_CLI_OPTIONS.MaxDiagnostics,\n MOLDEA_CLI_OPTIONS.MaxEvidence,\n MOLDEA_CLI_OPTIONS.MaxManifestBytes,\n ].some((option) => seenOptions.has(option))\n ) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n if (!isJson && (cursor !== null || seenOptions.has(MOLDEA_CLI_OPTIONS.MaxOutputBytes))) {\n return createArgumentError('INVALID_ARGUMENT', command, isJson);\n }\n\n const options: IMoldeaCliCommandOptions = {\n cursor,\n isColorDisabled,\n isJson,\n maxOutputBytes,\n path,\n pathsInput,\n repositoryDirectory,\n resourceLimits: Object.freeze({ ...resourceLimits }),\n };\n\n return {\n invocation: Object.freeze({ command, options: Object.freeze(options) }),\n kind: 'command',\n };\n};\n","import { MOLDEA_CLI_COMMANDS } from '../command-line/index.js';\n\n// stable safe presentation contracts for errors implemented by the CLI\nexport const MOLDEA_CLI_ERROR_DEFINITIONS = Object.freeze({\n COMPOSITION_STATE_INVALID: Object.freeze({\n message: 'The installed composition state is invalid.',\n retryable: false,\n source: 'cli',\n }),\n CONTENT_INVALID: Object.freeze({\n message: 'The requested canonical asset is not valid moldea text.',\n retryable: false,\n source: 'cli',\n }),\n CONTENT_PATH_INVALID: Object.freeze({\n message: 'The content path must identify one canonical moldea text asset.',\n retryable: false,\n source: 'cli',\n }),\n CURSOR_INVALID: Object.freeze({\n message: 'The continuation cursor is invalid for this request.',\n retryable: false,\n source: 'cli',\n }),\n CURSOR_SNAPSHOT_CHANGED: Object.freeze({\n message: 'The continuation cursor belongs to a different repository snapshot.',\n retryable: true,\n source: 'cli',\n }),\n GIT_ACCESS_DENIED: Object.freeze({\n message: 'Git access was denied.',\n retryable: true,\n source: 'git',\n }),\n GIT_COMMAND_FAILED: Object.freeze({\n message: 'The Git command failed.',\n retryable: true,\n source: 'git',\n }),\n GIT_CONTENT_TRANSFORM_UNSUPPORTED: Object.freeze({\n message: 'The requested file uses an unsupported Git content transformation.',\n retryable: false,\n source: 'git',\n }),\n GIT_NOT_FOUND: Object.freeze({\n message: 'The Git executable is unavailable.',\n retryable: false,\n source: 'git',\n }),\n GIT_OPERATION_ABORTED: Object.freeze({\n message: 'The Git operation was aborted.',\n retryable: true,\n source: 'git',\n }),\n GIT_OUTPUT_INVALID: Object.freeze({\n message: 'Git returned invalid output.',\n retryable: false,\n source: 'git',\n }),\n GIT_REPOSITORY_NOT_FOUND: Object.freeze({\n message: 'The selected path is not inside a Git repository.',\n retryable: false,\n source: 'git',\n }),\n GIT_SPARSE_CHECKOUT_UNSUPPORTED: Object.freeze({\n message: 'Sparse Git checkouts are unsupported.',\n retryable: false,\n source: 'git',\n }),\n GIT_VERSION_INVALID: Object.freeze({\n message: 'The Git version output is invalid.',\n retryable: false,\n source: 'git',\n }),\n GIT_VERSION_UNSUPPORTED: Object.freeze({\n message: 'The installed Git version is unsupported.',\n retryable: false,\n source: 'git',\n }),\n GIT_WORK_TREE_REQUIRED: Object.freeze({\n message: 'A usable Git working tree is required.',\n retryable: false,\n source: 'git',\n }),\n INTERNAL_ERROR: Object.freeze({\n message: 'The command could not be completed.',\n retryable: false,\n source: 'cli',\n }),\n INVALID_ARGUMENT: Object.freeze({\n message: 'The command invocation is invalid.',\n retryable: false,\n source: 'cli',\n }),\n OUTPUT_BUDGET_TOO_SMALL: Object.freeze({\n message: 'The output byte budget cannot contain the next complete result.',\n retryable: false,\n source: 'cli',\n }),\n PATH_INPUT_INVALID: Object.freeze({\n message:\n 'The scope path input is invalid. Use leading-slash repository-logical paths and NUL-delimited UTF-8 on stdin.',\n retryable: false,\n source: 'cli',\n }),\n RESOURCE_LIMIT_CONFIGURATION_INVALID: Object.freeze({\n message: 'The resource-limit configuration is invalid.',\n retryable: false,\n source: 'cli',\n }),\n RESOURCE_LIMIT_EXCEEDED: Object.freeze({\n message: 'A resource limit was exceeded.',\n retryable: false,\n source: 'cli',\n }),\n WORKING_TREE_UNSTABLE: Object.freeze({\n message: 'The working tree did not remain stable.',\n retryable: true,\n source: 'cli',\n }),\n} as const);\n\n// source descriptor for results derived from the selected Git working tree\nexport const MOLDEA_CLI_GIT_WORKING_TREE_SOURCE = Object.freeze({\n kind: 'git-working-tree' as const,\n});\n\n// top-level help presented without repository access\nexport const MOLDEA_CLI_TOP_LEVEL_HELP = `Usage: moldea <command> [options]\n\nCommands:\n validate Validate the current moldea project.\n inspect Inspect content-free project metadata.\n scope Match changed paths to declared moldea relationships.\n content Read one canonical moldea asset explicitly.\n composition Report the installed CLI composition state.\n\nGlobal options:\n --help Show top-level help.\n --version Show the CLI version.\n\nRun \"moldea <command> --help\" for command-specific options.\n`;\n\nconst REPOSITORY_OPTIONS_HELP = ` --repository <path> Select a Git working-tree directory.\n --json Emit one machine-readable JSON result.\n --no-color Disable ANSI styling in human output.\n`;\n\nconst BASE_RESOURCE_OPTIONS_HELP = ` --max-entries <integer> Override the repository entry limit.\n --max-file-bytes <integer> Override the per-file byte limit.\n --max-total-bytes <integer> Override the total cached-byte limit.\n`;\n\nconst INSPECTION_RESOURCE_OPTIONS_HELP = `${BASE_RESOURCE_OPTIONS_HELP} --max-manifest-bytes <integer> Override the manifest byte limit.\n --max-diagnostics <integer> Override the diagnostic count limit.\n`;\n\nconst PAGINATION_OPTIONS_HELP = ` --max-output-bytes <integer> Bound JSON output from 4096 to 1048576 bytes.\n --cursor <opaque-cursor> Continue a prior JSON result page.\n`;\n\nconst COMPLETE_INSPECTION_OPTIONS_HELP = `${REPOSITORY_OPTIONS_HELP}${INSPECTION_RESOURCE_OPTIONS_HELP} --max-evidence <integer> Override the adapter evidence count limit.\n${PAGINATION_OPTIONS_HELP}`;\n\nconst SCOPE_OPTIONS_HELP = `${REPOSITORY_OPTIONS_HELP}${INSPECTION_RESOURCE_OPTIONS_HELP}${PAGINATION_OPTIONS_HELP}`;\n\nconst CONTENT_OPTIONS_HELP = `${REPOSITORY_OPTIONS_HELP}${BASE_RESOURCE_OPTIONS_HELP}${PAGINATION_OPTIONS_HELP}`;\n\n// complete command-specific help keyed by the closed command set\nexport const MOLDEA_CLI_COMMAND_HELP = {\n [MOLDEA_CLI_COMMANDS.Composition]: `Usage: moldea composition [options]\n\nReport the installed CLI composition state.\n\nOptions:\n --json Emit one machine-readable JSON result.\n --no-color Disable ANSI styling in human output.\n --help Show this help.\n`,\n [MOLDEA_CLI_COMMANDS.Inspect]: `Usage: moldea inspect [options]\n\nInspect content-free metadata for the current moldea project.\n\nOptions:\n${COMPLETE_INSPECTION_OPTIONS_HELP} --help Show this help.\n`,\n [MOLDEA_CLI_COMMANDS.Scope]: `Usage: moldea scope (--path <logical-path> | --paths-stdin) [options]\n\nMatch changed repository paths to declared moldea relationships. The stdin form accepts NUL-delimited UTF-8 logical paths.\n\nOptions:\n${SCOPE_OPTIONS_HELP} --path <logical-path> Match one repository-logical path.\n --paths-stdin Read NUL-delimited paths from stdin.\n --help Show this help.\n`,\n [MOLDEA_CLI_COMMANDS.Content]: `Usage: moldea content --path <canonical-logical-path> [options]\n\nRead one canonical moldea text asset in bounded Unicode-safe chunks.\n\nOptions:\n${CONTENT_OPTIONS_HELP} --path <canonical-logical-path> Select exactly one canonical moldea file.\n --help Show this help.\n`,\n [MOLDEA_CLI_COMMANDS.Validate]: `Usage: moldea validate [options]\n\nValidate the current moldea project.\n\nOptions:\n${COMPLETE_INSPECTION_OPTIONS_HELP} --help Show this help.\n`,\n} as const;\n","import { MOLDEA_CLI_ERROR_DEFINITIONS } from './constants.js';\nimport type { IMoldeaCliError, IMoldeaCliOwnedErrorCode } from './types.js';\n\nconst EMPTY_ERROR_DETAILS = Object.freeze({});\n\n/**\n * Creates one immutable safe error from a CLI- or Git-owned definition.\n * @param code The stable executable-owned error code.\n * @returns The complete safe error object.\n */\nexport const createMoldeaCliOwnedError = (code: IMoldeaCliOwnedErrorCode): IMoldeaCliError => {\n const definition = MOLDEA_CLI_ERROR_DEFINITIONS[code];\n\n return Object.freeze({\n code,\n details: EMPTY_ERROR_DETAILS,\n message: definition.message,\n path: null,\n retryable: definition.retryable,\n source: definition.source,\n });\n};\n","import { serializeJsonDeterministically } from '../json-serialization/index.js';\n\nimport { MOLDEA_CLI_JSON_SCHEMA_VERSION } from './constants.js';\nimport type { IMoldeaCliJsonDocumentInput, IMoldeaCliJsonEnvelope } from './types.js';\n\n/** Creates one strict schema 5 JSON envelope. */\nexport const createMoldeaCliJsonEnvelope = <TResult>(\n input: IMoldeaCliJsonDocumentInput<TResult>,\n): IMoldeaCliJsonEnvelope<TResult> =>\n Object.freeze({\n cliVersion: input.cliVersion,\n command: input.command,\n error: input.error,\n result: input.result,\n schemaVersion: MOLDEA_CLI_JSON_SCHEMA_VERSION,\n status: input.status,\n });\n\n/** Serializes one schema 5 envelope with its required trailing line feed. */\nexport const serializeMoldeaCliJsonEnvelope = <TResult>(\n input: IMoldeaCliJsonDocumentInput<TResult>,\n): string => `${serializeJsonDeterministically(createMoldeaCliJsonEnvelope(input))}\\n`;\n\n/** Measures the exact final UTF-8 bytes of one schema 5 JSON document. */\nexport const measureMoldeaCliJsonEnvelope = <TResult>(\n input: IMoldeaCliJsonDocumentInput<TResult>,\n): number => Buffer.byteLength(serializeMoldeaCliJsonEnvelope(input), 'utf8');\n","/** Rejects canonical bodies and content fields from a non-content JSON result. */\nexport const assertMoldeaCliJsonResultIsContentFree = (\n value: unknown,\n canonicalBodies: readonly string[] = [],\n): void => {\n const pending: unknown[] = [value];\n const visited = new Set<object>();\n const bodies = new Set(canonicalBodies.filter((body) => body.length > 0));\n\n while (pending.length > 0) {\n const current = pending.pop();\n\n if (typeof current === 'string') {\n if (bodies.has(current)) {\n throw new TypeError('A non-content CLI result contains canonical document text.');\n }\n\n continue;\n }\n\n if (typeof current !== 'object' || current === null || visited.has(current)) {\n continue;\n }\n\n visited.add(current);\n\n if (Array.isArray(current)) {\n for (const item of current as readonly unknown[]) {\n pending.push(item);\n }\n\n continue;\n }\n\n const record = current as Readonly<Record<string, unknown>>;\n\n if (Object.hasOwn(record, 'content')) {\n throw new TypeError('A non-content CLI result contains a content property.');\n }\n\n pending.push(...Object.values(record));\n }\n};\n","import type { IDiagnosticEntity } from '@moldea.ai/core';\n\nimport { MOLDEA_CLI_COMMANDS, type IMoldeaCliCommand } from '../command-line/index.js';\nimport type { IMoldeaCliCompositionResult } from '../composition/index.js';\nimport {\n MOLDEA_CLI_JSON_SCHEMA_VERSION,\n serializeMoldeaCliJsonEnvelope,\n type IMoldeaCliJsonStatus,\n} from '../json-output-contract/index.js';\nimport type { IMoldeaCliContentResult } from '../project-content/index.js';\nimport type { IMoldeaCliScopeResult } from '../project-scope/index.js';\n\nimport { MOLDEA_CLI_COMMAND_HELP, MOLDEA_CLI_TOP_LEVEL_HELP } from './constants.js';\nimport type {\n IMoldeaCliDiagnosticRecord,\n IMoldeaCliError,\n IMoldeaCliInspectResult,\n IMoldeaCliValidateResult,\n} from './types.js';\n\nconst DIAGNOSTIC_ENTITY_KEYS = [\n 'agentId',\n 'capabilityKind',\n 'capabilityId',\n 'decisionId',\n 'variableId',\n 'adapterId',\n] as const satisfies readonly (keyof IDiagnosticEntity)[];\n\n/** Formats one diagnostic entity in the canonical Core field order. */\nconst formatMoldeaCliHumanDiagnosticEntity = (entity: IDiagnosticEntity): string =>\n DIAGNOSTIC_ENTITY_KEYS.flatMap((key) => {\n const identifier = entity[key];\n\n return identifier === undefined ? [] : [`${key}=${identifier}`];\n }).join(', ');\n\n/** Formats one projected diagnostic without exposing omitted arbitrary details. */\nconst formatMoldeaCliHumanDiagnostic = (diagnostic: IMoldeaCliDiagnosticRecord): string => {\n const location =\n diagnostic.path === null\n ? ''\n : diagnostic.range === null\n ? ` ${diagnostic.path}`\n : ` ${diagnostic.path}:${diagnostic.range.start.line}:${diagnostic.range.start.column}`;\n const lines = [`${diagnostic.source}:${diagnostic.code}${location} ${diagnostic.message}`];\n\n if (diagnostic.pointer !== null) {\n lines.push(` pointer: ${diagnostic.pointer}`);\n }\n\n if (diagnostic.entity !== null) {\n lines.push(` entity: ${formatMoldeaCliHumanDiagnosticEntity(diagnostic.entity)}`);\n }\n\n if (diagnostic.severity === 'warning') {\n lines.push(` unverified relationship: ${diagnostic.details.relationship}`);\n lines.push(` reason: ${diagnostic.details.reason.replaceAll('-', ' ')}`);\n\n if (diagnostic.details.reason === 'version-dependent-behavior') {\n lines.push(` package: ${diagnostic.details.packageName}`);\n lines.push(` declared range: ${diagnostic.details.declaredRange ?? 'unavailable'}`);\n lines.push(` behavior boundary: ${diagnostic.details.boundaryVersion}`);\n }\n }\n\n return lines.join('\\n');\n};\n\n/** Creates shared human status lines for one completed repository command. */\nconst createMoldeaCliHumanStatusLines = (\n isValid: boolean,\n formatVersion: number | null,\n warningCount = 0,\n): string[] => {\n const status = isValid ? (warningCount > 0 ? 'valid with warnings' : 'valid') : 'invalid';\n const lines = [`The moldea project is ${status}.`];\n\n if (formatVersion !== null) {\n lines.push(`Repository format: ${formatVersion}`);\n }\n\n return lines;\n};\n\n/** Formats one count label with correct singular or plural grammar. */\nconst formatMoldeaCliHumanCount = (\n count: number,\n singularLabel: string,\n pluralLabel: string,\n): string => `${count === 1 ? singularLabel : pluralLabel}: ${count}`;\n\n/** Formats top-level or command-specific help with its required trailing line feed. */\nexport const formatMoldeaCliHelp = (command: IMoldeaCliCommand | null): string => {\n return command === null ? MOLDEA_CLI_TOP_LEVEL_HELP : MOLDEA_CLI_COMMAND_HELP[command];\n};\n\n/** Formats one safe CLI error for human stderr output. */\nexport const formatMoldeaCliHumanError = (error: IMoldeaCliError): string =>\n `${error.source}:${error.code} ${error.message}\\n`;\n\n/** Formats any strict schema 5 JSON envelope. */\nexport const formatMoldeaCliJsonResult = <TResult>(\n command: IMoldeaCliCommand | null,\n result: TResult | null,\n error: IMoldeaCliError | null,\n status: IMoldeaCliJsonStatus,\n cliVersion: string,\n): string => serializeMoldeaCliJsonEnvelope({ cliVersion, command, error, result, status });\n\n/** Formats one safe schema 5 JSON error envelope. */\nexport const formatMoldeaCliJsonError = (\n error: IMoldeaCliError,\n command: IMoldeaCliCommand | null,\n cliVersion: string,\n): string => formatMoldeaCliJsonResult(command, null, error, 'error', cliVersion);\n\n/** Formats one valid composition result for human stdout. */\nexport const formatMoldeaCliHumanCompositionResult = (\n result: IMoldeaCliCompositionResult,\n cliVersion: string,\n): string => {\n const lines = [\n 'The installed CLI composition state is valid.',\n `CLI version: ${cliVersion}`,\n `Supported Node.js: ${result.supportedNodeRange}`,\n `JSON output schema: ${MOLDEA_CLI_JSON_SCHEMA_VERSION}`,\n `Minimum Git: ${result.minimumGitVersion}`,\n `Repository formats: ${result.repositoryFormatVersions.join(', ')}`,\n 'Packages:',\n ...result.packages.map(({ name, version }) => ` ${name}: ${version}`),\n 'Adapters:',\n ...result.adapters.map(\n ({ id, repositoryFormatVersions }) =>\n ` ${id}: repository formats ${repositoryFormatVersions.join(', ')}`,\n ),\n ];\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one composition result in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonCompositionResult = (\n result: IMoldeaCliCompositionResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(MOLDEA_CLI_COMMANDS.Composition, result, null, 'valid', cliVersion);\n\n/** Formats one completed validation result for human stdout. */\nexport const formatMoldeaCliHumanValidateResult = (result: IMoldeaCliValidateResult): string => {\n const lines = createMoldeaCliHumanStatusLines(\n result.valid,\n result.formatVersion,\n result.warningCount,\n );\n\n for (const diagnostic of result.page.records) {\n lines.push(formatMoldeaCliHumanDiagnostic(diagnostic));\n }\n\n lines.push(formatMoldeaCliHumanCount(result.diagnosticCount, 'Diagnostic', 'Diagnostics'));\n lines.push(formatMoldeaCliHumanCount(result.errorCount, 'Error', 'Errors'));\n lines.push(formatMoldeaCliHumanCount(result.warningCount, 'Warning', 'Warnings'));\n\n if (result.page.cursor !== null) {\n lines.push('Additional diagnostics are available through JSON pagination.');\n }\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one validation result in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonValidateResult = (\n result: IMoldeaCliValidateResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(\n MOLDEA_CLI_COMMANDS.Validate,\n result,\n null,\n result.valid ? 'valid' : 'invalid',\n cliVersion,\n );\n\n/** Formats one completed metadata inspection for human stdout. */\nexport const formatMoldeaCliHumanInspectResult = (result: IMoldeaCliInspectResult): string => {\n const lines = createMoldeaCliHumanStatusLines(\n result.valid,\n result.formatVersion,\n result.counts.warnings,\n );\n\n for (const [label, count] of Object.entries(result.counts)) {\n lines.push(`${label}: ${count}`);\n }\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one metadata inspection in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonInspectResult = (\n result: IMoldeaCliInspectResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(\n MOLDEA_CLI_COMMANDS.Inspect,\n result,\n null,\n result.valid ? 'valid' : 'invalid',\n cliVersion,\n );\n\n/** Formats one changed-path scope result for human stdout. */\nexport const formatMoldeaCliHumanScopeResult = (result: IMoldeaCliScopeResult): string => {\n const lines = [\n `The moldea scope result is ${result.valid ? 'valid' : 'invalid'}.`,\n `Relevant: ${result.relevant ? 'yes' : 'no'}`,\n ...Object.entries(result.counts).map(([label, count]) => `${label}: ${count}`),\n ];\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one changed-path scope result in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonScopeResult = (\n result: IMoldeaCliScopeResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(\n MOLDEA_CLI_COMMANDS.Scope,\n result,\n null,\n result.valid ? 'valid' : 'invalid',\n cliVersion,\n );\n\n/** Formats one explicit canonical content chunk for human stdout. */\nexport const formatMoldeaCliHumanContentResult = (result: IMoldeaCliContentResult): string => {\n const lines = [\n `Path: ${result.asset.path}`,\n `Content identity: ${result.asset.contentIdentity ?? 'unavailable'}`,\n `Bytes: ${result.chunk.byteStart}-${result.chunk.byteEnd} of ${result.asset.totalBytes}`,\n result.cursor === null ? 'Cursor: none' : `Cursor: ${result.cursor}`,\n ...(result.cursor === null\n ? []\n : ['Continue this asset by passing the cursor to a JSON content request.']),\n '',\n result.chunk.content,\n ];\n\n return `${lines.join('\\n')}\\n`;\n};\n\n/** Formats one explicit canonical content chunk in the strict schema 5 envelope. */\nexport const formatMoldeaCliJsonContentResult = (\n result: IMoldeaCliContentResult,\n cliVersion: string,\n): string =>\n formatMoldeaCliJsonResult(MOLDEA_CLI_COMMANDS.Content, result, null, 'valid', cliVersion);\n","import type {\n IDiagnostic,\n IProjectInspectionItem,\n IProjectInspectionPageResult,\n IProjectValidationResult,\n} from '@moldea.ai/core';\n\nimport type { IJsonValue } from '../json-serialization/index.js';\nimport { calculateMoldeaCliJsonDigest } from '../output-page/index.js';\n\nimport { MOLDEA_CLI_GIT_WORKING_TREE_SOURCE } from './constants.js';\nimport type {\n IMoldeaCliAgentRecord,\n IMoldeaCliDiagnosticRecord,\n IMoldeaCliEvidenceRecord,\n IMoldeaCliInspectProjection,\n IMoldeaCliInspectProjectMetadata,\n IMoldeaCliInspectRecord,\n IMoldeaCliMetadataRecord,\n IMoldeaCliValidateProjection,\n} from './types.js';\n\n/** Rejects a Core validation result whose completion fields contradict its validity. */\nconst assertProjectValidationInvariant = (validation: IProjectValidationResult): void => {\n const observedErrorCount = validation.diagnostics.filter(\n (diagnostic) => diagnostic.severity === 'error',\n ).length;\n const isConsistent =\n Number.isSafeInteger(validation.errorCount) &&\n Number.isSafeInteger(validation.warningCount) &&\n validation.errorCount === observedErrorCount &&\n validation.warningCount === validation.diagnostics.length - observedErrorCount &&\n validation.valid === (validation.summary !== null && validation.errorCount === 0) &&\n (validation.valid || validation.errorCount > 0);\n\n if (!isConsistent) {\n throw new TypeError('The Core validation result is internally inconsistent.');\n }\n};\n\n/** Creates one stable composite record key. */\nconst createRecordKey = (kind: string, ...parts: readonly unknown[]): string =>\n JSON.stringify([kind, ...parts]);\n\n/** Projects one diagnostic without retaining arbitrary detail payloads. */\nexport const createMoldeaCliDiagnosticRecord = (\n diagnostic: IDiagnostic,\n occurrence = 0,\n): IMoldeaCliDiagnosticRecord => {\n const record = {\n code: diagnostic.code,\n entity: diagnostic.entity,\n key: createRecordKey(\n 'diagnostic',\n diagnostic.source,\n diagnostic.severity,\n diagnostic.code,\n diagnostic.path,\n diagnostic.pointer,\n diagnostic.severity === 'warning' ? diagnostic.details : null,\n occurrence,\n ),\n kind: 'diagnostic' as const,\n message: diagnostic.message,\n path: diagnostic.path,\n pointer: diagnostic.pointer,\n range: diagnostic.range,\n source: diagnostic.source,\n };\n\n if (diagnostic.severity === 'warning') {\n const details =\n diagnostic.details.reason === 'version-dependent-behavior'\n ? Object.freeze({\n boundaryVersion: diagnostic.details.boundaryVersion,\n declaredRange: diagnostic.details.declaredRange,\n packageName: diagnostic.details.packageName,\n reason: diagnostic.details.reason,\n relationship: diagnostic.details.relationship,\n })\n : Object.freeze({\n reason: diagnostic.details.reason,\n relationship: diagnostic.details.relationship,\n });\n\n return Object.freeze({ ...record, details, severity: 'warning' as const });\n }\n\n return Object.freeze({ ...record, severity: 'error' as const });\n};\n\n/** Projects one bounded Core inspection item through the schema 5 allowlist. */\nconst createInspectRecord = (\n item: IProjectInspectionItem,\n index: number,\n): IMoldeaCliInspectRecord => {\n const order = index.toString().padStart(6, '0');\n\n if (item.kind === 'agent') {\n const record: IMoldeaCliAgentRecord = {\n agentId: item.agent.agentId,\n key: createRecordKey(order, 'agent', item.agent.agentId, item.agent.runtimeId),\n kind: 'agent',\n runtimeId: item.agent.runtimeId,\n };\n\n return Object.freeze(record);\n }\n\n if (item.kind === 'diagnostic') {\n return Object.freeze({\n ...createMoldeaCliDiagnosticRecord(item.diagnostic, index),\n key: createRecordKey(\n order,\n 'diagnostic',\n item.diagnostic.source,\n item.diagnostic.severity,\n item.diagnostic.code,\n item.diagnostic.severity === 'warning' ? item.diagnostic.details : null,\n ),\n });\n }\n\n if (item.kind === 'evidence') {\n const evidence = item.evidence;\n const record: IMoldeaCliEvidenceRecord = {\n agentId: evidence.agentId,\n capabilityId: evidence.capabilityId,\n capabilityKind: evidence.capabilityKind,\n evidenceKind: evidence.kind,\n key: createRecordKey(\n order,\n 'evidence',\n evidence.source,\n evidence.kind,\n evidence.agentId,\n evidence.capabilityKind,\n evidence.capabilityId,\n evidence.runtimeName,\n ),\n kind: 'evidence',\n references: Object.freeze(\n evidence.references.map((reference) =>\n Object.freeze({ path: reference.path, symbol: reference.symbol ?? null }),\n ),\n ),\n runtimeName: evidence.runtimeName,\n source: evidence.source,\n };\n\n return Object.freeze(record);\n }\n\n const metadata = item.metadata;\n const record: IMoldeaCliMetadataRecord = {\n agentId: metadata.agentId,\n byteLength: metadata.byteLength,\n canonicalDigest: metadata.canonicalDigest,\n decisionId: metadata.decisionId,\n digest: metadata.digest,\n key: createRecordKey(order, 'metadata', metadata.path, metadata.kind, metadata.agentId),\n kind: 'metadata',\n metadataKind: metadata.kind,\n path: metadata.path,\n scalarLength: metadata.scalarLength,\n };\n\n return Object.freeze(record);\n};\n\n/** Creates content-free validation metadata and ordered diagnostic records. */\nexport const createMoldeaCliValidateProjection = (\n validation: IProjectValidationResult,\n): IMoldeaCliValidateProjection => {\n assertProjectValidationInvariant(validation);\n const diagnostics = Object.freeze(\n validation.diagnostics\n .map((diagnostic, index) => createMoldeaCliDiagnosticRecord(diagnostic, index))\n .sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0)),\n );\n const snapshotDigest = calculateMoldeaCliJsonDigest({\n diagnostics,\n errorCount: validation.errorCount,\n formatVersion: validation.formatVersion,\n summary: validation.summary,\n valid: validation.valid,\n warningCount: validation.warningCount,\n } as unknown as IJsonValue);\n\n return Object.freeze({\n diagnostics,\n errorCount: validation.errorCount,\n formatVersion: validation.formatVersion,\n snapshotDigest,\n source: MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,\n valid: validation.valid,\n warningCount: validation.warningCount,\n });\n};\n\n/** Projects one bounded Core page through the content-free schema 5 allowlist. */\nexport const createMoldeaCliInspectProjection = (\n inspection: IProjectInspectionPageResult,\n): IMoldeaCliInspectProjection => {\n const project: IMoldeaCliInspectProjectMetadata | null =\n inspection.summary === null\n ? null\n : Object.freeze({\n manifest: Object.freeze({\n digest: inspection.summary.manifestDigest,\n path: inspection.summary.manifestPath,\n }),\n project: Object.freeze({\n digest: inspection.summary.projectDigest,\n path: inspection.summary.projectPath,\n }),\n });\n const records = Object.freeze(\n inspection.page.records.map(({ item }, index) => createInspectRecord(item, index)),\n );\n const sourceCursors = new Map(\n inspection.page.records.map((record, index) => {\n const projected = records[index];\n\n if (projected === undefined) {\n throw new TypeError('A projected inspection record is missing.');\n }\n\n return [projected.key, record.nextCursor] as const;\n }),\n );\n const snapshotDigest = inspection.inspectionDigest;\n\n return Object.freeze({\n counts: inspection.counts,\n formatVersion: inspection.formatVersion,\n getSourceCursor: (record: IMoldeaCliInspectRecord): string | null =>\n sourceCursors.get(record.key) ?? null,\n project,\n records,\n snapshotDigest,\n source: MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,\n valid: inspection.valid,\n view: inspection.view,\n });\n};\n","// maximum bytes accepted from each Git discovery output stream\nexport const MAX_GIT_DISCOVERY_OUTPUT_BYTES = 262_144;\n","import path from 'node:path';\nimport process from 'node:process';\n\nimport { hasOnlyUnicodeScalarValues } from '../command-line/index.js';\n\nimport { MAX_GIT_DISCOVERY_OUTPUT_BYTES } from './constants.js';\n\nconst UTF8_BYTE_ORDER_MARK = [0xef, 0xbb, 0xbf] as const;\n\n/**\n * Decodes one bounded Git output value as strict UTF-8.\n * @param output The raw Git output bytes.\n * @returns The exact decoded value, or null when invalid.\n */\nconst decodeGitOutput = (output: Uint8Array): string | null => {\n if (\n output.byteLength === 0 ||\n output.byteLength > MAX_GIT_DISCOVERY_OUTPUT_BYTES ||\n UTF8_BYTE_ORDER_MARK.every((byte, index) => output[index] === byte)\n ) {\n return null;\n }\n\n let decodedOutput: string;\n\n try {\n decodedOutput = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(output);\n } catch {\n return null;\n }\n\n if (decodedOutput.includes('\\0') || !hasOnlyUnicodeScalarValues(decodedOutput)) {\n return null;\n }\n\n return decodedOutput;\n};\n\n/**\n * Parses Git's canonical boolean output.\n * @param output The raw bounded Git stdout bytes.\n * @returns The parsed boolean, or null when the output is not canonical.\n */\nexport const parseGitBooleanOutput = (output: Uint8Array): boolean | null => {\n const decodedOutput = decodeGitOutput(output);\n\n if (decodedOutput === 'true\\n' || decodedOutput === 'true\\r\\n') {\n return true;\n }\n\n if (decodedOutput === 'false\\n' || decodedOutput === 'false\\r\\n') {\n return false;\n }\n\n return null;\n};\n\n/**\n * Parses one nonempty path returned by Git.\n * @param output The raw bounded Git stdout bytes.\n * @returns The exact relative or absolute path, or null when the output is invalid.\n */\nexport const parseGitPathOutput = (output: Uint8Array): string | null => {\n const decodedOutput = decodeGitOutput(output);\n\n if (decodedOutput === null || !decodedOutput.endsWith('\\n')) {\n return null;\n }\n\n const gitPath =\n process.platform === 'win32' && decodedOutput.endsWith('\\r\\n')\n ? decodedOutput.slice(0, -2)\n : decodedOutput.slice(0, -1);\n\n return gitPath.length === 0 ? null : gitPath;\n};\n\n/**\n * Parses one absolute path returned by Git.\n * @param output The raw bounded Git stdout bytes.\n * @returns The exact absolute path, or null when the output is invalid.\n */\nexport const parseGitAbsolutePathOutput = (output: Uint8Array): string | null => {\n const gitPath = parseGitPathOutput(output);\n\n if (gitPath === null || !path.isAbsolute(gitPath)) {\n return null;\n }\n\n return gitPath;\n};\n","import { stat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {\n hasOnlyUnicodeScalarValues,\n isRepositoryDirectoryInputValid,\n} from '../command-line/index.js';\n\nimport type {\n IGitStartingDirectoryInspectionResult,\n IGitStartingDirectoryInspector,\n IGitStartingDirectoryStat,\n} from './types.js';\n\n/**\n * Maps a filesystem failure without retaining host diagnostics or paths.\n * @param error The unknown filesystem failure.\n * @returns An immutable safe discovery failure.\n */\nconst mapFilesystemFailure = (error: unknown): IGitStartingDirectoryInspectionResult => {\n const errorCode = (error as NodeJS.ErrnoException | null)?.code?.toUpperCase();\n\n if (errorCode === 'ENOENT' || errorCode === 'ENOTDIR') {\n return Object.freeze({ errorCode: 'GIT_REPOSITORY_NOT_FOUND', kind: 'failed' });\n }\n\n if (errorCode === 'EACCES' || errorCode === 'EPERM') {\n return Object.freeze({ errorCode: 'GIT_ACCESS_DENIED', kind: 'failed' });\n }\n\n return Object.freeze({ errorCode: 'GIT_COMMAND_FAILED', kind: 'failed' });\n};\n\n/**\n * Creates a starting-directory inspector around an injectable filesystem boundary.\n * @param inspectPath The filesystem stat operation.\n * @returns A safe inspector that resolves and verifies the selected directory.\n */\nexport const createGitStartingDirectoryInspector =\n (inspectPath: IGitStartingDirectoryStat = stat): IGitStartingDirectoryInspector =>\n async (input): Promise<IGitStartingDirectoryInspectionResult> => {\n if (\n !path.isAbsolute(input.invocationDirectory) ||\n input.invocationDirectory.includes('\\0') ||\n !hasOnlyUnicodeScalarValues(input.invocationDirectory) ||\n (input.repositoryDirectory !== null &&\n !isRepositoryDirectoryInputValid(input.repositoryDirectory))\n ) {\n return Object.freeze({ errorCode: 'GIT_REPOSITORY_NOT_FOUND', kind: 'failed' });\n }\n\n const selectedDirectory =\n input.repositoryDirectory === null\n ? input.invocationDirectory\n : path.isAbsolute(input.repositoryDirectory)\n ? input.repositoryDirectory\n : path.resolve(input.invocationDirectory, input.repositoryDirectory);\n\n try {\n const directoryStats = await inspectPath(selectedDirectory);\n\n if (!directoryStats.isDirectory()) {\n return Object.freeze({ errorCode: 'GIT_REPOSITORY_NOT_FOUND', kind: 'failed' });\n }\n } catch (error) {\n return mapFilesystemFailure(error);\n }\n\n return Object.freeze({ directory: selectedDirectory, kind: 'found' });\n };\n\n// default starting-directory inspection boundary\nexport const inspectGitStartingDirectory = createGitStartingDirectoryInspector();\n","import {\n executeGitProcess,\n type IGitProcessExecutor,\n type IGitProcessFailureReason,\n} from '../git-process/index.js';\nimport { createGitVersionPreflight, type IGitVersionPreflight } from '../git-version/index.js';\nimport type { IMoldeaCliGitErrorCode } from '../presentation/index.js';\n\nimport { MAX_GIT_DISCOVERY_OUTPUT_BYTES } from './constants.js';\nimport { parseGitAbsolutePathOutput, parseGitBooleanOutput } from './parser.js';\nimport { inspectGitStartingDirectory } from './starting-directory.js';\nimport type {\n IGitStartingDirectoryInspector,\n IGitWorkingTreeDiscovery,\n IGitWorkingTreeDiscoveryFailedResult,\n IGitWorkingTreeDiscoveryResult,\n} from './types.js';\n\n/** Maps a normalized Git process failure to a safe discovery error. */\nconst mapGitProcessFailure = (reason: IGitProcessFailureReason): IMoldeaCliGitErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'repository-not-found':\n return 'GIT_REPOSITORY_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'output-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Creates one immutable discovery failure. */\nconst createDiscoveryFailure = (\n errorCode: IMoldeaCliGitErrorCode,\n): IGitWorkingTreeDiscoveryFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/**\n * Creates Git working-tree discovery around injectable process and filesystem boundaries.\n * @param processExecutor The normalized Git subprocess executor.\n * @param startingDirectoryInspector The safe directory inspection boundary.\n * @param gitVersionPreflight The Git version prerequisite check.\n * @returns A working-tree discovery operation.\n */\nexport const createGitWorkingTreeDiscovery =\n (\n processExecutor: IGitProcessExecutor = executeGitProcess,\n startingDirectoryInspector: IGitStartingDirectoryInspector = inspectGitStartingDirectory,\n gitVersionPreflight: IGitVersionPreflight = createGitVersionPreflight(processExecutor),\n ): IGitWorkingTreeDiscovery =>\n async (input): Promise<IGitWorkingTreeDiscoveryResult> => {\n const startingDirectoryResult = await startingDirectoryInspector(input);\n\n if (startingDirectoryResult.kind === 'failed') {\n return createDiscoveryFailure(startingDirectoryResult.errorCode);\n }\n\n const workTreeResult = await processExecutor({\n arguments: ['-C', startingDirectoryResult.directory, 'rev-parse', '--is-inside-work-tree'],\n maxBufferBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (workTreeResult.kind === 'failed') {\n return createDiscoveryFailure(mapGitProcessFailure(workTreeResult.reason));\n }\n\n if (workTreeResult.stderr.byteLength > 0) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n const isInsideWorkTree = parseGitBooleanOutput(workTreeResult.stdout);\n\n if (isInsideWorkTree === null) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n if (!isInsideWorkTree) {\n return createDiscoveryFailure('GIT_WORK_TREE_REQUIRED');\n }\n\n const rootResult = await processExecutor({\n arguments: ['-C', startingDirectoryResult.directory, 'rev-parse', '--show-toplevel'],\n maxBufferBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (rootResult.kind === 'failed') {\n return createDiscoveryFailure(mapGitProcessFailure(rootResult.reason));\n }\n\n if (rootResult.stderr.byteLength > 0) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n const repositoryRoot = parseGitAbsolutePathOutput(rootResult.stdout);\n\n if (repositoryRoot === null) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n const rootDirectoryResult = await startingDirectoryInspector({\n invocationDirectory: startingDirectoryResult.directory,\n repositoryDirectory: repositoryRoot,\n });\n\n if (rootDirectoryResult.kind === 'failed') {\n return createDiscoveryFailure(rootDirectoryResult.errorCode);\n }\n\n const versionResult = await gitVersionPreflight(input.signal);\n\n if (versionResult.kind === 'failed') {\n return createDiscoveryFailure(versionResult.errorCode);\n }\n\n const sparseCheckoutResult = await processExecutor({\n arguments: [\n '-C',\n rootDirectoryResult.directory,\n 'config',\n '--type=bool',\n '--default=false',\n '--get',\n 'core.sparseCheckout',\n ],\n maxBufferBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (sparseCheckoutResult.kind === 'failed') {\n return createDiscoveryFailure(mapGitProcessFailure(sparseCheckoutResult.reason));\n }\n\n if (sparseCheckoutResult.stderr.byteLength > 0) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n const isSparseCheckout = parseGitBooleanOutput(sparseCheckoutResult.stdout);\n\n if (isSparseCheckout === null) {\n return createDiscoveryFailure('GIT_OUTPUT_INVALID');\n }\n\n if (isSparseCheckout) {\n return createDiscoveryFailure('GIT_SPARSE_CHECKOUT_UNSUPPORTED');\n }\n\n return Object.freeze({ kind: 'discovered', repositoryRoot });\n };\n\n// default Git working-tree discovery used by command execution\nexport const discoverGitWorkingTree = createGitWorkingTreeDiscovery();\n","import path from 'node:path';\n\nimport type { IHostPathIdentity, IHostPathOperations } from './types.js';\n\n/**\n * Determines whether two absolute path spellings identify the same host path.\n * @param left The first host path.\n * @param right The second host path.\n * @param hostPathOperations The platform path operations used for comparison.\n * @returns Whether the paths are equivalent under the selected host semantics.\n */\nexport const areHostPathsEquivalent = (\n left: string,\n right: string,\n hostPathOperations: IHostPathOperations = path,\n): boolean =>\n hostPathOperations.relative(\n hostPathOperations.resolve(left),\n hostPathOperations.resolve(right),\n ) === '';\n\n/**\n * Determines whether two observations identify the same filesystem entry.\n * @param left The first filesystem observation.\n * @param right The second filesystem observation.\n * @returns Whether both observations have the same nonzero device and inode identity.\n */\nexport const haveSameHostPathIdentity = (\n left: IHostPathIdentity,\n right: IHostPathIdentity,\n): boolean => left.ino !== 0n && left.dev === right.dev && left.ino === right.ino;\n","import { haveSameHostPathIdentity } from '../../host-path-identity/index.js';\n\nimport type { IGitWorkingTreeIdentity, IGitWorkingTreeIdentityLocation } from './types.js';\n\n/** Determines whether two locations denote the same directory despite host-path aliases. */\nconst areLocationsEqual = (\n left: IGitWorkingTreeIdentityLocation,\n right: IGitWorkingTreeIdentityLocation,\n): boolean => haveSameHostPathIdentity(left, right);\n\n/**\n * Determines whether two observations identify the same working tree and Git repository.\n * @param left The pinned working-tree identity.\n * @param right The identity observed before a snapshot attempt.\n * @returns Whether the root, worktree Git directory, and common directory all match.\n */\nexport const areGitWorkingTreeIdentitiesEqual = (\n left: IGitWorkingTreeIdentity,\n right: IGitWorkingTreeIdentity,\n): boolean =>\n areLocationsEqual(left.repositoryRoot, right.repositoryRoot) &&\n areLocationsEqual(left.gitDirectory, right.gitDirectory) &&\n areLocationsEqual(left.commonDirectory, right.commonDirectory);\n","// fixed Git queries used to establish one working-tree identity\nexport const GIT_WORKING_TREE_IDENTITY_ARGUMENTS = Object.freeze({\n CommonDirectory: Object.freeze(['rev-parse', '--git-common-dir']),\n GitDirectory: Object.freeze(['rev-parse', '--absolute-git-dir']),\n RepositoryRoot: Object.freeze(['rev-parse', '--show-toplevel']),\n});\n","import { stat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { hasOnlyUnicodeScalarValues } from '../../command-line/index.js';\nimport {\n executeGitProcess,\n type IGitProcessExecutor,\n type IGitProcessFailureReason,\n} from '../../git-process/index.js';\nimport {\n areHostPathsEquivalent,\n haveSameHostPathIdentity,\n} from '../../host-path-identity/index.js';\nimport type { IMoldeaCliGitErrorCode } from '../../presentation/index.js';\nimport { MAX_GIT_DISCOVERY_OUTPUT_BYTES } from '../constants.js';\nimport { parseGitAbsolutePathOutput, parseGitPathOutput } from '../parser.js';\n\nimport { GIT_WORKING_TREE_IDENTITY_ARGUMENTS } from './constants.js';\nimport type {\n IGitWorkingTreeIdentityInspectionFailedResult,\n IGitWorkingTreeIdentityInspectionResult,\n IGitWorkingTreeIdentityInspector,\n IGitWorkingTreeIdentityLocation,\n IGitWorkingTreeIdentityStat,\n} from './types.js';\n\n/** Reads one followed directory identity with bigint filesystem fields. */\nconst inspectDirectoryIdentity: IGitWorkingTreeIdentityStat = async (hostPath) =>\n stat(hostPath, { bigint: true });\n\n/** Creates one immutable identity-inspection failure. */\nconst createInspectionFailure = (\n errorCode: IMoldeaCliGitErrorCode,\n): IGitWorkingTreeIdentityInspectionFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps one normalized Git process failure to the discovery error contract. */\nconst mapGitProcessFailure = (reason: IGitProcessFailureReason): IMoldeaCliGitErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'repository-not-found':\n return 'GIT_REPOSITORY_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'output-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Maps one private filesystem failure without exposing its host diagnostics. */\nconst mapFilesystemFailure = (error: unknown): IMoldeaCliGitErrorCode => {\n let errorCode: string | undefined;\n\n try {\n if (typeof error === 'object' && error !== null && 'code' in error) {\n const unknownCode: unknown = error.code;\n\n errorCode = typeof unknownCode === 'string' ? unknownCode.toUpperCase() : undefined;\n }\n } catch {\n return 'GIT_COMMAND_FAILED';\n }\n\n if (errorCode === 'ENOENT' || errorCode === 'ENOTDIR') {\n return 'GIT_REPOSITORY_NOT_FOUND';\n }\n\n if (errorCode === 'EACCES' || errorCode === 'EPERM') {\n return 'GIT_ACCESS_DENIED';\n }\n\n return 'GIT_COMMAND_FAILED';\n};\n\n/** Executes one bounded Git identity-path query. */\nconst queryGitPath = async (\n processExecutor: IGitProcessExecutor,\n repositoryRoot: string,\n arguments_: readonly string[],\n isAbsoluteRequired: boolean,\n signal?: AbortSignal,\n): Promise<string | IGitWorkingTreeIdentityInspectionFailedResult> => {\n const result = await processExecutor({\n arguments: ['-C', repositoryRoot, ...arguments_],\n maxBufferBytes: MAX_GIT_DISCOVERY_OUTPUT_BYTES,\n ...(signal === undefined ? {} : { signal }),\n });\n\n if (result.kind === 'failed') {\n return createInspectionFailure(mapGitProcessFailure(result.reason));\n }\n\n if (result.stderr.byteLength > 0) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const gitPath = isAbsoluteRequired\n ? parseGitAbsolutePathOutput(result.stdout)\n : parseGitPathOutput(result.stdout);\n\n return gitPath ?? createInspectionFailure('GIT_OUTPUT_INVALID');\n};\n\n/** Captures one directory path and stable filesystem identity. */\nconst captureLocation = async (\n inspectPath: IGitWorkingTreeIdentityStat,\n hostPath: string,\n invalidTypeCode: IMoldeaCliGitErrorCode,\n): Promise<IGitWorkingTreeIdentityLocation | IGitWorkingTreeIdentityInspectionFailedResult> => {\n try {\n const statistics = await inspectPath(hostPath);\n\n if (!statistics.isDirectory() || statistics.ino === 0n) {\n return createInspectionFailure(invalidTypeCode);\n }\n\n return Object.freeze({ dev: statistics.dev, ino: statistics.ino, path: hostPath });\n } catch (error) {\n return createInspectionFailure(mapFilesystemFailure(error));\n }\n};\n\n/** Determines whether an identity helper returned a safe failure. */\nconst isInspectionFailure = (\n result: string | IGitWorkingTreeIdentityLocation | IGitWorkingTreeIdentityInspectionFailedResult,\n): result is IGitWorkingTreeIdentityInspectionFailedResult =>\n typeof result === 'object' && 'kind' in result && result.kind === 'failed';\n\n/**\n * Creates a bounded working-tree identity inspector around Git and filesystem boundaries.\n * @param processExecutor The sanitized bounded Git process executor.\n * @param inspectPath The followed directory identity operation.\n * @returns An inspector that captures one private immutable identity.\n */\nexport const createGitWorkingTreeIdentityInspector = (\n processExecutor: IGitProcessExecutor = executeGitProcess,\n inspectPath: IGitWorkingTreeIdentityStat = inspectDirectoryIdentity,\n): IGitWorkingTreeIdentityInspector => {\n return async (input): Promise<IGitWorkingTreeIdentityInspectionResult> => {\n if (\n !path.isAbsolute(input.repositoryRoot) ||\n input.repositoryRoot.includes('\\0') ||\n !hasOnlyUnicodeScalarValues(input.repositoryRoot)\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const discoveredRoot = await queryGitPath(\n processExecutor,\n input.repositoryRoot,\n GIT_WORKING_TREE_IDENTITY_ARGUMENTS.RepositoryRoot,\n true,\n input.signal,\n );\n\n if (isInspectionFailure(discoveredRoot)) {\n return discoveredRoot;\n }\n\n const repositoryRoot = await captureLocation(\n inspectPath,\n discoveredRoot,\n 'GIT_WORK_TREE_REQUIRED',\n );\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isInspectionFailure(repositoryRoot)) {\n return repositoryRoot;\n }\n\n if (!areHostPathsEquivalent(discoveredRoot, input.repositoryRoot)) {\n const selectedRepositoryRoot = await captureLocation(\n inspectPath,\n input.repositoryRoot,\n 'GIT_WORK_TREE_REQUIRED',\n );\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isInspectionFailure(selectedRepositoryRoot)) {\n return selectedRepositoryRoot;\n }\n\n if (!haveSameHostPathIdentity(repositoryRoot, selectedRepositoryRoot)) {\n return Object.freeze({ kind: 'mismatched' });\n }\n }\n\n const gitDirectoryPath = await queryGitPath(\n processExecutor,\n input.repositoryRoot,\n GIT_WORKING_TREE_IDENTITY_ARGUMENTS.GitDirectory,\n true,\n input.signal,\n );\n\n if (isInspectionFailure(gitDirectoryPath)) {\n return gitDirectoryPath;\n }\n\n const commonDirectoryOutput = await queryGitPath(\n processExecutor,\n input.repositoryRoot,\n GIT_WORKING_TREE_IDENTITY_ARGUMENTS.CommonDirectory,\n false,\n input.signal,\n );\n\n if (isInspectionFailure(commonDirectoryOutput)) {\n return commonDirectoryOutput;\n }\n\n const commonDirectoryPath = path.isAbsolute(commonDirectoryOutput)\n ? commonDirectoryOutput\n : path.resolve(input.repositoryRoot, commonDirectoryOutput);\n const gitDirectory = await captureLocation(inspectPath, gitDirectoryPath, 'GIT_OUTPUT_INVALID');\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isInspectionFailure(gitDirectory)) {\n return gitDirectory;\n }\n\n const commonDirectory = await captureLocation(\n inspectPath,\n commonDirectoryPath,\n 'GIT_OUTPUT_INVALID',\n );\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isInspectionFailure(commonDirectory)) {\n return commonDirectory;\n }\n\n return Object.freeze({\n identity: Object.freeze({ commonDirectory, gitDirectory, repositoryRoot }),\n kind: 'inspected',\n });\n };\n};\n\n// default identity inspector used by snapshot execution\nexport const inspectGitWorkingTreeIdentity = createGitWorkingTreeIdentityInspector();\n","import type { IMoldeaCliProjectContentErrorCode } from './types.js';\n\n/** Represents an invalid explicit canonical content request. */\nexport class MoldeaCliProjectContentException extends Error {\n public readonly code: IMoldeaCliProjectContentErrorCode;\n\n /** Creates one content request failure with a stable public code. */\n public constructor(code: IMoldeaCliProjectContentErrorCode) {\n super(code);\n this.code = code;\n this.name = 'MoldeaCliProjectContentException';\n }\n}\n","import { parseRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport { MoldeaCliProjectContentException } from './exception.js';\n\nconst CONTEXT_PATH_PATTERN = /^\\/moldea\\/context\\/(?:[^/]+\\/)*[^/]+\\.md$/u;\nconst DECISION_PATH_PATTERN = /^\\/moldea\\/decisions\\/[^/]+\\.md$/u;\nconst RUNTIME_PATH_PATTERN = /^\\/moldea\\/runtimes\\/(?:[^/]+\\/)*[^/]+\\.md$/u;\nconst AGENT_PATH_PATTERN =\n /^\\/moldea\\/agents\\/[^/]+\\/(?:description|instruction|handoff-description)\\.md$/u;\n\n/** Determines whether a logical path names one canonical moldea text asset. */\nexport const isMoldeaCliCanonicalContentPath = (path: IRepositoryPath): boolean => {\n if (/[?*[\\]{}]/u.test(path)) {\n return false;\n }\n\n return (\n path === '/moldea/moldea.yaml' ||\n path === '/moldea/project.md' ||\n CONTEXT_PATH_PATTERN.test(path) ||\n DECISION_PATH_PATTERN.test(path) ||\n RUNTIME_PATH_PATTERN.test(path) ||\n AGENT_PATH_PATTERN.test(path)\n );\n};\n\n/**\n * Parses one untrusted path and restricts it to the canonical text layout.\n * @param input The command-line logical path.\n * @returns The validated canonical repository path.\n * @throws\n * - CONTENT_PATH_INVALID: The content path must identify one canonical moldea text asset.\n */\nexport const parseMoldeaCliCanonicalContentPath = (input: string): IRepositoryPath => {\n let path: IRepositoryPath;\n\n try {\n path = parseRepositoryPath(input);\n } catch {\n throw new MoldeaCliProjectContentException('CONTENT_PATH_INVALID');\n }\n\n if (!isMoldeaCliCanonicalContentPath(path)) {\n throw new MoldeaCliProjectContentException('CONTENT_PATH_INVALID');\n }\n\n return path;\n};\n","import { createCore } from '@moldea.ai/core';\n\nimport type {\n IMoldeaCliProjectContentCoreFactory,\n IMoldeaCliProjectContentExecutor,\n} from './types.js';\n\n/** Creates an adapter-free executor for one bounded canonical content range. */\nexport const createMoldeaCliProjectContentExecutor = (\n coreFactory: IMoldeaCliProjectContentCoreFactory = createCore,\n): IMoldeaCliProjectContentExecutor => {\n return async (input) => {\n const core = coreFactory({\n limits: Object.freeze({\n maxDiagnostics: input.resourceLimits.maxDiagnostics,\n maxEntries: input.resourceLimits.maxEntries,\n maxEvidence: input.resourceLimits.maxEvidence,\n maxFileBytes: input.resourceLimits.maxFileBytes,\n maxManifestBytes: input.resourceLimits.maxManifestBytes,\n maxTotalBytesRead: input.resourceLimits.maxTotalBytes,\n }),\n });\n\n return core.readCanonicalContentPage({\n maxBytes: input.maxBytes,\n offset: input.offset,\n path: input.path,\n repository: input.repository,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n };\n};\n\n/** Executes one adapter-free explicit canonical content range read. */\nexport const executeMoldeaCliProjectContent = createMoldeaCliProjectContentExecutor();\n","import type { IJsonValue } from '../json-serialization/index.js';\nimport {\n calculateMoldeaCliJsonDigest,\n decodeMoldeaCliCursor,\n encodeMoldeaCliCursor,\n MoldeaCliOutputPageException,\n} from '../output-page/index.js';\n\nimport type { IMoldeaCliContentPageInput, IMoldeaCliContentResult } from './types.js';\n\n/** Creates one candidate content result ending at a Unicode scalar boundary. */\nconst createCandidate = (\n input: IMoldeaCliContentPageInput,\n scalars: readonly string[],\n scalarEnd: number,\n snapshotDigest: string,\n): IMoldeaCliContentResult => {\n const content = scalars.slice(0, scalarEnd).join('');\n const byteEnd = input.page.byteStart + Buffer.byteLength(content, 'utf8');\n const isComplete = byteEnd === input.page.totalBytes;\n\n return {\n asset: {\n contentIdentity: input.page.contentIdentity,\n path: input.page.path,\n totalBytes: input.page.totalBytes,\n },\n chunk: {\n byteEnd,\n byteStart: input.page.byteStart,\n content,\n },\n cursor: isComplete\n ? null\n : encodeMoldeaCliCursor(\n 'content',\n { path: input.page.path },\n snapshotDigest,\n `byte:${byteEnd}`,\n `byte:${byteEnd}`,\n ),\n snapshotDigest,\n };\n};\n\n/** Creates the stable identity shared by every page of one canonical file snapshot. */\nconst createSnapshotDigest = (input: IMoldeaCliContentPageInput): string =>\n calculateMoldeaCliJsonDigest({\n contentIdentity: input.page.contentIdentity,\n path: input.page.path,\n totalBytes: input.page.totalBytes,\n } satisfies IJsonValue);\n\n/** Selects the largest Unicode-safe content prefix within the exact output budget. */\nexport const createMoldeaCliContentPage = (\n input: IMoldeaCliContentPageInput,\n): IMoldeaCliContentResult => {\n const snapshotDigest = createSnapshotDigest(input);\n const cursorState =\n input.cursor === null\n ? null\n : decodeMoldeaCliCursor({\n command: 'content',\n cursor: input.cursor,\n filters: { path: input.page.path },\n snapshotDigest,\n });\n const expectedSourceCursor = `byte:${input.page.byteStart}`;\n\n if (\n (cursorState === null && input.page.byteStart !== 0) ||\n (cursorState !== null && cursorState.sourceCursor !== expectedSourceCursor)\n ) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n const scalars = Array.from(input.page.content);\n const emptyResult = createCandidate(input, scalars, 0, snapshotDigest);\n\n if (scalars.length === 0) {\n if (!input.page.isComplete || input.measure(emptyResult) > input.maxOutputBytes) {\n throw new MoldeaCliOutputPageException('OUTPUT_BUDGET_TOO_SMALL');\n }\n\n return Object.freeze({\n ...emptyResult,\n asset: Object.freeze(emptyResult.asset),\n chunk: Object.freeze(emptyResult.chunk),\n });\n }\n\n let lower = 1;\n let upper = scalars.length;\n let selected: IMoldeaCliContentResult | null = null;\n\n while (lower <= upper) {\n const scalarEnd = lower + Math.floor((upper - lower) / 2);\n const candidate = createCandidate(input, scalars, scalarEnd, snapshotDigest);\n\n if (input.measure(candidate) <= input.maxOutputBytes) {\n selected = candidate;\n lower = scalarEnd + 1;\n } else {\n upper = scalarEnd - 1;\n }\n }\n\n if (selected === null) {\n throw new MoldeaCliOutputPageException('OUTPUT_BUDGET_TOO_SMALL');\n }\n\n return Object.freeze({\n ...selected,\n asset: Object.freeze(selected.asset),\n chunk: Object.freeze(selected.chunk),\n });\n};\n","import { parseRepositoryPath } from '@moldea.ai/repository';\n\n// only canonical asset required for changed-path relationship matching\nexport const MOLDEA_MANIFEST_PATH = parseRepositoryPath('/moldea/moldea.yaml');\n","import type { IMoldeaCliProjectScopeErrorCode } from './types.js';\n\n/** Represents invalid scope path input owned by the CLI. */\nexport class MoldeaCliProjectScopeException extends Error {\n public readonly code: IMoldeaCliProjectScopeErrorCode;\n\n /** Creates one scope-input failure with a stable public code. */\n public constructor(code: IMoldeaCliProjectScopeErrorCode) {\n super(code);\n this.code = code;\n this.name = 'MoldeaCliProjectScopeException';\n }\n}\n","import { MoldeaCliProjectScopeException } from './exception.js';\n\n/**\n * Parses bounded NUL-delimited UTF-8 changed paths without shell interpretation.\n * @param input Exact stdin bytes supplied to the scope command.\n * @param maxEntries Maximum changed-path records accepted by the operation.\n * @returns Detached path strings in supplied order for Core validation and normalization.\n * @throws\n * - PATH_INPUT_INVALID: The scope path input is invalid. Use leading-slash repository-logical paths and NUL-delimited UTF-8 on stdin.\n */\nexport const parseMoldeaCliScopePathBytes = (\n input: Uint8Array,\n maxEntries: number,\n): readonly string[] => {\n if (input.byteLength === 0) {\n return Object.freeze([]);\n }\n\n let text: string;\n\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(input);\n } catch {\n throw new MoldeaCliProjectScopeException('PATH_INPUT_INVALID');\n }\n\n if (!text.endsWith('\\0')) {\n throw new MoldeaCliProjectScopeException('PATH_INPUT_INVALID');\n }\n\n const paths = text.slice(0, -1).split('\\0');\n\n if (paths.length > maxEntries || paths.some((path) => path.length === 0)) {\n throw new MoldeaCliProjectScopeException('PATH_INPUT_INVALID');\n }\n\n return Object.freeze(paths);\n};\n","import { createCore } from '@moldea.ai/core';\nimport { RepositorySourceException } from '@moldea.ai/repository';\n\nimport { MOLDEA_MANIFEST_PATH } from './constants.js';\nimport type {\n IMoldeaCliProjectScopeCoreFactory,\n IMoldeaCliProjectScopeExecutor,\n IMoldeaCliProjectScopeInput,\n} from './types.js';\n\n/** Reads the complete manifest within its explicit small-file resource bound. */\nconst readBoundedManifest = async (input: IMoldeaCliProjectScopeInput): Promise<Uint8Array> => {\n const operationOptions = input.signal === undefined ? undefined : { signal: input.signal };\n const entry = await input.repository.getEntry(MOLDEA_MANIFEST_PATH, operationOptions);\n\n if (entry === null) {\n throw new RepositorySourceException({\n code: 'ENTRY_NOT_FOUND',\n operation: 'read-file-page',\n path: MOLDEA_MANIFEST_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: MOLDEA_MANIFEST_PATH,\n retryable: false,\n });\n }\n\n const maxBytes = Math.min(\n input.resourceLimits.maxManifestBytes,\n input.resourceLimits.maxTotalBytes,\n );\n\n if (entry.byteLength > maxBytes) {\n throw new RepositorySourceException({\n code: 'RESOURCE_LIMIT_EXCEEDED',\n operation: 'read-file-page',\n path: MOLDEA_MANIFEST_PATH,\n retryable: false,\n });\n }\n\n const chunks: Uint8Array[] = [];\n let byteLength = 0;\n let nextOffset = 0;\n let isComplete = false;\n\n while (!isComplete) {\n const page = await input.repository.readFilePage(MOLDEA_MANIFEST_PATH, {\n maxBytes: Math.max(1, entry.byteLength - byteLength),\n offset: nextOffset,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (\n page.snapshot.id !== input.repository.snapshot.id ||\n page.offset !== nextOffset ||\n page.totalBytes !== entry.byteLength ||\n page.bytes.byteLength > entry.byteLength - byteLength ||\n (page.bytes.byteLength === 0 && !page.isComplete) ||\n (!page.isComplete && page.nextOffset !== page.offset + page.bytes.byteLength)\n ) {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path: MOLDEA_MANIFEST_PATH,\n retryable: false,\n });\n }\n\n chunks.push(page.bytes);\n byteLength += page.bytes.byteLength;\n nextOffset = page.nextOffset ?? byteLength;\n isComplete = page.isComplete;\n }\n\n if (byteLength !== entry.byteLength) {\n throw new RepositorySourceException({\n code: 'PROVIDER_INCOMPLETE',\n operation: 'read-file-page',\n path: MOLDEA_MANIFEST_PATH,\n retryable: false,\n });\n }\n\n const manifestBytes = new Uint8Array(byteLength);\n let writeOffset = 0;\n\n for (const chunk of chunks) {\n manifestBytes.set(chunk, writeOffset);\n writeOffset += chunk.byteLength;\n }\n\n return manifestBytes;\n};\n\n/** Creates an adapter-free manifest-only Core scope executor. */\nexport const createMoldeaCliProjectScopeExecutor = (\n coreFactory: IMoldeaCliProjectScopeCoreFactory = createCore,\n): IMoldeaCliProjectScopeExecutor => {\n return async (input) => {\n const manifestBytes = await readBoundedManifest(input);\n const core = coreFactory({\n limits: Object.freeze({\n maxDiagnostics: input.resourceLimits.maxDiagnostics,\n maxEntries: input.resourceLimits.maxEntries,\n maxEvidence: input.resourceLimits.maxEvidence,\n maxFileBytes: input.resourceLimits.maxFileBytes,\n maxManifestBytes: input.resourceLimits.maxManifestBytes,\n maxTotalBytesRead: input.resourceLimits.maxTotalBytes,\n }),\n });\n const scope = await core.matchManifestScope({\n manifest: { content: manifestBytes, path: MOLDEA_MANIFEST_PATH },\n paths: input.paths,\n });\n\n return Object.freeze({\n manifestContent: new TextDecoder('utf-8').decode(manifestBytes),\n scope,\n });\n };\n};\n\n/** Executes one adapter-free manifest-only changed-path scope match. */\nexport const executeMoldeaCliProjectScope = createMoldeaCliProjectScopeExecutor();\n","import type { IManifestScopeMatch } from '@moldea.ai/core';\n\nimport { calculateMoldeaCliJsonDigest } from '../output-page/index.js';\nimport { createMoldeaCliDiagnosticRecord } from '../presentation/index.js';\nimport type { IJsonValue } from '../json-serialization/index.js';\n\nimport type {\n IMoldeaCliScopeProjection,\n IMoldeaCliScopeRecord,\n IMoldeaCliProjectScopeExecutionResult,\n} from './types.js';\n\nconst compareKeys = (left: IMoldeaCliScopeRecord, right: IMoldeaCliScopeRecord): number =>\n left.key < right.key ? -1 : left.key > right.key ? 1 : 0;\n\n/** Creates one stable key for a relationship-match projection. */\nconst createMatchKey = (match: IManifestScopeMatch): string =>\n JSON.stringify([\n 'match',\n match.owner.kind,\n match.owner.agentId,\n match.owner.id,\n match.field,\n match.declaration.kind === 'exact' ? match.declaration.path : match.declaration.pattern,\n match.inputPath,\n match.pointer,\n ]);\n\n/** Projects complete Core scope output into ordered content-free CLI records. */\nexport const createMoldeaCliScopeProjection = (\n execution: IMoldeaCliProjectScopeExecutionResult,\n): IMoldeaCliScopeProjection => {\n const records: IMoldeaCliScopeRecord[] = [\n ...execution.scope.diagnostics.map((diagnostic, index) =>\n createMoldeaCliDiagnosticRecord(diagnostic, index),\n ),\n ...execution.scope.matches.map((match): IMoldeaCliScopeRecord => ({\n key: createMatchKey(match),\n kind: 'match',\n match,\n })),\n ].sort(compareKeys);\n const snapshotDigest = calculateMoldeaCliJsonDigest({\n inputDigest: execution.scope.inputDigest,\n manifestDigest: execution.scope.manifestDigest,\n records,\n valid: execution.scope.valid,\n } as unknown as IJsonValue);\n\n return Object.freeze({\n canonicalBodies: Object.freeze([execution.manifestContent]),\n counts: Object.freeze({\n ...execution.scope.counts,\n diagnostics: execution.scope.diagnostics.length,\n }),\n inputDigest: execution.scope.inputDigest,\n manifestDigest: execution.scope.manifestDigest,\n records: Object.freeze(records),\n relevant: execution.scope.relevant,\n snapshotDigest,\n valid: execution.scope.valid,\n });\n};\n","import { RepositorySourceException, type IRepositoryPath } from '@moldea.ai/repository';\n\n/** Identifies a guarded logical file whose working-tree bytes are unsafe to inspect. */\nexport class GitContentTransformUnsupportedException extends RepositorySourceException {\n /** Creates the CLI-owned marker on the common repository-source failure boundary. */\n public constructor(path: IRepositoryPath) {\n super({\n code: 'SOURCE_UNAVAILABLE',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n this.name = 'GitContentTransformUnsupportedException';\n }\n}\n","import {\n REPOSITORY_ROOT,\n RepositorySourceException,\n createRepositoryComparison,\n parseRepositoryPath,\n type IRepositoryComparison,\n type IRepositoryEntry,\n type IRepositoryEntryPage,\n type IRepositoryEntryPageOptions,\n type IRepositoryFilePage,\n type IRepositoryFilePageOptions,\n type IRepositoryOperationOptions,\n type IRepositoryPath,\n type IRepositoryReader,\n type IRepositorySnapshot,\n} from '@moldea.ai/repository';\n\nimport { GitContentTransformUnsupportedException } from './exception.js';\n\n/** Throws the common cancellation contract for one guard-owned read step. */\nconst throwIfAborted = (signal: AbortSignal | undefined, path: IRepositoryPath): void => {\n if (!signal?.aborted) {\n return;\n }\n\n throw new RepositorySourceException({\n cause: signal.reason,\n code: 'ABORTED',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n};\n\n/** Creates the common failure for contradictory underlying lookup data. */\nconst createInvalidSourceException = (path: IRepositoryPath): RepositorySourceException =>\n new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'read-file-page',\n path,\n retryable: false,\n });\n\n// immutable guarded-read view over one coherent logical repository reader\nclass GitContentTransformationGuardRepositoryReader implements IRepositoryReader {\n public readonly snapshot: IRepositorySnapshot;\n\n readonly #guardedPaths: ReadonlySet<IRepositoryPath>;\n\n readonly #reader: IRepositoryReader;\n\n public constructor(reader: IRepositoryReader, guardedPaths: ReadonlySet<IRepositoryPath>) {\n this.#reader = reader;\n this.#guardedPaths = guardedPaths;\n this.snapshot = reader.snapshot;\n }\n\n /** Creates a bounded comparison from this guarded logical snapshot. */\n public compare(\n candidate: IRepositoryReader,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryComparison> {\n return createRepositoryComparison(this, candidate, options);\n }\n\n /**\n * Looks up an entry without changing the underlying logical inventory.\n * @param path The validated repository path to inspect.\n * @param options Optional cancellation controls.\n * @returns A promise resolving to the underlying detached entry or confirmed absence.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during the operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public getEntry(\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryEntry | null> {\n return this.#reader.getEntry(path, options);\n }\n\n /**\n * Reads ordinary files while refusing guarded logical regular-file bytes.\n * @param path The validated repository file path to read.\n * @param options Optional cancellation controls.\n * @returns A promise resolving to fresh bytes for an unguarded regular file.\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 or its regular file uses an unsupported Git content transformation.\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 repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public async readFilePage(\n path: IRepositoryPath,\n options: IRepositoryFilePageOptions,\n ): Promise<IRepositoryFilePage> {\n const parsedPath = parseRepositoryPath(path);\n\n if (!this.#guardedPaths.has(parsedPath)) {\n return this.#reader.readFilePage(parsedPath, options);\n }\n\n throwIfAborted(options?.signal, parsedPath);\n\n const entry = await this.#reader.getEntry(parsedPath, options);\n\n throwIfAborted(options?.signal, parsedPath);\n\n if (\n entry !== null &&\n (entry.path !== parsedPath ||\n (entry.type !== 'file' && entry.type !== 'directory' && entry.type !== 'symlink'))\n ) {\n throw createInvalidSourceException(parsedPath);\n }\n\n if (entry?.type !== 'file') {\n return this.#reader.readFilePage(parsedPath, options);\n }\n\n throw new GitContentTransformUnsupportedException(parsedPath);\n }\n\n /**\n * Recursively lists entries without changing the underlying logical inventory.\n * @param options Optional prefix and cancellation controls.\n * @returns The underlying async iterable of detached repository entries.\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_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 repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public listEntriesPage(options: IRepositoryEntryPageOptions): Promise<IRepositoryEntryPage> {\n return this.#reader.listEntriesPage(options);\n }\n}\n\n/**\n * Creates an immutable reader that blocks bytes for Git transform-guarded logical files.\n * @param reader The coherent reader after logical Git entry-type overlays are applied.\n * @param guardedPaths The paths whose working-tree bytes may differ from Git content.\n * @returns A reader preserving inventory semantics while refusing guarded regular-file reads.\n * @throws\n * - INVALID_REPOSITORY_PATH: A guarded repository path is invalid.\n * - INVALID_SOURCE_DATA: The repository root was supplied as a guarded file path.\n */\nexport const createGitContentTransformationGuardRepositoryReader = (\n reader: IRepositoryReader,\n guardedPaths: readonly IRepositoryPath[],\n): IRepositoryReader => {\n const parsedGuardedPaths = new Set<IRepositoryPath>();\n\n for (const guardedPath of guardedPaths) {\n const parsedPath = parseRepositoryPath(guardedPath);\n\n if (parsedPath === REPOSITORY_ROOT) {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'create-reader',\n path: parsedPath,\n retryable: false,\n });\n }\n\n parsedGuardedPaths.add(parsedPath);\n }\n\n return Object.freeze(\n new GitContentTransformationGuardRepositoryReader(reader, parsedGuardedPaths),\n );\n};\n","import type { ICoreConfigurationErrorCode, ICoreOperationErrorCode } from '@moldea.ai/core';\nimport type { IRepositorySourceErrorCode } from '@moldea.ai/repository';\n\n// safe messages for common repository-source failures\nexport const REPOSITORY_SOURCE_ERROR_MESSAGES = Object.freeze({\n ABORTED: 'The repository operation was aborted.',\n ACCESS_DENIED: 'Access to the repository source was denied.',\n ENTRY_NOT_DIRECTORY: 'The requested repository entry is not a directory.',\n ENTRY_NOT_FILE: 'The requested repository entry is not a file.',\n ENTRY_NOT_FOUND: 'The requested repository entry was not found.',\n INVALID_PAGE_REQUEST: 'The repository page request is invalid.',\n INVALID_SOURCE_DATA: 'The repository source returned invalid data.',\n PROVIDER_INCOMPLETE: 'The repository provider could not expose a complete result.',\n RESOURCE_LIMIT_EXCEEDED: 'A repository reading resource limit was exceeded.',\n SNAPSHOT_CHANGED: 'The repository snapshot changed during the operation.',\n SOURCE_UNAVAILABLE: 'The repository source is unavailable.',\n} as const satisfies Readonly<Record<IRepositorySourceErrorCode, string>>);\n\n// safe messages for Core configuration failures\nexport const CORE_CONFIGURATION_ERROR_MESSAGES = Object.freeze({\n DUPLICATE_ADAPTER_ID: 'A runtime adapter ID is registered more than once.',\n INVALID_ADAPTER_DEFINITION: 'A runtime adapter definition is invalid.',\n INVALID_RESOURCE_LIMIT: 'A Core resource limit is invalid.',\n RESERVED_ADAPTER_ID: 'A reserved runtime adapter ID was supplied.',\n} as const satisfies Readonly<Record<ICoreConfigurationErrorCode, string>>);\n\n// safe messages for Core operation failures\nexport const CORE_OPERATION_ERROR_MESSAGES = Object.freeze({\n ABORTED: 'The Core operation was aborted.',\n ADAPTER_EXECUTION_FAILED: 'A runtime adapter failed during inspection.',\n CONTENT_INVALID: 'The requested canonical content is invalid.',\n INVALID_ARGUMENT: 'The Core operation received an invalid argument.',\n RESOURCE_LIMIT_EXCEEDED: 'A Core resource limit was exceeded.',\n} as const satisfies Readonly<Record<ICoreOperationErrorCode, string>>);\n","import { CoreConfigurationException, CoreOperationException } from '@moldea.ai/core';\nimport { isRepositoryPath, RepositorySourceException } from '@moldea.ai/repository';\n\nimport { MoldeaCliOutputPageException } from '../output-page/index.js';\nimport { MoldeaCliProjectContentException } from '../project-content/index.js';\nimport { MoldeaCliProjectScopeException } from '../project-scope/index.js';\nimport { GitContentTransformUnsupportedException } from '../repository-content-transformation-guard/index.js';\nimport { createMoldeaCliOwnedError, type IMoldeaCliError } from '../presentation/index.js';\n\nimport {\n CORE_CONFIGURATION_ERROR_MESSAGES,\n CORE_OPERATION_ERROR_MESSAGES,\n REPOSITORY_SOURCE_ERROR_MESSAGES,\n} from './constants.js';\n\nconst EMPTY_ERROR_DETAILS = Object.freeze({});\n\n/** Creates frozen safe Core metadata without retaining null fields. */\nconst createCoreErrorDetails = (\n error: CoreConfigurationException | CoreOperationException,\n): Readonly<Record<string, string | number>> => {\n const details: Record<string, string | number> = { operation: error.operation };\n\n if (error.adapterId !== null) {\n details['adapterId'] = error.adapterId;\n }\n\n if (error instanceof CoreOperationException) {\n if (error.agentId !== null) {\n details['agentId'] = error.agentId;\n }\n\n if (error.limit !== null) {\n details['limit'] = error.limit;\n }\n\n if (error.limitMaximum !== null) {\n details['limitMaximum'] = error.limitMaximum;\n }\n\n if (error.nextAction !== null) {\n details['nextAction'] = error.nextAction;\n }\n\n if (error.observedUsage !== null) {\n details['observedUsage'] = error.observedUsage;\n }\n }\n\n return Object.freeze(details);\n};\n\n/**\n * Maps a known package exception or unknown failure to one safe CLI error object.\n * @param error The failure that escaped command composition.\n * @returns A complete immutable operational error without causes or private host data.\n */\nexport const mapMoldeaCliOperationalError = (error: unknown): IMoldeaCliError => {\n if (\n error instanceof MoldeaCliOutputPageException ||\n error instanceof MoldeaCliProjectContentException ||\n error instanceof MoldeaCliProjectScopeException\n ) {\n return createMoldeaCliOwnedError(error.code);\n }\n\n if (error instanceof GitContentTransformUnsupportedException) {\n return Object.freeze({\n ...createMoldeaCliOwnedError('GIT_CONTENT_TRANSFORM_UNSUPPORTED'),\n path: isRepositoryPath(error.path) ? error.path : null,\n });\n }\n\n if (error instanceof RepositorySourceException) {\n return Object.freeze({\n code: error.code,\n details: EMPTY_ERROR_DETAILS,\n message: REPOSITORY_SOURCE_ERROR_MESSAGES[error.code],\n path: error.path !== null && isRepositoryPath(error.path) ? error.path : null,\n retryable: error.retryable,\n source: 'repository',\n });\n }\n\n if (error instanceof CoreConfigurationException) {\n return Object.freeze({\n code: error.code,\n details: createCoreErrorDetails(error),\n message: CORE_CONFIGURATION_ERROR_MESSAGES[error.code],\n path: null,\n retryable: false,\n source: 'core',\n });\n }\n\n if (error instanceof CoreOperationException) {\n return Object.freeze({\n code: error.code,\n details: createCoreErrorDetails(error),\n message: CORE_OPERATION_ERROR_MESSAGES[error.code],\n path: null,\n retryable: error.retryable,\n source: 'core',\n });\n }\n\n return createMoldeaCliOwnedError('INTERNAL_ERROR');\n};\n","// fixed read-only Git commands used to enumerate raw working-tree candidates\nexport const GIT_TRACKED_INVENTORY_ARGUMENTS = [\n 'ls-files',\n '--cached',\n '--stage',\n '--full-name',\n '--no-abbrev',\n '--no-recurse-submodules',\n '-z',\n '--',\n] as const;\n\nexport const GIT_UNTRACKED_INVENTORY_ARGUMENTS = [\n 'ls-files',\n '--others',\n '--exclude-standard',\n '--full-name',\n '--no-recurse-submodules',\n '-z',\n '--',\n] as const;\n\n// Git index modes accepted by the version 1 inventory grammar\nexport const GIT_TRACKED_ENTRY_MODES = ['100644', '100755', '120000', '160000'] as const;\n","// Git attributes required to classify working-tree content transformations\nexport const GIT_CONTENT_TRANSFORMATION_ATTRIBUTES = [\n 'filter',\n 'working-tree-encoding',\n 'ident',\n] as const;\n\n// fixed read-only Git command used for NUL-delimited attribute inspection\nexport const GIT_CONTENT_TRANSFORMATION_ARGUMENTS = [\n 'check-attr',\n '--stdin',\n '-z',\n ...GIT_CONTENT_TRANSFORMATION_ATTRIBUTES,\n] as const;\n","import { GIT_CONTENT_TRANSFORMATION_ATTRIBUTES } from './constants.js';\nimport type {\n IGitContentTransformationAttribute,\n IGitContentTransformationAttributeValues,\n IGitContentTransformationParsedAttributes,\n IGitContentTransformationParser,\n IGitContentTransformationParserInput,\n IGitContentTransformationParserResult,\n} from './types.js';\n\ninterface IMutableAttributeValues {\n filter?: string;\n ident?: string;\n workingTreeEncoding?: string;\n}\n\n/** Concatenates one complete NUL-delimited field assembled across process chunks. */\nconst concatenateField = (fragments: readonly Uint8Array[], byteLength: number): Uint8Array => {\n const field = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const fragment of fragments) {\n field.set(fragment, offset);\n offset += fragment.byteLength;\n }\n\n return field;\n};\n\n/** Decodes one Git attribute field as strict UTF-8 while preserving an initial BOM scalar. */\nconst decodeField = (field: Uint8Array): string | null => {\n try {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(field);\n } catch {\n return null;\n }\n};\n\n/** Resolves one exact supported attribute name without accepting aliases. */\nconst resolveAttribute = (candidate: string): IGitContentTransformationAttribute | null => {\n return GIT_CONTENT_TRANSFORMATION_ATTRIBUTES.find((attribute) => attribute === candidate) ?? null;\n};\n\n/** Stores one exact Git value while rejecting duplicate attribute records. */\nconst storeAttribute = (\n values: IMutableAttributeValues,\n attribute: IGitContentTransformationAttribute,\n value: string,\n): boolean => {\n const property = attribute === 'working-tree-encoding' ? 'workingTreeEncoding' : attribute;\n\n if (Object.hasOwn(values, property)) {\n return false;\n }\n\n values[property] = value;\n return true;\n};\n\n/** Confirms that all three required effective attribute values were received. */\nconst hasCompleteValues = (\n values: IMutableAttributeValues,\n): values is IGitContentTransformationAttributeValues =>\n Object.hasOwn(values, 'filter') &&\n Object.hasOwn(values, 'ident') &&\n Object.hasOwn(values, 'workingTreeEncoding');\n\n/**\n * Creates a strict parser for NUL-delimited `git check-attr` triples.\n * @param input The exact paths whose three effective attributes must be present.\n * @returns An incremental all-or-nothing parser.\n */\nexport const createGitContentTransformationParser = (\n input: IGitContentTransformationParserInput,\n): IGitContentTransformationParser => {\n const paths = [...input.paths];\n const valuesByPath = new Map<string, IMutableAttributeValues>();\n let fields: Uint8Array[] = [];\n let isFailed = false;\n let pendingByteLength = 0;\n let pendingFragments: Uint8Array[] = [];\n\n for (const path of paths) {\n if (path.length === 0 || path.includes('\\u0000') || valuesByPath.has(path)) {\n isFailed = true;\n continue;\n }\n\n valuesByPath.set(path, {});\n }\n\n const consumeRecord = (): void => {\n if (isFailed || fields.length !== 3) {\n return;\n }\n\n const path = decodeField(fields[0] ?? new Uint8Array());\n const attributeCandidate = decodeField(fields[1] ?? new Uint8Array());\n const value = decodeField(fields[2] ?? new Uint8Array());\n\n fields = [];\n\n if (path === null || attributeCandidate === null || value === null) {\n isFailed = true;\n return;\n }\n\n const attribute = resolveAttribute(attributeCandidate);\n const values = valuesByPath.get(path);\n\n if (attribute === null || values === undefined || !storeAttribute(values, attribute, value)) {\n isFailed = true;\n }\n };\n\n const consumeField = (): void => {\n if (isFailed) {\n return;\n }\n\n fields.push(concatenateField(pendingFragments, pendingByteLength));\n pendingByteLength = 0;\n pendingFragments = [];\n\n if (fields.length === 3) {\n consumeRecord();\n }\n };\n\n return {\n consume: (chunk): void => {\n if (isFailed) {\n return;\n }\n\n let fragmentStart = 0;\n\n for (let index = 0; index < chunk.byteLength; index += 1) {\n if (chunk[index] !== 0x00) {\n continue;\n }\n\n const fragment = chunk.subarray(fragmentStart, index);\n\n pendingFragments.push(Uint8Array.from(fragment));\n pendingByteLength += fragment.byteLength;\n consumeField();\n\n if (isFailed) {\n return;\n }\n\n fragmentStart = index + 1;\n }\n\n const trailingFragment = chunk.subarray(fragmentStart);\n\n if (trailingFragment.byteLength > 0) {\n pendingFragments.push(Uint8Array.from(trailingFragment));\n pendingByteLength += trailingFragment.byteLength;\n }\n },\n finish: (): IGitContentTransformationParserResult => {\n if (isFailed || pendingByteLength > 0 || fields.length > 0) {\n return Object.freeze({ kind: 'failed' });\n }\n\n const attributes: IGitContentTransformationParsedAttributes[] = [];\n\n for (const path of paths) {\n const values = valuesByPath.get(path);\n\n if (values === undefined || !hasCompleteValues(values)) {\n return Object.freeze({ kind: 'failed' });\n }\n\n attributes.push(\n Object.freeze({\n filter: values.filter,\n ident: values.ident,\n path,\n workingTreeEncoding: values.workingTreeEncoding,\n }),\n );\n }\n\n return Object.freeze({ attributes: Object.freeze(attributes), kind: 'completed' });\n },\n };\n};\n","import {\n executeGitStreamingProcess,\n MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n type IGitStreamingProcessExecutor,\n type IGitStreamingProcessFailureReason,\n} from '../../git-process/index.js';\nimport type { IGitInventoryProbeErrorCode } from '../types.js';\n\nimport { GIT_CONTENT_TRANSFORMATION_ARGUMENTS } from './constants.js';\nimport { createGitContentTransformationParser } from './parser.js';\nimport type {\n IGitContentTransformationClassification,\n IGitContentTransformationClassificationFailedResult,\n IGitContentTransformationClassificationResult,\n IGitContentTransformationClassifier,\n} from './types.js';\n\n/** Creates one immutable content-transformation classification failure. */\nconst createClassificationFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitContentTransformationClassificationFailedResult =>\n Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps one bounded Git attribute failure to the existing safe inventory contract. */\nconst mapGitProcessFailure = (\n reason: IGitStreamingProcessFailureReason,\n): IGitInventoryProbeErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'repository-not-found':\n return 'GIT_REPOSITORY_NOT_FOUND';\n case 'output-limit-exceeded':\n case 'stdout-limit-exceeded':\n return 'RESOURCE_LIMIT_EXCEEDED';\n case 'stderr-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Determines whether one effective attribute value requires guarded reads. */\nconst isGuardedAttributeValue = (attributeValue: string): boolean =>\n attributeValue !== 'unset' && attributeValue !== 'unspecified';\n\n/** Encodes exact Git-relative paths as NUL-delimited stdin without shell interpretation. */\nconst encodePaths = (paths: readonly string[]): Uint8Array | null => {\n const encoder = new TextEncoder();\n const encodedPaths: Uint8Array[] = [];\n let byteLength = 0;\n\n for (const path of paths) {\n if (path.length === 0 || path.includes('\\u0000')) {\n return null;\n }\n\n const encodedPath = encoder.encode(path);\n\n if (!Number.isSafeInteger(byteLength + encodedPath.byteLength + 1)) {\n return null;\n }\n\n encodedPaths.push(encodedPath);\n byteLength += encodedPath.byteLength + 1;\n }\n\n const stdin = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const encodedPath of encodedPaths) {\n stdin.set(encodedPath, offset);\n offset += encodedPath.byteLength + 1;\n }\n\n return stdin;\n};\n\n/** Builds the exact retained classification and its conservative read guard. */\nconst createClassification = (\n filter: string,\n ident: string,\n workingTreeEncoding: string,\n): IGitContentTransformationClassification =>\n Object.freeze({\n filter,\n ident,\n isGuarded:\n isGuardedAttributeValue(filter) ||\n isGuardedAttributeValue(ident) ||\n isGuardedAttributeValue(workingTreeEncoding),\n workingTreeEncoding,\n });\n\n/**\n * Creates the effective Git content-transformation classifier around a process boundary.\n * @param processExecutor The sanitized streamed Git process executor.\n * @returns An all-or-nothing bounded classifier for effective inventory entries.\n */\nexport const createGitContentTransformationClassifier = (\n processExecutor: IGitStreamingProcessExecutor = executeGitStreamingProcess,\n): IGitContentTransformationClassifier => {\n return async (input): Promise<IGitContentTransformationClassificationResult> => {\n if (input.signal?.aborted) {\n return createClassificationFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) {\n return createClassificationFailure('RESOURCE_LIMIT_EXCEEDED');\n }\n\n if (input.entries.length === 0) {\n return Object.freeze({ entries: Object.freeze([]), gitMetadataBytes: 0, kind: 'classified' });\n }\n\n const paths = input.entries.map((entry) => entry.path);\n const stdin = encodePaths(paths);\n\n if (stdin === null) {\n return createClassificationFailure('GIT_OUTPUT_INVALID');\n }\n\n const parser = createGitContentTransformationParser({ paths });\n let consumedStdoutBytes = 0;\n const processResult = await processExecutor({\n arguments: ['-C', input.repositoryRoot, ...GIT_CONTENT_TRANSFORMATION_ARGUMENTS],\n consumeStdout: (chunk): void => {\n consumedStdoutBytes += chunk.byteLength;\n parser.consume(chunk);\n },\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: input.maxMetadataBytes,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n stdin,\n });\n\n if (processResult.kind === 'failed') {\n return createClassificationFailure(mapGitProcessFailure(processResult.reason));\n }\n\n if (\n processResult.stderr.byteLength > 0 ||\n processResult.stdoutBytes !== consumedStdoutBytes ||\n processResult.stdoutBytes > input.maxMetadataBytes\n ) {\n return createClassificationFailure('GIT_OUTPUT_INVALID');\n }\n\n const parserResult = parser.finish();\n\n if (parserResult.kind === 'failed' || parserResult.attributes.length !== input.entries.length) {\n return createClassificationFailure('GIT_OUTPUT_INVALID');\n }\n\n const entries = input.entries.map((entry, index) => {\n const attributes = parserResult.attributes[index];\n\n if (attributes === undefined || attributes.path !== entry.path) {\n return null;\n }\n\n return Object.freeze({\n ...entry,\n contentTransformation: createClassification(\n attributes.filter,\n attributes.ident,\n attributes.workingTreeEncoding,\n ),\n });\n });\n\n if (entries.some((entry) => entry === null)) {\n return createClassificationFailure('GIT_OUTPUT_INVALID');\n }\n\n return Object.freeze({\n entries: Object.freeze(entries.filter((entry) => entry !== null)),\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'classified',\n });\n };\n};\n\n// default effective Git content-transformation classifier used by inventory probing\nexport const classifyGitContentTransformations = createGitContentTransformationClassifier();\n","import type { IGitInventoryCandidate } from '../types.js';\n\nimport type {\n ICollapsedGitInventoryCandidate,\n IGitInventoryCandidateCollapseResult,\n IGitInventoryIndexEntry,\n} from './types.js';\n\ninterface IMutableTrackedCandidate {\n readonly indexEntriesByStage: Map<number, IGitInventoryIndexEntry>;\n readonly kind: 'tracked';\n readonly path: string;\n}\n\ninterface IMutableUntrackedCandidate {\n readonly kind: 'untracked';\n readonly path: string;\n}\n\ntype IMutableCollapsedCandidate = IMutableTrackedCandidate | IMutableUntrackedCandidate;\n\n/** Creates one immutable invalid candidate-collapse result. */\nconst createCollapseFailure = (): IGitInventoryCandidateCollapseResult =>\n Object.freeze({ kind: 'failed' });\n\n/**\n * Collapses raw stage records into one deterministic candidate per exact Git path.\n * @param candidates The ownership-filtered raw candidates to collapse.\n * @returns An immutable candidate set, or failure for duplicate or contradictory state.\n */\nexport const collapseGitInventoryCandidates = (\n candidates: readonly IGitInventoryCandidate[],\n): IGitInventoryCandidateCollapseResult => {\n const candidatesByPath = new Map<string, IMutableCollapsedCandidate>();\n\n for (const candidate of candidates) {\n const existingCandidate = candidatesByPath.get(candidate.path);\n\n if (candidate.kind === 'untracked') {\n if (existingCandidate !== undefined) {\n return createCollapseFailure();\n }\n\n candidatesByPath.set(candidate.path, { kind: 'untracked', path: candidate.path });\n continue;\n }\n\n if (candidate.mode === '160000' || existingCandidate?.kind === 'untracked') {\n return createCollapseFailure();\n }\n\n const trackedCandidate = existingCandidate ?? {\n indexEntriesByStage: new Map<number, IGitInventoryIndexEntry>(),\n kind: 'tracked' as const,\n path: candidate.path,\n };\n\n if (trackedCandidate.indexEntriesByStage.has(candidate.stage)) {\n return createCollapseFailure();\n }\n\n trackedCandidate.indexEntriesByStage.set(\n candidate.stage,\n Object.freeze({ mode: candidate.mode, stage: candidate.stage }),\n );\n candidatesByPath.set(candidate.path, trackedCandidate);\n }\n\n const collapsedCandidates: ICollapsedGitInventoryCandidate[] = [];\n\n for (const candidate of candidatesByPath.values()) {\n if (candidate.kind === 'untracked') {\n collapsedCandidates.push(Object.freeze(candidate));\n continue;\n }\n\n const hasStageZero = candidate.indexEntriesByStage.has(0);\n\n if (hasStageZero && candidate.indexEntriesByStage.size !== 1) {\n return createCollapseFailure();\n }\n\n const indexEntries = [...candidate.indexEntriesByStage.values()].sort(\n (left, right) => left.stage - right.stage,\n );\n\n if (indexEntries.length === 0) {\n return createCollapseFailure();\n }\n\n collapsedCandidates.push(\n Object.freeze({\n indexEntries: Object.freeze(indexEntries),\n kind: 'tracked',\n path: candidate.path,\n }),\n );\n }\n\n return Object.freeze({ candidates: Object.freeze(collapsedCandidates), kind: 'collapsed' });\n};\n","import { lstat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { IGitInventoryProbeErrorCode } from '../types.js';\n\nimport type {\n IGitInventoryEntryInspector,\n IGitInventoryEntryLstat,\n IGitInventoryHostEntryInspectionFailedResult,\n IGitInventoryHostEntryInspectionResult,\n} from './types.js';\n\n/** Creates one immutable host entry inspection failure. */\nconst createInspectionFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitInventoryHostEntryInspectionFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps an unknown no-follow filesystem failure without retaining host diagnostics. */\nconst mapFilesystemFailure = (\n error: unknown,\n): IGitInventoryHostEntryInspectionFailedResult | null => {\n const errorCode = (error as NodeJS.ErrnoException | null)?.code?.toUpperCase();\n\n if (errorCode === 'ENOENT' || errorCode === 'ENOTDIR') {\n return null;\n }\n\n if (errorCode === 'EACCES' || errorCode === 'EPERM') {\n return createInspectionFailure('GIT_ACCESS_DENIED');\n }\n\n if (errorCode === 'ELOOP') {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n return createInspectionFailure('GIT_COMMAND_FAILED');\n};\n\n/** Default no-follow stat boundary for current inventory entries. */\nconst inspectHostEntry: IGitInventoryEntryLstat = async (hostPath) => lstat(hostPath);\n\n/**\n * Creates current host entry inspection around an injectable no-follow stat boundary.\n * @param inspectEntry The no-follow filesystem stat operation.\n * @returns An inspector for one ownership-filtered candidate path.\n */\nexport const createGitInventoryEntryInspector = (\n inspectEntry: IGitInventoryEntryLstat = inspectHostEntry,\n): IGitInventoryEntryInspector => {\n return async (repositoryRoot, candidatePath): Promise<IGitInventoryHostEntryInspectionResult> => {\n let statistics: Awaited<ReturnType<IGitInventoryEntryLstat>>;\n\n try {\n statistics = await inspectEntry(path.join(repositoryRoot, candidatePath));\n } catch (error) {\n const failure = mapFilesystemFailure(error);\n\n return failure ?? Object.freeze({ kind: 'missing' });\n }\n\n if (statistics.isSymbolicLink()) {\n return Object.freeze({ entryType: 'symlink', kind: 'inspected' });\n }\n\n if (statistics.isFile()) {\n return Object.freeze({ entryType: 'file', kind: 'inspected' });\n }\n\n return Object.freeze({ entryType: 'unsupported', kind: 'inspected' });\n };\n};\n\n// default no-follow current host entry inspector\nexport const inspectGitInventoryEntry = createGitInventoryEntryInspector();\n","// fixed read-only query for the effective selected-repository symlink behavior\nexport const GIT_SYMLINK_CONFIGURATION_ARGUMENTS = [\n 'config',\n '--type=bool',\n '--default=true',\n '--get',\n 'core.symlinks',\n] as const;\n","import {\n executeGitStreamingProcess,\n MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n type IGitStreamingProcessExecutor,\n type IGitStreamingProcessFailureReason,\n} from '../../git-process/index.js';\nimport { parseGitBooleanOutput } from '../../git-working-tree/index.js';\nimport type { IGitInventoryProbeErrorCode } from '../types.js';\n\nimport { GIT_SYMLINK_CONFIGURATION_ARGUMENTS } from './constants.js';\nimport type {\n IGitSymlinkConfigurationFailedResult,\n IGitSymlinkConfigurationResolver,\n IGitSymlinkConfigurationResult,\n} from './types.js';\n\n/** Creates one immutable effective symlink configuration failure. */\nconst createConfigurationFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitSymlinkConfigurationFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps one bounded Git configuration failure to the existing safe CLI contract. */\nconst mapGitProcessFailure = (\n reason: IGitStreamingProcessFailureReason,\n): IGitInventoryProbeErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'output-limit-exceeded':\n case 'stdout-limit-exceeded':\n return 'RESOURCE_LIMIT_EXCEEDED';\n case 'repository-not-found':\n case 'stderr-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Concatenates already bounded Git stdout chunks for strict boolean parsing. */\nconst concatenateChunks = (chunks: readonly Uint8Array[], byteLength: number): Uint8Array => {\n const output = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const chunk of chunks) {\n output.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return output;\n};\n\n/**\n * Creates the bounded effective core.symlinks resolver around a Git process boundary.\n * @param processExecutor The sanitized streamed Git process executor.\n * @returns A resolver for the selected repository's effective symlink behavior.\n */\nexport const createGitSymlinkConfigurationResolver = (\n processExecutor: IGitStreamingProcessExecutor = executeGitStreamingProcess,\n): IGitSymlinkConfigurationResolver => {\n return async (input): Promise<IGitSymlinkConfigurationResult> => {\n if (input.signal?.aborted) {\n return createConfigurationFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) {\n return createConfigurationFailure('RESOURCE_LIMIT_EXCEEDED');\n }\n\n const stdoutChunks: Uint8Array[] = [];\n let consumedStdoutBytes = 0;\n const processResult = await processExecutor({\n arguments: ['-C', input.repositoryRoot, ...GIT_SYMLINK_CONFIGURATION_ARGUMENTS],\n consumeStdout: (chunk): void => {\n stdoutChunks.push(Uint8Array.from(chunk));\n consumedStdoutBytes += chunk.byteLength;\n },\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: input.maxMetadataBytes,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (processResult.kind === 'failed') {\n return createConfigurationFailure(mapGitProcessFailure(processResult.reason));\n }\n\n if (\n processResult.stderr.byteLength > 0 ||\n processResult.stdoutBytes !== consumedStdoutBytes ||\n processResult.stdoutBytes > input.maxMetadataBytes\n ) {\n return createConfigurationFailure('GIT_OUTPUT_INVALID');\n }\n\n const isEnabled = parseGitBooleanOutput(concatenateChunks(stdoutChunks, consumedStdoutBytes));\n\n if (isEnabled === null) {\n return createConfigurationFailure('GIT_OUTPUT_INVALID');\n }\n\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n isEnabled,\n kind: 'resolved',\n });\n };\n};\n\n// default bounded effective core.symlinks resolver\nexport const resolveGitSymlinkConfiguration = createGitSymlinkConfigurationResolver();\n","import { collapseGitInventoryCandidates } from './candidate-collapser.js';\nimport { inspectGitInventoryEntry } from './entry-inspector.js';\nimport { resolveGitSymlinkConfiguration } from './symlink-configuration.js';\nimport type {\n ICollapsedGitTrackedInventoryCandidate,\n IGitEntryTypeNormalizedEntry,\n IGitInventoryEntryInspector,\n IGitInventoryEntryTypeNormalizationFailedResult,\n IGitInventoryEntryTypeNormalizationResult,\n IGitInventoryEntryTypeNormalizer,\n IGitSymlinkConfigurationResolver,\n} from './types.js';\n\n/** Creates one immutable entry-type normalization failure. */\nconst createNormalizationFailure = (\n errorCode: IGitInventoryEntryTypeNormalizationFailedResult['errorCode'],\n): IGitInventoryEntryTypeNormalizationFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Determines whether retained index metadata contains a Git symlink mode. */\nconst hasSymlinkMode = (candidate: ICollapsedGitTrackedInventoryCandidate): boolean =>\n candidate.indexEntries.some(({ mode }) => mode === '120000');\n\n/** Determines whether retained index metadata contains a Git regular-file mode. */\nconst hasRegularFileMode = (candidate: ICollapsedGitTrackedInventoryCandidate): boolean =>\n candidate.indexEntries.some(({ mode }) => mode === '100644' || mode === '100755');\n\n/**\n * Creates entry-type normalization around injectable filesystem and Git configuration boundaries.\n * @param entryInspector The no-follow current host entry inspector.\n * @param symlinkConfigurationResolver The bounded effective core.symlinks resolver.\n * @returns An all-or-nothing effective working-tree entry normalizer.\n */\nexport const createGitInventoryEntryTypeNormalizer = (\n entryInspector: IGitInventoryEntryInspector = inspectGitInventoryEntry,\n symlinkConfigurationResolver: IGitSymlinkConfigurationResolver = resolveGitSymlinkConfiguration,\n): IGitInventoryEntryTypeNormalizer => {\n return async (input): Promise<IGitInventoryEntryTypeNormalizationResult> => {\n if (input.signal?.aborted) {\n return createNormalizationFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!Number.isSafeInteger(input.maxMetadataBytes) || input.maxMetadataBytes < 0) {\n return createNormalizationFailure('RESOURCE_LIMIT_EXCEEDED');\n }\n\n const collapseResult = collapseGitInventoryCandidates(input.candidates);\n\n if (collapseResult.kind === 'failed') {\n return createNormalizationFailure('GIT_OUTPUT_INVALID');\n }\n\n const entries: IGitEntryTypeNormalizedEntry[] = [];\n let symlinkConfiguration: Awaited<ReturnType<IGitSymlinkConfigurationResolver>> | null = null;\n\n for (const candidate of collapseResult.candidates) {\n if (input.signal?.aborted) {\n return createNormalizationFailure('GIT_OPERATION_ABORTED');\n }\n\n const inspectionResult = await entryInspector(input.repositoryRoot, candidate.path);\n\n if (input.signal?.aborted) {\n return createNormalizationFailure('GIT_OPERATION_ABORTED');\n }\n\n if (inspectionResult.kind === 'failed') {\n return inspectionResult;\n }\n\n if (inspectionResult.kind === 'missing') {\n continue;\n }\n\n if (inspectionResult.entryType === 'unsupported') {\n return createNormalizationFailure('GIT_OUTPUT_INVALID');\n }\n\n if (candidate.kind === 'untracked') {\n entries.push(\n Object.freeze({\n entryType: inspectionResult.entryType,\n kind: 'untracked',\n path: candidate.path,\n requiresSymlinkOverlay: false,\n }),\n );\n continue;\n }\n\n if (inspectionResult.entryType === 'symlink' || !hasSymlinkMode(candidate)) {\n entries.push(\n Object.freeze({\n entryType: inspectionResult.entryType,\n indexEntries: candidate.indexEntries,\n kind: 'tracked',\n path: candidate.path,\n requiresSymlinkOverlay: false,\n }),\n );\n continue;\n }\n\n symlinkConfiguration ??= await symlinkConfigurationResolver({\n maxMetadataBytes: input.maxMetadataBytes,\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (symlinkConfiguration.kind === 'failed') {\n return symlinkConfiguration;\n }\n\n if (\n !Number.isSafeInteger(symlinkConfiguration.gitMetadataBytes) ||\n symlinkConfiguration.gitMetadataBytes < 0 ||\n symlinkConfiguration.gitMetadataBytes > input.maxMetadataBytes\n ) {\n return createNormalizationFailure('GIT_OUTPUT_INVALID');\n }\n\n if (!symlinkConfiguration.isEnabled && hasRegularFileMode(candidate)) {\n return createNormalizationFailure('GIT_OUTPUT_INVALID');\n }\n\n const requiresSymlinkOverlay = !symlinkConfiguration.isEnabled;\n\n entries.push(\n Object.freeze({\n entryType: requiresSymlinkOverlay ? 'symlink' : 'file',\n indexEntries: candidate.indexEntries,\n kind: 'tracked',\n path: candidate.path,\n requiresSymlinkOverlay,\n }),\n );\n }\n\n return Object.freeze({\n entries: Object.freeze(entries),\n gitMetadataBytes:\n symlinkConfiguration?.kind === 'resolved' ? symlinkConfiguration.gitMetadataBytes : 0,\n kind: 'normalized',\n });\n };\n};\n\n// default effective working-tree entry-type normalizer\nexport const normalizeGitInventoryEntryTypes = createGitInventoryEntryTypeNormalizer();\n","import { isRepositoryPath, type IRepositoryPath } from '@moldea.ai/repository';\n\nimport type {\n IGitInventoryCandidateLogicalPathValidationResult,\n IGitInventoryCandidateLogicalPathValidatorInput,\n IGitInventoryEntry,\n IGitInventoryLogicalPathFailedResult,\n IGitInventoryLogicalPathCandidate,\n IGitInventoryLogicalPathNormalizationResult,\n IGitInventoryLogicalPathNormalizer,\n} from './types.js';\n\n/** Creates one immutable invalid logical-path result. */\nconst createLogicalPathFailure = (): IGitInventoryLogicalPathFailedResult =>\n Object.freeze({ errorCode: 'GIT_OUTPUT_INVALID', kind: 'failed' });\n\n/** Converts one Git-relative path into a validated repository logical path. */\nconst resolveRepositoryPath = (gitPath: string): IRepositoryPath | null => {\n const logicalPath = `/${gitPath}`;\n\n return logicalPath !== '/' && isRepositoryPath(logicalPath) ? logicalPath : null;\n};\n\n/** Resolves the logical path represented by one Git candidate record. */\nconst resolveCandidateRepositoryPath = (\n candidate: IGitInventoryLogicalPathCandidate,\n): IRepositoryPath | null => {\n const gitPath =\n candidate.kind === 'untracked' && candidate.path.endsWith('/')\n ? candidate.path.slice(0, -1)\n : candidate.path;\n\n return resolveRepositoryPath(gitPath);\n};\n\n/** Compares repository paths by exact Unicode code-point order. */\nconst compareRepositoryPaths = (left: IRepositoryPath, right: IRepositoryPath): number => {\n const leftScalars = left[Symbol.iterator]();\n const rightScalars = right[Symbol.iterator]();\n\n while (true) {\n const leftScalar = leftScalars.next();\n const rightScalar = rightScalars.next();\n\n if (leftScalar.done === true) {\n return rightScalar.done === true ? 0 : -1;\n }\n\n if (rightScalar.done === true) {\n return 1;\n }\n\n const leftCodePoint = leftScalar.value.codePointAt(0) ?? 0;\n const rightCodePoint = rightScalar.value.codePointAt(0) ?? 0;\n\n if (leftCodePoint !== rightCodePoint) {\n return leftCodePoint < rightCodePoint ? -1 : 1;\n }\n }\n};\n\n/**\n * Validates every decoded Git candidate before ownership or filesystem exclusions.\n * @param input The complete decoded tracked and untracked candidate set.\n * @returns A validated result, or failure when any candidate is not portable.\n */\nexport const validateGitInventoryCandidateLogicalPaths = (\n input: IGitInventoryCandidateLogicalPathValidatorInput,\n): IGitInventoryCandidateLogicalPathValidationResult => {\n for (const candidate of input.candidates) {\n if (resolveCandidateRepositoryPath(candidate) === null) {\n return createLogicalPathFailure();\n }\n }\n\n return Object.freeze({ kind: 'validated' });\n};\n\n/**\n * Converts Git-relative inventory entries into exact repository logical paths.\n * @param input The entry-type-normalized Git-relative inventory.\n * @returns An immutable code-point-sorted inventory, or failure for invalid path state.\n */\nexport const normalizeGitInventoryLogicalPaths: IGitInventoryLogicalPathNormalizer = (\n input,\n): IGitInventoryLogicalPathNormalizationResult => {\n const entries: IGitInventoryEntry[] = [];\n const logicalPaths = new Set<IRepositoryPath>();\n\n for (const entry of input.entries) {\n const logicalPath = resolveRepositoryPath(entry.path);\n\n if (logicalPath === null || logicalPaths.has(logicalPath)) {\n return createLogicalPathFailure();\n }\n\n logicalPaths.add(logicalPath);\n entries.push(Object.freeze({ ...entry, path: logicalPath }));\n }\n\n entries.sort((left, right) => compareRepositoryPaths(left.path, right.path));\n\n return Object.freeze({ entries: Object.freeze(entries), kind: 'normalized' });\n};\n","import type {\n IGitInventoryCandidate,\n IGitInventoryParser,\n IGitInventoryParserFailureReason,\n IGitInventoryParserResult,\n IGitTrackedEntryMode,\n IGitTrackedEntryStage,\n IGitTrackedInventoryCandidate,\n IGitUntrackedInventoryCandidate,\n} from './types.js';\n\nconst TRACKED_ENTRY_HEADER_PATTERN =\n /^(100644|100755|120000|160000) (?:[0-9a-f]{40}|[0-9a-f]{64}) ([0-3])$/u;\n\n/** Decodes one complete Git path as strict UTF-8 while preserving an initial BOM scalar. */\nconst decodeGitPath = (pathBytes: Uint8Array): string | null => {\n if (pathBytes.byteLength === 0) {\n return null;\n }\n\n try {\n return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(pathBytes);\n } catch {\n return null;\n }\n};\n\n/** Confirms that one decoded path contains only complete Unicode scalar values. */\nconst hasOnlyUnicodeScalarValues = (path: string): boolean => {\n for (let index = 0; index < path.length; index += 1) {\n const codeUnit = path.charCodeAt(index);\n\n if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {\n const trailingCodeUnit = path.charCodeAt(index + 1);\n\n if (trailingCodeUnit < 0xdc00 || trailingCodeUnit > 0xdfff) {\n return false;\n }\n\n index += 1;\n continue;\n }\n\n if (codeUnit >= 0xdc00 && codeUnit <= 0xdfff) {\n return false;\n }\n }\n\n return true;\n};\n\n/** Concatenates one complete record assembled across arbitrary process chunks. */\nconst concatenateRecord = (fragments: readonly Uint8Array[], byteLength: number): Uint8Array => {\n const record = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const fragment of fragments) {\n record.set(fragment, offset);\n offset += fragment.byteLength;\n }\n\n return record;\n};\n\n/** Parses one tracked `ls-files --stage` record without normalizing its path. */\nconst parseTrackedCandidate = (record: Uint8Array): IGitTrackedInventoryCandidate | null => {\n const separatorIndex = record.indexOf(0x09);\n\n if (separatorIndex <= 0 || separatorIndex === record.byteLength - 1) {\n return null;\n }\n\n let header: string;\n\n try {\n header = new TextDecoder('utf-8', { fatal: true }).decode(record.subarray(0, separatorIndex));\n } catch {\n return null;\n }\n\n const headerMatch = TRACKED_ENTRY_HEADER_PATTERN.exec(header);\n const path = decodeGitPath(record.subarray(separatorIndex + 1));\n\n if (headerMatch === null || path === null || !hasOnlyUnicodeScalarValues(path)) {\n return null;\n }\n\n return Object.freeze({\n kind: 'tracked',\n mode: headerMatch[1] as IGitTrackedEntryMode,\n path,\n stage: Number(headerMatch[2]) as IGitTrackedEntryStage,\n });\n};\n\n/** Parses one untracked `ls-files --others` record without normalizing its path. */\nconst parseUntrackedCandidate = (record: Uint8Array): IGitUntrackedInventoryCandidate | null => {\n const path = decodeGitPath(record);\n\n if (path === null || !hasOnlyUnicodeScalarValues(path)) {\n return null;\n }\n\n return Object.freeze({ kind: 'untracked', path });\n};\n\n/** Creates a strict incremental parser for one NUL-delimited Git record grammar. */\nconst createGitInventoryParser = <TCandidate extends IGitInventoryCandidate>(\n maxEntries: number,\n parseCandidate: (record: Uint8Array) => TCandidate | null,\n): IGitInventoryParser<TCandidate> => {\n const candidates: TCandidate[] = [];\n let failureReason: IGitInventoryParserFailureReason | null = null;\n let pendingByteLength = 0;\n let pendingFragments: Uint8Array[] = [];\n\n const consumeRecord = (): void => {\n if (failureReason !== null) {\n return;\n }\n\n if (candidates.length >= maxEntries) {\n failureReason = 'entry-limit-exceeded';\n pendingByteLength = 0;\n pendingFragments = [];\n return;\n }\n\n const candidate = parseCandidate(concatenateRecord(pendingFragments, pendingByteLength));\n\n pendingByteLength = 0;\n pendingFragments = [];\n\n if (candidate === null) {\n failureReason = 'invalid';\n return;\n }\n\n candidates.push(candidate);\n };\n\n return {\n consume: (chunk): void => {\n if (failureReason !== null) {\n return;\n }\n\n let fragmentStart = 0;\n\n for (let index = 0; index < chunk.byteLength; index += 1) {\n if (chunk[index] !== 0x00) {\n continue;\n }\n\n const fragment = chunk.subarray(fragmentStart, index);\n\n pendingFragments.push(fragment);\n pendingByteLength += fragment.byteLength;\n consumeRecord();\n\n if (failureReason !== null) {\n return;\n }\n\n fragmentStart = index + 1;\n }\n\n const trailingFragment = chunk.subarray(fragmentStart);\n\n if (trailingFragment.byteLength > 0) {\n pendingFragments.push(trailingFragment);\n pendingByteLength += trailingFragment.byteLength;\n }\n },\n finish: (): IGitInventoryParserResult<TCandidate> => {\n if (failureReason === null && pendingByteLength > 0) {\n failureReason = 'invalid';\n }\n\n if (failureReason !== null) {\n return Object.freeze({ kind: 'failed', reason: failureReason });\n }\n\n return Object.freeze({ candidates: Object.freeze([...candidates]), kind: 'completed' });\n },\n };\n};\n\n/** Creates a strict incremental parser for tracked Git inventory output. */\nexport const createTrackedGitInventoryParser = (\n maxEntries: number,\n): IGitInventoryParser<IGitTrackedInventoryCandidate> =>\n createGitInventoryParser(maxEntries, parseTrackedCandidate);\n\n/** Creates a strict incremental parser for untracked Git inventory output. */\nexport const createUntrackedGitInventoryParser = (\n maxEntries: number,\n): IGitInventoryParser<IGitUntrackedInventoryCandidate> =>\n createGitInventoryParser(maxEntries, parseUntrackedCandidate);\n","import { Buffer } from 'node:buffer';\nimport { lstat, readdir } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {\n executeGitStreamingProcess,\n MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n type IGitStreamingProcessExecutor,\n type IGitStreamingProcessFailureReason,\n} from '../../git-process/index.js';\nimport { parseGitAbsolutePathOutput } from '../../git-working-tree/index.js';\nimport {\n areHostPathsEquivalent,\n haveSameHostPathIdentity,\n} from '../../host-path-identity/index.js';\nimport type { IGitInventoryProbeErrorCode } from '../types.js';\n\nimport type {\n IGitInventoryBoundaryInspectedResult,\n IGitInventoryBoundaryInspectionFailedResult,\n IGitInventoryBoundaryInspectionResult,\n IGitInventoryBoundaryInspector,\n IGitInventoryBoundaryOwnership,\n IGitInventoryOwnershipLstat,\n IGitInventoryOwnershipReadDirectory,\n IGitInventoryOwnershipStatistics,\n} from './types.js';\n\nconst GIT_CONTROL_SEGMENT = '.git';\nconst GIT_REPOSITORY_ROOT_ARGUMENTS = ['rev-parse', '--show-toplevel'] as const;\n\ninterface IGitInventoryDirectoryObservation {\n readonly encodedNameKeys: ReadonlySet<string>;\n readonly hostPath: string;\n readonly ownership: IGitInventoryBoundaryOwnership;\n}\n\ninterface IGitInventoryDirectoryReadResult {\n readonly encodedNameKeys: ReadonlySet<string>;\n readonly kind: 'read';\n}\n\ninterface IGitInventoryPathInspectedResult {\n readonly kind: 'inspected';\n readonly statistics: IGitInventoryOwnershipStatistics;\n}\n\ntype IGitInventoryDirectoryReadAttempt =\n IGitInventoryBoundaryInspectionFailedResult | IGitInventoryDirectoryReadResult;\n\ntype IGitInventoryPathInspectionAttempt =\n IGitInventoryBoundaryInspectionFailedResult | IGitInventoryPathInspectedResult;\n\ninterface IGitInventoryBoundaryValidationResult {\n readonly gitMetadataBytes: number;\n readonly kind: 'validated';\n readonly ownership: IGitInventoryBoundaryOwnership;\n}\n\ntype IGitInventoryBoundaryValidationAttempt =\n IGitInventoryBoundaryInspectionFailedResult | IGitInventoryBoundaryValidationResult;\n\n/** Identifies one safe inspection failure in a filesystem result union. */\nconst isInspectionFailure = (\n result: IGitInventoryBoundaryInspectionFailedResult | IGitInventoryDirectoryObservation,\n): result is IGitInventoryBoundaryInspectionFailedResult => 'kind' in result;\n\n/** Creates one immutable ownership-inspection failure. */\nconst createInspectionFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitInventoryBoundaryInspectionFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps an unknown filesystem failure without retaining host diagnostics. */\nconst mapFilesystemFailure = (error: unknown): IGitInventoryProbeErrorCode => {\n const errorCode = (error as NodeJS.ErrnoException | null)?.code?.toUpperCase();\n\n if (errorCode === 'EACCES' || errorCode === 'EPERM') {\n return 'GIT_ACCESS_DENIED';\n }\n\n if (errorCode === 'ENOENT' || errorCode === 'ENOTDIR' || errorCode === 'ELOOP') {\n return 'GIT_OUTPUT_INVALID';\n }\n\n return 'GIT_COMMAND_FAILED';\n};\n\n/** Maps a streamed nested-root check failure into the existing safe CLI contract. */\nconst mapGitProcessFailure = (\n reason: IGitStreamingProcessFailureReason,\n): IGitInventoryProbeErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'output-limit-exceeded':\n case 'stdout-limit-exceeded':\n return 'RESOURCE_LIMIT_EXCEEDED';\n case 'repository-not-found':\n case 'stderr-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Reads one directory as native names without decoding unrelated entries. */\nconst readDirectoryNames = async (\n hostPath: string,\n readDirectory: IGitInventoryOwnershipReadDirectory,\n): Promise<IGitInventoryDirectoryReadAttempt> => {\n try {\n const encodedNames = await readDirectory(hostPath);\n\n return Object.freeze({\n encodedNameKeys: new Set(encodedNames.map((encodedName) => encodedName.toString('hex'))),\n kind: 'read',\n });\n } catch (error) {\n return createInspectionFailure(mapFilesystemFailure(error));\n }\n};\n\n/** Captures one path without following its final filesystem entry. */\nconst inspectPath = async (\n hostPath: string,\n inspectHostPath: IGitInventoryOwnershipLstat,\n): Promise<IGitInventoryPathInspectionAttempt> => {\n try {\n return Object.freeze({\n kind: 'inspected',\n statistics: await inspectHostPath(hostPath),\n });\n } catch (error) {\n return createInspectionFailure(mapFilesystemFailure(error));\n }\n};\n\n/** Determines whether native names contain one exact UTF-8 segment spelling. */\nconst hasExactDirectoryName = (encodedNameKeys: ReadonlySet<string>, segment: string): boolean =>\n encodedNameKeys.has(Buffer.from(segment, 'utf8').toString('hex'));\n\n/** Confirms that one directory observation retained its no-follow identity. */\nconst hasStableDirectoryIdentity = (\n initialStatistics: IGitInventoryOwnershipStatistics,\n revalidatedStatistics: IGitInventoryOwnershipStatistics,\n): boolean =>\n initialStatistics.isDirectory() &&\n !initialStatistics.isSymbolicLink() &&\n revalidatedStatistics.isDirectory() &&\n !revalidatedStatistics.isSymbolicLink() &&\n initialStatistics.dev === revalidatedStatistics.dev &&\n initialStatistics.ino === revalidatedStatistics.ino;\n\n/** Concatenates already bounded Git stdout chunks for strict root parsing. */\nconst concatenateChunks = (chunks: readonly Uint8Array[], byteLength: number): Uint8Array => {\n const output = new Uint8Array(byteLength);\n let offset = 0;\n\n for (const chunk of chunks) {\n output.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return output;\n};\n\n/**\n * Confirms whether a directory with an exact `.git` marker owns another working tree.\n * @param directory The exact no-follow directory being classified.\n * @param repositoryRoot The selected repository root.\n * @param directoryStatistics The stable no-follow boundary observation.\n * @param maxMetadataBytes The remaining bounded Git stdout budget.\n * @param processExecutor The sanitized streamed Git boundary.\n * @param inspectHostPath The no-follow filesystem stat operation.\n * @returns A safe ownership classification and the consumed Git metadata bytes.\n */\nconst validateGitBoundary = async (\n directory: string,\n repositoryRoot: string,\n directoryStatistics: IGitInventoryOwnershipStatistics,\n maxMetadataBytes: number,\n processExecutor: IGitStreamingProcessExecutor,\n inspectHostPath: IGitInventoryOwnershipLstat,\n signal?: AbortSignal,\n): Promise<IGitInventoryBoundaryValidationAttempt> => {\n if (signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!Number.isSafeInteger(maxMetadataBytes) || maxMetadataBytes < 0) {\n return createInspectionFailure('RESOURCE_LIMIT_EXCEEDED');\n }\n\n const stdoutChunks: Uint8Array[] = [];\n let consumedStdoutBytes = 0;\n const processResult = await processExecutor({\n arguments: ['-C', directory, ...GIT_REPOSITORY_ROOT_ARGUMENTS],\n consumeStdout: (chunk): void => {\n stdoutChunks.push(Uint8Array.from(chunk));\n consumedStdoutBytes += chunk.byteLength;\n },\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: maxMetadataBytes,\n ...(signal === undefined ? {} : { signal }),\n });\n\n if (processResult.kind === 'failed') {\n return createInspectionFailure(mapGitProcessFailure(processResult.reason));\n }\n\n if (processResult.stderr.byteLength > 0 || processResult.stdoutBytes !== consumedStdoutBytes) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const discoveredRoot = parseGitAbsolutePathOutput(\n concatenateChunks(stdoutChunks, consumedStdoutBytes),\n );\n\n if (discoveredRoot === null) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n if (areHostPathsEquivalent(discoveredRoot, directory)) {\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'validated',\n ownership: 'nested-repository',\n });\n }\n\n if (areHostPathsEquivalent(discoveredRoot, repositoryRoot)) {\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'validated',\n ownership: 'selected-repository',\n });\n }\n\n const discoveredRootInspection = await inspectPath(discoveredRoot, inspectHostPath);\n\n if (signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (discoveredRootInspection.kind === 'failed') {\n return discoveredRootInspection;\n }\n\n if (\n !discoveredRootInspection.statistics.isDirectory() ||\n discoveredRootInspection.statistics.isSymbolicLink()\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n if (haveSameHostPathIdentity(discoveredRootInspection.statistics, directoryStatistics)) {\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'validated',\n ownership: 'nested-repository',\n });\n }\n\n const repositoryRootInspection = await inspectPath(repositoryRoot, inspectHostPath);\n\n if (signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (repositoryRootInspection.kind === 'failed') {\n return repositoryRootInspection;\n }\n\n if (\n repositoryRootInspection.statistics.isDirectory() &&\n !repositoryRootInspection.statistics.isSymbolicLink() &&\n haveSameHostPathIdentity(\n discoveredRootInspection.statistics,\n repositoryRootInspection.statistics,\n )\n ) {\n return Object.freeze({\n gitMetadataBytes: processResult.stdoutBytes,\n kind: 'validated',\n ownership: 'selected-repository',\n });\n }\n\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n};\n\n/** Default no-follow stat boundary for ownership inspection. */\nconst inspectOwnershipPath: IGitInventoryOwnershipLstat = async (hostPath) =>\n lstat(hostPath, { bigint: true });\n\n/** Default raw directory-name boundary for ownership inspection. */\nconst readOwnershipDirectory: IGitInventoryOwnershipReadDirectory = async (hostPath) =>\n readdir(hostPath, { encoding: 'buffer' });\n\n/**\n * Creates nested-repository inspection around injectable filesystem and Git boundaries.\n * @param processExecutor The sanitized bounded Git process executor.\n * @param inspectHostPath The no-follow filesystem stat operation.\n * @param readDirectory The raw native-name directory operation.\n * @returns An all-or-nothing ownership inspector for untracked candidate paths.\n */\nexport const createGitInventoryBoundaryInspector = (\n processExecutor: IGitStreamingProcessExecutor = executeGitStreamingProcess,\n inspectHostPath: IGitInventoryOwnershipLstat = inspectOwnershipPath,\n readDirectory: IGitInventoryOwnershipReadDirectory = readOwnershipDirectory,\n): IGitInventoryBoundaryInspector => {\n return async (input): Promise<IGitInventoryBoundaryInspectionResult> => {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n const directoryObservations = new Map<string, IGitInventoryDirectoryObservation>();\n const ownership: IGitInventoryBoundaryOwnership[] = [];\n let gitMetadataBytes = 0;\n let rootEncodedNameKeys: ReadonlySet<string> | null = null;\n\n const getRootEncodedNames = async (): Promise<IGitInventoryDirectoryReadAttempt> => {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (rootEncodedNameKeys !== null) {\n return Object.freeze({ encodedNameKeys: rootEncodedNameKeys, kind: 'read' });\n }\n\n const readResult = await readDirectoryNames(input.repositoryRoot, readDirectory);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (readResult.kind === 'read') {\n rootEncodedNameKeys = readResult.encodedNameKeys;\n }\n\n return readResult;\n };\n\n const inspectDirectory = async (\n parentObservation: IGitInventoryDirectoryObservation | null,\n parentPrefix: string,\n segment: string,\n ): Promise<IGitInventoryBoundaryInspectionFailedResult | IGitInventoryDirectoryObservation> => {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n const prefix = parentPrefix.length === 0 ? segment : `${parentPrefix}/${segment}`;\n const cachedObservation = directoryObservations.get(prefix);\n\n if (cachedObservation !== undefined) {\n return cachedObservation;\n }\n\n const parentNamesResult =\n parentObservation === null\n ? await getRootEncodedNames()\n : Object.freeze({\n encodedNameKeys: parentObservation.encodedNameKeys,\n kind: 'read' as const,\n });\n\n if (parentNamesResult.kind === 'failed') {\n return parentNamesResult;\n }\n\n if (!hasExactDirectoryName(parentNamesResult.encodedNameKeys, segment)) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const parentHostPath = parentObservation?.hostPath ?? input.repositoryRoot;\n const hostPath = path.join(parentHostPath, segment);\n const initialInspection = await inspectPath(hostPath, inspectHostPath);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (initialInspection.kind === 'failed') {\n return initialInspection;\n }\n\n if (\n !initialInspection.statistics.isDirectory() ||\n initialInspection.statistics.isSymbolicLink()\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const directoryNamesResult = await readDirectoryNames(hostPath, readDirectory);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (directoryNamesResult.kind === 'failed') {\n return directoryNamesResult;\n }\n\n const revalidatedInspection = await inspectPath(hostPath, inspectHostPath);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (revalidatedInspection.kind === 'failed') {\n return revalidatedInspection;\n }\n\n if (\n !hasStableDirectoryIdentity(initialInspection.statistics, revalidatedInspection.statistics)\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const gitControlPath = path.join(hostPath, GIT_CONTROL_SEGMENT);\n const hasExactGitControlSegment = hasExactDirectoryName(\n directoryNamesResult.encodedNameKeys,\n GIT_CONTROL_SEGMENT,\n );\n let directoryOwnership: IGitInventoryBoundaryOwnership = 'selected-repository';\n\n if (!hasExactGitControlSegment) {\n try {\n await inspectHostPath(gitControlPath);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n } catch (error) {\n const errorCode = (error as NodeJS.ErrnoException | null)?.code?.toUpperCase();\n\n if (errorCode !== 'ENOENT' && errorCode !== 'ENOTDIR') {\n return createInspectionFailure(mapFilesystemFailure(error));\n }\n }\n } else {\n const gitControlInspection = await inspectPath(gitControlPath, inspectHostPath);\n\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n if (gitControlInspection.kind === 'failed') {\n return gitControlInspection;\n }\n\n if (\n gitControlInspection.statistics.isSymbolicLink() ||\n (!gitControlInspection.statistics.isDirectory() &&\n !gitControlInspection.statistics.isFile())\n ) {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n const boundaryValidation = await validateGitBoundary(\n hostPath,\n input.repositoryRoot,\n revalidatedInspection.statistics,\n input.maxMetadataBytes - gitMetadataBytes,\n processExecutor,\n inspectHostPath,\n input.signal,\n );\n\n if (boundaryValidation.kind === 'failed') {\n return boundaryValidation;\n }\n\n gitMetadataBytes += boundaryValidation.gitMetadataBytes;\n directoryOwnership = boundaryValidation.ownership;\n }\n\n const observation = Object.freeze({\n encodedNameKeys: directoryNamesResult.encodedNameKeys,\n hostPath,\n ownership: directoryOwnership,\n });\n\n directoryObservations.set(prefix, observation);\n\n return observation;\n };\n\n for (const plan of input.plans) {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n let candidateOwnership: IGitInventoryBoundaryOwnership = 'selected-repository';\n let parentObservation: IGitInventoryDirectoryObservation | null = null;\n let parentPrefix = '';\n\n for (const segment of plan.directorySegments) {\n if (input.signal?.aborted) {\n return createInspectionFailure('GIT_OPERATION_ABORTED');\n }\n\n const observation = await inspectDirectory(parentObservation, parentPrefix, segment);\n\n if (isInspectionFailure(observation)) {\n return observation;\n }\n\n parentObservation = observation;\n parentPrefix = parentPrefix.length === 0 ? segment : `${parentPrefix}/${segment}`;\n\n if (observation.ownership === 'nested-repository') {\n candidateOwnership = 'nested-repository';\n break;\n }\n }\n\n if (plan.isDirectoryRecord && candidateOwnership !== 'nested-repository') {\n return createInspectionFailure('GIT_OUTPUT_INVALID');\n }\n\n ownership.push(candidateOwnership);\n }\n\n const result: IGitInventoryBoundaryInspectedResult = Object.freeze({\n gitMetadataBytes,\n kind: 'inspected',\n ownership: Object.freeze([...ownership]),\n });\n\n return result;\n };\n};\n\n// default nested-repository ownership boundary used by inventory filtering\nexport const inspectGitInventoryBoundaries = createGitInventoryBoundaryInspector();\n","import type { IGitInventoryCandidate } from '../types.js';\n\nimport type { IGitInventoryOwnershipPathPlanResult } from './types.js';\n\n/**\n * Prepares one raw Git path for ownership inspection without logical-path normalization.\n * @param candidate The strictly decoded tracked or untracked candidate.\n * @returns An immutable segment plan, or a failure for an unsafe raw path shape.\n */\nexport const planGitInventoryOwnershipPath = (\n candidate: IGitInventoryCandidate,\n): IGitInventoryOwnershipPathPlanResult => {\n const isDirectoryRecord = candidate.path.endsWith('/');\n\n if (\n candidate.path.length === 0 ||\n candidate.path.startsWith('/') ||\n candidate.path.includes('\\\\') ||\n (candidate.kind === 'tracked' && isDirectoryRecord)\n ) {\n return Object.freeze({ kind: 'failed' });\n }\n\n const pathWithoutDirectoryTerminator = isDirectoryRecord\n ? candidate.path.slice(0, -1)\n : candidate.path;\n const segments = pathWithoutDirectoryTerminator.split('/');\n\n if (\n segments.length === 0 ||\n segments.some((segment) => segment.length === 0 || segment === '.' || segment === '..')\n ) {\n return Object.freeze({ kind: 'failed' });\n }\n\n const frozenSegments = Object.freeze([...segments]);\n const directorySegments = Object.freeze(\n isDirectoryRecord ? [...segments] : segments.slice(0, -1),\n );\n\n return Object.freeze({\n kind: 'planned',\n plan: Object.freeze({\n candidate,\n directorySegments,\n hasGitControlSegment: segments.includes('.git'),\n isDirectoryRecord,\n segments: frozenSegments,\n }),\n });\n};\n","import type { IGitInventoryCandidate, IGitInventoryProbeErrorCode } from '../types.js';\n\nimport { inspectGitInventoryBoundaries } from './boundary-inspector.js';\nimport { planGitInventoryOwnershipPath } from './path-planner.js';\nimport type {\n IGitInventoryBoundaryInspector,\n IGitInventoryOwnershipFilter,\n IGitInventoryOwnershipFilterFailedResult,\n IGitInventoryOwnershipFilterResult,\n IGitInventoryOwnershipPathPlan,\n IGitInventoryUntrackedOwnershipPlan,\n} from './types.js';\n\ninterface IGitInventoryIndexedOwnershipPlan {\n readonly candidateIndex: number;\n readonly plan: IGitInventoryOwnershipPathPlan;\n}\n\ninterface IGitInventoryGitlinkTrieNode {\n readonly children: Map<string, IGitInventoryGitlinkTrieNode>;\n isRoot: boolean;\n}\n\n/** Creates one immutable ownership-filtering failure. */\nconst createOwnershipFailure = (\n errorCode: IGitInventoryProbeErrorCode = 'GIT_OUTPUT_INVALID',\n): IGitInventoryOwnershipFilterFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Builds one segment trie for deterministic submodule-root lookup. */\nconst createGitlinkTrie = (\n rootSegments: readonly (readonly string[])[],\n): IGitInventoryGitlinkTrieNode => {\n const trie: IGitInventoryGitlinkTrieNode = { children: new Map(), isRoot: false };\n\n for (const segments of rootSegments) {\n let node = trie;\n\n for (const segment of segments) {\n let childNode = node.children.get(segment);\n\n if (childNode === undefined) {\n childNode = { children: new Map(), isRoot: false };\n node.children.set(segment, childNode);\n }\n\n node = childNode;\n }\n\n node.isRoot = true;\n }\n\n return trie;\n};\n\n/** Determines whether one candidate is a submodule root or segment descendant. */\nconst isAtOrBelowGitlink = (\n candidateSegments: readonly string[],\n gitlinkTrie: IGitInventoryGitlinkTrieNode,\n): boolean => {\n let node = gitlinkTrie;\n\n for (const segment of candidateSegments) {\n const childNode = node.children.get(segment);\n\n if (childNode === undefined) {\n return false;\n }\n\n if (childNode.isRoot) {\n return true;\n }\n\n node = childNode;\n }\n\n return false;\n};\n\n/**\n * Creates selected-repository ownership filtering around an injectable boundary inspector.\n * @param boundaryInspector The no-follow nested-repository ownership operation.\n * @returns An all-or-nothing raw candidate ownership filter.\n */\nexport const createGitInventoryOwnershipFilter = (\n boundaryInspector: IGitInventoryBoundaryInspector = inspectGitInventoryBoundaries,\n): IGitInventoryOwnershipFilter => {\n return async (input): Promise<IGitInventoryOwnershipFilterResult> => {\n const plannedCandidates: IGitInventoryIndexedOwnershipPlan[] = [];\n\n for (const [candidateIndex, candidate] of input.candidates.entries()) {\n if (input.signal?.aborted) {\n return createOwnershipFailure('GIT_OPERATION_ABORTED');\n }\n\n const planResult = planGitInventoryOwnershipPath(candidate);\n\n if (planResult.kind === 'failed') {\n return createOwnershipFailure();\n }\n\n plannedCandidates.push({ candidateIndex, plan: planResult.plan });\n }\n\n const gitlinkTrie = createGitlinkTrie(\n plannedCandidates\n .filter(\n ({ plan }) =>\n !plan.hasGitControlSegment &&\n plan.candidate.kind === 'tracked' &&\n plan.candidate.mode === '160000',\n )\n .map(({ plan }) => plan.segments),\n );\n const includedCandidates = Array.from({ length: input.candidates.length }, () => false);\n const untrackedPlans: IGitInventoryUntrackedOwnershipPlan[] = [];\n\n for (const { candidateIndex, plan } of plannedCandidates) {\n const isExcludedByGitPolicy =\n plan.hasGitControlSegment || isAtOrBelowGitlink(plan.segments, gitlinkTrie);\n\n if (isExcludedByGitPolicy) {\n continue;\n }\n\n if (plan.candidate.kind === 'tracked') {\n includedCandidates[candidateIndex] = true;\n continue;\n }\n\n untrackedPlans.push({ candidate: plan.candidate, candidateIndex, plan });\n }\n\n const boundaryResult = await boundaryInspector({\n maxMetadataBytes: input.maxMetadataBytes,\n plans: untrackedPlans.map(({ plan }) => plan),\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (boundaryResult.kind === 'failed') {\n return boundaryResult;\n }\n\n if (boundaryResult.ownership.length !== untrackedPlans.length) {\n return createOwnershipFailure();\n }\n\n for (const [ownershipIndex, ownership] of boundaryResult.ownership.entries()) {\n if (input.signal?.aborted) {\n return createOwnershipFailure('GIT_OPERATION_ABORTED');\n }\n\n const untrackedPlan = untrackedPlans[ownershipIndex];\n\n if (untrackedPlan === undefined) {\n return createOwnershipFailure();\n }\n\n if (ownership === 'selected-repository') {\n includedCandidates[untrackedPlan.candidateIndex] = true;\n }\n }\n\n const candidates = input.candidates.filter(\n (_candidate: IGitInventoryCandidate, candidateIndex) =>\n includedCandidates[candidateIndex] === true,\n );\n\n return Object.freeze({\n candidates: Object.freeze(candidates),\n gitMetadataBytes: boundaryResult.gitMetadataBytes,\n kind: 'filtered',\n });\n };\n};\n","import {\n executeGitStreamingProcess,\n MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n type IGitStreamingProcessExecutor,\n type IGitStreamingProcessFailureReason,\n} from '../git-process/index.js';\nimport { GIT_TRACKED_INVENTORY_ARGUMENTS, GIT_UNTRACKED_INVENTORY_ARGUMENTS } from './constants.js';\nimport {\n createGitContentTransformationClassifier,\n type IGitContentTransformationClassifier,\n} from './content-transformation/index.js';\nimport {\n createGitInventoryEntryTypeNormalizer,\n createGitSymlinkConfigurationResolver,\n inspectGitInventoryEntry,\n type IGitInventoryEntryTypeNormalizer,\n} from './entry-type/index.js';\nimport {\n normalizeGitInventoryLogicalPaths,\n type IGitInventoryLogicalPathNormalizer,\n validateGitInventoryCandidateLogicalPaths,\n} from './logical-path/index.js';\nimport { createTrackedGitInventoryParser, createUntrackedGitInventoryParser } from './parser.js';\nimport {\n createGitInventoryBoundaryInspector,\n createGitInventoryOwnershipFilter,\n type IGitInventoryOwnershipFilter,\n} from './repository-ownership/index.js';\nimport type {\n IGitInventoryCandidate,\n IGitInventoryParserResult,\n IGitInventoryProbe,\n IGitInventoryProbeErrorCode,\n IGitInventoryProbeFailedResult,\n IGitInventoryProbeResult,\n} from './types.js';\n\n/** Maps one normalized streamed Git failure to a safe inventory error. */\nconst mapGitProcessFailure = (\n reason: IGitStreamingProcessFailureReason,\n): IGitInventoryProbeErrorCode => {\n switch (reason) {\n case 'aborted':\n return 'GIT_OPERATION_ABORTED';\n case 'not-found':\n return 'GIT_NOT_FOUND';\n case 'repository-not-found':\n return 'GIT_REPOSITORY_NOT_FOUND';\n case 'access-denied':\n return 'GIT_ACCESS_DENIED';\n case 'stderr-limit-exceeded':\n return 'GIT_OUTPUT_INVALID';\n case 'output-limit-exceeded':\n case 'stdout-limit-exceeded':\n return 'RESOURCE_LIMIT_EXCEEDED';\n case 'command-failed':\n return 'GIT_COMMAND_FAILED';\n }\n};\n\n/** Creates one immutable inventory-probe failure. */\nconst createProbeFailure = (\n errorCode: IGitInventoryProbeErrorCode,\n): IGitInventoryProbeFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Maps one completed parser result into immutable candidates or a safe failure. */\nconst resolveParserResult = <TCandidate extends IGitInventoryCandidate>(\n parserResult: IGitInventoryParserResult<TCandidate>,\n): readonly TCandidate[] | IGitInventoryProbeFailedResult => {\n if (parserResult.kind === 'completed') {\n return parserResult.candidates;\n }\n\n return createProbeFailure(\n parserResult.reason === 'entry-limit-exceeded'\n ? 'RESOURCE_LIMIT_EXCEEDED'\n : 'GIT_OUTPUT_INVALID',\n );\n};\n\n/** Identifies a parser resolution failure without relying on array contents. */\nconst isProbeFailure = (\n result: readonly IGitInventoryCandidate[] | IGitInventoryProbeFailedResult,\n): result is IGitInventoryProbeFailedResult => !Array.isArray(result);\n\n/**\n * Creates the strict normalized Git inventory probe around injectable boundaries.\n * @param processExecutor The bounded incremental Git process executor.\n * @param ownershipFilter The submodule and nested-repository ownership filter.\n * @param entryTypeNormalizer The current filesystem and Git mode entry-type normalizer.\n * @param contentTransformationClassifier The bounded effective Git attribute classifier.\n * @param logicalPathNormalizer The portable repository logical-path normalizer.\n * @returns An all-or-nothing selected-repository entry probe.\n */\nexport const createGitInventoryProbe =\n (\n processExecutor: IGitStreamingProcessExecutor = executeGitStreamingProcess,\n ownershipFilter: IGitInventoryOwnershipFilter = createGitInventoryOwnershipFilter(\n createGitInventoryBoundaryInspector(processExecutor),\n ),\n entryTypeNormalizer: IGitInventoryEntryTypeNormalizer = createGitInventoryEntryTypeNormalizer(\n inspectGitInventoryEntry,\n createGitSymlinkConfigurationResolver(processExecutor),\n ),\n contentTransformationClassifier: IGitContentTransformationClassifier = createGitContentTransformationClassifier(\n processExecutor,\n ),\n logicalPathNormalizer: IGitInventoryLogicalPathNormalizer = normalizeGitInventoryLogicalPaths,\n ): IGitInventoryProbe =>\n async (input): Promise<IGitInventoryProbeResult> => {\n if (input.signal?.aborted) {\n return createProbeFailure('GIT_OPERATION_ABORTED');\n }\n\n const selectionPathspecs = (input.selectionPaths ?? []).map(\n (selectionPath) => `:(top,literal)${selectionPath.slice(1)}`,\n );\n const trackedParser = createTrackedGitInventoryParser(input.maxEntries);\n const trackedProcessResult = await processExecutor({\n arguments: [\n '-C',\n input.repositoryRoot,\n ...GIT_TRACKED_INVENTORY_ARGUMENTS,\n ...selectionPathspecs,\n ],\n consumeStdout: (chunk) => trackedParser.consume(chunk),\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: input.maxMetadataBytes,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (trackedProcessResult.kind === 'failed') {\n return createProbeFailure(mapGitProcessFailure(trackedProcessResult.reason));\n }\n\n if (trackedProcessResult.stderr.byteLength > 0) {\n return createProbeFailure('GIT_OUTPUT_INVALID');\n }\n\n const trackedCandidates = resolveParserResult(trackedParser.finish());\n\n if (isProbeFailure(trackedCandidates)) {\n return trackedCandidates;\n }\n\n const untrackedParser = createUntrackedGitInventoryParser(\n input.maxEntries - trackedCandidates.length,\n );\n const untrackedProcessResult = await processExecutor({\n arguments: [\n '-C',\n input.repositoryRoot,\n ...GIT_UNTRACKED_INVENTORY_ARGUMENTS,\n ...selectionPathspecs,\n ],\n consumeStdout: (chunk) => untrackedParser.consume(chunk),\n maxStderrBytes: MAX_GIT_PROCESS_DIAGNOSTIC_BYTES,\n maxStdoutBytes: input.maxMetadataBytes - trackedProcessResult.stdoutBytes,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (untrackedProcessResult.kind === 'failed') {\n return createProbeFailure(mapGitProcessFailure(untrackedProcessResult.reason));\n }\n\n if (untrackedProcessResult.stderr.byteLength > 0) {\n return createProbeFailure('GIT_OUTPUT_INVALID');\n }\n\n const untrackedCandidates = resolveParserResult(untrackedParser.finish());\n\n if (isProbeFailure(untrackedCandidates)) {\n return untrackedCandidates;\n }\n\n const candidates = Object.freeze([...trackedCandidates, ...untrackedCandidates]);\n const logicalPathValidationResult = validateGitInventoryCandidateLogicalPaths({ candidates });\n\n if (logicalPathValidationResult.kind === 'failed') {\n return logicalPathValidationResult;\n }\n\n const ownershipResult = await ownershipFilter({\n candidates,\n maxMetadataBytes:\n input.maxMetadataBytes -\n trackedProcessResult.stdoutBytes -\n untrackedProcessResult.stdoutBytes,\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (ownershipResult.kind === 'failed') {\n return ownershipResult;\n }\n\n const entryTypeResult = await entryTypeNormalizer({\n candidates: ownershipResult.candidates,\n maxMetadataBytes:\n input.maxMetadataBytes -\n trackedProcessResult.stdoutBytes -\n untrackedProcessResult.stdoutBytes -\n ownershipResult.gitMetadataBytes,\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (entryTypeResult.kind === 'failed') {\n return entryTypeResult;\n }\n\n const contentTransformationResult = await contentTransformationClassifier({\n entries: entryTypeResult.entries,\n maxMetadataBytes:\n input.maxMetadataBytes -\n trackedProcessResult.stdoutBytes -\n untrackedProcessResult.stdoutBytes -\n ownershipResult.gitMetadataBytes -\n entryTypeResult.gitMetadataBytes,\n repositoryRoot: input.repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (contentTransformationResult.kind === 'failed') {\n return contentTransformationResult;\n }\n\n const logicalPathResult = logicalPathNormalizer({\n entries: contentTransformationResult.entries,\n });\n\n if (logicalPathResult.kind === 'failed') {\n return logicalPathResult;\n }\n\n return Object.freeze({ entries: logicalPathResult.entries, kind: 'probed' });\n };\n\n// default normalized Git inventory probe used by command execution\nexport const probeGitInventory = createGitInventoryProbe();\n","import type { IGitContentTransformationClassification } from '../content-transformation/index.js';\nimport type { IGitInventoryIndexEntry } from '../entry-type/index.js';\nimport type { IGitInventoryEntry } from '../logical-path/index.js';\n\n/** Determines whether two exact transform classifications are equal. */\nconst areContentTransformationsEqual = (\n left: IGitContentTransformationClassification,\n right: IGitContentTransformationClassification,\n): boolean =>\n left.filter === right.filter &&\n left.ident === right.ident &&\n left.isGuarded === right.isGuarded &&\n left.workingTreeEncoding === right.workingTreeEncoding;\n\n/** Determines whether two retained Git mode-and-stage sequences are equal. */\nconst areIndexEntriesEqual = (\n left: readonly IGitInventoryIndexEntry[],\n right: readonly IGitInventoryIndexEntry[],\n): boolean =>\n left.length === right.length &&\n left.every(\n (leftEntry, index) =>\n leftEntry.mode === right[index]?.mode && leftEntry.stage === right[index]?.stage,\n );\n\n/** Determines whether two normalized inventory entries are exactly equal. */\nconst areInventoryEntriesEqual = (left: IGitInventoryEntry, right: IGitInventoryEntry): boolean => {\n if (\n left.kind !== right.kind ||\n left.path !== right.path ||\n left.entryType !== right.entryType ||\n left.requiresSymlinkOverlay !== right.requiresSymlinkOverlay ||\n !areContentTransformationsEqual(left.contentTransformation, right.contentTransformation)\n ) {\n return false;\n }\n\n if (left.kind === 'untracked' || right.kind === 'untracked') {\n return left.kind === right.kind;\n }\n\n return areIndexEntriesEqual(left.indexEntries, right.indexEntries);\n};\n\n/**\n * Determines whether two complete normalized Git inventories describe the same snapshot inputs.\n * @param left The first deterministic inventory.\n * @param right The second deterministic inventory.\n * @returns Whether ordering and every retained record field are equal.\n */\nexport const areGitInventoriesEqual = (\n left: readonly IGitInventoryEntry[],\n right: readonly IGitInventoryEntry[],\n): boolean =>\n left.length === right.length &&\n left.every((leftEntry, index) => {\n const rightEntry = right[index];\n\n return rightEntry !== undefined && areInventoryEntriesEqual(leftEntry, rightEntry);\n });\n","import {\n REPOSITORY_ROOT,\n RepositorySourceException,\n createRepositoryComparison,\n parseRepositoryPath,\n type IRepositoryComparison,\n type IRepositoryEntry,\n type IRepositoryEntryPage,\n type IRepositoryEntryPageOptions,\n type IRepositoryFilePage,\n type IRepositoryFilePageOptions,\n type IRepositoryOperation,\n type IRepositoryOperationOptions,\n type IRepositoryPath,\n type IRepositoryReader,\n type IRepositorySnapshot,\n} from '@moldea.ai/repository';\n\n/** Throws the common cancellation contract for wrapper-owned operations. */\nconst throwIfAborted = (\n signal: AbortSignal | undefined,\n operation: IRepositoryOperation,\n path: IRepositoryPath,\n): void => {\n if (!signal?.aborted) {\n return;\n }\n\n throw new RepositorySourceException({\n cause: signal.reason,\n code: 'ABORTED',\n operation,\n path,\n retryable: false,\n });\n};\n\n/** Creates the common failure for an overlay that contradicts its underlying snapshot. */\nconst createInvalidOverlayException = (\n operation: IRepositoryOperation,\n path: IRepositoryPath,\n): RepositorySourceException =>\n new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation,\n path,\n retryable: false,\n });\n\n/** Confirms that one overlay path remains a regular file in the underlying snapshot. */\nconst validateOverlayEntry = (\n entry: IRepositoryEntry | null,\n operation: Exclude<IRepositoryOperation, 'create-reader'>,\n path: IRepositoryPath,\n): void => {\n if (entry?.type !== 'file' || entry.path !== path) {\n throw createInvalidOverlayException(operation, path);\n }\n};\n\n/** Maps one expected underlying regular file to an immutable logical symlink entry. */\nconst overlayEntry = (\n entry: IRepositoryEntry | null,\n operation: 'get-entry' | 'list-entries-page',\n path: IRepositoryPath,\n): IRepositoryEntry => {\n validateOverlayEntry(entry, operation, path);\n\n return Object.freeze({ byteLength: null, contentIdentity: null, path, type: 'symlink' });\n};\n\n// immutable logical symlink view over one coherent repository reader\nclass GitSymlinkOverlayRepositoryReader implements IRepositoryReader {\n public readonly snapshot: IRepositorySnapshot;\n\n readonly #overlayPaths: ReadonlySet<IRepositoryPath>;\n\n readonly #reader: IRepositoryReader;\n\n public constructor(reader: IRepositoryReader, overlayPaths: ReadonlySet<IRepositoryPath>) {\n this.#reader = reader;\n this.#overlayPaths = overlayPaths;\n this.snapshot = reader.snapshot;\n }\n\n /** Creates a bounded comparison from this logical overlay snapshot. */\n public compare(\n candidate: IRepositoryReader,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryComparison> {\n return createRepositoryComparison(this, candidate, options);\n }\n\n /**\n * Looks up an entry while replacing configured host files with logical symlinks.\n * @param path The validated repository path to inspect.\n * @param options Optional cancellation controls.\n * @returns A promise resolving to the detached logical entry or confirmed absence.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - ACCESS_DENIED: Access to the repository source was denied.\n * - SOURCE_UNAVAILABLE: The repository source is unavailable.\n * - SNAPSHOT_CHANGED: The repository snapshot changed during the operation.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n * - RESOURCE_LIMIT_EXCEEDED: A repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public async getEntry(\n path: IRepositoryPath,\n options?: IRepositoryOperationOptions,\n ): Promise<IRepositoryEntry | null> {\n const entry = await this.#reader.getEntry(path, options);\n\n if (!this.#overlayPaths.has(path)) {\n return entry;\n }\n\n return overlayEntry(entry, 'get-entry', path);\n }\n\n /**\n * Reads ordinary files while refusing access to configured logical symlink bytes.\n * @param path The validated repository file path to read.\n * @param options Optional cancellation controls.\n * @returns A promise resolving to fresh bytes for a non-overlaid regular file.\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 repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public async readFilePage(\n path: IRepositoryPath,\n options: IRepositoryFilePageOptions,\n ): Promise<IRepositoryFilePage> {\n const parsedPath = parseRepositoryPath(path);\n\n if (!this.#overlayPaths.has(parsedPath)) {\n return this.#reader.readFilePage(parsedPath, options);\n }\n\n throwIfAborted(options.signal, 'read-file-page', parsedPath);\n\n const entry = await this.#reader.getEntry(parsedPath, options);\n\n validateOverlayEntry(entry, 'read-file-page', parsedPath);\n throwIfAborted(options.signal, 'read-file-page', parsedPath);\n\n throw new RepositorySourceException({\n code: 'ENTRY_NOT_FILE',\n operation: 'read-file-page',\n path: parsedPath,\n retryable: false,\n });\n }\n\n /**\n * Recursively lists descendants while replacing configured host files with logical symlinks.\n * @param options Optional prefix and cancellation controls.\n * @returns An async iterable of detached logical entries.\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_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 repository reading resource limit was exceeded.\n * - ABORTED: The repository operation was aborted.\n */\n public async listEntriesPage(\n options: IRepositoryEntryPageOptions,\n ): Promise<IRepositoryEntryPage> {\n const prefix =\n options.prefix === undefined ? REPOSITORY_ROOT : parseRepositoryPath(options.prefix);\n\n if (this.#overlayPaths.has(prefix)) {\n throwIfAborted(options.signal, 'list-entries-page', prefix);\n\n const operationOptions =\n options.signal === undefined ? undefined : { signal: options.signal };\n const entry = await this.#reader.getEntry(prefix, operationOptions);\n\n validateOverlayEntry(entry, 'list-entries-page', prefix);\n throwIfAborted(options.signal, 'list-entries-page', prefix);\n throw new RepositorySourceException({\n code: 'ENTRY_NOT_DIRECTORY',\n operation: 'list-entries-page',\n path: prefix,\n retryable: false,\n });\n }\n\n const page = await this.#reader.listEntriesPage(options);\n const entries = page.entries.map((entry) =>\n this.#overlayPaths.has(entry.path)\n ? overlayEntry(entry, 'list-entries-page', entry.path)\n : entry,\n );\n\n return Object.freeze({\n entries: Object.freeze(entries),\n isComplete: page.isComplete,\n nextCursor: page.nextCursor,\n snapshot: this.snapshot,\n });\n }\n}\n\n/**\n * Creates an immutable reader overlay for Git symlinks materialized as host files.\n * @param reader The coherent underlying repository reader.\n * @param symlinkPaths The logical paths whose host files represent Git symlinks.\n * @returns A reader that exposes the configured paths only as logical symlinks.\n * @throws\n * - INVALID_REPOSITORY_PATH: The repository path is invalid.\n * - INVALID_SOURCE_DATA: The repository source returned invalid data.\n */\nexport const createGitSymlinkOverlayRepositoryReader = (\n reader: IRepositoryReader,\n symlinkPaths: readonly IRepositoryPath[],\n): IRepositoryReader => {\n const overlayPaths = new Set<IRepositoryPath>();\n\n for (const symlinkPath of symlinkPaths) {\n const parsedPath = parseRepositoryPath(symlinkPath);\n\n if (parsedPath === REPOSITORY_ROOT) {\n throw new RepositorySourceException({\n code: 'INVALID_SOURCE_DATA',\n operation: 'create-reader',\n path: parsedPath,\n retryable: false,\n });\n }\n\n overlayPaths.add(parsedPath);\n }\n\n return Object.freeze(new GitSymlinkOverlayRepositoryReader(reader, overlayPaths));\n};\n","import type { IRepositoryPath, IRepositoryReader } from '@moldea.ai/repository';\nimport { createFilesystemRepositoryReader } from '@moldea.ai/repository-fs';\n\nimport { createGitContentTransformationGuardRepositoryReader } from '../repository-content-transformation-guard/index.js';\nimport { createGitSymlinkOverlayRepositoryReader } from '../repository-symlink-overlay/index.js';\n\nimport type { IWorkingTreeRepositoryReaderFactory } from './types.js';\n\n// injectable package and overlay factories used by the composition boundary\ntype IFilesystemRepositoryReaderFactory = typeof createFilesystemRepositoryReader;\ntype IGitContentTransformationGuardRepositoryReaderFactory =\n typeof createGitContentTransformationGuardRepositoryReader;\ntype IGitSymlinkOverlayRepositoryReaderFactory = typeof createGitSymlinkOverlayRepositoryReader;\n\n/**\n * Creates the private working-tree reader factory around injectable composition boundaries.\n * @param filesystemReaderFactory The exact-path filesystem snapshot factory.\n * @param symlinkOverlayFactory The logical Git symlink overlay factory.\n * @param contentTransformationGuardFactory The guarded logical regular-file reader factory.\n * @returns A factory that composes one coherent selected working-tree reader.\n */\nexport const createWorkingTreeRepositoryReaderFactory =\n (\n filesystemReaderFactory: IFilesystemRepositoryReaderFactory = createFilesystemRepositoryReader,\n symlinkOverlayFactory: IGitSymlinkOverlayRepositoryReaderFactory = createGitSymlinkOverlayRepositoryReader,\n contentTransformationGuardFactory: IGitContentTransformationGuardRepositoryReaderFactory = createGitContentTransformationGuardRepositoryReader,\n ): IWorkingTreeRepositoryReaderFactory =>\n async (input): Promise<IRepositoryReader> => {\n const selectedPaths = Object.freeze(input.entries.map((entry) => entry.path));\n const symlinkOverlayPaths = Object.freeze(\n input.entries.reduce<IRepositoryPath[]>((paths, entry) => {\n if (entry.requiresSymlinkOverlay) {\n paths.push(entry.path);\n }\n\n return paths;\n }, []),\n );\n const guardedPaths = Object.freeze(\n input.entries.reduce<IRepositoryPath[]>((paths, entry) => {\n if (entry.contentTransformation.isGuarded) {\n paths.push(entry.path);\n }\n\n return paths;\n }, []),\n );\n const filesystemReader = await filesystemReaderFactory({\n limits: Object.freeze({\n maxCachedBytes: input.resourceLimits.maxTotalBytes,\n maxDirectoryEntries: input.resourceLimits.maxEntries,\n maxEntries: input.resourceLimits.maxEntries,\n maxPageEntries: Math.min(4096, input.resourceLimits.maxEntries),\n maxReadBytes: input.resourceLimits.maxFileBytes,\n }),\n rootDirectory: input.repositoryRoot,\n selection: Object.freeze({ kind: 'paths', paths: selectedPaths }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n const overlaidReader = symlinkOverlayFactory(filesystemReader, symlinkOverlayPaths);\n\n return contentTransformationGuardFactory(overlaidReader, guardedPaths);\n };\n\n// default exact-path working-tree reader composition used by command execution\nexport const createWorkingTreeRepositoryReader = createWorkingTreeRepositoryReaderFactory();\n","import { RepositorySourceException, type IRepositoryReader } from '@moldea.ai/repository';\n\nimport {\n areGitInventoriesEqual,\n probeGitInventory,\n type IGitInventoryProbe,\n type IGitInventoryProbedResult,\n} from '../git-inventory/index.js';\nimport {\n areGitWorkingTreeIdentitiesEqual,\n inspectGitWorkingTreeIdentity,\n type IGitWorkingTreeIdentity,\n type IGitWorkingTreeIdentityInspector,\n} from '../git-working-tree/index.js';\nimport type { IMoldeaCliOwnedErrorCode } from '../presentation/index.js';\nimport {\n createWorkingTreeRepositoryReader,\n type IWorkingTreeRepositoryReaderFactory,\n} from '../repository-reader/index.js';\n\nimport { MAX_WORKING_TREE_SNAPSHOT_ATTEMPTS } from './constants.js';\nimport type {\n IWorkingTreeSnapshotExecutionInput,\n IWorkingTreeSnapshotExecutionResult,\n IWorkingTreeSnapshotExecutor,\n IWorkingTreeSnapshotFailedResult,\n IWorkingTreeSnapshotInventoryComparator,\n} from './types.js';\n\n/** Creates one immutable terminal snapshot failure. */\nconst createSnapshotFailure = (\n errorCode: IMoldeaCliOwnedErrorCode,\n): IWorkingTreeSnapshotFailedResult => Object.freeze({ errorCode, kind: 'failed' });\n\n/** Determines whether a source exception proves that the current reader is unusable. */\nconst isSnapshotChanged = (error: unknown): boolean =>\n error instanceof RepositorySourceException && error.code === 'SNAPSHOT_CHANGED';\n\n/** Determines whether reader creation may have raced with an inventory change. */\nconst isCreationInventoryRace = (error: unknown): boolean =>\n error instanceof RepositorySourceException &&\n error.operation === 'create-reader' &&\n (error.code === 'ENTRY_NOT_FOUND' || error.code === 'ENTRY_NOT_DIRECTORY');\n\n/** Determines whether identity inspection failed because the pinned source disappeared. */\nconst isPinnedIdentityUnavailable = (errorCode: IMoldeaCliOwnedErrorCode): boolean =>\n errorCode === 'GIT_REPOSITORY_NOT_FOUND' || errorCode === 'GIT_WORK_TREE_REQUIRED';\n\n/**\n * Creates the bounded whole-operation working-tree snapshot executor.\n * @param identityInspector The selected working-tree identity observation boundary.\n * @param inventoryProbe The complete normalized Git inventory probe.\n * @param repositoryReaderFactory The exact-path guarded reader factory.\n * @param compareInventories The exact normalized inventory comparator.\n * @returns An executor that discards and retries complete provisional attempts.\n */\nexport const createWorkingTreeSnapshotExecutor = (\n identityInspector: IGitWorkingTreeIdentityInspector = inspectGitWorkingTreeIdentity,\n inventoryProbe: IGitInventoryProbe = probeGitInventory,\n repositoryReaderFactory: IWorkingTreeRepositoryReaderFactory = createWorkingTreeRepositoryReader,\n compareInventories: IWorkingTreeSnapshotInventoryComparator = areGitInventoriesEqual,\n): IWorkingTreeSnapshotExecutor => {\n const executeSnapshot = async <TResult>(\n input: IWorkingTreeSnapshotExecutionInput<TResult>,\n ): Promise<IWorkingTreeSnapshotExecutionResult<TResult>> => {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n const repositoryRoot = input.repositoryRoot;\n const resourceLimits = Object.freeze({ ...input.resourceLimits });\n const pinnedIdentityResult = await identityInspector({\n repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (pinnedIdentityResult.kind === 'failed') {\n return createSnapshotFailure(pinnedIdentityResult.errorCode);\n }\n\n if (pinnedIdentityResult.kind === 'mismatched') {\n return createSnapshotFailure('GIT_OUTPUT_INVALID');\n }\n\n const pinnedIdentity: IGitWorkingTreeIdentity = pinnedIdentityResult.identity;\n\n const probeInventory = async (): Promise<\n IGitInventoryProbedResult | IWorkingTreeSnapshotFailedResult\n > => {\n const result = await inventoryProbe({\n maxEntries: resourceLimits.maxEntries,\n maxMetadataBytes: resourceLimits.maxTotalBytes,\n repositoryRoot,\n ...(input.selectionPaths === undefined ? {} : { selectionPaths: input.selectionPaths }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n return result.kind === 'failed' ? createSnapshotFailure(result.errorCode) : result;\n };\n\n for (let attempt = 0; attempt < MAX_WORKING_TREE_SNAPSHOT_ATTEMPTS; attempt += 1) {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n const currentIdentityResult = await identityInspector({\n repositoryRoot,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (currentIdentityResult.kind === 'failed') {\n return createSnapshotFailure(\n isPinnedIdentityUnavailable(currentIdentityResult.errorCode)\n ? 'WORKING_TREE_UNSTABLE'\n : currentIdentityResult.errorCode,\n );\n }\n\n if (\n currentIdentityResult.kind === 'mismatched' ||\n !areGitWorkingTreeIdentitiesEqual(pinnedIdentity, currentIdentityResult.identity)\n ) {\n return createSnapshotFailure('WORKING_TREE_UNSTABLE');\n }\n\n const firstInventoryResult = await probeInventory();\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (firstInventoryResult.kind === 'failed') {\n return firstInventoryResult;\n }\n\n let reader: IRepositoryReader;\n\n try {\n reader = await repositoryReaderFactory({\n entries: firstInventoryResult.entries,\n repositoryRoot,\n resourceLimits,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n } catch (error) {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (isSnapshotChanged(error)) {\n continue;\n }\n\n if (!isCreationInventoryRace(error)) {\n throw error;\n }\n\n const freshInventoryResult = await probeInventory();\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (freshInventoryResult.kind === 'failed') {\n return freshInventoryResult;\n }\n\n if (!compareInventories(firstInventoryResult.entries, freshInventoryResult.entries)) {\n continue;\n }\n\n throw error;\n }\n\n const secondInventoryResult = await probeInventory();\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (secondInventoryResult.kind === 'failed') {\n return secondInventoryResult;\n }\n\n if (!compareInventories(firstInventoryResult.entries, secondInventoryResult.entries)) {\n continue;\n }\n\n try {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n const result =\n input.signal === undefined\n ? await input.operation(reader)\n : await input.operation(reader, input.signal);\n\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n return Object.freeze({ kind: 'completed', result });\n } catch (error) {\n if (input.signal?.aborted) {\n return createSnapshotFailure('GIT_OPERATION_ABORTED');\n }\n\n if (!isSnapshotChanged(error)) {\n throw error;\n }\n }\n }\n\n return createSnapshotFailure('WORKING_TREE_UNSTABLE');\n };\n\n return executeSnapshot;\n};\n\n// default bounded snapshot executor used by command execution\nexport const executeWorkingTreeSnapshot = createWorkingTreeSnapshotExecutor();\n","import type { IProjectInspectionPageResult, IProjectValidationResult } from '@moldea.ai/core';\n\nimport type { IMoldeaCliCommand } from '../command-line/index.js';\nimport type { IMoldeaCliCompositionResult } from '../composition/index.js';\nimport { assertMoldeaCliJsonResultIsContentFree } from '../json-output-contract/index.js';\nimport {\n createMoldeaCliOutputPage,\n type IMoldeaCliOutputPage,\n type IMoldeaCliOutputRecord,\n} from '../output-page/index.js';\nimport {\n createMoldeaCliContentPage,\n type IMoldeaCliContentResult,\n type IMoldeaCliProjectContentExecutor,\n} from '../project-content/index.js';\nimport {\n createMoldeaCliScopeProjection,\n type IMoldeaCliProjectScopeExecutionResult,\n type IMoldeaCliScopeResult,\n} from '../project-scope/index.js';\nimport {\n createMoldeaCliInspectProjection,\n createMoldeaCliValidateProjection,\n formatMoldeaCliHumanCompositionResult,\n formatMoldeaCliHumanContentResult,\n formatMoldeaCliHumanError,\n formatMoldeaCliHumanInspectResult,\n formatMoldeaCliHumanScopeResult,\n formatMoldeaCliHumanValidateResult,\n formatMoldeaCliJsonCompositionResult,\n formatMoldeaCliJsonContentResult,\n formatMoldeaCliJsonError,\n formatMoldeaCliJsonInspectResult,\n formatMoldeaCliJsonScopeResult,\n formatMoldeaCliJsonValidateResult,\n MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,\n type IMoldeaCliError,\n type IMoldeaCliInspectResult,\n type IMoldeaCliValidateResult,\n} from '../presentation/index.js';\n\nimport { MOLDEA_CLI_EXIT_CODES } from './constants.js';\nimport type { IMoldeaCliExecutionResult } from './types.js';\n\nconst measureOutput = (output: string): number => Buffer.byteLength(output, 'utf8');\n\n/** Measures a paged result without repeatedly serializing its accumulated JSON records. */\nconst measurePagedOutput = <TRecord extends IMoldeaCliOutputRecord>(\n page: IMoldeaCliOutputPage<TRecord>,\n serializedRecordsUtf8Bytes: number,\n isJson: boolean,\n formatJson: (candidate: IMoldeaCliOutputPage<TRecord>) => string,\n formatHuman: (candidate: IMoldeaCliOutputPage<TRecord>) => string,\n): number => {\n if (!isJson) {\n return measureOutput(formatHuman(page));\n }\n\n const emptyPage = Object.freeze({\n cursor: page.cursor,\n records: Object.freeze([]),\n });\n\n return measureOutput(formatJson(emptyPage)) - 2 + serializedRecordsUtf8Bytes;\n};\n\n/** Creates one process-neutral result for a valid installed composition. */\nexport const createMoldeaCliCompositionExecutionResult = (\n result: IMoldeaCliCompositionResult,\n cliVersion: string,\n isJson: boolean,\n): IMoldeaCliExecutionResult =>\n Object.freeze({\n exitCode: MOLDEA_CLI_EXIT_CODES.Success,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonCompositionResult(result, cliVersion)\n : formatMoldeaCliHumanCompositionResult(result, cliVersion),\n });\n\n/** Creates one safe process-neutral error result in the requested output mode. */\nexport const createMoldeaCliErrorResult = (\n error: IMoldeaCliError,\n command: IMoldeaCliCommand | null,\n cliVersion: string,\n isJson: boolean,\n exitCode: number,\n): IMoldeaCliExecutionResult =>\n Object.freeze(\n isJson\n ? {\n exitCode,\n stderr: '',\n stdout: formatMoldeaCliJsonError(error, command, cliVersion),\n }\n : {\n exitCode,\n stderr: formatMoldeaCliHumanError(error),\n stdout: '',\n },\n );\n\n/**\n * Creates one bounded process-neutral result for a completed validate command.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliValidateExecutionResult = (\n inspection: IProjectValidationResult,\n cliVersion: string,\n isJson: boolean,\n cursor: string | null,\n maxOutputBytes: number,\n): IMoldeaCliExecutionResult => {\n const projection = createMoldeaCliValidateProjection(inspection);\n const createResult = (page: IMoldeaCliValidateResult['page']): IMoldeaCliValidateResult => ({\n diagnosticCount: projection.diagnostics.length,\n errorCount: projection.errorCount,\n formatVersion: projection.formatVersion,\n page,\n snapshotDigest: projection.snapshotDigest,\n source: projection.source,\n valid: projection.valid,\n warningCount: projection.warningCount,\n });\n const page = createMoldeaCliOutputPage({\n command: 'validate',\n cursor,\n filters: {},\n maxOutputBytes,\n measure: (candidate, serializedRecordsUtf8Bytes) =>\n measurePagedOutput(\n candidate,\n serializedRecordsUtf8Bytes,\n isJson,\n (page) => formatMoldeaCliJsonValidateResult(createResult(page), cliVersion),\n (page) => formatMoldeaCliHumanValidateResult(createResult(page)),\n ),\n records: projection.diagnostics,\n snapshotDigest: projection.snapshotDigest,\n });\n const result = Object.freeze(createResult(page));\n\n assertMoldeaCliJsonResultIsContentFree(result);\n\n return Object.freeze({\n exitCode: result.valid\n ? MOLDEA_CLI_EXIT_CODES.Success\n : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonValidateResult(result, cliVersion)\n : formatMoldeaCliHumanValidateResult(result),\n });\n};\n\n/**\n * Creates one bounded content-free result for a completed inspect command.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliInspectExecutionResult = (\n inspection: IProjectInspectionPageResult,\n cliVersion: string,\n isJson: boolean,\n cursor: string | null,\n maxOutputBytes: number,\n): IMoldeaCliExecutionResult => {\n const projection = createMoldeaCliInspectProjection(inspection);\n const createResult = (page: IMoldeaCliInspectResult['page']): IMoldeaCliInspectResult => ({\n counts: projection.counts,\n formatVersion: projection.formatVersion,\n page,\n project: projection.project,\n snapshotDigest: projection.snapshotDigest,\n source: projection.source,\n valid: projection.valid,\n view: projection.view,\n });\n const page = createMoldeaCliOutputPage({\n command: 'inspect',\n cursor,\n filters: {},\n maxOutputBytes,\n measure: (candidate, serializedRecordsUtf8Bytes) =>\n measurePagedOutput(\n candidate,\n serializedRecordsUtf8Bytes,\n isJson,\n (page) => formatMoldeaCliJsonInspectResult(createResult(page), cliVersion),\n (page) => formatMoldeaCliHumanInspectResult(createResult(page)),\n ),\n records: projection.records,\n sourceCursorForRecord: projection.getSourceCursor,\n snapshotDigest: projection.snapshotDigest,\n });\n const result = Object.freeze(createResult(page));\n\n assertMoldeaCliJsonResultIsContentFree(result);\n\n return Object.freeze({\n exitCode: inspection.valid\n ? MOLDEA_CLI_EXIT_CODES.Success\n : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonInspectResult(result, cliVersion)\n : formatMoldeaCliHumanInspectResult(result),\n });\n};\n\n/**\n * Creates one bounded content-free result for changed-path relationship scope.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliScopeExecutionResult = (\n execution: IMoldeaCliProjectScopeExecutionResult,\n cliVersion: string,\n isJson: boolean,\n cursor: string | null,\n maxOutputBytes: number,\n): IMoldeaCliExecutionResult => {\n const projection = createMoldeaCliScopeProjection(execution);\n const createResult = (page: IMoldeaCliScopeResult['page']): IMoldeaCliScopeResult => ({\n counts: projection.counts,\n inputDigest: projection.inputDigest,\n manifestDigest: projection.manifestDigest,\n page,\n relevant: projection.relevant,\n snapshotDigest: projection.snapshotDigest,\n source: MOLDEA_CLI_GIT_WORKING_TREE_SOURCE,\n valid: projection.valid,\n });\n const page = createMoldeaCliOutputPage({\n command: 'scope',\n cursor,\n filters: { inputDigest: projection.inputDigest },\n maxOutputBytes,\n measure: (candidate, serializedRecordsUtf8Bytes) =>\n measurePagedOutput(\n candidate,\n serializedRecordsUtf8Bytes,\n isJson,\n (page) => formatMoldeaCliJsonScopeResult(createResult(page), cliVersion),\n (page) => formatMoldeaCliHumanScopeResult(createResult(page)),\n ),\n records: projection.records,\n snapshotDigest: projection.snapshotDigest,\n });\n const result = Object.freeze(createResult(page));\n\n assertMoldeaCliJsonResultIsContentFree(result, projection.canonicalBodies);\n\n return Object.freeze({\n exitCode: projection.valid\n ? MOLDEA_CLI_EXIT_CODES.Success\n : MOLDEA_CLI_EXIT_CODES.StructuralInvalid,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonScopeResult(result, cliVersion)\n : formatMoldeaCliHumanScopeResult(result),\n });\n};\n\n/**\n * Creates one bounded Unicode-safe explicit canonical content result.\n * @throws\n * - CURSOR_INVALID: The continuation cursor is invalid for this request.\n * - CURSOR_SNAPSHOT_CHANGED: The continuation cursor belongs to a different repository snapshot.\n * - OUTPUT_BUDGET_TOO_SMALL: The output byte budget cannot contain the next complete result.\n */\nexport const createMoldeaCliContentExecutionResult = (\n pageResult: Awaited<ReturnType<IMoldeaCliProjectContentExecutor>>,\n cliVersion: string,\n isJson: boolean,\n cursor: string | null,\n maxOutputBytes: number,\n): IMoldeaCliExecutionResult => {\n const result: IMoldeaCliContentResult = createMoldeaCliContentPage({\n cursor,\n maxOutputBytes,\n measure: (candidate) =>\n measureOutput(\n isJson\n ? formatMoldeaCliJsonContentResult(candidate, cliVersion)\n : formatMoldeaCliHumanContentResult(candidate),\n ),\n page: pageResult,\n });\n\n return Object.freeze({\n exitCode: MOLDEA_CLI_EXIT_CODES.Success,\n stderr: '',\n stdout: isJson\n ? formatMoldeaCliJsonContentResult(result, cliVersion)\n : formatMoldeaCliHumanContentResult(result),\n });\n};\n","import type { IProjectInspectionPageResult, IProjectValidationResult } from '@moldea.ai/core';\nimport { isRepositoryPath } from '@moldea.ai/repository';\n\nimport { MOLDEA_CLI_COMMANDS } from '../command-line/index.js';\nimport type { IMoldeaCliCompositionResolver } from '../composition/index.js';\nimport type { IMoldeaCliCoreInspectionExecutor } from '../core-composition/index.js';\nimport {\n discoverGitWorkingTree,\n type IGitWorkingTreeDiscovery,\n} from '../git-working-tree/index.js';\nimport { mapMoldeaCliOperationalError } from '../operational-error/index.js';\nimport { decodeMoldeaCliCursor, MoldeaCliOutputPageException } from '../output-page/index.js';\nimport {\n executeMoldeaCliProjectContent,\n parseMoldeaCliCanonicalContentPath,\n type IMoldeaCliProjectContentExecutor,\n} from '../project-content/index.js';\nimport {\n executeMoldeaCliProjectScope,\n MOLDEA_MANIFEST_PATH,\n parseMoldeaCliScopePathBytes,\n type IMoldeaCliProjectScopeExecutor,\n} from '../project-scope/index.js';\nimport { createMoldeaCliOwnedError } from '../presentation/index.js';\nimport {\n executeWorkingTreeSnapshot,\n type IWorkingTreeSnapshotExecutor,\n} from '../working-tree-snapshot/index.js';\n\nimport { MOLDEA_CLI_EXIT_CODES } from './constants.js';\nimport {\n createMoldeaCliCompositionExecutionResult,\n createMoldeaCliContentExecutionResult,\n createMoldeaCliErrorResult,\n createMoldeaCliInspectExecutionResult,\n createMoldeaCliScopeExecutionResult,\n createMoldeaCliValidateExecutionResult,\n} from './results.js';\nimport type { IMoldeaCliCommandExecutor, IMoldeaCliExecutionResult } from './types.js';\n\n/** Loads adapter-backed Core inspection only for commands that need it. */\nconst executeLazyCoreInspection: IMoldeaCliCoreInspectionExecutor = async (input) => {\n const { executeMoldeaCliCoreInspection } = await import('../core-composition/index.js');\n\n return executeMoldeaCliCoreInspection(input);\n};\n\ntype IMoldeaCliCompositionLoader = (\n input: Parameters<IMoldeaCliCompositionResolver>[0],\n) => ReturnType<IMoldeaCliCompositionResolver> | Promise<ReturnType<IMoldeaCliCompositionResolver>>;\n\nconst loadInstalledComposition: IMoldeaCliCompositionLoader = async (input) => {\n const { resolveInstalledMoldeaCliComposition } = await import('../composition/index.js');\n\n return resolveInstalledMoldeaCliComposition(input);\n};\n\n/** Creates one operational error result without exposing caught failure details. */\nconst createOperationalErrorResult = (\n code: Parameters<typeof createMoldeaCliOwnedError>[0],\n input: Parameters<IMoldeaCliCommandExecutor>[0],\n): IMoldeaCliExecutionResult =>\n createMoldeaCliErrorResult(\n createMoldeaCliOwnedError(code),\n input.invocation.command,\n input.packageMetadata.version,\n input.invocation.options.isJson,\n MOLDEA_CLI_EXIT_CODES.OperationalError,\n );\n\n/**\n * Creates command dispatch with lazy adapter composition and bounded working-tree snapshots.\n * @param workingTreeDiscovery The Git working-tree discovery operation.\n * @param workingTreeSnapshotExecutor The complete working-tree snapshot operation.\n * @param coreInspectionExecutor The adapter-backed Core inspection operation.\n * @param compositionLoader The installed executable-integrity composition boundary.\n * @param projectScopeExecutor The adapter-free manifest scope operation.\n * @param projectContentExecutor The adapter-free canonical content operation.\n * @returns A command executor for the schema 5 CLI.\n */\nexport const createMoldeaCliCommandExecutor = (\n workingTreeDiscovery: IGitWorkingTreeDiscovery = discoverGitWorkingTree,\n workingTreeSnapshotExecutor: IWorkingTreeSnapshotExecutor = executeWorkingTreeSnapshot,\n coreInspectionExecutor: IMoldeaCliCoreInspectionExecutor = executeLazyCoreInspection,\n compositionLoader: IMoldeaCliCompositionLoader = loadInstalledComposition,\n projectScopeExecutor: IMoldeaCliProjectScopeExecutor = executeMoldeaCliProjectScope,\n projectContentExecutor: IMoldeaCliProjectContentExecutor = executeMoldeaCliProjectContent,\n): IMoldeaCliCommandExecutor => {\n return async (input): Promise<IMoldeaCliExecutionResult> => {\n const command = input.invocation.command;\n const options = input.invocation.options;\n\n try {\n if (\n command === MOLDEA_CLI_COMMANDS.Composition ||\n command === MOLDEA_CLI_COMMANDS.Inspect ||\n command === MOLDEA_CLI_COMMANDS.Validate\n ) {\n const compositionResolution = await compositionLoader({\n packageMetadata: input.packageMetadata,\n });\n\n if (compositionResolution.kind === 'invalid') {\n return createOperationalErrorResult('COMPOSITION_STATE_INVALID', input);\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Composition) {\n return createMoldeaCliCompositionExecutionResult(\n compositionResolution.result,\n input.packageMetadata.version,\n options.isJson,\n );\n }\n }\n\n let scopePaths: readonly string[] | null = null;\n let contentPath: ReturnType<typeof parseMoldeaCliCanonicalContentPath> | null = null;\n let contentOffset = 0;\n const inspectionCursor =\n command === MOLDEA_CLI_COMMANDS.Inspect && options.cursor !== null\n ? decodeMoldeaCliCursor({\n command: 'inspect',\n cursor: options.cursor,\n filters: {},\n }).sourceCursor\n : null;\n\n if (command === MOLDEA_CLI_COMMANDS.Scope) {\n if (options.pathsInput === 'path' && options.path !== null) {\n scopePaths = Object.freeze([options.path]);\n } else if (options.pathsInput === 'stdin' && input.stdin !== undefined) {\n if (input.stdin.byteLength > options.resourceLimits.maxTotalBytes) {\n return createOperationalErrorResult('RESOURCE_LIMIT_EXCEEDED', input);\n }\n\n scopePaths = parseMoldeaCliScopePathBytes(input.stdin, options.resourceLimits.maxEntries);\n } else {\n return createOperationalErrorResult('PATH_INPUT_INVALID', input);\n }\n\n if (scopePaths.some((path) => !isRepositoryPath(path))) {\n return createOperationalErrorResult('PATH_INPUT_INVALID', input);\n }\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Content) {\n if (options.path === null) {\n return createOperationalErrorResult('CONTENT_PATH_INVALID', input);\n }\n\n contentPath = parseMoldeaCliCanonicalContentPath(options.path);\n\n if (options.cursor !== null) {\n const sourceCursor = decodeMoldeaCliCursor({\n command: 'content',\n cursor: options.cursor,\n filters: { path: contentPath },\n }).sourceCursor;\n const match = sourceCursor === null ? null : /^byte:(0|[1-9][0-9]*)$/u.exec(sourceCursor);\n\n if (match === null) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n\n contentOffset = Number(match[1]);\n\n if (!Number.isSafeInteger(contentOffset)) {\n throw new MoldeaCliOutputPageException('CURSOR_INVALID');\n }\n }\n }\n\n const discoveryResult = await workingTreeDiscovery({\n invocationDirectory: input.invocationDirectory,\n repositoryDirectory: options.repositoryDirectory,\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (discoveryResult.kind === 'failed') {\n return createOperationalErrorResult(discoveryResult.errorCode, input);\n }\n\n const resourceLimits = options.resourceLimits;\n const snapshotResult = await workingTreeSnapshotExecutor({\n operation: async (repository, signal) => {\n if (command === MOLDEA_CLI_COMMANDS.Scope && scopePaths !== null) {\n return projectScopeExecutor({\n paths: scopePaths,\n repository,\n resourceLimits,\n ...(signal === undefined ? {} : { signal }),\n });\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Content && contentPath !== null) {\n return projectContentExecutor({\n maxBytes: Math.min(\n resourceLimits.maxFileBytes,\n resourceLimits.maxTotalBytes,\n Math.max(1, Math.floor(options.maxOutputBytes / 2)),\n ),\n offset: contentOffset,\n path: contentPath,\n repository,\n resourceLimits,\n ...(signal === undefined ? {} : { signal }),\n });\n }\n\n return coreInspectionExecutor({\n command: command === MOLDEA_CLI_COMMANDS.Inspect ? 'inspect' : 'validate',\n ...(inspectionCursor === null ? {} : { cursor: inspectionCursor }),\n repository,\n resourceLimits,\n ...(signal === undefined ? {} : { signal }),\n });\n },\n repositoryRoot: discoveryResult.repositoryRoot,\n resourceLimits,\n ...(command === MOLDEA_CLI_COMMANDS.Scope\n ? { selectionPaths: [MOLDEA_MANIFEST_PATH] }\n : contentPath === null\n ? {}\n : { selectionPaths: [contentPath] }),\n ...(input.signal === undefined ? {} : { signal: input.signal }),\n });\n\n if (snapshotResult.kind === 'failed') {\n return createOperationalErrorResult(snapshotResult.errorCode, input);\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Validate) {\n return createMoldeaCliValidateExecutionResult(\n snapshotResult.result as IProjectValidationResult,\n input.packageMetadata.version,\n options.isJson,\n options.cursor,\n options.maxOutputBytes,\n );\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Inspect) {\n return createMoldeaCliInspectExecutionResult(\n snapshotResult.result as IProjectInspectionPageResult,\n input.packageMetadata.version,\n options.isJson,\n options.cursor,\n options.maxOutputBytes,\n );\n }\n\n if (command === MOLDEA_CLI_COMMANDS.Scope) {\n return createMoldeaCliScopeExecutionResult(\n snapshotResult.result as Awaited<ReturnType<IMoldeaCliProjectScopeExecutor>>,\n input.packageMetadata.version,\n options.isJson,\n options.cursor,\n options.maxOutputBytes,\n );\n }\n\n return createMoldeaCliContentExecutionResult(\n snapshotResult.result as Awaited<ReturnType<IMoldeaCliProjectContentExecutor>>,\n input.packageMetadata.version,\n options.isJson,\n options.cursor,\n options.maxOutputBytes,\n );\n } catch (error) {\n return createMoldeaCliErrorResult(\n mapMoldeaCliOperationalError(error),\n command,\n input.packageMetadata.version,\n options.isJson,\n MOLDEA_CLI_EXIT_CODES.OperationalError,\n );\n }\n };\n};\n\n// default private command dispatcher used by the executable runner\nexport const executeMoldeaCliCommand = createMoldeaCliCommandExecutor();\n","import { parseMoldeaCliArguments } from '../command-line/index.js';\nimport { createMoldeaCliOwnedError, formatMoldeaCliHelp } from '../presentation/index.js';\n\nimport { executeMoldeaCliCommand } from './command-executor.js';\nimport { MOLDEA_CLI_EXIT_CODES } from './constants.js';\nimport { createMoldeaCliErrorResult } from './results.js';\nimport type { IMoldeaCliExecutionResult, IRunMoldeaCliOptions } from './types.js';\n\n/**\n * Runs one process-neutral CLI invocation through parsing and private command dispatch.\n * @param options The arguments, installed metadata, optional cancellation, and executor seam.\n * @returns A promise resolving to exact process output and the handled exit code.\n */\nexport const runMoldeaCli = async (\n options: IRunMoldeaCliOptions,\n): Promise<IMoldeaCliExecutionResult> => {\n const parseResult = parseMoldeaCliArguments(options.commandLineArguments);\n\n if (parseResult.kind === 'help') {\n return {\n exitCode: MOLDEA_CLI_EXIT_CODES.Success,\n stderr: '',\n stdout: formatMoldeaCliHelp(parseResult.command),\n };\n }\n\n if (parseResult.kind === 'version') {\n return {\n exitCode: MOLDEA_CLI_EXIT_CODES.Success,\n stderr: '',\n stdout: `${options.packageMetadata.version}\\n`,\n };\n }\n\n if (parseResult.kind === 'error') {\n return createMoldeaCliErrorResult(\n createMoldeaCliOwnedError(parseResult.code),\n parseResult.command,\n options.packageMetadata.version,\n parseResult.isJson,\n MOLDEA_CLI_EXIT_CODES.UsageError,\n );\n }\n\n const executeCommand = options.executeCommand ?? executeMoldeaCliCommand;\n\n try {\n let stdin: Uint8Array | undefined;\n\n if (parseResult.invocation.options.pathsInput === 'stdin') {\n if (options.readStdin === undefined) {\n return createMoldeaCliErrorResult(\n createMoldeaCliOwnedError('PATH_INPUT_INVALID'),\n parseResult.invocation.command,\n options.packageMetadata.version,\n parseResult.invocation.options.isJson,\n MOLDEA_CLI_EXIT_CODES.UsageError,\n );\n }\n\n const stdinResult = await options.readStdin(\n parseResult.invocation.options.resourceLimits.maxTotalBytes,\n options.signal,\n );\n\n if (stdinResult.kind === 'limit-exceeded') {\n return createMoldeaCliErrorResult(\n createMoldeaCliOwnedError('RESOURCE_LIMIT_EXCEEDED'),\n parseResult.invocation.command,\n options.packageMetadata.version,\n parseResult.invocation.options.isJson,\n MOLDEA_CLI_EXIT_CODES.OperationalError,\n );\n }\n\n stdin = stdinResult.bytes;\n }\n\n return await executeCommand({\n invocationDirectory: options.invocationDirectory,\n invocation: parseResult.invocation,\n packageMetadata: options.packageMetadata,\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n ...(stdin === undefined ? {} : { stdin }),\n });\n } catch {\n return createMoldeaCliErrorResult(\n createMoldeaCliOwnedError('INTERNAL_ERROR'),\n parseResult.invocation.command,\n options.packageMetadata.version,\n parseResult.invocation.options.isJson,\n MOLDEA_CLI_EXIT_CODES.OperationalError,\n );\n }\n};\n","import { readFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport { valid as isValidVersion } from 'semver';\n\nimport type { IMoldeaCliPackageEntryResolver, IMoldeaCliPackageMetadata } from './types.js';\n\nconst MOLDEA_CLI_PACKAGE_NAME = '@moldea.ai/cli';\n\n/** Checks exact SemVer syntax without accepting normalized prefixes or surrounding whitespace. */\nconst isExactSemanticVersion = (version: string): boolean =>\n version === version.trim() && /^[0-9]/u.test(version) && isValidVersion(version) !== null;\n\nconst isPlainRecord = (value: unknown): value is Readonly<Record<string, unknown>> => {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n\n const prototype = Object.getPrototypeOf(value) as object | null;\n\n return prototype === Object.prototype || prototype === null;\n};\n\n/** Returns a frozen string record, or null when a package composition field is malformed. */\nconst readStringRecord = (value: unknown): Readonly<Record<string, string>> | null => {\n if (!isPlainRecord(value)) {\n return null;\n }\n\n const entries = Object.entries(value);\n\n if (entries.some(([, entryValue]) => typeof entryValue !== 'string')) {\n return null;\n }\n\n return Object.freeze(Object.fromEntries(entries) as Record<string, string>);\n};\n\n/** Resolves one package entry through the executable's own module-resolution context. */\nconst resolvePackageEntry: IMoldeaCliPackageEntryResolver = (packageName) =>\n import.meta.resolve(packageName);\n\n/** Narrows a resolved package entry after the complete resolution pass succeeds. */\nconst isInstalledPackageEntry = (\n entry: readonly [string, string] | null,\n): entry is readonly [string, string] => entry !== null;\n\n/** Reads one resolved package's exact identity without executing package code. */\nconst readInstalledPackageVersion = async (\n packageName: string,\n packageEntry: string,\n): Promise<string | null> => {\n let packageDirectory: string;\n\n try {\n const packageEntryUrl = new URL(packageEntry);\n\n if (packageEntryUrl.protocol !== 'file:') {\n return null;\n }\n\n packageDirectory = path.dirname(fileURLToPath(packageEntryUrl));\n } catch {\n return null;\n }\n\n while (true) {\n try {\n const parsedManifest = JSON.parse(\n await readFile(path.join(packageDirectory, 'package.json'), 'utf8'),\n ) as unknown;\n\n if (isPlainRecord(parsedManifest) && parsedManifest['name'] === packageName) {\n const version = parsedManifest['version'];\n\n return typeof version === 'string' && isExactSemanticVersion(version) ? version : null;\n }\n } catch {\n // continue toward the package root when this directory has no readable manifest\n }\n\n const parentDirectory = path.dirname(packageDirectory);\n\n if (parentDirectory === packageDirectory) {\n return null;\n }\n\n packageDirectory = parentDirectory;\n }\n};\n\n/** Resolves the actual versions of every declared first-class package dependency. */\nconst readInstalledPackageVersions = async (\n dependencies: Readonly<Record<string, string>> | null,\n packageEntryResolver: IMoldeaCliPackageEntryResolver,\n): Promise<Readonly<Record<string, string>> | null> => {\n if (dependencies === null) {\n return null;\n }\n\n const packageNames = Object.keys(dependencies).filter((packageName) =>\n packageName.startsWith('@moldea.ai/'),\n );\n const installedPackageEntries = await Promise.all(\n packageNames.map(async (packageName) => {\n try {\n const version = await readInstalledPackageVersion(\n packageName,\n packageEntryResolver(packageName),\n );\n\n return version === null ? null : ([packageName, version] as const);\n } catch {\n return null;\n }\n }),\n );\n\n if (!installedPackageEntries.every(isInstalledPackageEntry)) {\n return null;\n }\n\n return Object.freeze(Object.fromEntries(installedPackageEntries));\n};\n\n/**\n * Loads the installed CLI identity and composition used by executable output and integrity checks.\n * @param packageManifestPath The package manifest adjacent to the distribution directory.\n * @param packageEntryResolver The module-resolution boundary for declared first-class packages.\n * @returns A promise resolving to validated package metadata.\n * @throws\n * - If the manifest cannot be read, parsed, or identified as the installed CLI package\n */\nexport const loadMoldeaCliPackageMetadata = async (\n packageManifestPath: string,\n packageEntryResolver: IMoldeaCliPackageEntryResolver = resolvePackageEntry,\n): Promise<IMoldeaCliPackageMetadata> => {\n const parsedManifest = JSON.parse(await readFile(packageManifestPath, 'utf8')) as unknown;\n\n if (\n !isPlainRecord(parsedManifest) ||\n parsedManifest['name'] !== MOLDEA_CLI_PACKAGE_NAME ||\n typeof parsedManifest['version'] !== 'string' ||\n !isExactSemanticVersion(parsedManifest['version'])\n ) {\n throw new TypeError('The installed CLI package metadata is invalid.');\n }\n\n const engines = readStringRecord(parsedManifest['engines']);\n const dependencies = readStringRecord(parsedManifest['dependencies']);\n\n return Object.freeze({\n dependencies,\n installedPackageVersions: await readInstalledPackageVersions(\n dependencies,\n packageEntryResolver,\n ),\n supportedNodeRange: engines?.['node'] ?? null,\n version: parsedManifest['version'],\n });\n};\n","import process from 'node:process';\n\nimport { MOLDEA_CLI_EXIT_CODES } from '../cli-execution/constants.js';\n\nimport type {\n IMoldeaCliProcessSignalSession,\n IMoldeaCliProcessSignalSource,\n IMoldeaCliSignalExitCode,\n IMoldeaCliTerminationSignal,\n} from './types.js';\n\nconst SIGNAL_EXIT_CODES = Object.freeze({\n SIGINT: MOLDEA_CLI_EXIT_CODES.Interrupted,\n SIGTERM: MOLDEA_CLI_EXIT_CODES.Terminated,\n} as const satisfies Readonly<Record<IMoldeaCliTerminationSignal, IMoldeaCliSignalExitCode>>);\n\nconst PROCESS_SIGNAL_SOURCE: IMoldeaCliProcessSignalSource = Object.freeze({\n addListener: (signal: IMoldeaCliTerminationSignal, listener: () => void): void => {\n process.on(signal, listener);\n },\n removeListener: (signal: IMoldeaCliTerminationSignal, listener: () => void): void => {\n process.off(signal, listener);\n },\n});\n\n/**\n * Creates one process-signal session around an operation-scoped abort controller.\n * @param signalSource The process-listener boundary.\n * @returns A session that records the first signal until output completes.\n */\nexport const createMoldeaCliProcessSignalSession = (\n signalSource: IMoldeaCliProcessSignalSource = PROCESS_SIGNAL_SOURCE,\n): IMoldeaCliProcessSignalSession => {\n const controller = new AbortController();\n let exitCode: IMoldeaCliSignalExitCode | null = null;\n let isDisposed = false;\n let isOutputComplete = false;\n\n const handleSignal = (signal: IMoldeaCliTerminationSignal): void => {\n if (exitCode !== null || isDisposed || isOutputComplete) {\n return;\n }\n\n exitCode = SIGNAL_EXIT_CODES[signal];\n controller.abort();\n };\n const handleSigint = (): void => handleSignal('SIGINT');\n const handleSigterm = (): void => handleSignal('SIGTERM');\n\n signalSource.addListener('SIGINT', handleSigint);\n signalSource.addListener('SIGTERM', handleSigterm);\n\n return Object.freeze({\n completeOutput: (): void => {\n isOutputComplete = true;\n },\n dispose: (): void => {\n if (isDisposed) {\n return;\n }\n\n isDisposed = true;\n signalSource.removeListener('SIGINT', handleSigint);\n signalSource.removeListener('SIGTERM', handleSigterm);\n },\n get exitCode(): IMoldeaCliSignalExitCode | null {\n return exitCode;\n },\n get hasReceivedSignal(): boolean {\n return exitCode !== null;\n },\n signal: controller.signal,\n });\n};\n","import path from 'node:path';\nimport process from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\nimport { runMoldeaCli } from '../cli-execution/index.js';\nimport type { IMoldeaCliStdinReader } from '../cli-execution/index.js';\nimport { loadMoldeaCliPackageMetadata } from '../package-metadata/index.js';\nimport { createMoldeaCliOwnedError, formatMoldeaCliHumanError } from '../presentation/index.js';\nimport { createMoldeaCliProcessSignalSession } from '../process-signal/index.js';\n\nconst executableDirectory = path.dirname(fileURLToPath(import.meta.url));\nconst packageManifestPath = path.resolve(executableDirectory, '..', 'package.json');\nconst signalSession = createMoldeaCliProcessSignalSession();\n\n/** Reads process stdin incrementally without retaining bytes above the requested limit. */\nconst readProcessStdin: IMoldeaCliStdinReader = async (maxBytes, signal) => {\n const chunks: Uint8Array[] = [];\n let totalBytes = 0;\n\n for await (const chunk of process.stdin) {\n if (signal?.aborted) {\n return { bytes: new Uint8Array(), kind: 'completed' };\n }\n\n const bytes = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : new Uint8Array(chunk);\n totalBytes += bytes.byteLength;\n\n if (totalBytes > maxBytes) {\n process.stdin.pause();\n return { kind: 'limit-exceeded' };\n }\n\n chunks.push(bytes);\n }\n\n return { bytes: Buffer.concat(chunks, totalBytes), kind: 'completed' };\n};\n\n/**\n * Writes one complete process output string.\n * @param outputStream The destination process stream.\n * @param output The complete output to write.\n * @returns A promise resolving after the stream accepts the output.\n */\nconst writeProcessOutput = async (\n outputStream: NodeJS.WriteStream,\n output: string,\n): Promise<void> => {\n if (output.length === 0) {\n return;\n }\n\n await new Promise<void>((resolve, reject) => {\n outputStream.write(output, (error) => {\n if (error) {\n reject(error);\n return;\n }\n\n resolve();\n });\n });\n};\n\ntry {\n const invocationDirectory = process.cwd();\n const packageMetadata = await loadMoldeaCliPackageMetadata(packageManifestPath);\n const executionResult = await runMoldeaCli({\n commandLineArguments: process.argv.slice(2),\n invocationDirectory,\n packageMetadata,\n readStdin: readProcessStdin,\n signal: signalSession.signal,\n });\n\n if (signalSession.hasReceivedSignal) {\n process.exitCode = signalSession.exitCode;\n } else {\n await writeProcessOutput(process.stdout, executionResult.stdout);\n\n if (!signalSession.hasReceivedSignal) {\n await writeProcessOutput(process.stderr, executionResult.stderr);\n }\n\n if (!signalSession.hasReceivedSignal) {\n signalSession.completeOutput();\n }\n\n process.exitCode = signalSession.exitCode ?? executionResult.exitCode;\n }\n} catch {\n if (signalSession.hasReceivedSignal) {\n process.exitCode = signalSession.exitCode;\n } else {\n await writeProcessOutput(\n process.stderr,\n formatMoldeaCliHumanError(createMoldeaCliOwnedError('INTERNAL_ERROR')),\n ).catch(() => undefined);\n signalSession.completeOutput();\n process.exitCode = 3;\n }\n} finally {\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