@fulmenhq/tsfulmen 0.3.3 → 0.4.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.
- package/CHANGELOG.md +76 -1
- package/README.md +30 -1
- package/config/crucible-ts/taxonomy/metrics.yaml +1 -1
- package/dist/appidentity/index.js +9 -2209
- package/dist/appidentity/index.js.map +1 -1
- package/dist/assets/index.d.ts +184 -0
- package/dist/assets/index.js +4 -0
- package/dist/assets/index.js.map +1 -0
- package/dist/bin/prometheus-cli.js +15 -9139
- package/dist/bin/prometheus-cli.js.map +1 -1
- package/dist/bin/schema-cli.js +4 -6098
- package/dist/bin/schema-cli.js.map +1 -1
- package/dist/bin/signals-cli.js +15 -1910
- package/dist/bin/signals-cli.js.map +1 -1
- package/dist/chunk-24BAF63H.js +194 -0
- package/dist/chunk-24BAF63H.js.map +1 -0
- package/dist/chunk-3HISR2XI.js +36 -0
- package/dist/chunk-3HISR2XI.js.map +1 -0
- package/dist/chunk-56F2EEAG.js +328 -0
- package/dist/chunk-56F2EEAG.js.map +1 -0
- package/dist/chunk-5HZEJGZ5.js +725 -0
- package/dist/chunk-5HZEJGZ5.js.map +1 -0
- package/dist/chunk-7YWACZEJ.js +837 -0
- package/dist/chunk-7YWACZEJ.js.map +1 -0
- package/dist/chunk-BCO3FUUO.js +682 -0
- package/dist/chunk-BCO3FUUO.js.map +1 -0
- package/dist/chunk-GOTEQYAD.js +410 -0
- package/dist/chunk-GOTEQYAD.js.map +1 -0
- package/dist/chunk-HY6JQOFN.js +32 -0
- package/dist/chunk-HY6JQOFN.js.map +1 -0
- package/dist/chunk-LMNAUTW7.js +43 -0
- package/dist/chunk-LMNAUTW7.js.map +1 -0
- package/dist/chunk-LWAH2UG7.js +103 -0
- package/dist/chunk-LWAH2UG7.js.map +1 -0
- package/dist/chunk-OHE2AOH4.js +273 -0
- package/dist/chunk-OHE2AOH4.js.map +1 -0
- package/dist/chunk-P3DNOZOG.js +1488 -0
- package/dist/chunk-P3DNOZOG.js.map +1 -0
- package/dist/chunk-PQ6TKPUN.js +27 -0
- package/dist/chunk-PQ6TKPUN.js.map +1 -0
- package/dist/chunk-QCCN6POA.js +211 -0
- package/dist/chunk-QCCN6POA.js.map +1 -0
- package/dist/chunk-QGTNV4U2.js +985 -0
- package/dist/chunk-QGTNV4U2.js.map +1 -0
- package/dist/chunk-RSLFR4TO.js +631 -0
- package/dist/chunk-RSLFR4TO.js.map +1 -0
- package/dist/chunk-SNV5WG5V.js +9412 -0
- package/dist/chunk-SNV5WG5V.js.map +1 -0
- package/dist/chunk-UP2VWCW5.js +33 -0
- package/dist/chunk-UP2VWCW5.js.map +1 -0
- package/dist/chunk-VJIGX7MH.js +208 -0
- package/dist/chunk-VJIGX7MH.js.map +1 -0
- package/dist/chunk-WCCMRVZF.js +130 -0
- package/dist/chunk-WCCMRVZF.js.map +1 -0
- package/dist/chunk-WSMVLWLB.js +269 -0
- package/dist/chunk-WSMVLWLB.js.map +1 -0
- package/dist/config/index.js +6 -1220
- package/dist/config/index.js.map +1 -1
- package/dist/crucible/fulpack/index.js +2 -25
- package/dist/crucible/fulpack/index.js.map +1 -1
- package/dist/crucible/index.js +13 -1129
- package/dist/crucible/index.js.map +1 -1
- package/dist/docscribe/index.js +2 -680
- package/dist/docscribe/index.js.map +1 -1
- package/dist/errors/index.js +5 -1831
- package/dist/errors/index.js.map +1 -1
- package/dist/errors-D7KXV3QW.js +4 -0
- package/dist/errors-D7KXV3QW.js.map +1 -0
- package/dist/errors-R7ZODJXS.js +8 -0
- package/dist/errors-R7ZODJXS.js.map +1 -0
- package/dist/export-EA3RNQNS.js +6 -0
- package/dist/export-EA3RNQNS.js.map +1 -0
- package/dist/foundry/index.js +340 -3949
- package/dist/foundry/index.js.map +1 -1
- package/dist/foundry/similarity/index.js +3 -134
- package/dist/foundry/similarity/index.js.map +1 -1
- package/dist/fulencode/index.js +3 -319
- package/dist/fulencode/index.js.map +1 -1
- package/dist/fulhash/index.js +3 -611
- package/dist/fulhash/index.js.map +1 -1
- package/dist/fulpack/index.js +3 -1515
- package/dist/fulpack/index.js.map +1 -1
- package/dist/hash-YOJYVOWH.js +4 -0
- package/dist/hash-YOJYVOWH.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +14 -4395
- package/dist/index.js.map +1 -1
- package/dist/loader-VP2ZIC4O.js +9 -0
- package/dist/loader-VP2ZIC4O.js.map +1 -0
- package/dist/logging/index.js +2 -723
- package/dist/logging/index.js.map +1 -1
- package/dist/pathfinder/index.js +18 -2341
- package/dist/pathfinder/index.js.map +1 -1
- package/dist/prom-client-PNEBGD3G.js +4801 -0
- package/dist/prom-client-PNEBGD3G.js.map +1 -0
- package/dist/reports/license-inventory.csv +1 -1
- package/dist/schema/index.d.ts +19 -6
- package/dist/schema/index.js +4 -6148
- package/dist/schema/index.js.map +1 -1
- package/dist/signals/index.js +8 -2767
- package/dist/signals/index.js.map +1 -1
- package/dist/similarity/index.js +3 -134
- package/dist/similarity/index.js.map +1 -1
- package/dist/telemetry/http/index.js +9 -930
- package/dist/telemetry/http/index.js.map +1 -1
- package/dist/telemetry/index.js +4 -1561
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/prometheus/index.js +7 -8422
- package/dist/telemetry/prometheus/index.js.map +1 -1
- package/dist/validator-I3ASDVDB.js +6 -0
- package/dist/validator-I3ASDVDB.js.map +1 -0
- package/package.json +5 -1
- package/schemas/crucible-ts/library/module-manifest/v1.0.0/module-manifest.schema.json +1 -1
- package/schemas/crucible-ts/observability/logging/v1.0.0/definitions.schema.json +1 -1
- package/schemas/crucible-ts/observability/logging/v1.0.0/log-event.schema.json +13 -13
- package/schemas/crucible-ts/observability/logging/v1.0.0/logger-config.schema.json +2 -2
- package/schemas/crucible-ts/observability/logging/v1.0.0/logging-policy.schema.json +1 -1
- package/schemas/crucible-ts/observability/logging/v1.0.0/middleware-config.schema.json +2 -2
- package/schemas/crucible-ts/observability/logging/v1.0.0/severity-filter.schema.json +3 -3
- package/schemas/crucible-ts/upstream/3leaps/crucible/PROVENANCE.md +3 -3
- package/schemas/crucible-ts/upstream/3leaps/crucible/docs/catalog/classifiers/README.md +1 -1
- package/schemas/crucible-ts/upstream/3leaps/crucible/docs/standards/classifiers-framework.md +1 -1
- package/schemas/crucible-ts/upstream/3leaps/crucible/docs/standards/data-sensitivity-classification.md +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/crucible/fulhash/types.ts","../../src/fulhash/errors.ts","../../src/fulhash/algorithms/crc32.ts","../../src/fulhash/algorithms/crc32c.ts","../../src/fulhash/algorithms/sha256.ts","../../src/fulhash/algorithms/xxh3.ts","../../src/fulhash/hash.ts","../../src/fulhash/digest.ts","../../src/errors/correlation.ts","../../src/errors/severity.ts","../../src/errors/serialization.ts","../../src/schema/ajv-formats.ts","../../src/schema/errors.ts","../../src/schema/utils.ts","../../src/schema/goneat-bridge.ts","../../src/schema/normalizer.ts","../../src/schema/registry.ts","../../src/telemetry/counter.ts","../../src/telemetry/gauge.ts","../../src/telemetry/taxonomy.ts","../../src/telemetry/histogram.ts","../../src/telemetry/registry.ts","../../src/telemetry/types.ts","../../src/telemetry/validators.ts","../../src/telemetry/index.ts","../../src/schema/validator.ts","../../src/schema/cli.ts","../../src/schema/export.ts","../../src/schema/index.ts","../../src/errors/validators.ts","../../src/errors/fulmen-error.ts","../../src/errors/index.ts","../../src/fulhash/index.ts","../../src/fulhash/convenience.ts","../../src/fulhash/stream.ts","../../src/fulhash/wasm-loader.ts","../../src/pathfinder/types.ts","../../src/pathfinder/checksum.ts","../../src/pathfinder/constants.ts","../../src/pathfinder/finder.ts","../../src/pathfinder/errors.ts","../../src/pathfinder/safety.ts","../../src/pathfinder/ignore.ts","../../src/pathfinder/convenience.ts","../../src/pathfinder/repoRoot.ts","../../src/pathfinder/validators.ts","../../src/pathfinder/index.ts"],"names":["Algorithm","hex","hexToBytes","hashBytes","crc32","hashString","createHasher","createCRC32","hash","init_errors","__dirname","parseYAML","access","join","readFile","parseYaml","init_registry","init_types","fileURLToPath","dirname","init_validators","createHash","EnforcementLevel","ConstraintType","LoaderType","ChecksumAlgorithm","ChecksumEncoding","path","PathfinderErrorCode","relative","fs","fg","lstat"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAQY,SAAA;AARZ,IAAA,UAAA,GAAA,KAAA,CAAA;AAAA,EAAA,+BAAA,GAAA;AAQO,IAAK,SAAA,qBAAAA,UAAAA,KAAL;AAKL,MAAAA,WAAA,UAAA,CAAA,GAAW,UAAA;AAMX,MAAAA,WAAA,QAAA,CAAA,GAAS,QAAA;AAMT,MAAAA,WAAA,OAAA,CAAA,GAAQ,OAAA;AAMR,MAAAA,WAAA,QAAA,CAAA,GAAS,QAAA;AAvBC,MAAA,OAAAA,UAAAA;AAAA,IAAA,CAAA,EAAA,SAAA,IAAA,EAAA,CAAA;AAAA,EAAA;AAAA,CAAA,CAAA;;;ACRZ,IAIa,YAAA,EAQA,yBAAA,EAUA,oBAAA,EAQA,0BAAA,EAQA,gBAAA;AAtCb,IAAA,WAAA,GAAA,KAAA,CAAA;AAAA,EAAA,uBAAA,GAAA;AAIO,IAAM,YAAA,GAAN,MAAM,aAAA,SAAqB,KAAA,CAAM;AAAA,MACtC,YAAY,OAAA,EAAiB;AAC3B,QAAA,KAAA,CAAM,OAAO,CAAA;AACb,QAAA,IAAA,CAAK,IAAA,GAAO,cAAA;AACZ,QAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,aAAA,CAAa,SAAS,CAAA;AAAA,MACpD;AAAA,KACF;AAEO,IAAM,yBAAA,GAAN,MAAM,0BAAA,SAAkC,YAAA,CAAa;AAAA,MAC1D,WAAA,CAAY,WAAmB,mBAAA,EAA+B;AAC5D,QAAA,KAAA;AAAA,UACE,0BAA0B,SAAS,CAAA,yBAAA,EAA4B,mBAAA,CAAoB,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,SAC/F;AACA,QAAA,IAAA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MAAA,8BAAA;AAAA,MAEJ,wBAAwB,QAAQ,CAAA,CAAA;AAAA,MAChC;AAAA,QACE,QAAA,EAAU,MAAA;AAAA,QACV,OAAA,EAAS,EAAE,WAAA,EAAa,gBAAA,CAAiB,WAAA;AAAY;AACvD,KACF;AAAA,EACF;AACF;;;ACjHO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * FulHash Types\n * Code generated by scripts/codegen/generate-fulhash-types.ts; DO NOT EDIT.\n */\n\n/**\n * Supported hashing algorithms for FulHash\n */\nexport enum Algorithm {\n /**\n * XXH3 (128-bit)\n * Fast non-cryptographic hash (default). Excellent collision resistance, extremely high throughput (50GB/s+).\n */\n XXH3_128 = \"xxh3-128\",\n\n /**\n * SHA-256\n * Cryptographic security standard. Resistant to intentional collisions. Use for security verification.\n */\n SHA256 = \"sha256\",\n\n /**\n * CRC-32 (IEEE)\n * 32-bit Cyclic Redundancy Check. Standard for GZIP/ZIP/PNG legacy format interoperability.\n */\n CRC32 = \"crc32\",\n\n /**\n * CRC-32C (Castagnoli)\n * 32-bit CRC (Castagnoli). HW accelerated (SSE4.2/ARMv8). Use for cloud storage (GCS, AWS) and networking.\n */\n CRC32C = \"crc32c\",\n}\n\n/**\n * Standard digest payload returned by FulHash helpers\n */\nexport interface Digest {\n /**\n * Hash algorithm identifier\n */\n algorithm: \"xxh3-128\" | \"crc32\" | \"crc32c\" | \"sha256\";\n\n /**\n * Lowercase hexadecimal representation of the digest\n */\n hex: string;\n\n /**\n * Canonical string representation '<algorithm>:<hex>'\n */\n formatted: string;\n\n /**\n * Raw digest bytes (optional)\n */\n bytes?: number[];\n}\n","/**\n * Error classes for FulHash module\n */\n\nexport class FulHashError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"FulHashError\";\n Object.setPrototypeOf(this, FulHashError.prototype);\n }\n}\n\nexport class UnsupportedAlgorithmError extends FulHashError {\n constructor(algorithm: string, supportedAlgorithms: string[]) {\n super(\n `Unsupported algorithm \"${algorithm}\". Supported algorithms: ${supportedAlgorithms.join(\", \")}`,\n );\n this.name = \"UnsupportedAlgorithmError\";\n Object.setPrototypeOf(this, UnsupportedAlgorithmError.prototype);\n }\n}\n\nexport class InvalidChecksumError extends FulHashError {\n constructor(checksum: string, reason: string) {\n super(`Invalid checksum \"${checksum}\": ${reason}. Expected format: algorithm:hex`);\n this.name = \"InvalidChecksumError\";\n Object.setPrototypeOf(this, InvalidChecksumError.prototype);\n }\n}\n\nexport class InvalidChecksumFormatError extends InvalidChecksumError {\n constructor(checksum: string, reason: string) {\n super(checksum, reason);\n this.name = \"InvalidChecksumFormatError\";\n Object.setPrototypeOf(this, InvalidChecksumFormatError.prototype);\n }\n}\n\nexport class DigestStateError extends FulHashError {\n constructor(operation: string) {\n super(`Cannot ${operation}: digest already finalized. Call reset() to reuse hasher.`);\n this.name = \"DigestStateError\";\n Object.setPrototypeOf(this, DigestStateError.prototype);\n }\n}\n","import type { IHasher } from \"hash-wasm\";\nimport { crc32, createCRC32 } from \"hash-wasm\";\n\n// Local definition to avoid importing from hash-wasm/dist/lib/util which is not a public export\ntype IDataType =\n | string\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Float32Array\n | Float64Array\n | DataView\n | ArrayBuffer\n | SharedArrayBuffer;\n\n/**\n * Convert hex string to Uint8Array\n * @internal\n */\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(4);\n for (let i = 0; i < 4; i++) {\n bytes[i] = Number.parseInt(hex.substr(i * 2, 2), 16);\n }\n return bytes;\n}\n\nexport async function hashBytes(data: Uint8Array): Promise<Uint8Array> {\n const hex = await crc32(data);\n return hexToBytes(hex);\n}\n\nexport async function hashString(\n str: string,\n encoding: BufferEncoding = \"utf8\",\n): Promise<Uint8Array> {\n if (encoding !== \"utf8\") {\n // hash-wasm only supports string input as UTF-8\n // For other encodings, convert to Buffer first\n const buf = Buffer.from(str, encoding);\n const hex = await crc32(buf);\n return hexToBytes(hex);\n }\n const hex = await crc32(str);\n return hexToBytes(hex);\n}\n\n// Ensure the hasher we return respects the IHasher interface correctly\ninterface CRC32Hasher extends IHasher {\n update(data: IDataType): IHasher;\n}\n\nexport async function createHasher(): Promise<CRC32Hasher> {\n const hasher = await createCRC32();\n return hasher as unknown as CRC32Hasher;\n}\n","import type { IHasher } from \"hash-wasm\";\nimport { crc32, createCRC32 } from \"hash-wasm\";\n\n// Local definition to avoid importing from hash-wasm/dist/lib/util\ntype IDataType =\n | string\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Float32Array\n | Float64Array\n | DataView\n | ArrayBuffer\n | SharedArrayBuffer;\n\nconst CRC32C_POLYNOMIAL = 0x82f63b78;\n\n/**\n * Convert hex string to Uint8Array\n * @internal\n */\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(4);\n for (let i = 0; i < 4; i++) {\n bytes[i] = Number.parseInt(hex.substr(i * 2, 2), 16);\n }\n return bytes;\n}\n\nexport async function hashBytes(data: Uint8Array): Promise<Uint8Array> {\n const hex = await crc32(data, CRC32C_POLYNOMIAL);\n return hexToBytes(hex);\n}\n\nexport async function hashString(\n str: string,\n encoding: BufferEncoding = \"utf8\",\n): Promise<Uint8Array> {\n if (encoding !== \"utf8\") {\n const buf = Buffer.from(str, encoding);\n const hex = await crc32(buf, CRC32C_POLYNOMIAL);\n return hexToBytes(hex);\n }\n const hex = await crc32(str, CRC32C_POLYNOMIAL);\n return hexToBytes(hex);\n}\n\ninterface CRC32Hasher extends IHasher {\n update(data: IDataType): IHasher;\n}\n\nexport async function createHasher(): Promise<CRC32Hasher> {\n const hasher = await createCRC32(CRC32C_POLYNOMIAL);\n return hasher as unknown as CRC32Hasher;\n}\n","/**\n * SHA-256 algorithm adapter using Node.js crypto module\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport function hashBytes(data: Uint8Array): Uint8Array {\n const hash = createHash(\"sha256\");\n hash.update(data);\n return new Uint8Array(hash.digest());\n}\n\nexport function hashString(str: string, encoding: BufferEncoding = \"utf8\"): Uint8Array {\n const hash = createHash(\"sha256\");\n hash.update(str, encoding);\n return new Uint8Array(hash.digest());\n}\n","import { xxhash128 } from \"hash-wasm\";\nimport { FulHashError } from \"../errors.js\";\n\n/**\n * Convert hex string to Uint8Array\n * @internal\n */\nfunction hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(16);\n for (let i = 0; i < 16; i++) {\n bytes[i] = Number.parseInt(hex.substr(i * 2, 2), 16);\n }\n return bytes;\n}\n\n/**\n * Hash bytes using XXH3-128 algorithm\n *\n * Uses the cached hash-wasm xxhash128() helper for optimal performance.\n * The WASM module is initialized once and reused across all calls.\n *\n * @param data - Input data as Uint8Array\n * @returns Hash digest as Uint8Array (16 bytes)\n */\nexport async function hashBytes(data: Uint8Array): Promise<Uint8Array> {\n // Use cached xxhash128 helper - returns hex string\n const hex = await xxhash128(data);\n return hexToBytes(hex);\n}\n\n/**\n * Hash string using XXH3-128 algorithm\n *\n * Uses the cached hash-wasm xxhash128() helper for optimal performance.\n * The WASM module is initialized once and reused across all calls.\n *\n * @param str - Input string\n * @param encoding - Character encoding (only 'utf8' supported)\n * @returns Hash digest as Uint8Array (16 bytes)\n */\nexport async function hashString(\n str: string,\n encoding: \"utf8\" | \"utf16le\" = \"utf8\",\n): Promise<Uint8Array> {\n if (encoding !== \"utf8\") {\n throw new FulHashError(\n \"XXH3-128 only supports UTF-8 encoding. Use utf8 encoding or convert data to Uint8Array.\",\n );\n }\n\n // Use cached xxhash128 helper directly on string\n const hex = await xxhash128(str);\n return hexToBytes(hex);\n}\n","/**\n * Block hashing helpers for one-shot hashing operations\n */\n\nimport { Algorithm } from \"../crucible/fulhash/types.js\";\nimport * as crc32 from \"./algorithms/crc32.js\";\nimport * as crc32c from \"./algorithms/crc32c.js\";\nimport * as sha256 from \"./algorithms/sha256.js\";\nimport * as xxh3 from \"./algorithms/xxh3.js\";\nimport type { HashOptions } from \"./definitions.js\";\nimport { Digest } from \"./digest.js\";\nimport { UnsupportedAlgorithmError } from \"./errors.js\";\n\nexport async function hash(input: string | Uint8Array, options?: HashOptions): Promise<Digest> {\n const algorithm = options?.algorithm ?? Algorithm.XXH3_128;\n const encoding = options?.encoding ?? \"utf8\";\n\n let bytes: Uint8Array;\n\n switch (algorithm) {\n case Algorithm.SHA256:\n if (typeof input === \"string\") {\n bytes = sha256.hashString(input, encoding);\n } else {\n bytes = sha256.hashBytes(input);\n }\n break;\n case Algorithm.XXH3_128:\n if (typeof input === \"string\") {\n if (encoding !== \"utf8\") {\n // Fallback via buffer if non-utf8 is requested, as xxh3-wasm is utf8 only\n bytes = await xxh3.hashBytes(Buffer.from(input, encoding));\n } else {\n bytes = await xxh3.hashString(input, \"utf8\");\n }\n } else {\n bytes = await xxh3.hashBytes(input);\n }\n break;\n case Algorithm.CRC32:\n if (typeof input === \"string\") {\n bytes = await crc32.hashString(input, encoding);\n } else {\n bytes = await crc32.hashBytes(input);\n }\n break;\n case Algorithm.CRC32C:\n if (typeof input === \"string\") {\n bytes = await crc32c.hashString(input, encoding);\n } else {\n bytes = await crc32c.hashBytes(input);\n }\n break;\n default:\n throw new UnsupportedAlgorithmError(algorithm, Object.values(Algorithm));\n }\n\n return new Digest(algorithm, bytes);\n}\n\nexport async function hashString(str: string, options?: HashOptions): Promise<Digest> {\n return hash(str, options);\n}\n\nexport async function hashBytes(data: Uint8Array, options?: HashOptions): Promise<Digest> {\n return hash(data, options);\n}\n","/**\n * Digest implementation - immutable hash result container\n */\n\nimport { Algorithm, type Digest as DigestInterface } from \"../crucible/fulhash/types.js\";\nimport {\n InvalidChecksumError,\n InvalidChecksumFormatError,\n UnsupportedAlgorithmError,\n} from \"./errors.js\";\n\nexport class Digest implements DigestInterface {\n readonly algorithm: Algorithm;\n private readonly _bytes: Uint8Array;\n readonly hex: string;\n readonly formatted: string;\n\n constructor(algorithm: Algorithm, bytes: Uint8Array) {\n this.algorithm = algorithm;\n this._bytes = new Uint8Array(bytes);\n this.hex = Array.from(this._bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n this.formatted = `${this.algorithm}:${this.hex}`;\n Object.freeze(this);\n }\n\n get bytes(): number[] {\n return Array.from(this._bytes);\n }\n\n toJSON(): object {\n return {\n algorithm: this.algorithm,\n hex: this.hex,\n formatted: this.formatted,\n };\n }\n\n toString(): string {\n return this.formatted;\n }\n\n static parse(formatted: string): Digest {\n if (!formatted.includes(\":\")) {\n throw new InvalidChecksumFormatError(formatted, \"missing separator\");\n }\n\n const [algorithmStr, hex] = formatted.split(\":\", 2);\n\n if (!algorithmStr || !hex) {\n throw new InvalidChecksumFormatError(formatted, \"invalid format\");\n }\n\n const algorithm = algorithmStr as Algorithm;\n if (!Object.values(Algorithm).includes(algorithm)) {\n throw new UnsupportedAlgorithmError(algorithm, Object.values(Algorithm));\n }\n\n if (!/^[0-9a-f]+$/.test(hex)) {\n throw new InvalidChecksumError(\n formatted,\n \"hex must contain only lowercase hexadecimal characters\",\n );\n }\n\n let expectedLength: number;\n switch (algorithm) {\n case Algorithm.XXH3_128:\n expectedLength = 32;\n break;\n case Algorithm.SHA256:\n expectedLength = 64;\n break;\n case Algorithm.CRC32:\n case Algorithm.CRC32C:\n expectedLength = 8;\n break;\n default:\n // Should have been caught by Object.values check, but TS safety\n throw new UnsupportedAlgorithmError(algorithm, Object.values(Algorithm));\n }\n\n if (hex.length !== expectedLength) {\n throw new InvalidChecksumError(\n formatted,\n `invalid hex length for ${algorithm}: expected ${expectedLength}, got ${hex.length}`,\n );\n }\n\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(hex.slice(i, i + 2), 16);\n }\n\n return new Digest(algorithm, bytes);\n }\n\n equals(other: Digest): boolean {\n if (this.algorithm !== other.algorithm) {\n return false;\n }\n if (this.hex !== other.hex) {\n return false;\n }\n return true;\n }\n\n static async verify(data: string | Uint8Array, checksum: string): Promise<boolean> {\n const expected = Digest.parse(checksum);\n const { hash } = await import(\"./hash.js\");\n const actual = await hash(data, { algorithm: expected.algorithm });\n return actual.equals(expected);\n }\n}\n","/**\n * Correlation ID generation and validation for error tracking\n *\n * Provides UUID v4 generation for correlation IDs used in observability\n * and distributed tracing scenarios.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\n/**\n * UUID v4 regex pattern for validation\n */\nconst UUID_V4_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/**\n * Generate a new correlation ID (UUID v4)\n *\n * Uses Node.js crypto.randomUUID() for cryptographically strong random values.\n *\n * @returns UUID v4 string (e.g., \"550e8400-e29b-41d4-a716-446655440000\")\n *\n * @example\n * ```typescript\n * const correlationId = generateCorrelationId();\n * // \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\nexport function generateCorrelationId(): string {\n return randomUUID();\n}\n\n/**\n * Validate if a string is a valid UUID v4 correlation ID\n *\n * Checks format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\n * where y is one of [8, 9, a, b]\n *\n * @param id - String to validate\n * @returns True if valid UUID v4 format\n *\n * @example\n * ```typescript\n * isValidCorrelationId('550e8400-e29b-41d4-a716-446655440000') // true\n * isValidCorrelationId('not-a-uuid') // false\n * isValidCorrelationId('550e8400-e29b-31d4-a716-446655440000') // false (version 3, not 4)\n * ```\n */\nexport function isValidCorrelationId(id: string): boolean {\n return UUID_V4_PATTERN.test(id);\n}\n\n/**\n * Normalize a correlation ID (lowercase, trim whitespace)\n *\n * @param id - Correlation ID to normalize\n * @returns Normalized correlation ID\n *\n * @example\n * ```typescript\n * normalizeCorrelationId(' 550E8400-E29B-41D4-A716-446655440000 ')\n * // \"550e8400-e29b-41d4-a716-446655440000\"\n * ```\n */\nexport function normalizeCorrelationId(id: string): string {\n return id.trim().toLowerCase();\n}\n\n/**\n * Type guard to check if a value is a valid correlation ID\n *\n * @param value - Value to check\n * @returns True if value is a string and valid UUID v4\n *\n * @example\n * ```typescript\n * if (isCorrelationId(value)) {\n * // TypeScript knows value is string here\n * const normalized = normalizeCorrelationId(value);\n * }\n * ```\n */\nexport function isCorrelationId(value: unknown): value is string {\n return typeof value === \"string\" && isValidCorrelationId(value);\n}\n","/**\n * Severity mappings for error handling\n *\n * Implements severity levels from assessment/v1.0.0/severity-definitions schema\n * Provides bidirectional mapping between severity names and numeric levels\n */\n\n/**\n * Severity names aligned with assessment taxonomy\n */\nexport const Severity = {\n INFO: \"info\",\n LOW: \"low\",\n MEDIUM: \"medium\",\n HIGH: \"high\",\n CRITICAL: \"critical\",\n} as const;\n\n/**\n * Severity name type (string literal union)\n */\nexport type SeverityName = (typeof Severity)[keyof typeof Severity];\n\n/**\n * Numeric severity level for sorting and comparison\n * info=0, low=1, medium=2, high=3, critical=4\n */\nexport type SeverityLevel = 0 | 1 | 2 | 3 | 4;\n\n/**\n * Canonical severity level mapping (name → level)\n * Aligned with schemas/crucible-ts/assessment/v1.0.0/severity-definitions.schema.json\n */\nexport const SEVERITY_LEVELS: Record<SeverityName, SeverityLevel> = {\n info: 0,\n low: 1,\n medium: 2,\n high: 3,\n critical: 4,\n};\n\n/**\n * Reverse mapping (level → name)\n */\nexport const LEVEL_TO_SEVERITY: Record<SeverityLevel, SeverityName> = {\n 0: \"info\",\n 1: \"low\",\n 2: \"medium\",\n 3: \"high\",\n 4: \"critical\",\n};\n\n/**\n * Convert severity name to numeric level\n *\n * @param name - Severity name (info, low, medium, high, critical)\n * @returns Numeric severity level (0-4)\n * @throws {Error} If severity name is invalid\n *\n * @example\n * ```typescript\n * severityToLevel('high') // returns 3\n * severityToLevel('info') // returns 0\n * ```\n */\nexport function severityToLevel(name: string): SeverityLevel {\n if (!isSeverityName(name)) {\n throw new Error(\n `Invalid severity name: \"${name}\". Must be one of: ${Object.values(Severity).join(\", \")}`,\n );\n }\n return SEVERITY_LEVELS[name];\n}\n\n/**\n * Convert numeric level to severity name\n *\n * @param level - Numeric severity level (0-4)\n * @returns Severity name\n * @throws {Error} If level is invalid\n *\n * @example\n * ```typescript\n * levelToSeverity(3) // returns 'high'\n * levelToSeverity(0) // returns 'info'\n * ```\n */\nexport function levelToSeverity(level: number): SeverityName {\n if (!isSeverityLevel(level)) {\n throw new Error(`Invalid severity level: ${level}. Must be 0-4`);\n }\n return LEVEL_TO_SEVERITY[level];\n}\n\n/**\n * Type guard to check if a value is a valid severity name\n *\n * @param value - Value to check\n * @returns True if value is a valid SeverityName\n *\n * @example\n * ```typescript\n * if (isSeverityName(value)) {\n * const level = severityToLevel(value); // Type-safe\n * }\n * ```\n */\nexport function isSeverityName(value: unknown): value is SeverityName {\n return typeof value === \"string\" && Object.values(Severity).includes(value as SeverityName);\n}\n\n/**\n * Type guard to check if a value is a valid severity level\n *\n * @param value - Value to check\n * @returns True if value is a valid SeverityLevel\n *\n * @example\n * ```typescript\n * if (isSeverityLevel(value)) {\n * const name = levelToSeverity(value); // Type-safe\n * }\n * ```\n */\nexport function isSeverityLevel(value: unknown): value is SeverityLevel {\n return typeof value === \"number\" && value >= 0 && value <= 4 && Number.isInteger(value);\n}\n\n/**\n * Get default severity (medium/2) when not specified\n *\n * @returns Default severity name and level\n */\nexport function getDefaultSeverity(): {\n name: SeverityName;\n level: SeverityLevel;\n} {\n return {\n name: Severity.MEDIUM,\n level: 2,\n };\n}\n\n/**\n * Compare two severity levels\n *\n * @param a - First severity (name or level)\n * @param b - Second severity (name or level)\n * @returns Negative if a < b, positive if a > b, zero if equal\n *\n * @example\n * ```typescript\n * compareSeverity('high', 'low') // returns positive (high > low)\n * compareSeverity(2, 'critical') // returns negative (medium < critical)\n * ```\n */\nexport function compareSeverity(\n a: SeverityName | SeverityLevel,\n b: SeverityName | SeverityLevel,\n): number {\n const levelA = typeof a === \"string\" ? severityToLevel(a) : a;\n const levelB = typeof b === \"string\" ? severityToLevel(b) : b;\n return levelA - levelB;\n}\n","/**\n * Error serialization utilities\n *\n * Provides safe serialization of Error objects and unknown errors to structured data\n */\n\nimport { Severity, type SeverityLevel, type SeverityName } from \"./severity.js\";\n\n/**\n * FulmenError data structure (for serialization)\n * Defined here to avoid circular dependency\n */\nexport interface FulmenErrorData {\n readonly code: string;\n readonly message: string;\n readonly details?: Record<string, unknown>;\n readonly path?: string;\n readonly timestamp?: string;\n readonly severity?: SeverityName;\n readonly severity_level?: SeverityLevel;\n readonly correlation_id?: string;\n readonly trace_id?: string;\n readonly exit_code?: number;\n readonly context?: Record<string, unknown>;\n readonly original?: string | object;\n}\n\n/**\n * Safely serialize any error-like value to FulmenErrorData structure\n *\n * Handles native Error objects, plain objects, strings, and unknown types.\n *\n * @param error - Error value to serialize\n * @param code - Optional error code (defaults to 'UNKNOWN_ERROR')\n * @param severity - Optional severity (defaults to 'medium')\n * @returns Structured error data\n *\n * @example\n * ```typescript\n * try {\n * throw new Error('Something failed');\n * } catch (err) {\n * const data = serializeError(err, 'OPERATION_FAILED', 'high');\n * console.log(JSON.stringify(data));\n * }\n * ```\n */\nexport function serializeError(\n error: unknown,\n code = \"UNKNOWN_ERROR\",\n severity: SeverityName = Severity.MEDIUM,\n): FulmenErrorData {\n // Handle Error instances\n if (error instanceof Error) {\n return {\n code,\n message: error.message,\n severity,\n timestamp: new Date().toISOString(),\n context: {\n name: error.name,\n stack: error.stack,\n },\n original: error.stack || error.message,\n };\n }\n\n // Handle plain objects with message\n if (isErrorLike(error)) {\n return {\n code,\n message: error.message,\n severity,\n timestamp: new Date().toISOString(),\n details: error.details,\n context: error.context,\n original: JSON.stringify(error),\n };\n }\n\n // Handle strings\n if (typeof error === \"string\") {\n return {\n code,\n message: error,\n severity,\n timestamp: new Date().toISOString(),\n };\n }\n\n // Handle everything else\n return {\n code,\n message: String(error),\n severity,\n timestamp: new Date().toISOString(),\n original: typeof error === \"object\" ? JSON.stringify(error) : String(error),\n };\n}\n\n/**\n * Extract error message from unknown error value\n *\n * @param error - Error value\n * @returns Error message string\n */\nexport function extractErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (isErrorLike(error)) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n return String(error);\n}\n\n/**\n * Extract stack trace from error if available\n *\n * @param error - Error value\n * @returns Stack trace string or undefined\n */\nexport function extractStackTrace(error: unknown): string | undefined {\n if (error instanceof Error) {\n return error.stack;\n }\n if (isErrorLike(error) && typeof error.stack === \"string\") {\n return error.stack;\n }\n return undefined;\n}\n\n/**\n * Type guard for error-like objects\n */\nfunction isErrorLike(value: unknown): value is {\n message: string;\n stack?: string;\n details?: Record<string, unknown>;\n context?: Record<string, unknown>;\n} {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"message\" in value &&\n typeof (value as { message: unknown }).message === \"string\"\n );\n}\n","import type Ajv from \"ajv\";\nimport addFormats from \"ajv-formats\";\n\nexport interface FulmenAjvFormatsOptions {\n mode?: \"fast\" | \"full\";\n formats?: string[];\n}\n\nconst DEFAULT_FORMATS = [\n \"date-time\",\n \"email\",\n \"hostname\",\n \"ipv4\",\n \"ipv6\",\n \"uri\",\n \"uri-reference\",\n \"uuid\",\n];\n\n/**\n * Apply Fulmen-standard AJV format support.\n *\n * Useful when configuring AJV in other frameworks (e.g. Fastify) so JSON Schema\n * `format` keywords are enforced consistently.\n */\nexport function applyFulmenAjvFormats(ajv: Ajv, options: FulmenAjvFormatsOptions = {}): Ajv {\n const mode = options.mode ?? \"fast\";\n const formats = options.formats ?? DEFAULT_FORMATS;\n\n // ajv-formats types use a string-literal union; allow callers to supply strings.\n // The `as never` on ajv works around ajv-formats bundling its own older ajv types\n // that diverge from ajv@8.18+ (CodeKeywordDefinition.code parameter incompatibility).\n addFormats(ajv as never, { mode, formats: formats as unknown as never[] });\n return ajv;\n}\n","/**\n * Schema validation errors - implements Fulmen Schema Validation Standard\n */\n\nimport type { SchemaSource, SchemaValidationDiagnostic } from \"./types.js\";\n\n/**\n * Export error reason enum for type-safe error categorization\n */\nexport enum ExportErrorReason {\n FILE_EXISTS = \"FILE_EXISTS\",\n WRITE_FAILED = \"WRITE_FAILED\",\n INVALID_FORMAT = \"INVALID_FORMAT\",\n PROVENANCE_FAILED = \"PROVENANCE_FAILED\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/**\n * Base error class for schema validation operations\n */\nexport class SchemaValidationError extends Error {\n constructor(\n message: string,\n public schemaId?: string,\n public diagnostics: SchemaValidationDiagnostic[] = [],\n public source?: SchemaSource,\n public cause?: Error,\n ) {\n super(message);\n this.name = \"SchemaValidationError\";\n\n // Maintains proper stack trace for where our error was thrown (only available on V8)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, SchemaValidationError);\n }\n }\n\n /**\n * Create error for schema not found\n */\n static schemaNotFound(schemaId: string): SchemaValidationError {\n return new SchemaValidationError(`Schema not found: ${schemaId}`, schemaId);\n }\n\n /**\n * Create error for invalid schema input\n */\n static invalidSchemaInput(source: SchemaSource, details: string): SchemaValidationError {\n return new SchemaValidationError(`Invalid schema input: ${details}`, undefined, [], source);\n }\n\n /**\n * Create error for validation failure\n */\n static validationFailed(\n schemaId: string,\n diagnostics: SchemaValidationDiagnostic[],\n source?: SchemaSource,\n ): SchemaValidationError {\n const errorCount = diagnostics.filter((d) => d.severity === \"ERROR\").length;\n const warningCount = diagnostics.filter((d) => d.severity === \"WARN\").length;\n\n const message = `Schema validation failed: ${errorCount} error(s), ${warningCount} warning(s)`;\n\n return new SchemaValidationError(message, schemaId, diagnostics, source);\n }\n\n /**\n * Create error for goneat binary not found\n */\n static goneatNotFound(goneatPath?: string): SchemaValidationError {\n const pathInfo = goneatPath ? ` at ${goneatPath}` : \"\";\n return new SchemaValidationError(\n `Goneat binary not found${pathInfo}. Falling back to AJV validation.`,\n );\n }\n\n /**\n * Create error for goneat execution failure\n */\n static goneatExecutionFailed(error: Error): SchemaValidationError {\n return new SchemaValidationError(\n \"Goneat execution failed. Falling back to AJV validation.\",\n undefined,\n [],\n undefined,\n error,\n );\n }\n\n /**\n * Create error for empty schema input\n */\n static emptySchemaInput(source?: SchemaSource): SchemaValidationError {\n return new SchemaValidationError(\"Schema content is empty\", undefined, [], source);\n }\n\n /**\n * Create error for parse failure\n */\n static parseFailed(source: SchemaSource, error: Error): SchemaValidationError {\n return new SchemaValidationError(\n `Failed to parse schema: ${error.message}`,\n undefined,\n [],\n source,\n error,\n );\n }\n\n /**\n * Create error for encoding failure\n */\n static encodingFailed(source: SchemaSource, error: Error): SchemaValidationError {\n return new SchemaValidationError(\n `Failed to encode schema: ${error.message}`,\n undefined,\n [],\n source,\n error,\n );\n }\n\n /**\n * Create error for registry operation failure\n */\n static registryError(operation: string, details: string): SchemaValidationError {\n return new SchemaValidationError(`Schema registry ${operation} failed: ${details}`);\n }\n\n /**\n * Format error for display\n */\n format(): string {\n let output = this.message;\n\n if (this.schemaId) {\n output += `\\nSchema ID: ${this.schemaId}`;\n }\n\n if (this.diagnostics.length > 0) {\n output += \"\\n\\nValidation Issues:\";\n this.diagnostics.forEach((diag, index) => {\n output += `\\n ${index + 1}. [${diag.severity}] ${diag.message}`;\n if (diag.pointer) {\n output += ` at ${diag.pointer}`;\n }\n if (diag.keyword) {\n output += ` (keyword: ${diag.keyword})`;\n }\n if (diag.source) {\n output += ` [${diag.source}]`;\n }\n });\n }\n\n if (this.source) {\n output += `\\n\\nSource: ${this.source.type}`;\n if (this.source.id) {\n output += ` (${this.source.id})`;\n }\n }\n\n return output;\n }\n\n /**\n * Convert to JSON representation\n */\n toJSON(): {\n name: string;\n message: string;\n schemaId?: string;\n diagnostics: SchemaValidationDiagnostic[];\n source?: SchemaSource;\n cause?: string;\n } {\n return {\n name: this.name,\n message: this.message,\n schemaId: this.schemaId,\n diagnostics: this.diagnostics,\n source: this.source,\n cause: this.cause?.message,\n };\n }\n}\n\n/**\n * Error class for schema export operations\n */\nexport class SchemaExportError extends SchemaValidationError {\n constructor(\n message: string,\n public reason: ExportErrorReason,\n public schemaId?: string,\n public outPath?: string,\n public cause?: Error,\n ) {\n super(message, schemaId, [], undefined, cause);\n this.name = \"SchemaExportError\";\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, SchemaExportError);\n }\n }\n\n /**\n * Create error for file already exists\n */\n static fileExists(outPath: string): SchemaExportError {\n return new SchemaExportError(\n `Output file already exists: ${outPath}. Use overwrite option to replace.`,\n ExportErrorReason.FILE_EXISTS,\n undefined,\n outPath,\n );\n }\n\n /**\n * Create error for invalid export format\n */\n static invalidFormat(format: string, outPath: string): SchemaExportError {\n return new SchemaExportError(\n `Invalid export format: ${format}. Must be 'json' or 'yaml'.`,\n ExportErrorReason.INVALID_FORMAT,\n undefined,\n outPath,\n );\n }\n\n /**\n * Create error for write failure\n */\n static writeFailed(outPath: string, error: Error): SchemaExportError {\n return new SchemaExportError(\n `Failed to write schema to ${outPath}: ${error.message}`,\n ExportErrorReason.WRITE_FAILED,\n undefined,\n outPath,\n error,\n );\n }\n\n /**\n * Create error for provenance extraction failure\n */\n static provenanceFailed(details: string, error?: Error): SchemaExportError {\n return new SchemaExportError(\n `Failed to extract provenance metadata: ${details}`,\n ExportErrorReason.PROVENANCE_FAILED,\n undefined,\n undefined,\n error,\n );\n }\n}\n","/**\n * Schema validation utilities - helper functions for formatting and validation\n */\n\nimport { SchemaValidationError } from \"./errors.js\";\nimport type { SchemaValidationDiagnostic, SchemaValidationResult } from \"./types.js\";\n\n/**\n * Format validation diagnostics for display\n */\nexport function formatDiagnostics(diagnostics: SchemaValidationDiagnostic[]): string {\n if (diagnostics.length === 0) {\n return \"No validation issues found.\";\n }\n\n const lines: string[] = [];\n const errors = diagnostics.filter((d) => d.severity === \"ERROR\");\n const warnings = diagnostics.filter((d) => d.severity === \"WARN\");\n\n if (errors.length > 0) {\n lines.push(`❌ ${errors.length} error(s) found:`);\n errors.forEach((diag, index) => {\n lines.push(` ${index + 1}. ${diag.message}`);\n if (diag.pointer) {\n lines.push(` at ${diag.pointer}`);\n }\n if (diag.keyword) {\n lines.push(` keyword: ${diag.keyword}`);\n }\n });\n }\n\n if (warnings.length > 0) {\n lines.push(\"\");\n lines.push(`⚠️ ${warnings.length} warning(s) found:`);\n warnings.forEach((diag, index) => {\n lines.push(` ${index + 1}. ${diag.message}`);\n if (diag.pointer) {\n lines.push(` at ${diag.pointer}`);\n }\n });\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Format validation result for display\n */\nexport function formatValidationResult(result: SchemaValidationResult): string {\n if (result.valid) {\n return \"✅ Validation passed\";\n }\n\n const output: string[] = [];\n output.push(\"❌ Validation failed\");\n output.push(formatDiagnostics(result.diagnostics));\n output.push(`\\nSource: ${result.source}`);\n\n return output.join(\"\\n\");\n}\n\n/**\n * Check if value is a SchemaValidationError\n */\nexport function isValidationError(error: unknown): error is SchemaValidationError {\n return error instanceof SchemaValidationError;\n}\n\n/**\n * Extract validation result from error or return success\n */\nexport function extractValidationResult(error: unknown): {\n valid: boolean;\n diagnostics: SchemaValidationDiagnostic[];\n source: \"ajv\" | \"goneat\";\n} {\n if (isValidationError(error)) {\n return {\n valid: false,\n diagnostics: error.diagnostics,\n source: error.diagnostics[0]?.source || \"ajv\",\n };\n }\n\n return {\n valid: true,\n diagnostics: [],\n source: \"ajv\",\n };\n}\n\n/**\n * Normalize JSON pointer path for display\n */\nexport function normalizePointer(pointer: string): string {\n if (pointer === \"\") {\n return \"root\";\n }\n return pointer.replace(/^\\//, \"\").replace(/\\//g, \".\");\n}\n\n/**\n * Create a validation diagnostic\n */\nexport function createDiagnostic(\n pointer: string,\n message: string,\n keyword: string,\n severity: \"ERROR\" | \"WARN\" = \"ERROR\",\n source: \"ajv\" | \"goneat\" = \"ajv\",\n data?: unknown,\n): SchemaValidationDiagnostic {\n return {\n pointer,\n message,\n keyword,\n severity,\n source,\n data,\n };\n}\n\n/**\n * Group diagnostics by severity\n */\nexport function groupDiagnosticsBySeverity(diagnostics: SchemaValidationDiagnostic[]): {\n errors: SchemaValidationDiagnostic[];\n warnings: SchemaValidationDiagnostic[];\n} {\n return {\n errors: diagnostics.filter((d) => d.severity === \"ERROR\"),\n warnings: diagnostics.filter((d) => d.severity === \"WARN\"),\n };\n}\n\n/**\n * Count diagnostics by severity\n */\nexport function countDiagnostics(diagnostics: SchemaValidationDiagnostic[]): {\n total: number;\n errors: number;\n warnings: number;\n} {\n const grouped = groupDiagnosticsBySeverity(diagnostics);\n return {\n total: diagnostics.length,\n errors: grouped.errors.length,\n warnings: grouped.warnings.length,\n };\n}\n","/**\n * Goneat bridge - Optional integration for CLI-only goneat validation\n *\n * Provides goneat validation as an opt-in alternative for CLI exploration.\n * NOT used by library consumers - AJV validation is the primary implementation.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { access } from \"node:fs/promises\";\nimport type { SchemaValidationDiagnostic, SchemaValidationResult } from \"./types.js\";\nimport { createDiagnostic } from \"./utils.js\";\n\n/**\n * Goneat validation output structure\n */\ninterface GoneatValidationOutput {\n valid: boolean;\n errors?: Array<{\n path: string;\n message: string;\n keyword?: string;\n }>;\n}\n\n/**\n * Detect goneat binary location\n */\nexport async function detectGoneat(customPath?: string): Promise<string | null> {\n // Try custom path first\n if (customPath) {\n try {\n await access(customPath);\n return customPath;\n } catch {\n return null;\n }\n }\n\n // Try GONEAT_PATH environment variable\n if (process.env.GONEAT_PATH) {\n try {\n await access(process.env.GONEAT_PATH);\n return process.env.GONEAT_PATH;\n } catch {\n // Continue to next option\n }\n }\n\n // Try local bin/goneat\n try {\n await access(\"./bin/goneat\");\n return \"./bin/goneat\";\n } catch {\n // Continue to next option\n }\n\n // Try system PATH (assume 'goneat' command available)\n return \"goneat\";\n}\n\n/**\n * Check if goneat is available\n *\n * If goneatPath is provided, use it directly to test availability.\n * Otherwise, detect goneat location first.\n */\nexport async function isGoneatAvailable(goneatPath?: string): Promise<boolean> {\n let pathToTest: string | null;\n\n if (goneatPath) {\n // Use provided path directly - don't re-detect\n // This allows testing 'goneat' command from PATH\n pathToTest = goneatPath;\n } else {\n // Detect goneat location\n pathToTest = await detectGoneat();\n if (!pathToTest) return false;\n }\n\n return new Promise((resolve) => {\n const proc = spawn(pathToTest as string, [\"version\"], { stdio: \"ignore\" });\n\n // Timeout after 5 seconds to prevent hanging in CI\n const timeout = setTimeout(() => {\n proc.kill();\n resolve(false);\n }, 5000);\n\n proc.on(\"close\", (code) => {\n clearTimeout(timeout);\n resolve(code === 0);\n });\n proc.on(\"error\", () => {\n clearTimeout(timeout);\n resolve(false);\n });\n });\n}\n\n/**\n * Run goneat schema validation (CLI-only, opt-in)\n *\n * This is NOT used by library validation - it's purely for CLI comparison.\n * Library users get full AJV validation without goneat dependency.\n */\nexport async function runGoneatValidation(\n schemaPath: string,\n dataPath: string,\n goneatPath?: string,\n): Promise<SchemaValidationResult> {\n const detected = await detectGoneat(goneatPath);\n\n if (!detected) {\n return {\n valid: false,\n diagnostics: [\n createDiagnostic(\n \"\",\n \"goneat binary not found. Install goneat or specify path with --goneat-path\",\n \"goneat-unavailable\",\n \"ERROR\",\n \"goneat\",\n ),\n ],\n source: \"goneat\",\n };\n }\n\n // Check availability using the detected path directly\n if (!(await isGoneatAvailable(detected))) {\n return {\n valid: false,\n diagnostics: [\n createDiagnostic(\n \"\",\n `goneat binary found at '${detected}' but not executable or version check failed`,\n \"goneat-not-executable\",\n \"ERROR\",\n \"goneat\",\n ),\n ],\n source: \"goneat\",\n };\n }\n\n return new Promise((resolve) => {\n const args = [\n \"schema\",\n \"validate\",\n \"--schema\",\n schemaPath,\n \"--data\",\n dataPath,\n \"--format\",\n \"json\",\n ];\n const proc = spawn(detected, args);\n\n let stdout = \"\";\n let stderr = \"\";\n\n proc.stdout.on(\"data\", (data) => {\n stdout += data.toString();\n });\n\n proc.stderr.on(\"data\", (data) => {\n stderr += data.toString();\n });\n\n proc.on(\"close\", (code: number | null) => {\n // Parse goneat output\n let output: GoneatValidationOutput;\n\n try {\n output = JSON.parse(stdout) as GoneatValidationOutput;\n } catch {\n // Failed to parse output, treat as error\n resolve({\n valid: false,\n diagnostics: [\n createDiagnostic(\n \"\",\n `goneat validation failed: ${stderr || \"unknown error\"}`,\n \"goneat-error\",\n \"ERROR\",\n \"goneat\",\n ),\n ],\n source: \"goneat\",\n });\n return;\n }\n\n // Convert goneat errors to our diagnostic format\n const diagnostics: SchemaValidationDiagnostic[] =\n output.errors?.map((error) =>\n createDiagnostic(\n error.path || \"\",\n error.message,\n error.keyword || \"validation\",\n \"ERROR\",\n \"goneat\",\n ),\n ) || [];\n\n resolve({\n valid: code === 0 && output.valid,\n diagnostics,\n source: \"goneat\",\n });\n });\n\n proc.on(\"error\", (error) => {\n resolve({\n valid: false,\n diagnostics: [\n createDiagnostic(\n \"\",\n `Failed to execute goneat: ${error.message}`,\n \"goneat-spawn-error\",\n \"ERROR\",\n \"goneat\",\n ),\n ],\n source: \"goneat\",\n });\n });\n });\n}\n","/**\n * Schema normalizer - implements schema normalization per Fulmen standard\n *\n * Provides utilities for canonicalizing and comparing schemas across\n * JSON and YAML formats with comment preservation and deterministic output.\n */\n\nimport { parse as parseYAML } from \"yaml\";\nimport { SchemaValidationError } from \"./errors.js\";\nimport type { SchemaInput, SchemaNormalizationOptions } from \"./types.js\";\n\n/**\n * Parse schema input to object\n */\nfunction parseSchemaInput(input: SchemaInput): Record<string, unknown> {\n if (!input) {\n throw SchemaValidationError.parseFailed(\n { type: \"string\", content: \"\" },\n new Error(\"schema content is empty\"),\n );\n }\n\n try {\n if (typeof input === \"string\") {\n // Try JSON first, fall back to YAML\n try {\n return JSON.parse(input) as Record<string, unknown>;\n } catch {\n return parseYAML(input) as Record<string, unknown>;\n }\n }\n\n if (Buffer.isBuffer(input)) {\n const content = input.toString(\"utf-8\");\n try {\n return JSON.parse(content) as Record<string, unknown>;\n } catch {\n return parseYAML(content) as Record<string, unknown>;\n }\n }\n\n // Already an object\n return input as Record<string, unknown>;\n } catch (error) {\n throw SchemaValidationError.parseFailed(\n {\n type: typeof input === \"string\" ? \"string\" : \"object\",\n content: typeof input === \"string\" ? input : JSON.stringify(input),\n },\n error as Error,\n );\n }\n}\n\n/**\n * Sort object keys recursively in lexicographical order\n */\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortObjectKeys);\n }\n\n const sorted: Record<string, unknown> = {};\n const keys = Object.keys(obj).sort();\n\n for (const key of keys) {\n sorted[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n }\n\n return sorted;\n}\n\n/**\n * Normalize schema to canonical JSON format\n *\n * Per Fulmen Schema Normalization Standard:\n * - Accepts YAML or JSON input\n * - Strips comments while preserving semantic structure\n * - Sorts keys lexicographically\n * - Produces deterministic, pretty-printed JSON (or compact if requested)\n */\nexport function normalizeSchema(\n input: SchemaInput,\n options: SchemaNormalizationOptions = {},\n): string {\n try {\n // Parse input to object\n const parsed = parseSchemaInput(input);\n\n // Sort keys recursively\n const sorted = sortObjectKeys(parsed);\n\n // Serialize to JSON with optional compact mode\n if (options.compact) {\n return JSON.stringify(sorted);\n }\n\n // Default: pretty-printed with 2-space indentation\n return JSON.stringify(sorted, null, 2);\n } catch (error) {\n if (error instanceof SchemaValidationError) {\n throw error;\n }\n throw SchemaValidationError.parseFailed(\n {\n type: typeof input === \"string\" ? \"string\" : \"object\",\n content: typeof input === \"string\" ? input : JSON.stringify(input),\n },\n error as Error,\n );\n }\n}\n\n/**\n * Compare two schemas for semantic equality\n *\n * Normalizes both schemas and compares the canonical JSON output.\n * Returns equality result along with normalized versions for debugging.\n */\nexport function compareSchemas(\n schemaA: SchemaInput,\n schemaB: SchemaInput,\n options: SchemaNormalizationOptions = {},\n): { equal: boolean; normalizedA: string; normalizedB: string } {\n const normalizedA = normalizeSchema(schemaA, options);\n const normalizedB = normalizeSchema(schemaB, options);\n\n return {\n equal: normalizedA === normalizedB,\n normalizedA,\n normalizedB,\n };\n}\n","/**\n * Schema registry - implements schema discovery and metadata extraction\n */\n\nimport { access, readFile } from \"node:fs/promises\";\nimport { dirname, extname, join, relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport glob from \"fast-glob\";\nimport { parse as parseYAML } from \"yaml\";\nimport { SchemaValidationError } from \"./errors.js\";\nimport type { SchemaFormat, SchemaMetadata, SchemaRegistryOptions } from \"./types.js\";\n\n/**\n * Default schema file patterns\n */\nconst DEFAULT_PATTERNS = [\"**/*.schema.json\", \"**/*.schema.yaml\", \"**/*.schema.yml\"];\n\n/**\n * Schema registry class for managing schema discovery and metadata\n */\nexport class SchemaRegistry {\n private schemas: Map<string, SchemaMetadata> = new Map();\n private options: SchemaRegistryOptions;\n\n constructor(options: SchemaRegistryOptions = {}) {\n this.options = {\n baseDir: options.baseDir || this.getDefaultSchemaDir(),\n patterns: options.patterns || DEFAULT_PATTERNS,\n followSymlinks: options.followSymlinks ?? false,\n maxDepth: options.maxDepth ?? 10,\n };\n }\n\n /**\n * Get default schema directory using import.meta.url\n */\n private getDefaultSchemaDir(): string {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n // From src/schema/ we need to go up 2 levels to repo root, then into schemas/crucible-ts\n return join(__dirname, \"..\", \"..\", \"schemas\", \"crucible-ts\");\n }\n\n /**\n * Build logical schema ID from file path\n */\n private buildSchemaId(filePath: string, baseDir: string): string {\n const relativePath = relative(baseDir, filePath);\n const withoutExt = relativePath.replace(/\\.(schema\\.(json|yaml|yml))$/, \"\");\n return withoutExt.replace(/\\\\/g, \"/\"); // Normalize path separators\n }\n\n /**\n * Extract schema format from file extension\n */\n private getSchemaFormat(filePath: string): SchemaFormat {\n const ext = extname(filePath).toLowerCase();\n switch (ext) {\n case \".json\":\n return \"json\";\n case \".yaml\":\n case \".yml\":\n return \"yaml\";\n default:\n return \"json\"; // Default fallback\n }\n }\n\n /**\n * Extract metadata from schema file\n */\n private async extractMetadata(filePath: string): Promise<SchemaMetadata> {\n try {\n const content = await readFile(filePath, \"utf-8\");\n const format = this.getSchemaFormat(filePath);\n\n let parsed: Record<string, unknown>;\n if (format === \"yaml\") {\n parsed = parseYAML(content) as Record<string, unknown>;\n } else {\n parsed = JSON.parse(content) as Record<string, unknown>;\n }\n\n const baseDir = this.options.baseDir ?? \"\";\n const relativePath = relative(baseDir, filePath);\n\n return {\n id: this.buildSchemaId(filePath, baseDir),\n path: filePath,\n relativePath: relativePath,\n format,\n version: (parsed.$schema as string) || (parsed.version as string),\n description: (parsed.title as string) || (parsed.description as string),\n schemaDraft: parsed.$schema as string,\n };\n } catch (error) {\n throw SchemaValidationError.registryError(\n \"metadata extraction\",\n `Failed to process ${filePath}: ${(error as Error).message}`,\n );\n }\n }\n\n /**\n * Discover and index all available schemas\n */\n async discoverSchemas(): Promise<void> {\n try {\n const baseDir = this.options.baseDir ?? \"\";\n const patterns = this.options.patterns ?? [];\n\n if (patterns.length === 0) {\n this.schemas.clear();\n return;\n }\n\n const pattern = patterns.map((p) => join(baseDir, p));\n\n // Check if base directory exists\n try {\n await access(baseDir);\n } catch {\n // Base directory doesn't exist, clear registry and return\n this.schemas.clear();\n return;\n }\n\n const files = await glob(pattern, {\n absolute: true,\n followSymbolicLinks: this.options.followSymlinks,\n deep: this.options.maxDepth,\n onlyFiles: true,\n suppressErrors: true, // Don't throw on permission errors\n });\n\n // Clear existing schemas\n this.schemas.clear();\n\n // Process each schema file\n for (const filePath of files) {\n try {\n const metadata = await this.extractMetadata(filePath);\n this.schemas.set(metadata.id, metadata);\n } catch (error) {\n // Log error but continue processing other schemas\n console.warn(`Warning: Failed to process schema ${filePath}:`, error);\n }\n }\n } catch (error) {\n throw SchemaValidationError.registryError(\"discovery\", (error as Error).message);\n }\n }\n\n /**\n * List available schemas with optional prefix filtering\n */\n async listSchemas(prefix?: string): Promise<SchemaMetadata[]> {\n if (this.schemas.size === 0) {\n await this.discoverSchemas();\n }\n\n const schemas = Array.from(this.schemas.values());\n\n if (prefix) {\n return schemas.filter((schema) => schema.id.startsWith(prefix));\n }\n\n return schemas;\n }\n\n /**\n * Get schema by logical ID\n */\n async getSchema(id: string): Promise<SchemaMetadata> {\n if (this.schemas.size === 0) {\n await this.discoverSchemas();\n }\n\n const schema = this.schemas.get(id);\n if (!schema) {\n throw SchemaValidationError.schemaNotFound(id);\n }\n\n return schema;\n }\n\n /**\n * Get schema by file path\n */\n async getSchemaByPath(filePath: string): Promise<SchemaMetadata> {\n if (this.schemas.size === 0) {\n await this.discoverSchemas();\n }\n\n const absolutePath = filePath.startsWith(\"/\") ? filePath : join(process.cwd(), filePath);\n\n for (const schema of this.schemas.values()) {\n if (schema.path === absolutePath) {\n return schema;\n }\n }\n\n throw SchemaValidationError.schemaNotFound(filePath);\n }\n\n /**\n * Check if schema exists\n */\n async hasSchema(id: string): Promise<boolean> {\n if (this.schemas.size === 0) {\n await this.discoverSchemas();\n }\n\n return this.schemas.has(id);\n }\n\n /**\n * Get registry size\n */\n get size(): number {\n return this.schemas.size;\n }\n\n /**\n * Clear registry cache\n */\n clear(): void {\n this.schemas.clear();\n }\n}\n\n/**\n * Global schema registry instance with cached options\n */\nlet globalRegistry: SchemaRegistry | undefined;\nlet globalRegistryOptions: SchemaRegistryOptions | undefined;\n\n/**\n * Check if registry options have changed\n */\nfunction optionsChanged(newOptions?: SchemaRegistryOptions): boolean {\n if (!newOptions && !globalRegistryOptions) return false;\n if (!newOptions || !globalRegistryOptions) return true;\n\n return (\n newOptions.baseDir !== globalRegistryOptions.baseDir ||\n JSON.stringify(newOptions.patterns) !== JSON.stringify(globalRegistryOptions.patterns) ||\n newOptions.followSymlinks !== globalRegistryOptions.followSymlinks ||\n newOptions.maxDepth !== globalRegistryOptions.maxDepth\n );\n}\n\n/**\n * Get or create global schema registry, rebuilding if options change\n */\nexport function getSchemaRegistry(options?: SchemaRegistryOptions): SchemaRegistry {\n if (!globalRegistry || optionsChanged(options)) {\n globalRegistry = new SchemaRegistry(options);\n globalRegistryOptions = options;\n }\n return globalRegistry;\n}\n\n/**\n * List available schemas with optional prefix filtering\n */\nexport async function listSchemas(\n prefix?: string,\n options?: SchemaRegistryOptions,\n): Promise<SchemaMetadata[]> {\n const registry = getSchemaRegistry(options);\n return registry.listSchemas(prefix);\n}\n\n/**\n * Get schema by logical ID\n */\nexport async function getSchema(\n id: string,\n options?: SchemaRegistryOptions,\n): Promise<SchemaMetadata> {\n const registry = getSchemaRegistry(options);\n return registry.getSchema(id);\n}\n\n/**\n * Get schema by file path\n */\nexport async function getSchemaByPath(\n filePath: string,\n options?: SchemaRegistryOptions,\n): Promise<SchemaMetadata> {\n const registry = getSchemaRegistry(options);\n return registry.getSchemaByPath(filePath);\n}\n\n/**\n * Check if schema exists\n */\nexport async function hasSchema(id: string, options?: SchemaRegistryOptions): Promise<boolean> {\n const registry = getSchemaRegistry(options);\n return registry.hasSchema(id);\n}\n","/**\n * Counter metric implementation\n *\n * Monotonically increasing counter for counting events\n */\n\nimport type { MetricName } from \"./types.js\";\n\n/**\n * Counter metric\n *\n * Monotonically increasing value for counting events.\n * Supports labeled metrics (Crucible v0.2.7+).\n * Use for metrics like request counts, error counts, etc.\n */\nexport class Counter {\n private value = 0;\n private labeledValues = new Map<string, number>();\n\n constructor(public readonly name: MetricName) {}\n\n /**\n * Increment counter by delta (default: 1)\n *\n * @param delta - Amount to increment (must be non-negative)\n * @param labels - Optional label dimensions for this observation\n * @throws {Error} If delta is negative\n *\n * @example\n * ```typescript\n * counter.inc(); // Increment unlabeled by 1\n * counter.inc(5); // Increment unlabeled by 5\n * counter.inc(1, { status: '200' }); // Increment labeled instance\n * counter.inc(1, { result: 'success' }); // Different label set\n * ```\n */\n inc(delta = 1, labels?: Record<string, string>): void {\n if (delta < 0) {\n throw new Error(`Counter delta must be non-negative, got: ${delta}`);\n }\n\n if (labels && Object.keys(labels).length > 0) {\n // Labeled metric - track per label combination\n const labelKey = this.serializeLabels(labels);\n const current = this.labeledValues.get(labelKey) || 0;\n this.labeledValues.set(labelKey, current + delta);\n } else {\n // Unlabeled metric\n this.value += delta;\n }\n }\n\n /**\n * Get current counter value (unlabeled)\n */\n getValue(): number {\n return this.value;\n }\n\n /**\n * Get all labeled values\n * @returns Map of serialized label keys to values\n */\n getLabeledValues(): Map<string, number> {\n return new Map(this.labeledValues);\n }\n\n /**\n * Get value for specific label combination\n */\n getValueForLabels(labels: Record<string, string>): number {\n const labelKey = this.serializeLabels(labels);\n return this.labeledValues.get(labelKey) || 0;\n }\n\n /**\n * Reset counter to zero (all label combinations)\n */\n reset(): void {\n this.value = 0;\n this.labeledValues.clear();\n }\n\n /**\n * Serialize labels to deterministic string key\n * Format: key1=value1,key2=value2 (sorted by key)\n */\n private serializeLabels(labels: Record<string, string>): string {\n return Object.entries(labels)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join(\",\");\n }\n}\n","/**\n * Gauge metric implementation\n *\n * Gauge for arbitrary values that can go up and down\n */\n\nimport type { MetricName } from \"./types.js\";\n\n/**\n * Gauge metric\n *\n * Arbitrary value that can increase or decrease.\n * Supports labeled metrics (Crucible v0.2.7+).\n * Use for metrics like current connections, memory usage, temperature, etc.\n */\nexport class Gauge {\n private value = 0;\n private labeledValues = new Map<string, number>();\n\n constructor(public readonly name: MetricName) {}\n\n /**\n * Set gauge to specific value\n *\n * @param value - New gauge value (can be any number, including negative)\n * @param labels - Optional label dimensions for this observation\n *\n * @example\n * ```typescript\n * gauge.set(42); // Set unlabeled to 42\n * gauge.set(-10); // Negative values allowed\n * gauge.set(1, { phase: 'collect' }); // Set labeled instance\n * ```\n */\n set(value: number, labels?: Record<string, string>): void {\n if (labels && Object.keys(labels).length > 0) {\n const labelKey = this.serializeLabels(labels);\n this.labeledValues.set(labelKey, value);\n } else {\n this.value = value;\n }\n }\n\n /**\n * Increment gauge by delta (default: 1)\n *\n * @param delta - Amount to increment (can be negative)\n * @param labels - Optional label dimensions for this observation\n */\n inc(delta = 1, labels?: Record<string, string>): void {\n if (labels && Object.keys(labels).length > 0) {\n const labelKey = this.serializeLabels(labels);\n const current = this.labeledValues.get(labelKey) || 0;\n this.labeledValues.set(labelKey, current + delta);\n } else {\n this.value += delta;\n }\n }\n\n /**\n * Decrement gauge by delta (default: 1)\n *\n * @param delta - Amount to decrement (can be negative)\n * @param labels - Optional label dimensions for this observation\n */\n dec(delta = 1, labels?: Record<string, string>): void {\n if (labels && Object.keys(labels).length > 0) {\n const labelKey = this.serializeLabels(labels);\n const current = this.labeledValues.get(labelKey) || 0;\n this.labeledValues.set(labelKey, current - delta);\n } else {\n this.value -= delta;\n }\n }\n\n /**\n * Get current gauge value (unlabeled)\n */\n getValue(): number {\n return this.value;\n }\n\n /**\n * Get all labeled values\n * @returns Map of serialized label keys to values\n */\n getLabeledValues(): Map<string, number> {\n return new Map(this.labeledValues);\n }\n\n /**\n * Get value for specific label combination\n */\n getValueForLabels(labels: Record<string, string>): number {\n const labelKey = this.serializeLabels(labels);\n return this.labeledValues.get(labelKey) || 0;\n }\n\n /**\n * Reset gauge to zero (all label combinations)\n */\n reset(): void {\n this.value = 0;\n this.labeledValues.clear();\n }\n\n /**\n * Serialize labels to deterministic string key\n * Format: key1=value1,key2=value2 (sorted by key)\n */\n private serializeLabels(labels: Record<string, string>): string {\n return Object.entries(labels)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join(\",\");\n }\n}\n","/**\n * Taxonomy loader for metrics definitions\n *\n * Loads and caches metrics taxonomy from config/crucible-ts/taxonomy/metrics.yaml\n * Provides default histogram buckets per ADR-0007\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport type { MetricName, MetricUnit } from \"./types.js\";\n\n/**\n * Metric definition from taxonomy\n */\nexport interface MetricDefinition {\n name: MetricName;\n unit: MetricUnit;\n description: string;\n}\n\n/**\n * Taxonomy structure\n */\nexport interface MetricsTaxonomy {\n version: string;\n defaults: {\n histogram_buckets: {\n ms_metrics: number[];\n };\n };\n metrics: MetricDefinition[];\n}\n\n/**\n * Default histogram buckets for _ms metrics (ADR-0007)\n * [1, 5, 10, 50, 100, 500, 1000, 5000, 10000] milliseconds\n */\nexport const DEFAULT_MS_BUCKETS = [1, 5, 10, 50, 100, 500, 1000, 5000, 10000];\n\n/**\n * Singleton taxonomy loader\n */\nclass TaxonomyLoader {\n private static instance: TaxonomyLoader;\n private taxonomy: MetricsTaxonomy | null = null;\n private loadPromise: Promise<MetricsTaxonomy> | null = null;\n private loadError: Error | null = null;\n\n private constructor() {\n // Private constructor for singleton\n }\n\n /**\n * Get singleton instance\n */\n static getInstance(): TaxonomyLoader {\n if (!TaxonomyLoader.instance) {\n TaxonomyLoader.instance = new TaxonomyLoader();\n }\n return TaxonomyLoader.instance;\n }\n\n /**\n * Load taxonomy from YAML file\n */\n private async load(): Promise<MetricsTaxonomy> {\n if (this.taxonomy !== null) {\n return this.taxonomy;\n }\n\n if (this.loadError !== null) {\n throw this.loadError;\n }\n\n if (this.loadPromise) {\n return this.loadPromise;\n }\n\n this.loadPromise = (async () => {\n try {\n // Resolve path to taxonomy file\n // From src/telemetry/ → ../../config/crucible-ts/taxonomy/metrics.yaml\n const taxonomyPath = join(\n __dirname,\n \"..\",\n \"..\",\n \"config\",\n \"crucible-ts\",\n \"taxonomy\",\n \"metrics.yaml\",\n );\n\n const content = await readFile(taxonomyPath, \"utf-8\");\n this.taxonomy = parseYaml(content) as MetricsTaxonomy;\n\n return this.taxonomy;\n } catch (err) {\n this.loadError = err instanceof Error ? err : new Error(String(err));\n throw new Error(`Failed to load metrics taxonomy: ${this.loadError.message}`);\n }\n })();\n\n return this.loadPromise;\n }\n\n /**\n * Get taxonomy (async)\n */\n async getTaxonomy(): Promise<MetricsTaxonomy> {\n return this.load();\n }\n\n /**\n * Get metric definition by name\n */\n async getMetric(name: MetricName): Promise<MetricDefinition | undefined> {\n const taxonomy = await this.load();\n return taxonomy.metrics.find((m) => m.name === name);\n }\n\n /**\n * Get default unit for metric\n */\n async getDefaultUnit(name: MetricName): Promise<MetricUnit | undefined> {\n const metric = await this.getMetric(name);\n return metric?.unit;\n }\n\n /**\n * Get default histogram buckets for metric\n * Returns ADR-0007 buckets for _ms metrics, undefined for others\n */\n async getDefaultBuckets(name: MetricName): Promise<number[] | undefined> {\n // Check if metric name ends with _ms\n if (name.endsWith(\"_ms\")) {\n const taxonomy = await this.load();\n return taxonomy.defaults.histogram_buckets.ms_metrics;\n }\n return undefined;\n }\n\n /**\n * Check if metric name is valid (exists in taxonomy)\n */\n async isValidMetricName(name: string): Promise<boolean> {\n try {\n const taxonomy = await this.load();\n return taxonomy.metrics.some((m) => m.name === name);\n } catch {\n return false;\n }\n }\n\n /**\n * Reset loader state (for testing)\n * @internal\n */\n static _reset(): void {\n TaxonomyLoader.instance = new TaxonomyLoader();\n }\n}\n\n/**\n * Get metrics taxonomy\n *\n * @returns Promise resolving to taxonomy\n */\nexport async function getTaxonomy(): Promise<MetricsTaxonomy> {\n return TaxonomyLoader.getInstance().getTaxonomy();\n}\n\n/**\n * Get metric definition by name\n *\n * @param name - Metric name\n * @returns Promise resolving to metric definition or undefined\n */\nexport async function getMetric(name: MetricName): Promise<MetricDefinition | undefined> {\n return TaxonomyLoader.getInstance().getMetric(name);\n}\n\n/**\n * Get default unit for metric from taxonomy\n *\n * @param name - Metric name\n * @returns Promise resolving to unit or undefined\n */\nexport async function getDefaultUnit(name: MetricName): Promise<MetricUnit | undefined> {\n return TaxonomyLoader.getInstance().getDefaultUnit(name);\n}\n\n/**\n * Get default histogram buckets for metric\n *\n * Returns ADR-0007 buckets ([1, 5, 10, 50, 100, 500, 1000, 5000, 10000]) for\n * metrics ending with _ms, undefined for others.\n *\n * @param name - Metric name\n * @returns Promise resolving to bucket array or undefined\n *\n * @example\n * ```typescript\n * const buckets = await getDefaultBuckets('config_load_ms');\n * // Returns [1, 5, 10, 50, 100, 500, 1000, 5000, 10000]\n * ```\n */\nexport async function getDefaultBuckets(name: MetricName): Promise<number[] | undefined> {\n return TaxonomyLoader.getInstance().getDefaultBuckets(name);\n}\n\n/**\n * Check if metric name is valid (exists in taxonomy)\n *\n * @param name - Metric name to check\n * @returns Promise resolving to true if valid\n */\nexport async function isValidMetricName(name: string): Promise<boolean> {\n return TaxonomyLoader.getInstance().isValidMetricName(name);\n}\n\n// Export for testing\nexport { TaxonomyLoader };\n","/**\n * Histogram metric implementation\n *\n * Histogram with OTLP-compatible cumulative buckets, auto-applying ADR-0007\n * default buckets for _ms metrics.\n */\n\nimport { DEFAULT_MS_BUCKETS } from \"./taxonomy.js\";\nimport type { HistogramBucket, HistogramOptions, HistogramSummary, MetricName } from \"./types.js\";\n\n/**\n * Labeled histogram state\n */\ninterface LabeledHistogramState {\n count: number;\n sum: number;\n bucketCounts: Map<number, number>;\n}\n\n/**\n * Histogram metric\n *\n * Tracks distribution of values using cumulative buckets (OTLP-compatible).\n * Automatically applies ADR-0007 default buckets for _ms metrics.\n * Supports labeled metrics (Crucible v0.2.7+).\n */\nexport class Histogram {\n private count = 0;\n private sum = 0;\n private bucketCounts: Map<number, number> = new Map();\n private labeledStates = new Map<string, LabeledHistogramState>();\n private readonly buckets: number[];\n\n constructor(\n public readonly name: MetricName,\n options?: HistogramOptions,\n ) {\n // Determine buckets: custom > ADR-0007 defaults for _ms metrics > empty\n if (options?.buckets) {\n this.buckets = [...options.buckets].sort((a, b) => a - b);\n } else if (name.endsWith(\"_ms\") || name.endsWith(\"_seconds\")) {\n this.buckets = [...DEFAULT_MS_BUCKETS];\n } else {\n this.buckets = [];\n }\n\n // Initialize bucket counts\n for (const bucket of this.buckets) {\n this.bucketCounts.set(bucket, 0);\n }\n }\n\n /**\n * Record an observation\n *\n * @param value - Value to observe (typically a duration in ms or seconds)\n * @param labels - Optional label dimensions for this observation\n *\n * @example\n * ```typescript\n * const start = performance.now();\n * // ... operation ...\n * histogram.observe(performance.now() - start);\n * histogram.observe(duration, { phase: 'collect', result: 'success' });\n * ```\n */\n observe(value: number, labels?: Record<string, string>): void {\n if (labels && Object.keys(labels).length > 0) {\n // Labeled observation\n const labelKey = this.serializeLabels(labels);\n let state = this.labeledStates.get(labelKey);\n\n if (!state) {\n // Initialize new labeled state\n state = {\n count: 0,\n sum: 0,\n bucketCounts: new Map(),\n };\n for (const bucket of this.buckets) {\n state.bucketCounts.set(bucket, 0);\n }\n this.labeledStates.set(labelKey, state);\n }\n\n state.count++;\n state.sum += value;\n\n // Update cumulative bucket counts\n for (const bucket of this.buckets) {\n if (value <= bucket) {\n state.bucketCounts.set(bucket, (state.bucketCounts.get(bucket) || 0) + 1);\n }\n }\n } else {\n // Unlabeled observation\n this.count++;\n this.sum += value;\n\n // Update cumulative bucket counts\n for (const bucket of this.buckets) {\n if (value <= bucket) {\n this.bucketCounts.set(bucket, (this.bucketCounts.get(bucket) || 0) + 1);\n }\n }\n }\n }\n\n /**\n * Get histogram summary\n *\n * Returns OTLP-compatible histogram summary with cumulative bucket counts.\n */\n getSummary(): HistogramSummary {\n const buckets: HistogramBucket[] = this.buckets.map((le) => ({\n le,\n count: this.bucketCounts.get(le) || 0,\n }));\n\n return {\n count: this.count,\n sum: this.sum,\n buckets,\n };\n }\n\n /**\n * Get current observation count\n */\n getCount(): number {\n return this.count;\n }\n\n /**\n * Get sum of all observed values\n */\n getSum(): number {\n return this.sum;\n }\n\n /**\n * Get average of observed values\n */\n getAverage(): number {\n return this.count > 0 ? this.sum / this.count : 0;\n }\n\n /**\n * Get all labeled summaries\n * @returns Map of serialized label keys to histogram summaries\n */\n getLabeledSummaries(): Map<string, HistogramSummary> {\n const summaries = new Map<string, HistogramSummary>();\n\n for (const [labelKey, state] of this.labeledStates) {\n const buckets: HistogramBucket[] = this.buckets.map((le) => ({\n le,\n count: state.bucketCounts.get(le) || 0,\n }));\n\n summaries.set(labelKey, {\n count: state.count,\n sum: state.sum,\n buckets,\n });\n }\n\n return summaries;\n }\n\n /**\n * Get summary for specific label combination\n */\n getSummaryForLabels(labels: Record<string, string>): HistogramSummary | null {\n const labelKey = this.serializeLabels(labels);\n const state = this.labeledStates.get(labelKey);\n\n if (!state) {\n return null;\n }\n\n const buckets: HistogramBucket[] = this.buckets.map((le) => ({\n le,\n count: state.bucketCounts.get(le) || 0,\n }));\n\n return {\n count: state.count,\n sum: state.sum,\n buckets,\n };\n }\n\n /**\n * Reset histogram to initial state (all label combinations)\n */\n reset(): void {\n this.count = 0;\n this.sum = 0;\n for (const bucket of this.buckets) {\n this.bucketCounts.set(bucket, 0);\n }\n this.labeledStates.clear();\n }\n\n /**\n * Serialize labels to deterministic string key\n * Format: key1=value1,key2=value2 (sorted by key)\n */\n private serializeLabels(labels: Record<string, string>): string {\n return Object.entries(labels)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([k, v]) => `${k}=${v}`)\n .join(\",\");\n }\n}\n","/**\n * Metrics registry - central registry for all metrics\n *\n * Provides singleton registry for counters, gauges, and histograms.\n * Exports events in schema-compliant format.\n */\n\nimport { Counter } from \"./counter.js\";\nimport { Gauge } from \"./gauge.js\";\nimport { Histogram } from \"./histogram.js\";\nimport { getDefaultUnit } from \"./taxonomy.js\";\nimport type { FlushOptions, HistogramOptions, MetricName, MetricsEvent } from \"./types.js\";\n\n/**\n * Metrics registry\n *\n * Central registry for all metrics. Provides factory methods for counters,\n * gauges, and histograms. Exports metrics as schema-compliant events.\n */\nexport class MetricsRegistry {\n private counters: Map<MetricName, Counter> = new Map();\n private gauges: Map<MetricName, Gauge> = new Map();\n private histograms: Map<MetricName, Histogram> = new Map();\n\n /**\n * Get or create a counter\n *\n * @param name - Metric name from taxonomy\n * @returns Counter instance\n *\n * @example\n * ```typescript\n * const counter = registry.counter('schema_validations');\n * counter.inc();\n * ```\n */\n counter(name: MetricName): Counter {\n let counter = this.counters.get(name);\n if (!counter) {\n counter = new Counter(name);\n this.counters.set(name, counter);\n }\n return counter;\n }\n\n /**\n * Get or create a gauge\n *\n * @param name - Metric name from taxonomy\n * @returns Gauge instance\n *\n * @example\n * ```typescript\n * const gauge = registry.gauge('foundry_lookup_count');\n * gauge.set(42);\n * ```\n */\n gauge(name: MetricName): Gauge {\n let gauge = this.gauges.get(name);\n if (!gauge) {\n gauge = new Gauge(name);\n this.gauges.set(name, gauge);\n }\n return gauge;\n }\n\n /**\n * Get or create a histogram\n *\n * @param name - Metric name from taxonomy\n * @param options - Optional histogram options\n * @returns Histogram instance\n *\n * @example\n * ```typescript\n * // Auto-applies ADR-0007 buckets for _ms metrics\n * const histogram = registry.histogram('config_load_ms');\n * histogram.observe(42.5);\n *\n * // Custom buckets\n * const custom = registry.histogram('custom_metric', {\n * buckets: [10, 50, 100, 500, 1000]\n * });\n * ```\n */\n histogram(name: MetricName, options?: HistogramOptions): Histogram {\n let histogram = this.histograms.get(name);\n if (!histogram) {\n histogram = new Histogram(name, options);\n this.histograms.set(name, histogram);\n }\n return histogram;\n }\n\n /**\n * Export all metrics as events\n *\n * Returns array of schema-compliant MetricsEvent objects.\n * Does not clear metrics (use flush() to clear after export).\n *\n * @returns Promise resolving to array of metrics events\n *\n * @example\n * ```typescript\n * const events = await registry.export();\n * console.log(JSON.stringify(events, null, 2));\n * ```\n */\n async export(): Promise<MetricsEvent[]> {\n const events: MetricsEvent[] = [];\n const timestamp = new Date().toISOString();\n\n // Export counters (unlabeled + labeled) - Crucible v0.2.7+\n for (const [name, counter] of this.counters) {\n const unit = await getDefaultUnit(name);\n\n // Always export unlabeled value (for backwards compatibility)\n events.push({\n timestamp,\n name,\n value: counter.getValue(),\n unit,\n });\n\n // Export labeled values (only if > 0)\n for (const [labelKey, value] of counter.getLabeledValues()) {\n if (value > 0) {\n const tags = this.deserializeLabels(labelKey);\n events.push({\n timestamp,\n name,\n value,\n tags,\n unit,\n });\n }\n }\n }\n\n // Export gauges (unlabeled + labeled) - Crucible v0.2.7+\n for (const [name, gauge] of this.gauges) {\n const unit = await getDefaultUnit(name);\n\n // Export unlabeled value (always export gauges, even if zero)\n events.push({\n timestamp,\n name,\n value: gauge.getValue(),\n unit,\n });\n\n // Export labeled values\n for (const [labelKey, value] of gauge.getLabeledValues()) {\n const tags = this.deserializeLabels(labelKey);\n events.push({\n timestamp,\n name,\n value,\n tags,\n unit,\n });\n }\n }\n\n // Export histograms (unlabeled + labeled) - Crucible v0.2.7+\n for (const [name, histogram] of this.histograms) {\n const unit = await getDefaultUnit(name);\n\n // Always export unlabeled summary (for backwards compatibility)\n events.push({\n timestamp,\n name,\n value: histogram.getSummary(),\n unit,\n });\n\n // Export labeled summaries (only if count > 0)\n for (const [labelKey, summary] of histogram.getLabeledSummaries()) {\n if (summary.count > 0) {\n const tags = this.deserializeLabels(labelKey);\n events.push({\n timestamp,\n name,\n value: summary,\n tags,\n unit,\n });\n }\n }\n }\n\n return events;\n }\n\n /**\n * Deserialize label key back to tags object\n * Format: key1=value1,key2=value2 → {key1: \"value1\", key2: \"value2\"}\n */\n private deserializeLabels(labelKey: string): Record<string, string> {\n if (!labelKey) {\n return {};\n }\n\n const tags: Record<string, string> = {};\n for (const pair of labelKey.split(\",\")) {\n const [key, value] = pair.split(\"=\");\n if (key && value) {\n tags[key] = value;\n }\n }\n return tags;\n }\n\n /**\n * Export and clear all metrics\n *\n * Exports metrics as events, optionally emits them via logger,\n * then resets all metrics to zero.\n *\n * @param options - Flush options\n * @returns Promise resolving to array of exported events\n *\n * @example\n * ```typescript\n * // Export and clear\n * const events = await registry.flush();\n *\n * // Export, emit to logger, and clear\n * const events = await registry.flush({\n * emit: (events) => console.log(JSON.stringify(events))\n * });\n * ```\n */\n async flush(options?: FlushOptions): Promise<MetricsEvent[]> {\n const events = await this.export();\n\n try {\n // Emit if logger provided\n if (options?.emit) {\n options.emit(events);\n }\n } finally {\n // Always clear metrics, even if emit throws\n this.clear();\n }\n\n return events;\n }\n\n /**\n * Clear all metrics (reset to zero)\n *\n * Resets all counters, gauges, and histograms to their initial state.\n */\n clear(): void {\n for (const counter of this.counters.values()) {\n counter.reset();\n }\n for (const gauge of this.gauges.values()) {\n gauge.reset();\n }\n for (const histogram of this.histograms.values()) {\n histogram.reset();\n }\n }\n\n /**\n * Get all registered metric names\n *\n * Returns array of all metric names that have been accessed\n * (counters, gauges, or histograms).\n */\n getMetricNames(): MetricName[] {\n const names = new Set<MetricName>();\n for (const name of this.counters.keys()) {\n names.add(name);\n }\n for (const name of this.gauges.keys()) {\n names.add(name);\n }\n for (const name of this.histograms.keys()) {\n names.add(name);\n }\n return Array.from(names);\n }\n\n /**\n * Get total count of registered metrics\n */\n getMetricCount(): number {\n return this.counters.size + this.gauges.size + this.histograms.size;\n }\n}\n","/**\n * Telemetry types - TypeScript types for metrics events\n *\n * Based on schemas/crucible-ts/observability/metrics/v1.0.0/metrics-event.schema.json\n * and config/crucible-ts/taxonomy/metrics.yaml\n */\n\n/**\n * Metric name from taxonomy\n * Aligned with config/crucible-ts/taxonomy/metrics.yaml#/$defs/metricName\n * Updated for Crucible v0.2.18 (HTTP server metrics)\n */\nexport type MetricName =\n // Core module metrics\n | \"schema_validations\"\n | \"schema_validation_errors\"\n | \"config_load_ms\"\n | \"config_load_errors\"\n | \"pathfinder_find_ms\"\n | \"pathfinder_validation_errors\"\n | \"pathfinder_security_warnings\"\n | \"foundry_lookup_count\"\n | \"logging_emit_count\"\n | \"logging_emit_latency_ms\"\n | \"goneat_command_duration_ms\"\n // Prometheus exporter metrics\n | \"prometheus_exporter_refresh_duration_seconds\"\n | \"prometheus_exporter_refresh_total\"\n | \"prometheus_exporter_refresh_errors_total\"\n | \"prometheus_exporter_refresh_inflight\"\n | \"prometheus_exporter_http_requests_total\"\n | \"prometheus_exporter_http_errors_total\"\n | \"prometheus_exporter_restarts_total\"\n // Foundry MIME detection metrics\n | \"foundry_mime_detections_total_json\"\n | \"foundry_mime_detections_total_xml\"\n | \"foundry_mime_detections_total_yaml\"\n | \"foundry_mime_detections_total_csv\"\n | \"foundry_mime_detections_total_plain_text\"\n | \"foundry_mime_detections_total_unknown\"\n | \"foundry_mime_detection_ms_json\"\n | \"foundry_mime_detection_ms_xml\"\n | \"foundry_mime_detection_ms_yaml\"\n | \"foundry_mime_detection_ms_csv\"\n | \"foundry_mime_detection_ms_plain_text\"\n | \"foundry_mime_detection_ms_unknown\"\n // Error handling metrics\n | \"error_handling_wraps_total\"\n | \"error_handling_wrap_ms\"\n // FulHash metrics\n | \"fulhash_operations_total_xxh3_128\"\n | \"fulhash_operations_total_sha256\"\n | \"fulhash_hash_string_total\"\n | \"fulhash_bytes_hashed_total\"\n | \"fulhash_operation_ms\"\n // HTTP server metrics (v0.2.18)\n | \"http_requests_total\"\n | \"http_request_duration_seconds\"\n | \"http_request_size_bytes\"\n | \"http_response_size_bytes\"\n | \"http_active_requests\";\n\n/**\n * Metric unit from taxonomy\n * Aligned with config/crucible-ts/taxonomy/metrics.yaml#/$defs/metricUnit\n * Updated for Crucible v0.2.7 (adds 's' for seconds)\n */\nexport type MetricUnit = \"count\" | \"ms\" | \"bytes\" | \"percent\" | \"s\";\n\n/**\n * Histogram bucket for OTLP-compatible histograms\n */\nexport interface HistogramBucket {\n /** Upper bound (less-than-or-equal) for the bucket */\n le: number;\n /** Cumulative count up to and including this bucket */\n count: number;\n}\n\n/**\n * Histogram summary payload\n */\nexport interface HistogramSummary {\n /** Total count of observations */\n count: number;\n /** Sum of all observed values */\n sum: number;\n /** Ordered buckets with cumulative counts (OTLP-compatible) */\n buckets: HistogramBucket[];\n}\n\n/**\n * Metric value (scalar or histogram)\n */\nexport type MetricValue = number | HistogramSummary;\n\n/**\n * Metrics event structure\n * Aligned with schemas/crucible-ts/observability/metrics/v1.0.0/metrics-event.schema.json\n */\nexport interface MetricsEvent {\n /** RFC3339 timestamp of metric emission */\n timestamp: string;\n /** Metric identifier from taxonomy */\n name: MetricName;\n /** Measurement payload (scalar or histogram summary) */\n value: MetricValue;\n /** Optional key/value dimensions */\n tags?: Record<string, string>;\n /** Optional metric unit (defaults to taxonomy default) */\n unit?: MetricUnit;\n}\n\n/**\n * Histogram options for customization\n */\nexport interface HistogramOptions {\n /** Custom bucket boundaries (overrides default ADR-0007 buckets) */\n buckets?: number[];\n}\n\n/**\n * Flush options for metrics registry\n */\nexport interface FlushOptions {\n /** Optional logger function to emit metrics */\n emit?: (events: MetricsEvent[]) => void;\n}\n\n/**\n * Type guard to check if value is a histogram summary\n */\nexport function isHistogramSummary(value: unknown): value is HistogramSummary {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"count\" in value &&\n \"sum\" in value &&\n \"buckets\" in value\n );\n}\n\n/**\n * Type guard to check if metric name is valid\n * Aligned with Crucible v0.2.18 taxonomy\n */\nexport function isValidMetricName(name: string): name is MetricName {\n const validNames: MetricName[] = [\n // Core module metrics\n \"schema_validations\",\n \"schema_validation_errors\",\n \"config_load_ms\",\n \"config_load_errors\",\n \"pathfinder_find_ms\",\n \"pathfinder_validation_errors\",\n \"pathfinder_security_warnings\",\n \"foundry_lookup_count\",\n \"logging_emit_count\",\n \"logging_emit_latency_ms\",\n \"goneat_command_duration_ms\",\n // Prometheus exporter metrics\n \"prometheus_exporter_refresh_duration_seconds\",\n \"prometheus_exporter_refresh_total\",\n \"prometheus_exporter_refresh_errors_total\",\n \"prometheus_exporter_refresh_inflight\",\n \"prometheus_exporter_http_requests_total\",\n \"prometheus_exporter_http_errors_total\",\n \"prometheus_exporter_restarts_total\",\n // Foundry MIME detection metrics\n \"foundry_mime_detections_total_json\",\n \"foundry_mime_detections_total_xml\",\n \"foundry_mime_detections_total_yaml\",\n \"foundry_mime_detections_total_csv\",\n \"foundry_mime_detections_total_plain_text\",\n \"foundry_mime_detections_total_unknown\",\n \"foundry_mime_detection_ms_json\",\n \"foundry_mime_detection_ms_xml\",\n \"foundry_mime_detection_ms_yaml\",\n \"foundry_mime_detection_ms_csv\",\n \"foundry_mime_detection_ms_plain_text\",\n \"foundry_mime_detection_ms_unknown\",\n // Error handling metrics\n \"error_handling_wraps_total\",\n \"error_handling_wrap_ms\",\n // FulHash metrics\n \"fulhash_operations_total_xxh3_128\",\n \"fulhash_operations_total_sha256\",\n \"fulhash_hash_string_total\",\n \"fulhash_bytes_hashed_total\",\n \"fulhash_operation_ms\",\n // HTTP server metrics\n \"http_requests_total\",\n \"http_request_duration_seconds\",\n \"http_request_size_bytes\",\n \"http_response_size_bytes\",\n \"http_active_requests\",\n ];\n return validNames.includes(name as MetricName);\n}\n\n/**\n * Type guard to check if unit is valid\n */\nexport function isValidMetricUnit(unit: string): unit is MetricUnit {\n const validUnits: MetricUnit[] = [\"count\", \"ms\", \"bytes\", \"percent\", \"s\"];\n return validUnits.includes(unit as MetricUnit);\n}\n","/**\n * Metrics event validators\n *\n * Schema validation for metrics events using existing src/schema infrastructure\n */\n\nimport { compileSchemaById } from \"../schema/index.js\";\nimport type { CompiledValidator } from \"../schema/types.js\";\n\n/**\n * Singleton validator for metrics events\n *\n * Pre-compiles the metrics-event schema at first access for optimal performance.\n * Reuses existing AJV setup from src/schema module.\n */\nclass MetricsValidator {\n private static instance: MetricsValidator;\n private validateFn: CompiledValidator | null = null;\n private initPromise: Promise<void> | null = null;\n private initError: Error | null = null;\n\n private constructor() {\n // Private constructor for singleton\n }\n\n /**\n * Get singleton instance\n */\n static getInstance(): MetricsValidator {\n if (!MetricsValidator.instance) {\n MetricsValidator.instance = new MetricsValidator();\n }\n return MetricsValidator.instance;\n }\n\n /**\n * Initialize validator (lazy load, async)\n */\n private async init(): Promise<void> {\n if (this.validateFn !== null || this.initError !== null) {\n return; // Already initialized\n }\n\n if (this.initPromise) {\n return this.initPromise; // Already initializing\n }\n\n this.initPromise = (async () => {\n try {\n // Compile schema using existing schema infrastructure\n this.validateFn = await compileSchemaById(\"observability/metrics/v1.0.0/metrics-event\");\n } catch (err) {\n this.initError = err instanceof Error ? err : new Error(String(err));\n throw new Error(`Failed to initialize metrics validator: ${this.initError.message}`);\n }\n })();\n\n return this.initPromise;\n }\n\n /**\n * Validate metrics event against schema\n *\n * @param event - Metrics event to validate\n * @returns Promise resolving to true if valid, false otherwise\n */\n async validate(event: unknown): Promise<boolean> {\n if (this.validateFn === null) {\n await this.init();\n }\n\n if (this.initError) {\n throw this.initError;\n }\n\n if (!this.validateFn) {\n throw new Error(\"Validator not initialized\");\n }\n\n return this.validateFn(event);\n }\n\n /**\n * Get validation errors from last validation\n */\n getErrors() {\n if (!this.validateFn) {\n return null;\n }\n return this.validateFn.errors;\n }\n\n /**\n * Reset validator state (for testing)\n * @internal\n */\n static _reset(): void {\n MetricsValidator.instance = new MetricsValidator();\n }\n}\n\n/**\n * Validate metrics event against schema\n *\n * Uses pre-compiled validator singleton for optimal performance.\n *\n * @param event - Metrics event to validate\n * @returns Promise resolving to true if valid\n *\n * @example\n * ```typescript\n * const event: MetricsEvent = {\n * timestamp: new Date().toISOString(),\n * name: 'schema_validations',\n * value: 42\n * };\n *\n * if (await validateMetricsEvent(event)) {\n * // Event is schema-compliant\n * } else {\n * const errors = getValidationErrors();\n * console.error('Validation failed:', errors);\n * }\n * ```\n */\nexport async function validateMetricsEvent(event: unknown): Promise<boolean> {\n return MetricsValidator.getInstance().validate(event);\n}\n\n/**\n * Validate array of metrics events\n *\n * @param events - Array of metrics events\n * @returns Promise resolving to true if all valid\n */\nexport async function validateMetricsEvents(events: unknown[]): Promise<boolean> {\n for (const event of events) {\n if (!(await validateMetricsEvent(event))) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Get validation errors from last validation\n */\nexport function getValidationErrors() {\n return MetricsValidator.getInstance().getErrors();\n}\n\n/**\n * Format validation errors as human-readable string\n */\nexport function formatValidationErrors(\n errors: Array<{ instancePath?: string; message?: string }>,\n): string {\n return errors\n .map((err) => {\n const path = err.instancePath || \"(root)\";\n const message = err.message || \"validation failed\";\n return `${path}: ${message}`;\n })\n .join(\"; \");\n}\n\n/**\n * Assert that metrics event is valid (throws if not)\n *\n * @param event - Metrics event to validate\n * @throws {Error} If validation fails\n */\nexport async function assertValidMetricsEvent(event: unknown): Promise<void> {\n if (!(await validateMetricsEvent(event))) {\n const errors = getValidationErrors();\n const message = errors ? formatValidationErrors(errors) : \"Metrics event validation failed\";\n throw new Error(`Invalid metrics event: ${message}`);\n }\n}\n\n// Export for testing\nexport { MetricsValidator };\n","/**\n * Telemetry module - metrics collection and export\n *\n * Provides counter, gauge, and histogram metrics with schema validation\n * and taxonomy-based defaults (ADR-0007).\n */\n\nexport const VERSION = \"1.0.0\";\n\n// Core registry and singleton\nexport { MetricsRegistry } from \"./registry.js\";\n\nimport { MetricsRegistry } from \"./registry.js\";\n\n/**\n * Default singleton metrics registry\n *\n * Use this for application-wide metrics collection.\n *\n * @example\n * ```typescript\n * import { metrics } from '@fulmenhq/tsfulmen/telemetry';\n *\n * // Increment counter\n * metrics.counter('schema_validations').inc();\n *\n * // Record histogram observation\n * metrics.histogram('config_load_ms').observe(42.5);\n *\n * // Export all metrics\n * const events = await metrics.export();\n * ```\n */\nexport const metrics = new MetricsRegistry();\n\n// Metric types\nexport { Counter } from \"./counter.js\";\nexport { Gauge } from \"./gauge.js\";\nexport { Histogram } from \"./histogram.js\";\n// Taxonomy\nexport type { MetricDefinition, MetricsTaxonomy } from \"./taxonomy.js\";\nexport {\n DEFAULT_MS_BUCKETS,\n getDefaultBuckets,\n getDefaultUnit,\n getMetric,\n getTaxonomy,\n isValidMetricName as isValidMetricNameTaxonomy,\n} from \"./taxonomy.js\";\n// Types\nexport type {\n FlushOptions,\n HistogramBucket,\n HistogramOptions,\n HistogramSummary,\n MetricName,\n MetricsEvent,\n MetricUnit,\n MetricValue,\n} from \"./types.js\";\nexport {\n isHistogramSummary,\n isValidMetricName,\n isValidMetricUnit,\n} from \"./types.js\";\n\n// Validators\nexport {\n assertValidMetricsEvent,\n formatValidationErrors,\n getValidationErrors,\n validateMetricsEvent,\n validateMetricsEvents,\n} from \"./validators.js\";\n","/**\n * Schema validator - implements AJV-based schema validation with goneat integration\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { AnySchema } from \"ajv\";\nimport Ajv from \"ajv\";\nimport Ajv2019 from \"ajv/dist/2019.js\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport AjvDraft04 from \"ajv-draft-04\";\nimport { parse as parseYAML } from \"yaml\";\nimport { metrics } from \"../telemetry/index.js\";\nimport { applyFulmenAjvFormats } from \"./ajv-formats.js\";\nimport { SchemaValidationError } from \"./errors.js\";\nimport { getSchemaRegistry } from \"./registry.js\";\nimport type {\n CompiledValidator,\n SchemaInput,\n SchemaRegistryOptions,\n SchemaValidationResult,\n} from \"./types.js\";\nimport { createDiagnostic } from \"./utils.js\";\n\n/**\n * Supported JSON Schema dialects for meta validation + compilation.\n */\ntype JsonSchemaDialect = \"draft-04\" | \"draft-06\" | \"draft-07\" | \"draft-2019-09\" | \"draft-2020-12\";\n\n/**\n * AJV instances by dialect\n */\nconst ajvInstances = new Map<JsonSchemaDialect, Ajv>();\n\n/**\n * Metaschema initialization promises by dialect\n */\nconst metaschemaReady = new Map<JsonSchemaDialect, Promise<void>>();\n\n/**\n * Schema cache for compiled validators\n */\nconst schemaCache = new Map<string, CompiledValidator>();\n\n/**\n * Load metaschema from Crucible SSOT\n */\nasync function loadMetaSchema(draft: JsonSchemaDialect): Promise<Record<string, unknown>> {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const metaSchemaPath = join(\n __dirname,\n \"..\",\n \"..\",\n \"schemas\",\n \"crucible-ts\",\n \"meta\",\n draft,\n \"schema.json\",\n );\n\n const content = await readFile(metaSchemaPath, \"utf-8\");\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Load vocabulary schemas (draft 2019-09 / 2020-12)\n */\nasync function loadVocabularySchemas(draft: JsonSchemaDialect): Promise<Record<string, unknown>[]> {\n if (draft !== \"draft-2019-09\" && draft !== \"draft-2020-12\") {\n return [];\n }\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const vocabDir = join(__dirname, \"..\", \"..\", \"schemas\", \"crucible-ts\", \"meta\", draft, \"meta\");\n\n const vocabFiles =\n draft === \"draft-2020-12\"\n ? [\n \"core.json\",\n \"applicator.json\",\n \"unevaluated.json\",\n \"validation.json\",\n \"meta-data.json\",\n \"format-annotation.json\",\n \"content.json\",\n ]\n : [\n \"core.json\",\n \"applicator.json\",\n \"validation.json\",\n \"meta-data.json\",\n \"format.json\",\n \"content.json\",\n ];\n\n const schemas: Record<string, unknown>[] = [];\n for (const file of vocabFiles) {\n try {\n const content = await readFile(join(vocabDir, file), \"utf-8\");\n schemas.push(JSON.parse(content) as Record<string, unknown>);\n } catch {\n // Vocabulary schema not found, skip\n }\n }\n\n return schemas;\n}\n\n/**\n * Load referenced schemas (including YAML files) for AJV\n *\n * Resolves relative paths from schemas/ and config/ directories.\n * Handles both relative paths and https://schemas.fulmenhq.dev URIs.\n *\n * Per Canonical URI Resolution Standard (v0.4.2+), crucible-hosted schemas use:\n * https://schemas.fulmenhq.dev/crucible/<topic>/<version>/<filename>\n *\n * We only embed crucible schemas locally. Other modules (goneat/, enact/, etc.)\n * are not embedded and cannot be resolved offline.\n */\nasync function loadReferencedSchema(uri: string): Promise<Record<string, unknown>> {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const repoRoot = join(__dirname, \"..\", \"..\");\n\n let resolvedPath: string;\n\n // Handle https://schemas.fulmenhq.dev/ URIs - map to local files\n if (uri.startsWith(\"https://schemas.fulmenhq.dev/\")) {\n let relativePath = uri.replace(\"https://schemas.fulmenhq.dev/\", \"\");\n\n // Strip crucible/ module prefix if present (v0.4.2+ canonical URIs)\n // We only embed crucible schemas - other modules cannot be resolved locally\n if (relativePath.startsWith(\"crucible/\")) {\n relativePath = relativePath.slice(\"crucible/\".length);\n }\n\n // Check if it's a config taxonomy reference\n if (relativePath.startsWith(\"config/taxonomy/\")) {\n resolvedPath = join(\n repoRoot,\n \"config\",\n \"crucible-ts\",\n \"taxonomy\",\n relativePath.split(\"/\").pop() || \"\",\n );\n } else {\n // Schema reference - map to schemas/crucible-ts/\n resolvedPath = join(repoRoot, \"schemas\", \"crucible-ts\", relativePath);\n }\n }\n // Handle relative paths (e.g., \"../../../../config/taxonomy/metrics.yaml\")\n else if (uri.startsWith(\"../../\") || uri.startsWith(\"../\")) {\n // Resolve relative to schemas/crucible-ts/observability/metrics/v1.0.0/\n // (where metrics-event.schema.json is located)\n const schemaBase = join(\n repoRoot,\n \"schemas\",\n \"crucible-ts\",\n \"observability\",\n \"metrics\",\n \"v1.0.0\",\n );\n resolvedPath = join(schemaBase, uri);\n }\n // Handle file:// URIs\n else if (uri.startsWith(\"file://\")) {\n resolvedPath = fileURLToPath(uri);\n }\n // Unhandled URI scheme\n else {\n throw new Error(`Cannot load remote schema: ${uri}`);\n }\n\n // Read and parse the file\n const content = await readFile(resolvedPath, \"utf-8\");\n const ext = resolvedPath.split(\".\").pop()?.toLowerCase();\n\n if (ext === \"yaml\" || ext === \"yml\") {\n return parseYAML(content) as Record<string, unknown>;\n }\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Resolve JSON Schema dialect from schema content.\n */\nfunction detectDialect(schema: unknown): JsonSchemaDialect {\n if (schema && typeof schema === \"object\" && !Array.isArray(schema)) {\n const maybeSchema = schema as Record<string, unknown>;\n const declared = (maybeSchema as { $schema?: unknown }).$schema;\n\n if (typeof declared === \"string\") {\n if (declared.includes(\"draft-04\")) return \"draft-04\";\n if (declared.includes(\"draft-06\")) return \"draft-06\";\n if (declared.includes(\"draft-07\")) return \"draft-07\";\n if (declared.includes(\"draft/2019-09\")) return \"draft-2019-09\";\n if (declared.includes(\"draft/2020-12\")) return \"draft-2020-12\";\n }\n }\n\n // Default to 2020-12 in Fulmen ecosystem.\n return \"draft-2020-12\";\n}\n\n/**\n * Create AJV instance for a specific dialect\n */\nfunction createAjv(dialect: JsonSchemaDialect): Ajv {\n const AjvCtor =\n dialect === \"draft-2020-12\"\n ? Ajv2020\n : dialect === \"draft-2019-09\"\n ? Ajv2019\n : dialect === \"draft-04\"\n ? (AjvDraft04 as unknown as typeof Ajv)\n : Ajv;\n\n const ajv = new AjvCtor({\n strict: false,\n allErrors: true,\n verbose: true,\n // Allow schemas with $id to be added without replacing existing ones\n addUsedSchema: false,\n // draft-04 uses \"id\"; later drafts use \"$id\"\n schemaId: dialect === \"draft-04\" ? \"id\" : \"$id\",\n // Enable async schema loading for YAML references\n loadSchema: loadReferencedSchema,\n });\n\n applyFulmenAjvFormats(ajv);\n\n return ajv;\n}\n\n/**\n * Get or create AJV instance for a dialect, ensuring metaschemas are loaded.\n */\nasync function getAjv(dialect: JsonSchemaDialect): Promise<Ajv> {\n const existing = ajvInstances.get(dialect);\n if (existing) {\n const ready = metaschemaReady.get(dialect);\n if (ready) await ready;\n return existing;\n }\n\n const ajv = createAjv(dialect);\n ajvInstances.set(dialect, ajv);\n\n const readyPromise = Promise.all([loadVocabularySchemas(dialect), loadMetaSchema(dialect)])\n .then(([vocabSchemas, metaSchema]) => {\n // Add vocabulary schemas first (referenced by meta schema)\n for (const vocabSchema of vocabSchemas) {\n try {\n ajv.addMetaSchema(vocabSchema);\n } catch {\n // Already added or incompatible with Ajv's built-ins\n }\n }\n\n try {\n ajv.addMetaSchema(metaSchema);\n } catch {\n // Already added or incompatible with Ajv's built-ins\n }\n })\n .catch((error) => {\n throw new Error(`Failed to load metaschemas (${dialect}): ${error}`);\n });\n\n metaschemaReady.set(dialect, readyPromise);\n await readyPromise;\n\n return ajv;\n}\n\n/**\n * Compile a schema for validation\n */\nexport async function compileSchema(\n schema: SchemaInput,\n options: { aliases?: string[] } = {},\n): Promise<CompiledValidator> {\n const baseKey = typeof schema === \"string\" ? schema : JSON.stringify(schema);\n\n let parsedSchema: unknown;\n if (typeof schema === \"string\") {\n try {\n parsedSchema = JSON.parse(schema);\n } catch {\n // Try YAML if JSON parsing fails\n parsedSchema = parseYAML(schema);\n }\n } else if (Buffer.isBuffer(schema)) {\n const content = schema.toString(\"utf-8\");\n try {\n parsedSchema = JSON.parse(content);\n } catch {\n parsedSchema = parseYAML(content);\n }\n } else {\n parsedSchema = schema;\n }\n\n const dialect = detectDialect(parsedSchema);\n const ajv = await getAjv(dialect);\n\n const cacheKey = `${dialect}:${baseKey}`;\n const cached = schemaCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n\n try {\n // Register schema aliases (e.g., alternate $id values) before compile to support relative refs\n if (options.aliases && options.aliases.length > 0) {\n for (const alias of options.aliases) {\n if (alias && ajv.getSchema(alias) === undefined) {\n try {\n if (typeof parsedSchema === \"object\" && parsedSchema !== null) {\n ajv.addSchema(parsedSchema as Record<string, unknown>, alias);\n }\n } catch {\n // Ignore if alias already registered or invalid\n }\n }\n }\n }\n\n const validator =\n typeof parsedSchema === \"boolean\"\n ? ajv.compile(parsedSchema)\n : await ajv.compileAsync(parsedSchema as Record<string, unknown>);\n\n // Cache the compiled validator\n schemaCache.set(cacheKey, validator as CompiledValidator);\n\n return validator as CompiledValidator;\n } catch (error) {\n throw SchemaValidationError.parseFailed(\n {\n type: \"string\",\n content: typeof schema === \"string\" ? schema : JSON.stringify(schema),\n },\n error as Error,\n );\n }\n}\n\n/**\n * Validate data against a compiled schema\n */\nexport function validateData(data: unknown, validator: CompiledValidator): SchemaValidationResult {\n const valid = validator(data);\n\n const result: SchemaValidationResult = {\n valid,\n diagnostics: [],\n source: \"ajv\",\n };\n\n if (!valid && validator.errors) {\n const errors = validator.errors;\n if (Array.isArray(errors)) {\n result.diagnostics = errors.map((error) =>\n createDiagnostic(\n error.instancePath || \"\",\n error.message || \"Validation failed\",\n error.keyword || \"unknown\",\n \"ERROR\",\n \"ajv\",\n ),\n );\n }\n metrics.counter(\"schema_validation_errors\").inc();\n } else {\n metrics.counter(\"schema_validations\").inc();\n }\n\n return result;\n}\n\n/**\n * Validate file against a schema\n */\nexport async function validateFile(\n filePath: string,\n validator: CompiledValidator,\n): Promise<SchemaValidationResult> {\n try {\n const content = await readFile(filePath, \"utf-8\");\n let data: unknown;\n\n try {\n data = JSON.parse(content);\n } catch {\n // Try YAML if JSON parsing fails\n data = parseYAML(content);\n }\n\n return validateData(data, validator);\n } catch (error) {\n if (error instanceof SchemaValidationError) {\n throw error;\n }\n throw SchemaValidationError.validationFailed(\n filePath,\n [\n createDiagnostic(\n \"\",\n `Failed to read or parse file: ${(error as Error).message}`,\n \"file-read\",\n \"ERROR\",\n \"ajv\",\n ),\n ],\n { type: \"file\", id: filePath },\n );\n }\n}\n\n/**\n * Validate a schema document itself\n */\nexport async function validateSchema(schema: SchemaInput): Promise<SchemaValidationResult> {\n try {\n // Parse schema so we can both meta-validate and compile with dialect-specific Ajv.\n let parsedSchema: unknown;\n if (typeof schema === \"string\") {\n try {\n parsedSchema = JSON.parse(schema);\n } catch {\n parsedSchema = parseYAML(schema);\n }\n } else if (Buffer.isBuffer(schema)) {\n const content = schema.toString(\"utf-8\");\n try {\n parsedSchema = JSON.parse(content);\n } catch {\n parsedSchema = parseYAML(content);\n }\n } else {\n parsedSchema = schema;\n }\n\n const dialect = detectDialect(parsedSchema);\n const ajv = await getAjv(dialect);\n\n // 1) Meta validation against declared dialect\n const metaValid = ajv.validateSchema(parsedSchema as AnySchema);\n if (!metaValid && ajv.errors) {\n const diagnostics = ajv.errors.map((error) =>\n createDiagnostic(\n error.instancePath || \"\",\n error.message || \"Schema meta-validation failed\",\n error.keyword || \"unknown\",\n \"ERROR\",\n \"ajv\",\n ),\n );\n\n return { valid: false, diagnostics, source: \"ajv\" };\n }\n\n // 2) Compilation check (refs resolvable, keywords supported)\n await compileSchema(parsedSchema as SchemaInput);\n\n return {\n valid: true,\n diagnostics: [],\n source: \"ajv\",\n };\n } catch (error) {\n if (error instanceof SchemaValidationError) {\n return {\n valid: false,\n diagnostics: error.diagnostics,\n source: \"ajv\",\n };\n }\n\n return {\n valid: false,\n diagnostics: [\n createDiagnostic(\n \"\",\n `Schema validation failed: ${(error as Error).message}`,\n \"schema-validation\",\n \"ERROR\",\n \"ajv\",\n ),\n ],\n source: \"ajv\",\n };\n }\n}\n\n/**\n * Clear schema cache\n */\nexport function clearCache(): void {\n schemaCache.clear();\n // Keep Ajv instances cached; they hold metaschemas. Tests can still clear schema cache.\n}\n\n/**\n * Get schema cache size\n */\nexport function getCacheSize(): number {\n return schemaCache.size;\n}\n\n/**\n * Load schema by ID from registry and compile\n */\nexport async function compileSchemaById(\n schemaId: string,\n registryOptions?: SchemaRegistryOptions,\n): Promise<CompiledValidator> {\n try {\n const registry = getSchemaRegistry(registryOptions);\n const metadata = await registry.getSchema(schemaId);\n\n const content = await readFile(metadata.path, \"utf-8\");\n const aliases: string[] = [];\n\n const normalizedRelativePath = metadata.relativePath.replace(/\\\\/g, \"/\");\n if (normalizedRelativePath) {\n // Per Canonical URI Resolution Standard (v0.4.2+), include crucible/ module prefix\n aliases.push(\n new URL(`crucible/${normalizedRelativePath}`, \"https://schemas.fulmenhq.dev/\").toString(),\n );\n }\n\n return compileSchema(content, { aliases });\n } catch (error) {\n metrics.counter(\"schema_validation_errors\").inc();\n throw error;\n }\n}\n\n/**\n * Validate data against a schema ID from registry\n */\nexport async function validateDataBySchemaId(\n data: unknown,\n schemaId: string,\n registryOptions?: SchemaRegistryOptions,\n): Promise<SchemaValidationResult> {\n try {\n const validator = await compileSchemaById(schemaId, registryOptions);\n return validateData(data, validator);\n } catch (error) {\n metrics.counter(\"schema_validation_errors\").inc();\n throw error;\n }\n}\n\n/**\n * Validate file against a schema ID from registry\n */\nexport async function validateFileBySchemaId(\n filePath: string,\n schemaId: string,\n registryOptions?: SchemaRegistryOptions,\n): Promise<SchemaValidationResult> {\n try {\n const validator = await compileSchemaById(schemaId, registryOptions);\n return validateFile(filePath, validator);\n } catch (error) {\n metrics.counter(\"schema_validation_errors\").inc();\n throw error;\n }\n}\n","/**\n * Schema CLI - Commander-based CLI for schema operations\n *\n * Provides command-line interface for schema discovery, validation,\n * and normalization operations. This is a developer tool for exploration\n * and testing, not for production use.\n */\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { Command } from \"commander\";\nimport { isGoneatAvailable, runGoneatValidation } from \"./goneat-bridge.js\";\nimport { compareSchemas, normalizeSchema } from \"./normalizer.js\";\nimport { getSchemaRegistry, listSchemas } from \"./registry.js\";\nimport type { CLIOptions, SchemaValidationResult } from \"./types.js\";\nimport { formatDiagnostics } from \"./utils.js\";\nimport { validateFileBySchemaId } from \"./validator.js\";\n\n/**\n * Create CLI command structure\n */\nexport function createCLI(options: CLIOptions = {}): Command {\n const program = new Command();\n\n program\n .name(\"tsfulmen-schema\")\n .description(\"Schema validation and discovery CLI for Fulmen (developer tool)\")\n .version(\"0.1.0\");\n\n // List schemas command\n program\n .command(\"list\")\n .description(\"List available schemas from registry\")\n .argument(\"[prefix]\", \"Filter schemas by prefix\")\n .option(\"--base-dir <path>\", \"Override schema base directory\")\n .action(async (prefix?: string, cmdOptions?: { baseDir?: string }) => {\n try {\n const schemas = await listSchemas(prefix, {\n baseDir: cmdOptions?.baseDir || options.baseDir,\n });\n\n if (schemas.length === 0) {\n console.log(\"No schemas found\");\n return;\n }\n\n console.log(`Found ${schemas.length} schema(s):\\n`);\n for (const schema of schemas) {\n console.log(` ${schema.id}`);\n console.log(` Format: ${schema.format}`);\n console.log(` Path: ${schema.relativePath}`);\n if (schema.description) {\n console.log(` Description: ${schema.description}`);\n }\n console.log();\n }\n } catch (error) {\n console.error(\"Error listing schemas:\", (error as Error).message);\n process.exit(1);\n }\n });\n\n // Show schema command\n program\n .command(\"show\")\n .description(\"Show schema details\")\n .requiredOption(\"--schema-id <id>\", \"Schema ID to show\")\n .option(\"--base-dir <path>\", \"Override schema base directory\")\n .action(async (cmdOptions: { schemaId: string; baseDir?: string }) => {\n try {\n const registry = getSchemaRegistry({\n baseDir: cmdOptions.baseDir || options.baseDir,\n });\n const schema = await registry.getSchema(cmdOptions.schemaId);\n\n console.log(\"Schema Details:\\n\");\n console.log(` ID: ${schema.id}`);\n console.log(` Format: ${schema.format}`);\n console.log(` Path: ${schema.path}`);\n console.log(` Relative Path: ${schema.relativePath}`);\n if (schema.version) {\n console.log(` Version: ${schema.version}`);\n }\n if (schema.description) {\n console.log(` Description: ${schema.description}`);\n }\n if (schema.schemaDraft) {\n console.log(` Schema Draft: ${schema.schemaDraft}`);\n }\n\n // Read and display schema content\n const content = await readFile(schema.path, \"utf-8\");\n console.log(\"\\nSchema Content:\");\n console.log(content);\n } catch (error) {\n console.error(\"Error showing schema:\", (error as Error).message);\n process.exit(1);\n }\n });\n\n // Validate data command\n program\n .command(\"validate\")\n .description(\"Validate data file against schema\")\n .requiredOption(\"--schema-id <id>\", \"Schema ID to validate against\")\n .argument(\"<file>\", \"Data file to validate\")\n .option(\"--use-goneat\", \"Use goneat for validation (requires goneat binary)\")\n .option(\"--goneat-path <path>\", \"Path to goneat binary\")\n .option(\"--base-dir <path>\", \"Override schema base directory\")\n .action(\n async (\n file: string,\n cmdOptions: {\n schemaId: string;\n useGoneat?: boolean;\n goneatPath?: string;\n baseDir?: string;\n },\n ) => {\n try {\n let result: SchemaValidationResult;\n\n if (cmdOptions.useGoneat) {\n // Check goneat availability\n const available = await isGoneatAvailable(cmdOptions.goneatPath);\n if (!available) {\n console.error(\"❌ goneat not available. Install goneat or remove --use-goneat flag.\");\n console.error(\" AJV validation (default) works without external dependencies.\");\n process.exit(1);\n }\n\n // Get schema path\n const registry = getSchemaRegistry({\n baseDir: cmdOptions.baseDir || options.baseDir,\n });\n const schema = await registry.getSchema(cmdOptions.schemaId);\n\n console.log(\"Using goneat validation...\");\n result = await runGoneatValidation(schema.path, file, cmdOptions.goneatPath);\n } else {\n // Use AJV validation (default, library implementation)\n console.log(\"Using AJV validation...\");\n result = await validateFileBySchemaId(file, cmdOptions.schemaId, {\n baseDir: cmdOptions.baseDir || options.baseDir,\n });\n }\n\n if (result.valid) {\n console.log(`✅ Validation passed (${result.source})`);\n process.exit(0);\n } else {\n console.log(`❌ Validation failed (${result.source})`);\n console.log(\"\\nDiagnostics:\");\n console.log(formatDiagnostics(result.diagnostics));\n process.exit(1);\n }\n } catch (error) {\n console.error(\"Error validating file:\", (error as Error).message);\n process.exit(1);\n }\n },\n );\n\n // Validate schema command\n program\n .command(\"validate-schema\")\n .description(\"Validate a schema file itself\")\n .argument(\"<file>\", \"Schema file to validate\")\n .action(async (file: string) => {\n try {\n const content = await readFile(file, \"utf-8\");\n const { validateSchema } = await import(\"./validator.js\");\n const result = await validateSchema(content);\n\n if (result.valid) {\n console.log(\"✅ Schema is valid\");\n process.exit(0);\n } else {\n console.log(\"❌ Schema is invalid\");\n console.log(\"\\nDiagnostics:\");\n console.log(formatDiagnostics(result.diagnostics));\n process.exit(1);\n }\n } catch (error) {\n console.error(\"Error validating schema:\", (error as Error).message);\n process.exit(1);\n }\n });\n\n // Normalize schema command\n program\n .command(\"normalize\")\n .description(\"Normalize schema to canonical JSON format\")\n .argument(\"<file>\", \"Schema file to normalize\")\n .option(\"--compact\", \"Output compact JSON (no formatting)\")\n .option(\"-o, --output <file>\", \"Write to output file instead of stdout\")\n .action(async (file: string, cmdOptions: { compact?: boolean; output?: string }) => {\n try {\n const content = await readFile(file, \"utf-8\");\n const normalized = normalizeSchema(content, {\n compact: cmdOptions.compact,\n });\n\n if (cmdOptions.output) {\n await writeFile(cmdOptions.output, normalized, \"utf-8\");\n console.log(`✅ Normalized schema written to ${cmdOptions.output}`);\n } else {\n console.log(normalized);\n }\n } catch (error) {\n console.error(\"Error normalizing schema:\", (error as Error).message);\n process.exit(1);\n }\n });\n\n // Compare schemas command\n program\n .command(\"compare\")\n .description(\"Compare two schemas for semantic equality\")\n .argument(\"<file1>\", \"First schema file\")\n .argument(\"<file2>\", \"Second schema file\")\n .option(\"--show-normalized\", \"Show normalized outputs\")\n .action(async (file1: string, file2: string, cmdOptions: { showNormalized?: boolean }) => {\n try {\n const content1 = await readFile(file1, \"utf-8\");\n const content2 = await readFile(file2, \"utf-8\");\n\n const result = compareSchemas(content1, content2);\n\n if (result.equal) {\n console.log(\"✅ Schemas are semantically equal\");\n } else {\n console.log(\"❌ Schemas differ\");\n }\n\n if (cmdOptions.showNormalized) {\n console.log(\"\\nNormalized Schema 1:\");\n console.log(result.normalizedA);\n console.log(\"\\nNormalized Schema 2:\");\n console.log(result.normalizedB);\n }\n\n process.exit(result.equal ? 0 : 1);\n } catch (error) {\n console.error(\"Error comparing schemas:\", (error as Error).message);\n process.exit(1);\n }\n });\n\n // Export schema command\n program\n .command(\"export\")\n .description(\"Export schema from registry to file with provenance\")\n .requiredOption(\"--schema-id <id>\", \"Schema ID to export\")\n .requiredOption(\"--out <path>\", \"Output file path\")\n .option(\"--force\", \"Overwrite existing file\", false)\n .option(\"--no-provenance\", \"Exclude provenance metadata\")\n .option(\"--no-validate\", \"Skip schema validation before export\")\n .option(\"--format <format>\", \"Export format (json|yaml|auto)\", \"auto\")\n .option(\"--base-dir <path>\", \"Override schema base directory\")\n .action(\n async (cmdOptions: {\n schemaId: string;\n out: string;\n force?: boolean;\n provenance?: boolean;\n validate?: boolean;\n format?: string;\n baseDir?: string;\n }) => {\n try {\n const { exportSchema } = await import(\"./export.js\");\n const { exitCodes } = await import(\"../foundry/index.js\");\n\n const result = await exportSchema({\n schemaId: cmdOptions.schemaId,\n outPath: cmdOptions.out,\n includeProvenance: cmdOptions.provenance ?? true,\n validate: cmdOptions.validate ?? true,\n overwrite: cmdOptions.force ?? false,\n format: (cmdOptions.format as \"json\" | \"yaml\" | \"auto\") ?? \"auto\",\n baseDir: cmdOptions.baseDir || options.baseDir,\n });\n\n console.log(\"✅ Schema exported successfully\");\n console.log(` Schema ID: ${result.schemaId}`);\n console.log(` Output: ${result.outPath}`);\n console.log(` Format: ${result.format}`);\n\n if (result.provenance) {\n console.log(\"\\nProvenance:\");\n console.log(` Crucible: ${result.provenance.crucible_version}`);\n console.log(` Library: ${result.provenance.library_version}`);\n if (result.provenance.revision) {\n console.log(` Revision: ${result.provenance.revision}`);\n }\n console.log(` Exported: ${result.provenance.exported_at}`);\n }\n\n process.exit(exitCodes.EXIT_SUCCESS);\n } catch (error) {\n const { exitCodes } = await import(\"../foundry/index.js\");\n const { SchemaExportError, SchemaValidationError, ExportErrorReason } = await import(\n \"./errors.js\"\n );\n\n console.error(\"❌ Schema export failed:\", (error as Error).message);\n\n // Map specific error types to appropriate exit codes\n if (error instanceof SchemaExportError) {\n if (error.outPath) {\n console.error(` Output path: ${error.outPath}`);\n }\n\n // Use error reason for type-safe exit code mapping\n switch (error.reason) {\n case ExportErrorReason.FILE_EXISTS:\n case ExportErrorReason.WRITE_FAILED:\n process.exit(exitCodes.EXIT_FILE_WRITE_ERROR);\n break;\n\n case ExportErrorReason.INVALID_FORMAT:\n process.exit(exitCodes.EXIT_INVALID_ARGUMENT);\n break;\n\n default:\n // PROVENANCE_FAILED, UNKNOWN, and any future reasons\n process.exit(exitCodes.EXIT_FAILURE);\n }\n }\n\n if (error instanceof SchemaValidationError) {\n // Schema not found or validation failed\n const errorMsg = error.message.toLowerCase();\n\n if (errorMsg.includes(\"not found\")) {\n process.exit(exitCodes.EXIT_FILE_NOT_FOUND);\n }\n\n // Validation failures\n process.exit(exitCodes.EXIT_DATA_INVALID);\n }\n\n process.exit(exitCodes.EXIT_FAILURE);\n }\n },\n );\n\n // Identity show command\n program\n .command(\"identity-show\")\n .description(\"Show application identity from .fulmen/app.yaml\")\n .option(\"--path <path>\", \"Explicit path to app.yaml\")\n .option(\"--json\", \"Output as JSON\")\n .action(async (cmdOptions: { path?: string; json?: boolean }) => {\n try {\n const { loadIdentity } = await import(\"../appidentity/loader.js\");\n const { exitCodes } = await import(\"../foundry/index.js\");\n\n const identity = await loadIdentity({ path: cmdOptions.path });\n\n if (cmdOptions.json) {\n console.log(JSON.stringify(identity, null, 2));\n } else {\n console.log(\"Application Identity:\\n\");\n console.log(` Binary Name: ${identity.app.binary_name}`);\n console.log(` Vendor: ${identity.app.vendor}`);\n console.log(` Env Prefix: ${identity.app.env_prefix}`);\n console.log(` Config Name: ${identity.app.config_name}`);\n console.log(` Description: ${identity.app.description}`);\n\n if (identity.metadata) {\n console.log(\"\\nMetadata:\");\n if (identity.metadata.license) {\n console.log(` License: ${identity.metadata.license}`);\n }\n if (identity.metadata.repository_category) {\n console.log(` Category: ${identity.metadata.repository_category}`);\n }\n if (identity.metadata.telemetry_namespace) {\n console.log(` Telemetry: ${identity.metadata.telemetry_namespace}`);\n }\n if (identity.metadata.project_url) {\n console.log(` Project URL: ${identity.metadata.project_url}`);\n }\n }\n }\n\n process.exit(exitCodes.EXIT_SUCCESS);\n } catch (error) {\n const { exitCodes } = await import(\"../foundry/index.js\");\n const { AppIdentityError } = await import(\"../appidentity/errors.js\");\n\n console.error(\"❌ Failed to load identity:\", (error as Error).message);\n\n if (error instanceof AppIdentityError) {\n if (error.message.includes(\"not found\")) {\n process.exit(exitCodes.EXIT_FILE_NOT_FOUND);\n }\n if (error.message.includes(\"Invalid\") || error.message.includes(\"validation\")) {\n process.exit(exitCodes.EXIT_DATA_INVALID);\n }\n }\n\n process.exit(exitCodes.EXIT_FAILURE);\n }\n });\n\n // Identity validate command\n program\n .command(\"identity-validate\")\n .description(\"Validate application identity against schema\")\n .argument(\"[file]\", \"Path to app.yaml (defaults to discovery)\")\n .action(async (file?: string) => {\n try {\n const { loadIdentity } = await import(\"../appidentity/loader.js\");\n const { exitCodes } = await import(\"../foundry/index.js\");\n\n console.log(\"Validating application identity...\");\n\n const identity = await loadIdentity({ path: file });\n\n console.log(\"✅ Identity is valid\");\n console.log(` Binary: ${identity.app.binary_name}`);\n console.log(` Vendor: ${identity.app.vendor}`);\n\n process.exit(exitCodes.EXIT_SUCCESS);\n } catch (error) {\n const { exitCodes } = await import(\"../foundry/index.js\");\n const { AppIdentityError } = await import(\"../appidentity/errors.js\");\n\n console.error(\"❌ Identity validation failed:\", (error as Error).message);\n\n if (error instanceof AppIdentityError) {\n if (error.message.includes(\"not found\")) {\n process.exit(exitCodes.EXIT_FILE_NOT_FOUND);\n }\n if (error.message.includes(\"Invalid\") || error.message.includes(\"validation\")) {\n process.exit(exitCodes.EXIT_DATA_INVALID);\n }\n }\n\n process.exit(exitCodes.EXIT_FAILURE);\n }\n });\n\n return program;\n}\n","/**\n * Schema export utilities - implements schema export with provenance\n */\n\nimport { access, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, extname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { parse as parseYAML, stringify as stringifyYAML } from \"yaml\";\nimport { SchemaExportError, SchemaValidationError } from \"./errors.js\";\nimport { getSchemaRegistry } from \"./registry.js\";\nimport type {\n ExportSchemaOptions,\n ExportSchemaResult,\n SchemaExportFormat,\n SchemaProvenanceMetadata,\n} from \"./types.js\";\nimport { validateSchema } from \"./validator.js\";\n\n/**\n * Extract provenance metadata from Crucible sync metadata\n */\nasync function extractProvenanceMetadata(schemaId: string): Promise<SchemaProvenanceMetadata> {\n try {\n // Read Crucible metadata using proper path resolution\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const metadataPath = join(__dirname, \"..\", \"..\", \".crucible\", \"metadata\", \"metadata.yaml\");\n const metadataContent = await readFile(metadataPath, \"utf-8\");\n\n // Parse YAML properly to avoid brittle regex matching\n const metadata = parseYAML(metadataContent) as {\n sources?: Array<{\n name?: string;\n version?: string;\n commit?: string;\n }>;\n };\n\n // Extract Crucible source metadata (first source is typically 'crucible')\n const crucibleSource = metadata.sources?.[0];\n const crucibleVersion = crucibleSource?.version || \"unknown\";\n const revision = crucibleSource?.commit;\n\n // Read library version from package.json\n const pkgPath = join(__dirname, \"..\", \"..\", \"package.json\");\n const pkgContent = await readFile(pkgPath, \"utf-8\");\n const pkg = JSON.parse(pkgContent) as { version: string };\n\n return {\n schema_id: schemaId,\n crucible_version: crucibleVersion,\n library_version: pkg.version,\n revision: revision,\n exported_at: new Date().toISOString(),\n export_source: \"tsfulmen\",\n };\n } catch (error) {\n throw SchemaExportError.provenanceFailed((error as Error).message, error as Error);\n }\n}\n\n/**\n * Embed provenance metadata in schema content\n */\nfunction embedProvenance(\n schemaContent: Record<string, unknown>,\n provenance: SchemaProvenanceMetadata,\n format: SchemaExportFormat,\n): string {\n if (format === \"json\") {\n // For JSON: embed under $comment[\"x-crucible-source\"]\n const withProvenance = {\n ...schemaContent,\n $comment: {\n ...(typeof schemaContent.$comment === \"object\" ? schemaContent.$comment : {}),\n \"x-crucible-source\": provenance,\n },\n };\n return JSON.stringify(withProvenance, null, 2);\n }\n\n // For YAML: prepend comment block\n const yamlContent = stringifyYAML(schemaContent, {\n indent: 2,\n lineWidth: 0,\n });\n\n const provenanceComment = [\n \"# x-crucible-source:\",\n `# schema_id: ${provenance.schema_id}`,\n `# crucible_version: ${provenance.crucible_version}`,\n `# library_version: ${provenance.library_version}`,\n ...(provenance.revision ? [`# revision: ${provenance.revision}`] : []),\n `# exported_at: ${provenance.exported_at}`,\n `# export_source: ${provenance.export_source}`,\n \"\",\n ].join(\"\\n\");\n\n return provenanceComment + yamlContent;\n}\n\n/**\n * Detect export format from file extension or explicit option\n */\nfunction detectFormat(outPath: string, formatOption?: SchemaExportFormat): SchemaExportFormat {\n if (formatOption && formatOption !== \"auto\") {\n return formatOption;\n }\n\n const ext = extname(outPath).toLowerCase();\n switch (ext) {\n case \".json\":\n return \"json\";\n case \".yaml\":\n case \".yml\":\n return \"yaml\";\n default:\n throw SchemaExportError.invalidFormat(ext, outPath);\n }\n}\n\n/**\n * Export schema from registry to file with provenance\n *\n * @param options - Export options\n * @returns Export result with metadata\n *\n * @throws {SchemaExportError} If export fails\n * @throws {SchemaValidationError} If schema not found or validation fails\n *\n * @example\n * ```typescript\n * import { exportSchema } from '@fulmenhq/tsfulmen/schema';\n *\n * await exportSchema({\n * schemaId: 'library/foundry/v1.0.0/exit-codes',\n * outPath: './schemas/exit-codes.schema.json',\n * includeProvenance: true,\n * validate: true,\n * });\n * ```\n */\nexport async function exportSchema(options: ExportSchemaOptions): Promise<ExportSchemaResult> {\n const {\n schemaId,\n outPath,\n includeProvenance = true,\n validate = true,\n overwrite = false,\n format: formatOption,\n baseDir,\n } = options;\n\n // Detect output format\n const format = detectFormat(outPath, formatOption);\n\n // Check if file exists\n if (!overwrite) {\n try {\n await access(outPath);\n throw SchemaExportError.fileExists(outPath);\n } catch (error) {\n // File doesn't exist - proceed\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n }\n\n // Get schema from registry\n const registry = getSchemaRegistry({ baseDir });\n const schema = await registry.getSchema(schemaId);\n\n // Read schema content\n const schemaContent = await readFile(schema.path, \"utf-8\");\n\n // Validate if requested\n if (validate) {\n const validationResult = await validateSchema(schemaContent);\n if (!validationResult.valid) {\n throw SchemaValidationError.validationFailed(schemaId, validationResult.diagnostics, {\n type: \"file\",\n id: schema.path,\n });\n }\n }\n\n // Parse schema content\n let schemaObject: Record<string, unknown>;\n try {\n schemaObject = JSON.parse(schemaContent) as Record<string, unknown>;\n } catch {\n schemaObject = parseYAML(schemaContent) as Record<string, unknown>;\n }\n\n // Freeze schema object to prevent mutation\n Object.freeze(schemaObject);\n\n let provenance: SchemaProvenanceMetadata | undefined;\n let outputContent: string;\n\n if (includeProvenance) {\n // Extract provenance metadata\n provenance = await extractProvenanceMetadata(schemaId);\n\n // Embed provenance in output\n outputContent = embedProvenance(schemaObject, provenance, format);\n } else {\n // Export without provenance\n if (format === \"json\") {\n outputContent = JSON.stringify(schemaObject, null, 2);\n } else {\n outputContent = stringifyYAML(schemaObject, { indent: 2, lineWidth: 0 });\n }\n }\n\n // Ensure output directory exists\n await mkdir(dirname(outPath), { recursive: true });\n\n // Write to file\n try {\n await writeFile(outPath, outputContent, \"utf-8\");\n } catch (error) {\n throw SchemaExportError.writeFailed(outPath, error as Error);\n }\n\n return {\n success: true,\n schemaId,\n outPath,\n format,\n includeProvenance,\n provenance,\n };\n}\n\n/**\n * Strip provenance metadata from schema content\n *\n * This helper is useful for comparing exported schemas with runtime\n * schemas or validating that provenance doesn't affect schema semantics.\n *\n * @param content - Schema content (JSON or YAML string)\n * @returns Schema content without provenance metadata\n *\n * @example\n * ```typescript\n * import { stripProvenance } from '@fulmenhq/tsfulmen/schema';\n *\n * const exported = await readFile('./schema.json', 'utf-8');\n * const withoutProvenance = stripProvenance(exported);\n * ```\n */\nexport function stripProvenance(content: string): string {\n try {\n // Try parsing as JSON\n const parsed = JSON.parse(content) as Record<string, unknown>;\n\n // Remove provenance from $comment\n if (parsed.$comment && typeof parsed.$comment === \"object\") {\n const comment = { ...parsed.$comment } as Record<string, unknown>;\n delete comment[\"x-crucible-source\"];\n\n // Remove $comment entirely if it's now empty\n if (Object.keys(comment).length === 0) {\n delete parsed.$comment;\n } else {\n parsed.$comment = comment;\n }\n }\n\n return JSON.stringify(parsed, null, 2);\n } catch {\n // YAML format - strip comment lines\n const lines = content.split(\"\\n\");\n const filtered = lines.filter((line) => {\n const trimmed = line.trim();\n return !(\n trimmed.startsWith(\"# x-crucible-source:\") ||\n (trimmed.startsWith(\"# \") &&\n /^#\\s+(schema_id|crucible_version|library_version|revision|exported_at|export_source):/.test(\n trimmed,\n ))\n );\n });\n\n // Remove leading blank lines\n while (filtered.length > 0 && filtered[0]?.trim() === \"\") {\n filtered.shift();\n }\n\n return filtered.join(\"\\n\");\n }\n}\n","/**\n * Schema validation module - implements Fulmen Schema Validation Standard\n *\n * Provides schema discovery, validation, and normalization utilities for Crucible schemas\n * with JSON Schema 2020-12 support and optional goneat integration.\n */\n\nexport const VERSION = \"0.1.0\";\n\nexport {\n applyFulmenAjvFormats,\n type FulmenAjvFormatsOptions,\n} from \"./ajv-formats.js\";\n\n// CLI exports\nexport { createCLI } from \"./cli.js\";\n// Error exports\nexport * from \"./errors.js\";\n// Export exports\nexport { exportSchema, stripProvenance } from \"./export.js\";\n// Goneat bridge exports (CLI-only, optional)\nexport {\n detectGoneat,\n isGoneatAvailable,\n runGoneatValidation,\n} from \"./goneat-bridge.js\";\n// Normalizer exports\nexport { compareSchemas, normalizeSchema } from \"./normalizer.js\";\n// Registry exports\nexport {\n getSchema,\n getSchemaByPath,\n getSchemaRegistry,\n hasSchema,\n listSchemas,\n SchemaRegistry,\n} from \"./registry.js\";\n// Core exports\nexport type {\n AjvError,\n CLIOptions,\n CompiledValidator,\n ExportSchemaOptions,\n ExportSchemaResult,\n SchemaComparisonResult,\n SchemaExportFormat,\n SchemaFormat,\n SchemaInput,\n SchemaMetadata,\n SchemaNormalizationOptions,\n SchemaProvenanceMetadata,\n SchemaRegistryOptions,\n SchemaSource,\n SchemaValidationDiagnostic,\n SchemaValidationOptions,\n SchemaValidationResult,\n} from \"./types.js\";\n// Utility exports\nexport {\n countDiagnostics,\n createDiagnostic,\n formatDiagnostics,\n formatValidationResult,\n groupDiagnosticsBySeverity,\n isValidationError,\n normalizePointer,\n} from \"./utils.js\";\n// Validator exports\nexport {\n clearCache,\n compileSchema,\n compileSchemaById,\n getCacheSize,\n validateData,\n validateDataBySchemaId,\n validateFile,\n validateFileBySchemaId,\n validateSchema,\n} from \"./validator.js\";\n","/**\n * Schema validation for FulmenError data\n *\n * Provides singleton validator that pre-compiles error-response schema\n * using existing src/schema infrastructure. Performance target: <1ms per validation.\n */\n\nimport { compileSchemaById } from \"../schema/index.js\";\nimport type { CompiledValidator } from \"../schema/types.js\";\n\n/**\n * Singleton validator for FulmenError data\n *\n * Pre-compiles the error-response schema at first access for optimal performance.\n * Reuses existing AJV setup from src/schema module.\n */\nclass ErrorValidator {\n private static instance: ErrorValidator;\n private validateFn: CompiledValidator | null = null;\n private initPromise: Promise<void> | null = null;\n private initError: Error | null = null;\n\n private constructor() {\n // Private constructor for singleton\n }\n\n /**\n * Get singleton instance\n */\n static getInstance(): ErrorValidator {\n if (!ErrorValidator.instance) {\n ErrorValidator.instance = new ErrorValidator();\n }\n return ErrorValidator.instance;\n }\n\n /**\n * Initialize validator (lazy load, async)\n */\n private async init(): Promise<void> {\n if (this.validateFn !== null || this.initError !== null) {\n return; // Already initialized\n }\n\n if (this.initPromise) {\n return this.initPromise; // Already initializing\n }\n\n this.initPromise = (async () => {\n try {\n // Ensure dependency schemas are registered before compiling error-response\n // Error handling schema references pathfinder error-response relatively.\n await compileSchemaById(\"pathfinder/v1.0.0/error-response\");\n await compileSchemaById(\"assessment/v1.0.0/severity-definitions\");\n\n // Compile schema using existing schema infrastructure\n // Schema ID for error-response extends pathfinder error-response\n this.validateFn = await compileSchemaById(\"error-handling/v1.0.0/error-response\");\n } catch (err) {\n this.initError = err instanceof Error ? err : new Error(String(err));\n throw new Error(`Failed to initialize error validator: ${this.initError.message}`);\n }\n })();\n\n return this.initPromise;\n }\n\n /**\n * Validate error data against schema\n *\n * @param data - Data to validate\n * @returns Promise resolving to true if valid, false otherwise\n * @throws {Error} If validator failed to initialize\n */\n async validate(data: unknown): Promise<boolean> {\n if (this.validateFn === null) {\n await this.init();\n }\n\n if (this.initError) {\n throw this.initError;\n }\n\n if (!this.validateFn) {\n throw new Error(\"Validator not initialized\");\n }\n\n return this.validateFn(data);\n }\n\n /**\n * Get validation errors from last validation\n *\n * @returns Validation errors or null\n */\n getErrors() {\n if (!this.validateFn) {\n return null;\n }\n return this.validateFn.errors;\n }\n\n /**\n * Reset validator state (for testing)\n * @internal\n */\n static _reset(): void {\n ErrorValidator.instance = new ErrorValidator();\n }\n}\n\n/**\n * Validate FulmenError data against error-response schema\n *\n * Uses pre-compiled validator singleton for optimal performance (<1ms target).\n *\n * @param data - Error data to validate\n * @returns Promise resolving to true if valid, false otherwise\n *\n * @example\n * ```typescript\n * const data = {\n * code: 'CONFIG_INVALID',\n * message: 'Configuration validation failed'\n * };\n *\n * if (await validateErrorData(data)) {\n * // Data is schema-compliant\n * } else {\n * const errors = await getValidationErrors();\n * console.error('Validation failed:', errors);\n * }\n * ```\n */\nexport async function validateErrorData(data: unknown): Promise<boolean> {\n return ErrorValidator.getInstance().validate(data);\n}\n\n/**\n * Get validation errors from last validation\n *\n * @returns Validation errors or null\n *\n * @example\n * ```typescript\n * if (!(await validateErrorData(data))) {\n * const errors = getValidationErrors();\n * errors?.forEach(err => {\n * console.error(`${err.instancePath}: ${err.message}`);\n * });\n * }\n * ```\n */\nexport function getValidationErrors() {\n return ErrorValidator.getInstance().getErrors();\n}\n\n/**\n * Format validation errors as human-readable string\n *\n * @param errors - Validation error objects\n * @returns Formatted error message\n *\n * @example\n * ```typescript\n * const errors = getValidationErrors();\n * if (errors) {\n * throw new Error(formatValidationErrors(errors));\n * }\n * ```\n */\nexport function formatValidationErrors(\n errors: Array<{ instancePath?: string; message?: string }>,\n): string {\n return errors\n .map((err) => {\n const path = err.instancePath || \"(root)\";\n const message = err.message || \"validation failed\";\n return `${path}: ${message}`;\n })\n .join(\"; \");\n}\n\n/**\n * Validate and throw if invalid\n *\n * @param data - Error data to validate\n * @throws {Error} If validation fails\n *\n * @example\n * ```typescript\n * await assertValidErrorData(data); // Throws if invalid\n * // Safe to use data here\n * ```\n */\nexport async function assertValidErrorData(data: unknown): Promise<void> {\n if (!(await validateErrorData(data))) {\n const errors = getValidationErrors();\n const message = errors ? formatValidationErrors(errors) : \"Error data validation failed\";\n throw new Error(`Invalid error data: ${message}`);\n }\n}\n\n// Export for testing\nexport { ErrorValidator };\n","/**\n * FulmenError - Structured error data model for observability\n *\n * Implements ADR-0006 error data model extending Pathfinder error-response\n * with optional telemetry metadata (severity, correlation_id, trace_id, etc.)\n */\n\nimport { extractErrorMessage, extractStackTrace, type FulmenErrorData } from \"./serialization.js\";\nimport type { SeverityLevel, SeverityName } from \"./severity.js\";\nimport { getDefaultSeverity, SEVERITY_LEVELS, Severity } from \"./severity.js\";\nimport { validateErrorData } from \"./validators.js\";\n\n// Re-export FulmenErrorData from serialization\nexport type { FulmenErrorData } from \"./serialization.js\";\n\n/**\n * Options for creating/wrapping FulmenError\n */\nexport interface FulmenErrorOptions {\n code?: string;\n severity?: SeverityName;\n correlation_id?: string;\n trace_id?: string;\n exit_code?: number;\n context?: Record<string, unknown>;\n details?: Record<string, unknown>;\n path?: string;\n}\n\n/**\n * FulmenError class - wraps structured error data with helper methods\n *\n * Implements ADR-0006 canonical data model pattern:\n * - Data stored in immutable FulmenErrorData interface\n * - Class provides ergonomic API and methods\n * - Extends native Error for stack traces and instanceof checks\n */\nexport class FulmenError extends Error {\n readonly data: FulmenErrorData;\n\n constructor(data: FulmenErrorData) {\n super(data.message);\n this.name = \"FulmenError\";\n\n // Freeze data for immutability\n this.data = Object.freeze({ ...data });\n\n // Capture stack trace\n Error.captureStackTrace(this, FulmenError);\n }\n\n /**\n * Serialize to JSON (schema-compliant)\n */\n toJSON(): FulmenErrorData {\n return this.data;\n }\n\n /**\n * Check equality with another FulmenError\n */\n equals(other: FulmenError): boolean {\n return JSON.stringify(this.data) === JSON.stringify(other.data);\n }\n\n /**\n * Get severity level for comparison\n */\n getSeverityLevel(): SeverityLevel {\n return this.data.severity_level ?? SEVERITY_LEVELS[this.data.severity ?? \"medium\"];\n }\n\n /**\n * Wrap an existing error with FulmenError structure\n *\n * @param error - Error to wrap (Error instance or FulmenErrorData)\n * @param options - Additional error options\n * @returns New FulmenError instance\n *\n * @example\n * ```typescript\n * try {\n * throw new Error('Config invalid');\n * } catch (err) {\n * const fulmenErr = FulmenError.wrap(err, {\n * code: 'CONFIG_INVALID',\n * severity: 'high',\n * exit_code: 2\n * });\n * throw fulmenErr;\n * }\n * ```\n */\n static wrap(error: Error | FulmenErrorData, options: FulmenErrorOptions = {}): FulmenError {\n // If already FulmenError, merge options with recomputed derived fields\n if (error instanceof FulmenError) {\n // Determine effective severity (prefer options, fallback to existing, default to medium)\n const effectiveSeverity = options.severity ?? error.data.severity ?? Severity.MEDIUM;\n // CRITICAL: Recompute severity_level from severity to maintain consistency (ADR-0006)\n const effectiveSeverityLevel = SEVERITY_LEVELS[effectiveSeverity];\n\n // Update timestamp when re-wrapping (indicates new error context)\n const timestamp = new Date().toISOString();\n\n return new FulmenError({\n ...error.data,\n ...options,\n code: options.code ?? error.data.code,\n message: error.data.message,\n severity: effectiveSeverity, // Consistent severity\n severity_level: effectiveSeverityLevel, // Recomputed level\n timestamp, // Updated timestamp\n });\n }\n\n // If FulmenErrorData, recompute derived fields\n if (isFulmenErrorData(error)) {\n const defaultSeverity = getDefaultSeverity();\n // Prefer options.severity, fall back to error.severity, default to medium\n const effectiveSeverity = options.severity ?? error.severity ?? defaultSeverity.name;\n // CRITICAL: Always recompute severity_level from severity (never trust provided level)\n const effectiveSeverityLevel = SEVERITY_LEVELS[effectiveSeverity];\n\n return new FulmenError({\n ...error,\n ...options,\n severity: effectiveSeverity,\n severity_level: effectiveSeverityLevel, // Recomputed, not from error.severity_level\n timestamp: error.timestamp ?? new Date().toISOString(),\n });\n }\n\n // Wrap native Error\n return FulmenError.fromError(error, options);\n }\n\n /**\n * Create FulmenError from native Error object\n *\n * @param err - Native Error instance\n * @param options - Error options\n * @returns New FulmenError instance\n *\n * @example\n * ```typescript\n * const err = new TypeError('Invalid type');\n * const fulmenErr = FulmenError.fromError(err, {\n * code: 'TYPE_ERROR',\n * severity: 'medium'\n * });\n * ```\n */\n static fromError(err: Error | unknown, options: FulmenErrorOptions = {}): FulmenError {\n const code = options.code ?? \"UNKNOWN_ERROR\";\n const severity = options.severity ?? Severity.MEDIUM;\n const severityLevel = SEVERITY_LEVELS[severity];\n\n const message = extractErrorMessage(err);\n const stack = extractStackTrace(err);\n\n const data: FulmenErrorData = {\n code,\n message,\n severity,\n severity_level: severityLevel,\n timestamp: new Date().toISOString(),\n ...options,\n context: {\n ...options.context,\n originalName: err instanceof Error ? err.name : typeof err,\n stack,\n },\n original: stack || message,\n };\n\n return new FulmenError(data);\n }\n\n /**\n * Validate error data against schema\n *\n * @param data - Error data to validate\n * @returns Promise resolving to true if valid\n *\n * @example\n * ```typescript\n * const data = { code: 'TEST', message: 'Test error' };\n * if (await FulmenError.validate(data)) {\n * const err = new FulmenError(data);\n * }\n * ```\n */\n static async validate(data: unknown): Promise<boolean> {\n return validateErrorData(data);\n }\n\n /**\n * Exit process with structured error\n *\n * Logs error as JSON and exits with specified exit code.\n * Mockable for testing (override process.exit).\n *\n * @param error - FulmenError instance\n * @param options - Exit options\n *\n * @example\n * ```typescript\n * const err = FulmenError.fromError(new Error('Fatal'), {\n * code: 'FATAL_ERROR',\n * exit_code: 1\n * });\n * FulmenError.exitWithError(err); // Exits with code 1\n * ```\n */\n static exitWithError(\n error: FulmenError,\n options: { logger?: (msg: string) => void } = {},\n ): never {\n const logger = options.logger ?? console.error;\n const exitCode = error.data.exit_code ?? 1;\n\n // Log structured error\n logger(JSON.stringify(error.toJSON(), null, 2));\n\n // Exit with code\n process.exit(exitCode);\n }\n}\n\n/**\n * Type guard to check if value is FulmenError instance\n *\n * @param value - Value to check\n * @returns True if value is FulmenError\n */\nexport function isFulmenError(value: unknown): value is FulmenError {\n return value instanceof FulmenError;\n}\n\n/**\n * Type guard to check if value is FulmenErrorData\n *\n * @param value - Value to check\n * @returns True if value is FulmenErrorData\n */\nexport function isFulmenErrorData(value: unknown): value is FulmenErrorData {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"code\" in value &&\n typeof (value as FulmenErrorData).code === \"string\" &&\n \"message\" in value &&\n typeof (value as FulmenErrorData).message === \"string\"\n );\n}\n","/**\n * Errors module - structured error handling with telemetry\n *\n * Provides FulmenError data model and utilities for schema-backed error responses\n * with optional telemetry metadata (severity, correlation IDs, exit codes).\n */\n\nexport const VERSION = \"0.2.0\";\n\n// Correlation ID utilities\nexport {\n generateCorrelationId,\n isCorrelationId,\n isValidCorrelationId,\n normalizeCorrelationId,\n} from \"./correlation.js\";\n// Core error class and types\nexport {\n FulmenError,\n type FulmenErrorData,\n type FulmenErrorOptions,\n isFulmenError,\n isFulmenErrorData,\n} from \"./fulmen-error.js\";\n// Serialization utilities\nexport {\n extractErrorMessage,\n extractStackTrace,\n serializeError,\n} from \"./serialization.js\";\n// Severity utilities\nexport {\n compareSeverity,\n getDefaultSeverity,\n isSeverityLevel,\n isSeverityName,\n LEVEL_TO_SEVERITY,\n levelToSeverity,\n SEVERITY_LEVELS,\n Severity,\n type SeverityLevel,\n type SeverityName,\n severityToLevel,\n} from \"./severity.js\";\n// Validation utilities\nexport {\n assertValidErrorData,\n formatValidationErrors,\n getValidationErrors,\n validateErrorData,\n} from \"./validators.js\";\n","/**\n * FulHash - Consistent hashing API for Fulmen ecosystem\n *\n * Provides block and streaming hashing with XXH3-128, SHA-256, CRC32, and CRC32C algorithms.\n * Cross-language compatible with gofulmen and pyfulmen.\n */\n\nexport const VERSION = \"1.0.0\";\n\nexport * from \"../crucible/fulhash/types.js\";\nexport { type HashInput, multiHash, verify } from \"./convenience.js\";\nexport type {\n HashOptions,\n StreamHasher,\n StreamHasherOptions,\n} from \"./definitions.js\";\nexport { Digest } from \"./digest.js\";\nexport {\n DigestStateError,\n FulHashError,\n InvalidChecksumError,\n InvalidChecksumFormatError,\n UnsupportedAlgorithmError,\n} from \"./errors.js\";\nexport { hash, hashBytes, hashString } from \"./hash.js\";\nexport { createStreamHasher } from \"./stream.js\";\n","import type { Algorithm } from \"../crucible/fulhash/types.js\";\nimport type { MultiHashResult, StreamHasher } from \"./definitions.js\";\nimport { Digest } from \"./digest.js\";\nimport { createStreamHasher } from \"./stream.js\";\n\nexport type HashInput = string | Uint8Array | AsyncIterable<string | Uint8Array>;\n\n/**\n * Compute multiple hashes in a single pass over the data.\n * Useful for generating checksums for multiple algorithms (e.g. SHA256 + XXH3)\n * without reading the stream multiple times.\n */\nexport async function multiHash(\n input: HashInput,\n algorithms: Algorithm[],\n encoding: BufferEncoding = \"utf8\",\n): Promise<MultiHashResult> {\n const uniqueAlgorithms = [...new Set(algorithms)];\n const hashers: StreamHasher[] = await Promise.all(\n uniqueAlgorithms.map((algo) => createStreamHasher({ algorithm: algo })),\n );\n\n if (typeof input === \"string\") {\n if (encoding !== \"utf8\") {\n // Manual buffer conversion for non-utf8 encodings, as some stream hashers\n // (like XXH3) might default to UTF-8 for string inputs.\n const buf = Buffer.from(input, encoding);\n for (const hasher of hashers) {\n hasher.update(buf);\n }\n } else {\n for (const hasher of hashers) {\n hasher.update(input);\n }\n }\n } else if (input instanceof Uint8Array) {\n for (const hasher of hashers) {\n hasher.update(input);\n }\n } else {\n // AsyncIterable (Stream)\n for await (const chunk of input) {\n // If chunk is string and encoding is non-utf8, we might have an issue here\n // as the stream chunk doesn't carry encoding info.\n // Standard Node streams yield Buffers or strings (usually utf8).\n // If the user passes an async iterable of strings, we assume they are safe to pass to update().\n // If strict encoding control is needed for streams, the stream should yield Buffers.\n for (const hasher of hashers) {\n hasher.update(chunk);\n }\n }\n }\n\n const result: MultiHashResult = {};\n for (let i = 0; i < uniqueAlgorithms.length; i++) {\n result[uniqueAlgorithms[i]] = hashers[i].digest();\n }\n\n return result;\n}\n\n/**\n * Verify data against a formatted checksum (e.g. \"sha256:abc...\").\n * Automatically selects the algorithm from the checksum prefix.\n */\nexport async function verify(\n input: HashInput,\n checksum: string,\n encoding: BufferEncoding = \"utf8\",\n): Promise<boolean> {\n const expected = Digest.parse(checksum);\n const result = await multiHash(input, [expected.algorithm], encoding);\n const actual = result[expected.algorithm];\n\n if (!actual) return false;\n return actual.algorithm === expected.algorithm && actual.hex === expected.hex;\n}\n","import { createHash } from \"node:crypto\";\nimport type { IHasher } from \"hash-wasm\";\nimport { Algorithm } from \"../crucible/fulhash/types.js\";\nimport * as crc32 from \"./algorithms/crc32.js\";\nimport * as crc32c from \"./algorithms/crc32c.js\";\nimport type { StreamHasher, StreamHasherOptions } from \"./definitions.js\";\nimport { Digest } from \"./digest.js\";\nimport { DigestStateError, UnsupportedAlgorithmError } from \"./errors.js\";\nimport { createHasher as createXXH3Hasher, initializeWasm } from \"./wasm-loader.js\";\n\nenum State {\n INITIAL = \"initial\",\n UPDATING = \"updating\",\n FINALIZED = \"finalized\",\n}\n\nfunction intToBytes(crc: number): Uint8Array {\n const bytes = new Uint8Array(4);\n const unsigned = crc >>> 0;\n bytes[0] = (unsigned >>> 24) & 0xff;\n bytes[1] = (unsigned >>> 16) & 0xff;\n bytes[2] = (unsigned >>> 8) & 0xff;\n bytes[3] = unsigned & 0xff;\n return bytes;\n}\n\ntype IDataType =\n | string\n | Uint8Array\n | Uint16Array\n | Uint32Array\n | Int8Array\n | Int16Array\n | Int32Array\n | Float32Array\n | Float64Array\n | DataView\n | ArrayBuffer\n | SharedArrayBuffer;\n\n// Helper to define local interface for CRC hashers returned by our modules\ninterface CRC32Hasher extends IHasher {\n // We only use the update method with Uint8Array in our wrapper,\n // but we declare it compatible with IHasher to avoid TS complaints if possible,\n // or cast it. hash-wasm's IHasher expects IDataType (string | Buffer | TypedArray).\n update(data: IDataType): IHasher;\n}\n\nabstract class BaseStreamHasher implements StreamHasher {\n protected state: State = State.INITIAL;\n protected readonly algorithm: Algorithm;\n\n constructor(algorithm: Algorithm) {\n this.algorithm = algorithm;\n }\n\n abstract update(data: string | Uint8Array): StreamHasher;\n abstract digest(): Digest;\n abstract reset(): StreamHasher;\n\n protected ensureNotFinalized(): void {\n if (this.state === State.FINALIZED) {\n throw new DigestStateError(\"Cannot update after digest(). Call reset() to reuse hasher.\");\n }\n }\n\n protected ensureUpdating(): void {\n if (this.state !== State.UPDATING && this.state !== State.INITIAL) {\n throw new DigestStateError(\"Invalid state for digest(). Hasher may have been finalized.\");\n }\n }\n\n protected markUpdating(): void {\n this.state = State.UPDATING;\n }\n\n protected markFinalized(): void {\n this.state = State.FINALIZED;\n }\n\n protected markInitial(): void {\n this.state = State.INITIAL;\n }\n}\n\nclass SHA256StreamHasher extends BaseStreamHasher {\n private hasher: ReturnType<typeof createHash>;\n\n constructor() {\n super(Algorithm.SHA256);\n this.hasher = createHash(\"sha256\");\n }\n\n update(data: string | Uint8Array): StreamHasher {\n this.ensureNotFinalized();\n this.markUpdating();\n\n if (typeof data === \"string\") {\n this.hasher.update(data, \"utf8\");\n } else {\n this.hasher.update(data);\n }\n\n return this;\n }\n\n digest(): Digest {\n this.ensureUpdating();\n this.markFinalized();\n\n const bytes = new Uint8Array(this.hasher.digest());\n return new Digest(this.algorithm, bytes);\n }\n\n reset(): StreamHasher {\n this.hasher = createHash(\"sha256\");\n this.markInitial();\n return this;\n }\n}\n\nclass XXH3StreamHasher extends BaseStreamHasher {\n private hasher: IHasher;\n\n constructor(hasher: IHasher) {\n super(Algorithm.XXH3_128);\n this.hasher = hasher;\n this.hasher.init();\n }\n\n update(data: string | Uint8Array): StreamHasher {\n this.ensureNotFinalized();\n this.markUpdating();\n\n if (typeof data === \"string\") {\n const encoder = new TextEncoder();\n this.hasher.update(encoder.encode(data));\n } else {\n this.hasher.update(data);\n }\n\n return this;\n }\n\n digest(): Digest {\n this.ensureUpdating();\n this.markFinalized();\n\n const bytes = this.hasher.digest(\"binary\");\n return new Digest(this.algorithm, bytes);\n }\n\n reset(): StreamHasher {\n this.hasher.init();\n this.markInitial();\n return this;\n }\n}\n\nclass CRC32StreamHasher extends BaseStreamHasher {\n private hasher: CRC32Hasher | null = null;\n\n constructor() {\n super(Algorithm.CRC32);\n }\n\n async init(): Promise<void> {\n this.hasher = await crc32.createHasher();\n this.hasher.init();\n }\n\n update(data: string | Uint8Array): StreamHasher {\n this.ensureNotFinalized();\n this.markUpdating();\n\n if (!this.hasher) {\n // This shouldn't happen if createStreamHasher calls init, but technically\n // synchronous update() can't await. We might need to buffer or assume initialized.\n // However, the Factory createStreamHasher is async, so we can await init there.\n throw new Error(\"Hasher not initialized\");\n }\n\n if (typeof data === \"string\") {\n const encoder = new TextEncoder();\n this.hasher.update(encoder.encode(data));\n } else {\n this.hasher.update(data);\n }\n return this;\n }\n\n digest(): Digest {\n this.ensureUpdating();\n this.markFinalized();\n if (!this.hasher) throw new Error(\"Hasher not initialized\");\n\n const hex = this.hasher.digest();\n const bytes = intToBytes(parseInt(hex, 16));\n return new Digest(this.algorithm, bytes);\n }\n\n reset(): StreamHasher {\n if (!this.hasher) throw new Error(\"Hasher not initialized\");\n this.hasher.init();\n this.markInitial();\n return this;\n }\n}\n\nclass CRC32CStreamHasher extends BaseStreamHasher {\n private hasher: CRC32Hasher | null = null;\n\n constructor() {\n super(Algorithm.CRC32C);\n }\n\n async init(): Promise<void> {\n this.hasher = await crc32c.createHasher();\n this.hasher.init();\n }\n\n update(data: string | Uint8Array): StreamHasher {\n this.ensureNotFinalized();\n this.markUpdating();\n\n if (!this.hasher) throw new Error(\"Hasher not initialized\");\n\n if (typeof data === \"string\") {\n const encoder = new TextEncoder();\n this.hasher.update(encoder.encode(data));\n } else {\n this.hasher.update(data);\n }\n return this;\n }\n\n digest(): Digest {\n this.ensureUpdating();\n this.markFinalized();\n if (!this.hasher) throw new Error(\"Hasher not initialized\");\n\n const hex = this.hasher.digest();\n const bytes = intToBytes(parseInt(hex, 16));\n return new Digest(this.algorithm, bytes);\n }\n\n reset(): StreamHasher {\n if (!this.hasher) throw new Error(\"Hasher not initialized\");\n this.hasher.init();\n this.markInitial();\n return this;\n }\n}\n\nexport async function createStreamHasher(options: StreamHasherOptions = {}): Promise<StreamHasher> {\n const algorithm = options.algorithm ?? Algorithm.XXH3_128;\n\n switch (algorithm) {\n case Algorithm.SHA256:\n return new SHA256StreamHasher();\n case Algorithm.XXH3_128: {\n await initializeWasm();\n const wasmHasher = await createXXH3Hasher();\n return new XXH3StreamHasher(wasmHasher);\n }\n case Algorithm.CRC32: {\n const hasher = new CRC32StreamHasher();\n await hasher.init();\n return hasher;\n }\n case Algorithm.CRC32C: {\n const hasher = new CRC32CStreamHasher();\n await hasher.init();\n return hasher;\n }\n default:\n throw new UnsupportedAlgorithmError(algorithm, Object.values(Algorithm));\n }\n}\n","import type { IHasher } from \"hash-wasm\";\nimport { createXXHash128 } from \"hash-wasm\";\nimport { FulHashError } from \"./errors.js\";\n\nlet isWasmReady = false;\nlet initPromise: Promise<void> | null = null;\n\nexport async function initializeWasm(): Promise<void> {\n if (isWasmReady) {\n return;\n }\n\n if (initPromise) {\n return initPromise;\n }\n\n initPromise = createXXHash128()\n .then(() => {\n isWasmReady = true;\n })\n .catch((error) => {\n initPromise = null;\n throw new FulHashError(`Failed to initialize hash-wasm XXH3-128 module: ${error.message}`);\n });\n\n return initPromise;\n}\n\nexport function isInitialized(): boolean {\n return isWasmReady;\n}\n\nexport async function createHasher(): Promise<IHasher> {\n if (!isWasmReady) {\n throw new FulHashError(\"WASM not initialized. Call initializeWasm() first.\");\n }\n return createXXHash128();\n}\n","/**\n * Pathfinder types - Core type definitions for filesystem traversal\n *\n * Implements types aligned with Crucible schemas:\n * - schemas/crucible-ts/pathfinder/v1.0.0/finder-config.schema.json\n * - schemas/crucible-ts/pathfinder/v1.0.0/path-result.schema.json\n * - schemas/crucible-ts/pathfinder/v1.0.0/metadata.schema.json\n */\n\n/**\n * Enforcement levels for path constraints\n *\n * Controls how path constraint violations are handled during traversal.\n */\nexport enum EnforcementLevel {\n /** Reject constraint violations */\n STRICT = \"strict\",\n\n /** Log violations but continue */\n WARN = \"warn\",\n\n /** Disable constraint enforcement */\n PERMISSIVE = \"permissive\",\n}\n\n/**\n * Supported constraint types (repository/workspace/cloud)\n */\nexport enum ConstraintType {\n REPOSITORY = \"repository\",\n WORKSPACE = \"workspace\",\n CLOUD = \"cloud\",\n}\n\n/**\n * Supported loader implementations for discovery operations\n */\nexport enum LoaderType {\n LOCAL = \"local\",\n REMOTE = \"remote\",\n CLOUD = \"cloud\",\n}\n\n/**\n * Supported checksum algorithms for FulHash integration\n */\nexport enum ChecksumAlgorithm {\n XXH3_128 = \"xxh3-128\",\n SHA256 = \"sha256\",\n}\n\n/**\n * Supported checksum encodings for serialized results\n */\nexport enum ChecksumEncoding {\n HEX = \"hex\",\n}\n\n/**\n * Path constraint specification (mirrors Crucible schema)\n *\n * Encapsulates repository/workspace boundaries and enforcement behaviour.\n */\nexport interface PathConstraint {\n /** Root path for the constraint scope */\n root?: string;\n\n /** Constraint classification (repository/workspace/cloud) */\n type: ConstraintType;\n\n /** Enforcement behaviour for path violations */\n enforcementLevel: EnforcementLevel;\n}\n\n/**\n * Pathfinder configuration options (Crucible-aligned)\n *\n * Aligns with schemas/crucible-ts/pathfinder/v1.0.0/finder-config.schema.json.\n */\nexport interface PathfinderConfig {\n /** Maximum number of worker routines for traversal */\n maxWorkers?: number;\n\n /** Enable filesystem metadata/result caching */\n cacheEnabled?: boolean;\n\n /** Cache time-to-live (seconds) */\n cacheTTL?: number;\n\n /** Path constraint applied to traversal */\n constraint?: PathConstraint;\n\n /** Default loader used to resolve paths */\n loaderType?: LoaderType;\n\n /** Calculate file checksums */\n calculateChecksums?: boolean;\n\n /** Hash algorithm used for checksum calculation */\n checksumAlgorithm?: ChecksumAlgorithm;\n\n /** Encoding format for serialized checksums */\n checksumEncoding?: ChecksumEncoding;\n\n /** Honor .fulmenignore files during traversal */\n honorIgnoreFiles?: boolean;\n}\n\n/**\n * Pathfinder discovery query (Crucible-aligned)\n *\n * Matches schemas/crucible-ts/pathfinder/v1.0.0/find-query.schema.json.\n */\nexport interface PathfinderQuery {\n /** Root directory for traversal (required) */\n root: string;\n\n /** Glob include patterns (defaults to matching all files) */\n include?: string[];\n\n /** Glob exclude patterns */\n exclude?: string[];\n\n /** Maximum traversal depth (0 = unlimited) */\n maxDepth?: number;\n\n /** Follow symbolic links during traversal */\n followSymlinks?: boolean;\n\n /** Include hidden files and directories (dot-prefixed) */\n includeHidden?: boolean;\n\n /** Honor .fulmenignore files during traversal */\n honorIgnoreFiles?: boolean;\n}\n\n/**\n * File metadata returned by pathfinder\n *\n * Includes size, modification time, and optional checksum information.\n */\nexport interface FileMetadata {\n /** File size in bytes */\n size?: number;\n\n /** Last modification timestamp (ISO 8601) */\n modified?: string;\n\n /** File permissions (e.g., rwxr-xr-x or 0755) */\n permissions?: string;\n\n /** MIME type of the file */\n mimeType?: string;\n\n /** Character encoding if applicable */\n encoding?: string;\n\n /** FulHash output formatted as algorithm:hex */\n checksum?: string;\n\n /** Algorithm used for the checksum */\n checksumAlgorithm?: ChecksumAlgorithm;\n\n /** Error message when checksum calculation fails */\n checksumError?: string;\n\n /** User-defined tags associated with the result */\n tags?: string[];\n\n /** Custom metadata bag for provider-specific data */\n custom?: Record<string, unknown>;\n\n /** Whether result represents a symbolic link */\n isSymlink?: boolean;\n\n /** Target path for symbolic links */\n symlinkTarget?: string;\n\n /** Allow additional provider-specific properties */\n [key: string]: unknown;\n}\n\n/**\n * Path result returned by finder operations\n *\n * Represents a single discovered file with its metadata.\n */\nexport interface PathResult {\n /** Path relative to traversal root */\n relativePath: string;\n\n /** Absolute path to the discovered file */\n sourcePath: string;\n\n /** Logical path presented to downstream consumers */\n logicalPath?: string;\n\n /** Loader type that produced the result */\n loaderType: LoaderType;\n\n /** Provider metadata attached to the result */\n metadata?: FileMetadata;\n}\n\n/**\n * Progress callback for long-running operations\n *\n * Called for each discovered file during traversal.\n * Can be async to allow for processing or throttling.\n */\nexport type ProgressCallback = (result: PathResult) => void | Promise<void>;\n\n/**\n * Error handler callback\n *\n * Called when non-fatal errors occur during traversal.\n * Allows custom error handling without stopping the entire operation.\n */\nexport type ErrorCallback = (error: Error, path: string) => void | Promise<void>;\n\n/**\n * Result handler callback (fires for each result)\n *\n * Alternative to collecting all results in memory.\n * Process results as they're discovered.\n */\nexport type ResultCallback = (result: PathResult) => void | Promise<void>;\n\n/**\n * Execution callbacks for finder operations\n *\n * Allows callers to subscribe to progress, per-result, and recoverable errors.\n */\nexport interface PathfinderExecuteOptions {\n /** Invoked for each discovered result */\n resultCallback?: ResultCallback;\n\n /** Invoked for each discovered result (alias for resultCallback) */\n progressCallback?: ProgressCallback;\n\n /** Invoked when recoverable errors occur during traversal */\n errorCallback?: ErrorCallback;\n}\n\n/**\n * Options for repository root discovery\n *\n * Controls behavior of findRepositoryRoot() operation including\n * boundaries, max depth, symlink handling, and path constraints.\n *\n * Aligned with Crucible v0.2.15 pathfinder extension spec.\n */\nexport interface FindRepoOptions {\n /**\n * Maximum depth to search upward\n *\n * Defaults to 10. Prevents excessive traversal up the directory tree.\n */\n maxDepth?: number;\n\n /**\n * Boundary ceiling for upward search\n *\n * Stops traversal when reaching this directory.\n * Defaults to user home directory if not specified.\n * Always stops at filesystem root/drive/UNC regardless.\n */\n boundary?: string;\n\n /**\n * Stop at first marker match\n *\n * If true, returns immediately upon finding any marker.\n * If false, continues to find deepest marker (closest to filesystem root).\n * Defaults to true.\n */\n stopAtFirst?: boolean;\n\n /**\n * Path constraint for upper boundary enforcement\n *\n * If provided, prevents discovery outside this constraint.\n * Returns REPOSITORY_NOT_FOUND if constraint prevents marker hit.\n */\n constraint?: PathConstraint;\n\n /**\n * Follow symbolic links during traversal\n *\n * Defaults to false (security). If enabled, tracks visited\n * real paths to detect loops.\n */\n followSymlinks?: boolean;\n}\n\n/**\n * Helper to create FindRepoOptions with maxDepth\n *\n * @param maxDepth - Maximum depth to search upward\n * @returns FindRepoOptions with maxDepth set\n */\nexport function withMaxDepth(maxDepth: number): FindRepoOptions {\n return { maxDepth };\n}\n\n/**\n * Helper to create FindRepoOptions with boundary\n *\n * @param boundary - Boundary ceiling directory\n * @returns FindRepoOptions with boundary set\n */\nexport function withBoundary(boundary: string): FindRepoOptions {\n return { boundary };\n}\n\n/**\n * Helper to create FindRepoOptions with stopAtFirst\n *\n * @param stopAtFirst - Whether to stop at first marker\n * @returns FindRepoOptions with stopAtFirst set\n */\nexport function withStopAtFirst(stopAtFirst: boolean): FindRepoOptions {\n return { stopAtFirst };\n}\n\n/**\n * Helper to create FindRepoOptions with constraint\n *\n * @param constraint - Path constraint for upper boundary\n * @returns FindRepoOptions with constraint set\n */\nexport function withConstraint(constraint: PathConstraint): FindRepoOptions {\n return { constraint };\n}\n\n/**\n * Helper to create FindRepoOptions with followSymlinks\n *\n * @param followSymlinks - Whether to follow symbolic links\n * @returns FindRepoOptions with followSymlinks set\n */\nexport function withFollowSymlinks(followSymlinks: boolean): FindRepoOptions {\n return { followSymlinks };\n}\n","import { createReadStream } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Algorithm, createStreamHasher } from \"../fulhash/index.js\";\nimport { ChecksumAlgorithm, type FileMetadata } from \"./types.js\";\n\n/**\n * Result fragment returned when calculating a checksum.\n */\nexport type ChecksumMetadata = Pick<\n FileMetadata,\n \"checksum\" | \"checksumAlgorithm\" | \"checksumError\"\n>;\n\nfunction toFulHashAlgorithm(algorithm: ChecksumAlgorithm): Algorithm {\n switch (algorithm) {\n case ChecksumAlgorithm.SHA256:\n return Algorithm.SHA256;\n default:\n return Algorithm.XXH3_128;\n }\n}\n\n/**\n * Calculate the checksum for a single file using FulHash streaming hasher.\n *\n * Returns checksum metadata compatible with Pathfinder metadata schema.\n */\nexport async function calculateChecksum(\n filePath: string,\n algorithm: ChecksumAlgorithm,\n): Promise<ChecksumMetadata> {\n const absolutePath = path.resolve(filePath);\n\n try {\n const hasher = await createStreamHasher({ algorithm: toFulHashAlgorithm(algorithm) });\n const stream = createReadStream(absolutePath);\n\n try {\n for await (const chunk of stream) {\n hasher.update(chunk as Uint8Array);\n }\n } catch (error) {\n stream.destroy();\n throw error;\n }\n\n const digest = hasher.digest();\n\n return {\n checksum: `${algorithm}:${digest.hex}`,\n checksumAlgorithm: algorithm,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n checksumAlgorithm: algorithm,\n checksumError: message,\n };\n }\n}\n\n/**\n * Calculate checksums for a list of files with a simple concurrency limiter.\n */\nexport async function calculateChecksumsBatch(\n filePaths: string[],\n algorithm: ChecksumAlgorithm,\n concurrency: number = 1,\n): Promise<Map<string, ChecksumMetadata>> {\n const safeConcurrency = Math.max(1, Math.floor(concurrency));\n const results = new Map<string, ChecksumMetadata>();\n\n if (filePaths.length === 0) {\n return results;\n }\n\n let index = 0;\n\n const worker = async (): Promise<void> => {\n while (index < filePaths.length) {\n const currentIndex = index++;\n const filePath = filePaths[currentIndex];\n const metadata = await calculateChecksum(filePath, algorithm);\n results.set(filePath, metadata);\n }\n };\n\n const workers = Array.from({ length: Math.min(safeConcurrency, filePaths.length) }, () =>\n worker(),\n );\n await Promise.all(workers);\n\n return results;\n}\n","/**\n * Pathfinder constants - Default configuration and standard values\n */\n\nimport type { PathfinderConfig } from \"./types.js\";\nimport { ChecksumAlgorithm, ChecksumEncoding, LoaderType } from \"./types.js\";\n\n/**\n * Default Pathfinder configuration\n *\n * Provides schema-aligned defaults for optional configuration parameters.\n * Callers should override constraint.root and other deployment-specific values.\n */\nexport const DEFAULT_CONFIG: Partial<PathfinderConfig> = {\n maxWorkers: 4,\n cacheEnabled: false,\n cacheTTL: 300,\n loaderType: LoaderType.LOCAL,\n calculateChecksums: false,\n checksumAlgorithm: ChecksumAlgorithm.XXH3_128,\n checksumEncoding: ChecksumEncoding.HEX,\n honorIgnoreFiles: true,\n};\n\n/**\n * Default ignore file names (checked in order)\n *\n * Pathfinder will look for these files in each directory during traversal.\n * First match wins. .fulmenignore takes precedence over .gitignore.\n */\nexport const DEFAULT_IGNORE_FILES = [\".fulmenignore\", \".gitignore\"];\n\n/**\n * Platform-specific path separator\n *\n * Used for normalizing paths across Windows and Unix-like systems.\n */\nexport const PATH_SEPARATOR = process.platform === \"win32\" ? \"\\\\\" : \"/\";\n\n/**\n * Maximum reasonable path length\n *\n * Used for validation to prevent excessively long paths.\n * Windows MAX_PATH is 260, Unix typically 4096. Use conservative limit.\n */\nexport const MAX_PATH_LENGTH = 4096;\n\n/**\n * Default buffer size for file operations (bytes)\n *\n * Used when reading files for checksum calculation.\n */\nexport const DEFAULT_BUFFER_SIZE = 65536; // 64KB\n\n/**\n * Default maximum depth for repository root search\n *\n * Prevents excessive traversal up the directory tree.\n * Can be overridden via FindRepoOptions.\n */\nexport const DEFAULT_MAX_DEPTH = 10;\n\n/**\n * Git repository markers\n *\n * Identifies Git repositories by presence of .git directory.\n */\nexport const GitMarkers = [\".git\"];\n\n/**\n * Node.js/npm project markers (ordered by specificity)\n *\n * Identifies Node.js projects by package.json or package-lock.json.\n * Order: most specific first.\n */\nexport const NodeMarkers = [\"package.json\", \"package-lock.json\"];\n\n/**\n * Go module markers\n *\n * Identifies Go modules by go.mod file.\n */\nexport const GoModMarkers = [\"go.mod\"];\n\n/**\n * Python project markers (ordered by specificity)\n *\n * Identifies Python projects by various project files.\n * Order: most specific first.\n */\nexport const PythonMarkers = [\"pyproject.toml\", \"setup.py\", \"requirements.txt\", \"Pipfile\"];\n\n/**\n * Monorepo markers (common tools)\n *\n * Identifies monorepo roots by presence of workspace configuration files.\n * Order: most specific first.\n */\nexport const MonorepoMarkers = [\n \"lerna.json\",\n \"pnpm-workspace.yaml\",\n \"nx.json\",\n \"turbo.json\",\n \"rush.json\",\n];\n","/**\n * Pathfinder Finder - Main traversal class (Phase 1)\n *\n * Implements secure filesystem traversal with glob-based discovery, include/exclude\n * pattern support, optional symlink following, and constraint enforcement.\n */\n\nimport type { Stats } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport fg, { type Options as FastGlobOptions } from \"fast-glob\";\n\nimport { FulmenError, generateCorrelationId } from \"../errors/index.js\";\nimport type { SeverityName } from \"../errors/severity.js\";\nimport type { Logger } from \"../logging/logger.js\";\nimport { metrics as defaultMetrics } from \"../telemetry/index.js\";\nimport type { MetricsRegistry } from \"../telemetry/registry.js\";\nimport { calculateChecksum } from \"./checksum.js\";\nimport { DEFAULT_CONFIG, DEFAULT_IGNORE_FILES } from \"./constants.js\";\nimport { createPathfinderError, PathfinderErrorCode } from \"./errors.js\";\nimport { IgnoreMatcher } from \"./ignore.js\";\nimport {\n type ConstraintEvaluation,\n enforcePathConstraints,\n isPathWithinRoot,\n toPosixPath,\n} from \"./safety.js\";\nimport type {\n PathfinderConfig,\n PathfinderExecuteOptions,\n PathfinderQuery,\n PathResult,\n} from \"./types.js\";\nimport {\n ChecksumAlgorithm,\n ChecksumEncoding,\n EnforcementLevel,\n type FileMetadata,\n LoaderType,\n} from \"./types.js\";\n\nexport interface PathfinderOptions {\n logger?: Logger;\n correlationId?: string;\n metrics?: MetricsRegistry;\n}\n\n/**\n * Resolved configuration with defaults applied.\n */\ninterface ResolvedPathfinderConfig {\n maxWorkers: number;\n cacheEnabled: boolean;\n cacheTTL: number;\n loaderType: LoaderType;\n calculateChecksums: boolean;\n checksumAlgorithm: ChecksumAlgorithm;\n checksumEncoding: ChecksumEncoding;\n constraint?: PathfinderConfig[\"constraint\"];\n honorIgnoreFiles: boolean;\n}\n\n/**\n * Normalized discovery query with absolute paths and defaults applied.\n */\ninterface NormalizedPathfinderQuery {\n /** Absolute root path retaining caller symlink semantics */\n root: string;\n /** Real path of the root (symlinks resolved) */\n realRoot: string;\n include: string[];\n exclude: string[];\n maxDepth: number;\n followSymlinks: boolean;\n includeHidden: boolean;\n honorIgnoreFiles: boolean;\n}\n\n/**\n * Pathfinder class - Filesystem traversal with pattern matching\n */\nexport class Pathfinder {\n private readonly config: ResolvedPathfinderConfig;\n private readonly logger?: Logger;\n private readonly correlationId: string;\n private readonly metrics: MetricsRegistry;\n\n constructor(config?: PathfinderConfig, options: PathfinderOptions = {}) {\n this.config = this.normalizeConfig(config);\n this.logger = options.logger;\n this.correlationId = options.correlationId ?? generateCorrelationId();\n this.metrics = options.metrics ?? defaultMetrics;\n }\n\n private log(\n level: \"debug\" | \"info\" | \"warn\" | \"error\",\n message: string,\n context?: Record<string, unknown>,\n error?: Error,\n ): void {\n if (!this.logger) return;\n\n const logContext = {\n correlation_id: this.correlationId,\n domain: \"pathfinder\",\n ...context,\n };\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, logContext);\n break;\n case \"info\":\n this.logger.info(message, logContext);\n break;\n case \"warn\":\n this.logger.warn(message, logContext);\n break;\n case \"error\":\n this.logger.error(message, error, logContext);\n break;\n }\n }\n\n private createError(\n code: PathfinderErrorCode,\n message: string,\n severity: SeverityName = \"medium\",\n context?: Record<string, unknown>,\n ): FulmenError {\n return createPathfinderError(code, message, {\n severity,\n correlation_id: this.correlationId,\n context,\n });\n }\n\n private throwError(\n code: PathfinderErrorCode,\n message: string,\n severity: SeverityName = \"medium\",\n context?: Record<string, unknown>,\n ): never {\n const error = this.createError(code, message, severity, context);\n const level = severity === \"critical\" || severity === \"high\" ? \"error\" : \"warn\";\n this.log(level, message, { code, ...context }, error);\n throw error;\n }\n\n private wrapError(\n error: unknown,\n code: PathfinderErrorCode,\n severity: SeverityName = \"medium\",\n context: Record<string, unknown> = {},\n ): FulmenError {\n const baseError =\n error instanceof Error ? error : new Error(typeof error === \"string\" ? error : String(error));\n\n if (error instanceof FulmenError) {\n return FulmenError.wrap(error, {\n severity,\n correlation_id: this.correlationId,\n context: {\n domain: \"pathfinder\",\n category: \"filesystem\",\n ...context,\n },\n });\n }\n\n return FulmenError.wrap(baseError, {\n code,\n severity,\n correlation_id: this.correlationId,\n context: {\n domain: \"pathfinder\",\n category: \"filesystem\",\n ...context,\n },\n });\n }\n\n private wrapAndLogError(\n error: unknown,\n code: PathfinderErrorCode,\n severity: SeverityName = \"medium\",\n context: Record<string, unknown> = {},\n message?: string,\n ): FulmenError {\n const wrapped = this.wrapError(error, code, severity, context);\n const logMessage = message ?? wrapped.message;\n const level = severity === \"critical\" || severity === \"high\" ? \"error\" : \"warn\";\n this.log(level, logMessage, { code, ...context }, wrapped);\n return wrapped;\n }\n\n private recordSecurityWarning(details: Record<string, unknown>, reason?: string): void {\n this.metrics.counter(\"pathfinder_security_warnings\").inc();\n this.log(\"warn\", reason ?? \"Pathfinder security warning\", details);\n }\n\n /**\n * Discover files matching the specified query.\n *\n * Collects all results in memory before returning.\n */\n async find(\n query: PathfinderQuery,\n options: PathfinderExecuteOptions = {},\n ): Promise<PathResult[]> {\n const histogram = this.metrics.histogram(\"pathfinder_find_ms\");\n const start = performance.now();\n\n try {\n const results: PathResult[] = [];\n\n for await (const result of this.iterate(query, options)) {\n results.push(result);\n }\n\n histogram.observe(performance.now() - start);\n return results;\n } catch (error) {\n histogram.observe(performance.now() - start);\n throw this.wrapAndLogError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n operation: \"find\",\n });\n }\n }\n\n async *findIterable(\n query: PathfinderQuery,\n options: PathfinderExecuteOptions = {},\n ): AsyncIterable<PathResult> {\n const histogram = this.metrics.histogram(\"pathfinder_find_ms\");\n const start = performance.now();\n\n try {\n for await (const result of this.iterate(query, options)) {\n yield result;\n }\n histogram.observe(performance.now() - start);\n } catch (error) {\n histogram.observe(performance.now() - start);\n throw this.wrapAndLogError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n operation: \"findIterable\",\n });\n }\n }\n\n /**\n * Discover files lazily via async iteration.\n */\n private async *iterate(\n query: PathfinderQuery,\n options: PathfinderExecuteOptions = {},\n ): AsyncIterable<PathResult> {\n const normalizedQuery = await this.normalizeQuery(query);\n this.validateConstraintCompatibility(normalizedQuery);\n\n const ignoreMatcher = normalizedQuery.honorIgnoreFiles\n ? new IgnoreMatcher(normalizedQuery.root)\n : undefined;\n\n const globOptions: FastGlobOptions = {\n cwd: normalizedQuery.root,\n absolute: true,\n dot: normalizedQuery.includeHidden,\n onlyFiles: true,\n followSymbolicLinks: normalizedQuery.followSymlinks,\n unique: true,\n ignore: normalizedQuery.exclude,\n };\n\n if (normalizedQuery.maxDepth > 0) {\n globOptions.deep = normalizedQuery.maxDepth;\n }\n\n let matches: string[];\n try {\n matches = await fg(normalizedQuery.include, globOptions);\n } catch (error) {\n throw this.wrapAndLogError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n root: normalizedQuery.root,\n operation: \"glob\",\n });\n }\n\n for (const candidatePath of matches) {\n const lstat = await this.safeLstat(candidatePath, options);\n if (!lstat) continue;\n\n if (lstat.isDirectory()) {\n // Should not happen with onlyFiles=true, but guard defensively\n continue;\n }\n\n if (lstat.isSymbolicLink() && !normalizedQuery.followSymlinks) {\n continue;\n }\n\n const isDefaultIgnoreFile = DEFAULT_IGNORE_FILES.includes(path.basename(candidatePath));\n if (isDefaultIgnoreFile) {\n if (normalizedQuery.honorIgnoreFiles) {\n this.log(\"debug\", \"Skipping default ignore file\", { path: candidatePath });\n continue;\n }\n\n this.log(\"debug\", \"Including default ignore file because honorIgnoreFiles is disabled\", {\n path: candidatePath,\n });\n }\n\n let evaluationPath = candidatePath;\n if (lstat.isSymbolicLink()) {\n const resolved = await this.safeRealpath(candidatePath, options);\n if (!resolved) continue;\n evaluationPath = resolved;\n }\n\n // Ensure the resolved path remains within the real root.\n if (!isPathWithinRoot(evaluationPath, normalizedQuery.realRoot)) {\n const violationContext = {\n path: evaluationPath,\n root: normalizedQuery.realRoot,\n operation: \"validatePathWithinRoot\",\n };\n this.recordSecurityWarning(\n violationContext,\n `Path ${evaluationPath} escapes discovery root ${normalizedQuery.realRoot}`,\n );\n const violationError = this.createError(\n PathfinderErrorCode.CONSTRAINT_VIOLATION,\n `Path ${evaluationPath} escapes discovery root ${normalizedQuery.realRoot}`,\n \"high\",\n violationContext,\n );\n await this.dispatchError(violationError, candidatePath, options);\n continue;\n }\n\n const relativeFromRoot = path.relative(normalizedQuery.root, candidatePath);\n if (relativeFromRoot.startsWith(\"..\") || path.isAbsolute(relativeFromRoot)) {\n const violationContext = {\n path: candidatePath,\n root: normalizedQuery.root,\n operation: \"validateRelativePath\",\n };\n this.recordSecurityWarning(\n violationContext,\n `Path ${candidatePath} is outside discovery root ${normalizedQuery.root}`,\n );\n const violationError = this.createError(\n PathfinderErrorCode.CONSTRAINT_VIOLATION,\n `Path ${candidatePath} is outside discovery root ${normalizedQuery.root}`,\n \"high\",\n violationContext,\n );\n await this.dispatchError(violationError, candidatePath, options);\n continue;\n }\n\n const relativePosix = toPosixPath(relativeFromRoot);\n if (ignoreMatcher && (await ignoreMatcher.shouldIgnore(candidatePath, relativePosix))) {\n this.log(\"debug\", \"Excluded by ignore matcher\", {\n path: candidatePath,\n relativePath: relativePosix,\n });\n continue;\n }\n\n const constraintResult = this.evaluateConstraint(evaluationPath, relativePosix);\n if (!constraintResult.allowed) {\n const enforcement = this.config.constraint?.enforcementLevel ?? EnforcementLevel.WARN;\n const message = constraintResult.reason ?? \"Path violates configured constraint\";\n const violationContext = {\n path: evaluationPath,\n relativePath: relativePosix,\n constraintRoot: this.config.constraint?.root,\n enforcement,\n };\n\n this.recordSecurityWarning(violationContext, message);\n\n const violationError = this.createError(\n PathfinderErrorCode.CONSTRAINT_VIOLATION,\n message,\n enforcement === EnforcementLevel.STRICT ? \"high\" : \"medium\",\n violationContext,\n );\n\n if (enforcement === EnforcementLevel.STRICT) {\n this.log(\"error\", message, violationContext, violationError);\n throw violationError;\n }\n\n if (enforcement === EnforcementLevel.WARN) {\n this.log(\"warn\", message, violationContext, violationError);\n if (options.errorCallback) {\n await options.errorCallback(violationError, candidatePath);\n }\n continue;\n }\n\n // Permissive mode allows the path through.\n }\n\n let statsForMetadata = lstat;\n if (evaluationPath !== candidatePath) {\n const resolvedStats = await this.safeStat(evaluationPath, options);\n statsForMetadata = resolvedStats ?? lstat;\n }\n\n const metadata = await this.buildMetadata(\n candidatePath,\n evaluationPath,\n statsForMetadata,\n lstat.isSymbolicLink(),\n );\n\n const result: PathResult = {\n relativePath: relativePosix,\n sourcePath: candidatePath,\n logicalPath: relativePosix,\n loaderType: this.config.loaderType,\n metadata,\n };\n\n await this.dispatchResult(result, options);\n yield result;\n }\n }\n\n /**\n * Normalize finder configuration by applying defaults.\n */\n private normalizeConfig(config?: PathfinderConfig): ResolvedPathfinderConfig {\n const merged: PathfinderConfig = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n return {\n maxWorkers: merged.maxWorkers ?? 4,\n cacheEnabled: merged.cacheEnabled ?? false,\n cacheTTL: merged.cacheTTL ?? 300,\n loaderType: merged.loaderType ?? LoaderType.LOCAL,\n calculateChecksums: merged.calculateChecksums ?? false,\n checksumAlgorithm: merged.checksumAlgorithm ?? ChecksumAlgorithm.XXH3_128,\n checksumEncoding: merged.checksumEncoding ?? ChecksumEncoding.HEX,\n constraint: merged.constraint,\n honorIgnoreFiles: merged.honorIgnoreFiles ?? true,\n };\n }\n\n /**\n * Normalize a discovery query and ensure the root exists.\n */\n private async normalizeQuery(query: PathfinderQuery): Promise<NormalizedPathfinderQuery> {\n if (!query || !query.root) {\n this.throwError(\n PathfinderErrorCode.INVALID_CONFIG,\n \"Pathfinder query requires a root directory\",\n \"high\",\n { operation: \"normalizeQuery\" },\n );\n }\n\n const absoluteRoot = path.resolve(query.root);\n\n let stats: Stats;\n try {\n stats = await fs.stat(absoluteRoot);\n } catch (error) {\n throw this.wrapAndLogError(error, PathfinderErrorCode.INVALID_ROOT, \"high\", {\n root: absoluteRoot,\n operation: \"stat\",\n });\n }\n\n if (!stats.isDirectory()) {\n this.throwError(\n PathfinderErrorCode.INVALID_ROOT,\n `Pathfinder root must be a directory: ${absoluteRoot}`,\n \"high\",\n { root: absoluteRoot },\n );\n }\n\n let realRoot: string;\n try {\n realRoot = await fs.realpath(absoluteRoot);\n } catch (error) {\n throw this.wrapAndLogError(error, PathfinderErrorCode.INVALID_ROOT, \"high\", {\n root: absoluteRoot,\n operation: \"realpath\",\n });\n }\n\n const include = query.include && query.include.length > 0 ? [...query.include] : [\"**/*\"];\n const exclude = query.exclude ? [...query.exclude] : [];\n const maxDepth = query.maxDepth ?? 0;\n\n if (maxDepth < 0) {\n this.throwError(\n PathfinderErrorCode.INVALID_CONFIG,\n \"Pathfinder maxDepth must be >= 0\",\n \"high\",\n { maxDepth },\n );\n }\n\n return {\n root: absoluteRoot,\n realRoot,\n include,\n exclude,\n maxDepth,\n followSymlinks: query.followSymlinks ?? false,\n includeHidden: query.includeHidden ?? false,\n honorIgnoreFiles: query.honorIgnoreFiles ?? this.config.honorIgnoreFiles,\n };\n }\n\n /**\n * Ensure constraint root encompasses the discovery root when provided.\n */\n private validateConstraintCompatibility(query: NormalizedPathfinderQuery): void {\n const constraint = this.config.constraint;\n if (!constraint) {\n return;\n }\n\n const constraintRoot = constraint.root ? path.resolve(constraint.root) : undefined;\n if (!constraintRoot) {\n return;\n }\n\n if (!isPathWithinRoot(query.realRoot, constraintRoot)) {\n this.throwError(\n PathfinderErrorCode.INVALID_CONFIG,\n `Discovery root ${query.realRoot} must be within constraint root ${constraintRoot}`,\n \"high\",\n { root: query.realRoot, constraintRoot },\n );\n }\n }\n\n /**\n * Evaluate constraint applicability for a discovered path.\n */\n private evaluateConstraint(evaluationPath: string, relativePath: string): ConstraintEvaluation {\n return enforcePathConstraints(evaluationPath, relativePath, this.config.constraint);\n }\n\n /**\n * Invoke result/progress callbacks prior to yielding.\n */\n private async dispatchResult(\n result: PathResult,\n options: PathfinderExecuteOptions,\n ): Promise<void> {\n if (options.resultCallback) {\n await options.resultCallback(result);\n }\n\n if (options.progressCallback && options.progressCallback !== options.resultCallback) {\n await options.progressCallback(result);\n }\n }\n\n private async buildMetadata(\n originalPath: string,\n resolvedPath: string,\n stats: Stats,\n isSymlink: boolean,\n ): Promise<FileMetadata> {\n const metadata: FileMetadata = {};\n\n if (Number.isFinite(stats.size)) {\n metadata.size = stats.size;\n }\n\n if (stats.mtime instanceof Date && Number.isFinite(stats.mtime.valueOf())) {\n metadata.modified = stats.mtime.toISOString();\n }\n\n metadata.permissions = this.formatPermissions(stats.mode);\n\n if (isSymlink) {\n metadata.isSymlink = true;\n try {\n metadata.symlinkTarget = await fs.readlink(originalPath);\n } catch {\n // Ignore readlink errors; metadata remains without target\n }\n }\n\n if (this.config.calculateChecksums) {\n const algorithm = this.config.checksumAlgorithm ?? ChecksumAlgorithm.XXH3_128;\n const checksumMetadata = await calculateChecksum(resolvedPath, algorithm);\n\n if (checksumMetadata.checksumError) {\n this.log(\"warn\", \"Checksum calculation failed\", {\n path: originalPath,\n resolvedPath,\n algorithm,\n error: checksumMetadata.checksumError,\n });\n }\n\n Object.assign(metadata, checksumMetadata);\n }\n\n return metadata;\n }\n\n private formatPermissions(mode: number): string {\n const normalized = mode & 0o777;\n return normalized.toString(8).padStart(4, \"0\");\n }\n\n private async safeStat(\n targetPath: string,\n options: PathfinderExecuteOptions,\n ): Promise<Stats | undefined> {\n try {\n return await fs.stat(targetPath);\n } catch (error) {\n const wrapped = this.wrapError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n path: targetPath,\n operation: \"stat\",\n });\n await this.dispatchError(wrapped, targetPath, options);\n return undefined;\n }\n }\n\n /**\n * Invoke error callback or throw when unrecoverable.\n */\n private async dispatchError(\n error: Error,\n pathContext: string,\n options: PathfinderExecuteOptions,\n ): Promise<void> {\n const normalized =\n error instanceof FulmenError\n ? error\n : this.wrapError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n path: pathContext,\n operation: \"dispatchError\",\n });\n\n const severity = normalized.data.severity ?? \"medium\";\n const level = severity === \"critical\" || severity === \"high\" ? \"error\" : \"warn\";\n\n this.log(\n level,\n \"Pathfinder recoverable error\",\n {\n path: pathContext,\n code: normalized.data.code,\n severity,\n },\n normalized,\n );\n\n if (options.errorCallback) {\n await options.errorCallback(normalized, pathContext);\n return;\n }\n\n throw normalized;\n }\n\n /**\n * lstat wrapper that routes recoverable errors through callbacks.\n */\n private async safeLstat(\n targetPath: string,\n options: PathfinderExecuteOptions,\n ): Promise<Stats | undefined> {\n try {\n return await fs.lstat(targetPath);\n } catch (error) {\n const wrapped = this.wrapError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n path: targetPath,\n operation: \"lstat\",\n });\n await this.dispatchError(wrapped, targetPath, options);\n return undefined;\n }\n }\n\n /**\n * realpath wrapper that routes recoverable errors through callbacks.\n */\n private async safeRealpath(\n targetPath: string,\n options: PathfinderExecuteOptions,\n ): Promise<string | undefined> {\n try {\n return await fs.realpath(targetPath);\n } catch (error) {\n const wrapped = this.wrapError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n path: targetPath,\n operation: \"realpath\",\n });\n await this.dispatchError(wrapped, targetPath, options);\n return undefined;\n }\n }\n}\n","/**\n * Pathfinder errors - Domain-specific error helpers\n *\n * Provides pathfinder-specific error codes and factory functions\n * that wrap FulmenError with appropriate metadata.\n */\n\nimport type { FulmenErrorOptions } from \"../errors/index.js\";\nimport { FulmenError } from \"../errors/index.js\";\n\n/**\n * Pathfinder error codes\n *\n * All codes prefixed with 'pathfinder.' for domain identification.\n */\nexport enum PathfinderErrorCode {\n /** Configuration validation failed */\n INVALID_CONFIG = \"pathfinder.invalid_config\",\n\n /** Root directory invalid or inaccessible */\n INVALID_ROOT = \"pathfinder.invalid_root\",\n\n /** Filesystem traversal operation failed */\n TRAVERSAL_FAILED = \"pathfinder.traversal_failed\",\n\n /** Path constraint violation detected */\n CONSTRAINT_VIOLATION = \"pathfinder.constraint_violation\",\n\n /** Checksum calculation failed */\n CHECKSUM_FAILED = \"pathfinder.checksum_failed\",\n\n /** Schema validation failed */\n VALIDATION_FAILED = \"pathfinder.validation_failed\",\n\n /** Ignore file parsing failed */\n IGNORE_FILE_ERROR = \"pathfinder.ignore_file_error\",\n\n /** Repository root not found */\n REPOSITORY_NOT_FOUND = \"pathfinder.repository_not_found\",\n\n /** Invalid start path for repository search */\n INVALID_START_PATH = \"pathfinder.invalid_start_path\",\n\n /** Invalid boundary specified */\n INVALID_BOUNDARY = \"pathfinder.invalid_boundary\",\n\n /** Traversal loop detected (cyclic symlinks) */\n TRAVERSAL_LOOP = \"pathfinder.traversal_loop\",\n\n /** Security violation detected during traversal */\n SECURITY_VIOLATION = \"pathfinder.security_violation\",\n}\n\n/**\n * Create a pathfinder-specific FulmenError\n *\n * Factory function that creates properly structured errors with\n * pathfinder domain, filesystem category, and appropriate severity.\n *\n * @param code - Pathfinder error code\n * @param message - Human-readable error message\n * @param options - Additional error options (severity, context, etc.)\n * @returns FulmenError instance with pathfinder metadata\n *\n * @example\n * ```typescript\n * throw createPathfinderError(\n * PathfinderErrorCode.INVALID_ROOT,\n * 'Root directory does not exist',\n * { severity: 'high', context: { root: '/nonexistent' } }\n * );\n * ```\n */\nexport function createPathfinderError(\n code: PathfinderErrorCode,\n message: string,\n options?: Partial<FulmenErrorOptions>,\n): FulmenError {\n return new FulmenError({\n code,\n message,\n severity: options?.severity ?? \"medium\",\n context: {\n domain: \"pathfinder\",\n category: \"filesystem\",\n ...options?.context,\n },\n ...options,\n });\n}\n\n/**\n * Wrap an existing error as a PathfinderError\n *\n * Preserves the original error as the cause while adding\n * pathfinder-specific metadata.\n *\n * @param error - Original error to wrap\n * @param code - Pathfinder error code\n * @param context - Additional context information\n * @returns FulmenError wrapping the original error\n *\n * @example\n * ```typescript\n * try {\n * await fs.readdir(dir);\n * } catch (err) {\n * throw wrapPathfinderError(\n * err,\n * PathfinderErrorCode.TRAVERSAL_FAILED,\n * { directory: dir }\n * );\n * }\n * ```\n */\nexport function wrapPathfinderError(\n error: Error,\n code: PathfinderErrorCode,\n context?: Record<string, unknown>,\n): FulmenError {\n return FulmenError.wrap(error, {\n code,\n severity: \"medium\",\n context: {\n domain: \"pathfinder\",\n category: \"filesystem\",\n ...context,\n },\n });\n}\n","/**\n * Path safety and constraint enforcement utilities\n */\n\nimport path from \"node:path\";\n\nimport { createPathfinderError, PathfinderErrorCode } from \"./errors.js\";\nimport type { PathConstraint } from \"./types.js\";\n\n/**\n * Result of evaluating a path against configured constraints.\n */\nexport interface ConstraintEvaluation {\n /** Whether the path satisfied all constraints */\n allowed: boolean;\n /** Optional reason describing the violation */\n reason?: string;\n}\n\n/**\n * Normalize a path for comparison by resolving against root.\n */\nfunction normalizeAbsolute(p: string): string {\n return path.resolve(p);\n}\n\n/**\n * Convert filesystem-relative paths to POSIX form for glob evaluation.\n */\nexport function toPosixPath(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/**\n * Determine if candidate path is contained within the provided root directory.\n *\n * @param candidate - Absolute path to check\n * @param root - Root directory that bounds traversal\n */\nexport function isPathWithinRoot(candidate: string, root: string): boolean {\n const normalizedCandidate = normalizeAbsolute(candidate);\n const normalizedRoot = normalizeAbsolute(root);\n const relative = path.relative(normalizedRoot, normalizedCandidate);\n\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\n/**\n * Evaluate a path against a configured constraint definition.\n *\n * Does not throw directly; callers should inspect {@link ConstraintEvaluation.allowed}\n * and escalate according to enforcement level.\n *\n * @param absolutePath - Absolute path being evaluated\n * @param relativePath - Path relative to discovery root (POSIX or platform-specific)\n * @param constraint - Constraint configuration (may be undefined)\n */\nexport function enforcePathConstraints(\n absolutePath: string,\n _relativePath: string,\n constraint?: PathConstraint,\n): ConstraintEvaluation {\n if (!constraint) {\n return { allowed: true };\n }\n\n const constraintRoot = constraint.root ? normalizeAbsolute(constraint.root) : undefined;\n\n if (!constraintRoot) {\n return { allowed: true };\n }\n\n const normalizedConstraintRoot = constraintRoot;\n const normalizedAbsolutePath = normalizeAbsolute(absolutePath);\n\n if (!isPathWithinRoot(normalizedAbsolutePath, normalizedConstraintRoot)) {\n return {\n allowed: false,\n reason: `Path ${normalizedAbsolutePath} escapes constraint root ${normalizedConstraintRoot}`,\n };\n }\n\n return { allowed: true };\n}\n\n/**\n * Create a constraint violation error for STRICT enforcement modes.\n *\n * @param reason - Human-readable violation reason\n * @param context - Additional error context\n */\nexport function createConstraintViolationError(\n reason: string,\n context?: Record<string, unknown>,\n): Error {\n return createPathfinderError(PathfinderErrorCode.CONSTRAINT_VIOLATION, reason, {\n severity: \"critical\",\n context,\n });\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nimport picomatch from \"picomatch\";\n\nimport { DEFAULT_IGNORE_FILES } from \"./constants.js\";\nimport { toPosixPath } from \"./safety.js\";\n\ninterface CompiledRule {\n raw: string;\n negate: boolean;\n directory: boolean;\n pattern: string;\n matcher: picomatch.Matcher;\n}\n\n/**\n * `.fulmenignore` support with directory-level caching.\n *\n * Inspired by gitignore semantics: the last matching rule wins and patterns\n * prefixed with `!` re-include paths. Patterns ending with a slash apply to a\n * directory and all descendants.\n */\nexport class IgnoreMatcher {\n private readonly root: string;\n private readonly ignoreFileNames: string[];\n private readonly ruleCache = new Map<string, CompiledRule[]>();\n private readonly aggregateCache = new Map<string, CompiledRule[]>();\n\n constructor(root: string, ignoreFileNames: string[] = DEFAULT_IGNORE_FILES) {\n this.root = path.resolve(root);\n this.ignoreFileNames = ignoreFileNames;\n }\n\n /**\n * Determine whether the relative path should be ignored.\n *\n * @param absolutePath - Absolute filesystem path\n * @param relativePath - Path relative to the finder root (POSIX)\n */\n async shouldIgnore(absolutePath: string, relativePath: string): Promise<boolean> {\n const directory = path.dirname(path.resolve(absolutePath));\n const rules = await this.loadAggregateRules(directory);\n\n if (rules.length === 0) {\n return false;\n }\n\n const posixPath = toPosixPath(relativePath);\n let ignored = false;\n\n for (const rule of rules) {\n if (!this.matchesRule(rule, posixPath)) {\n continue;\n }\n\n ignored = !rule.negate;\n }\n\n return ignored;\n }\n\n private matchesRule(rule: CompiledRule, posixPath: string): boolean {\n if (rule.directory) {\n return posixPath === rule.pattern || posixPath.startsWith(`${rule.pattern}/`);\n }\n\n if (rule.matcher(posixPath)) {\n return true;\n }\n\n if (!rule.pattern.includes(\"/\")) {\n const basename = posixPath.split(\"/\").pop() ?? posixPath;\n return rule.matcher(basename);\n }\n\n return false;\n }\n\n private async loadAggregateRules(directory: string): Promise<CompiledRule[]> {\n const normalizedDirectory = this.normalizeDirectory(directory);\n\n const cachedAggregate = this.aggregateCache.get(normalizedDirectory);\n if (cachedAggregate) {\n return cachedAggregate;\n }\n\n if (!this.isWithinRoot(normalizedDirectory)) {\n this.aggregateCache.set(normalizedDirectory, []);\n return [];\n }\n\n const parentDirectory = path.dirname(normalizedDirectory);\n const parentRules =\n normalizedDirectory === this.root ? [] : await this.loadAggregateRules(parentDirectory);\n const localRules = await this.loadRulesForDirectory(normalizedDirectory);\n\n const combined = parentRules.length > 0 ? [...parentRules, ...localRules] : localRules;\n\n this.aggregateCache.set(normalizedDirectory, combined);\n return combined;\n }\n\n private async loadRulesForDirectory(directory: string): Promise<CompiledRule[]> {\n const cachedRules = this.ruleCache.get(directory);\n if (cachedRules) {\n return cachedRules;\n }\n\n const rules: CompiledRule[] = [];\n const relativePrefix = toRelativePrefix(directory, this.root);\n\n for (const fileName of this.ignoreFileNames) {\n const filePath = path.join(directory, fileName);\n\n let content: string | undefined;\n try {\n content = await fs.readFile(filePath, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n continue;\n }\n throw error;\n }\n\n const fileRules = this.parseRules(content, relativePrefix);\n rules.push(...fileRules);\n }\n\n this.ruleCache.set(directory, rules);\n return rules;\n }\n\n private parseRules(content: string, relativePrefix: string): CompiledRule[] {\n const compiled: CompiledRule[] = [];\n\n for (const rawLine of content.split(/\\r?\\n/)) {\n const trimmed = rawLine.trim();\n\n if (!trimmed || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n let negate = false;\n let pattern = trimmed;\n\n if (pattern.startsWith(\"!\")) {\n negate = true;\n pattern = pattern.slice(1).trim();\n if (!pattern) continue;\n }\n\n let directory = false;\n if (pattern.endsWith(\"/\")) {\n directory = true;\n pattern = pattern.slice(0, -1);\n }\n\n const normalizedPatternFromFile = pattern.replace(/\\\\/g, \"/\");\n const resolvedPattern = resolvePattern(normalizedPatternFromFile, relativePrefix);\n\n const normalizedPattern = resolvedPattern.pattern;\n directory = directory || resolvedPattern.directory;\n const matcher = picomatch(normalizedPattern, {\n dot: true,\n matchBase: !normalizedPattern.includes(\"/\"),\n });\n\n compiled.push({\n raw: rawLine,\n negate,\n directory,\n pattern: normalizedPattern,\n matcher,\n });\n }\n\n return compiled;\n }\n\n private normalizeDirectory(directory: string): string {\n return path.resolve(directory);\n }\n\n private isWithinRoot(directory: string): boolean {\n return isSubPath(directory, this.root);\n }\n}\n\nfunction isSubPath(candidate: string, root: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction toRelativePrefix(directory: string, root: string): string {\n const relative = path.relative(root, directory);\n if (!relative || relative === \".\") {\n return \"\";\n }\n\n return toPosixPath(relative);\n}\n\nfunction resolvePattern(\n pattern: string,\n relativePrefix: string,\n): {\n pattern: string;\n directory: boolean;\n} {\n let directory = false;\n let normalized = pattern;\n\n if (pattern.startsWith(\"/\")) {\n normalized = pattern.slice(1);\n } else if (relativePrefix) {\n normalized = `${relativePrefix}/${pattern}`;\n }\n\n if (normalized.endsWith(\"/\")) {\n directory = true;\n normalized = normalized.slice(0, -1);\n }\n\n return {\n pattern: normalized.replace(/\\\\/g, \"/\"),\n directory,\n };\n}\n","import { Pathfinder } from \"./finder.js\";\nimport type { PathfinderConfig, PathfinderQuery, PathResult } from \"./types.js\";\n\nconst DEFAULT_CONFIG_EXTENSIONS = [\".yaml\", \".yml\", \".json\"];\nconst DEFAULT_SCHEMA_PATTERNS = [\"**/*.schema.json\", \"**/*.schema.yaml\"];\n\nfunction normalizeExtension(extension: string): string {\n return extension.startsWith(\".\") ? extension : `.${extension}`;\n}\n\nfunction buildIncludePatternsFromExtensions(extensions: string[]): string[] {\n return extensions.map((extension) => `**/*${normalizeExtension(extension)}`);\n}\n\nfunction createFinder(additionalConfig?: Partial<PathfinderConfig>): Pathfinder {\n return new Pathfinder(additionalConfig);\n}\n\nasync function executeFinder(finder: Pathfinder, query: PathfinderQuery): Promise<PathResult[]> {\n return finder.find(query);\n}\n\nexport async function findConfigFiles(\n root: string,\n extensions: string[] = DEFAULT_CONFIG_EXTENSIONS,\n additionalConfig?: Partial<PathfinderConfig>,\n): Promise<PathResult[]> {\n const include = buildIncludePatternsFromExtensions(extensions);\n const finder = createFinder(additionalConfig);\n\n return executeFinder(finder, {\n root,\n include,\n });\n}\n\nexport async function findSchemaFiles(\n root: string,\n additionalConfig?: Partial<PathfinderConfig>,\n): Promise<PathResult[]> {\n const finder = createFinder(additionalConfig);\n return executeFinder(finder, {\n root,\n include: DEFAULT_SCHEMA_PATTERNS,\n });\n}\n\nexport async function findByExtensions(\n root: string,\n extensions: string[],\n additionalConfig?: Partial<PathfinderConfig>,\n): Promise<PathResult[]> {\n if (extensions.length === 0) {\n return [];\n }\n\n const include = buildIncludePatternsFromExtensions(extensions);\n const finder = createFinder(additionalConfig);\n\n return executeFinder(finder, {\n root,\n include,\n });\n}\n","/**\n * Repository root discovery - Find repository markers in ancestor directories\n *\n * Implements Crucible v0.2.15 pathfinder extension for secure upward traversal.\n * Prevents data leakage with boundaries, max-depth, and path constraint enforcement.\n */\n\nimport { access, lstat, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { DEFAULT_MAX_DEPTH } from \"./constants.js\";\nimport { createPathfinderError, PathfinderErrorCode } from \"./errors.js\";\nimport type { FindRepoOptions } from \"./types.js\";\n\n/**\n * Find repository root by walking up directory tree\n *\n * Searches for marker files (e.g., .git, package.json) by traversing\n * upward from startPath, respecting boundaries and security constraints.\n *\n * **Security**: Enforces boundaries (home/explicit), max-depth, root/drive/UNC\n * ceilings, and optional path constraints. Default followSymlinks=false.\n *\n * @param startPath - Directory to start search from\n * @param markers - Array of marker files/directories to search for (e.g., [\".git\", \"package.json\"])\n * @param options - Optional configuration for boundaries, depth, and symlink handling\n * @returns Absolute path to repository root containing marker\n * @throws {FulmenError} REPOSITORY_NOT_FOUND if no marker found within constraints\n * @throws {FulmenError} INVALID_START_PATH if startPath doesn't exist or isn't accessible\n * @throws {FulmenError} INVALID_BOUNDARY if boundary is outside startPath ancestry\n * @throws {FulmenError} TRAVERSAL_LOOP if cyclic symlink detected (when followSymlinks=true)\n * @throws {FulmenError} SECURITY_VIOLATION if constraint prevents marker discovery\n *\n * @example\n * ```typescript\n * import { findRepositoryRoot, GitMarkers } from \"@fulmenhq/tsfulmen/pathfinder\";\n *\n * // Find Git repository root\n * const gitRoot = await findRepositoryRoot(process.cwd(), GitMarkers);\n *\n * // Find with custom boundary\n * const root = await findRepositoryRoot(\"./src/components\", [\".git\"], {\n * boundary: \"/home/user/projects\",\n * maxDepth: 5\n * });\n * ```\n */\nexport async function findRepositoryRoot(\n startPath: string,\n markers: string[] = [\".git\"],\n options?: FindRepoOptions,\n): Promise<string> {\n // Normalize and validate start path\n const normalizedStart = resolve(startPath);\n await validateStartPath(normalizedStart);\n\n // Apply defaults\n const maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;\n const stopAtFirst = options?.stopAtFirst ?? true;\n const followSymlinks = options?.followSymlinks ?? false;\n const constraint = options?.constraint;\n\n // Determine boundary: explicit or default (home), but only if start is under it\n let boundary: string;\n if (options?.boundary) {\n boundary = resolve(options.boundary);\n // Validate explicit boundary is ancestor of start\n validateBoundary(normalizedStart, boundary);\n } else {\n // Default boundary: use home if start is under it, otherwise filesystem root\n const home = getDefaultBoundary();\n boundary = normalizedStart.startsWith(home) ? home : \"/\";\n }\n\n // Validate constraint if provided\n if (constraint?.root) {\n const constraintRoot = resolve(constraint.root);\n if (!normalizedStart.startsWith(constraintRoot)) {\n throw createPathfinderError(\n PathfinderErrorCode.SECURITY_VIOLATION,\n `Start path ${normalizedStart} is outside constraint root ${constraintRoot}`,\n { severity: \"high\", context: { startPath: normalizedStart, constraint: constraintRoot } },\n );\n }\n }\n\n // Track visited paths for loop detection (when followSymlinks=true)\n const visitedRealPaths = new Set<string>();\n\n // Track all found markers (for stopAtFirst=false)\n let deepestMarkerPath: string | null = null;\n\n let currentDir = normalizedStart;\n let depth = 0;\n\n // Walk upward until we hit a boundary\n while (depth < maxDepth) {\n // Check for cyclic symlinks (if following symlinks)\n if (followSymlinks) {\n const realPath = await getRealPath(currentDir);\n if (visitedRealPaths.has(realPath)) {\n throw createPathfinderError(\n PathfinderErrorCode.TRAVERSAL_LOOP,\n `Cyclic symlink detected at ${currentDir}`,\n { severity: \"high\", context: { currentDir, realPath, depth } },\n );\n }\n visitedRealPaths.add(realPath);\n }\n\n // Check if we're outside constraint (if provided)\n if (constraint?.root) {\n const constraintRoot = resolve(constraint.root);\n if (!currentDir.startsWith(constraintRoot)) {\n // We've walked above the constraint - stop here\n break;\n }\n }\n\n // Check for markers in current directory\n for (const marker of markers) {\n if (await markerExists(currentDir, marker)) {\n if (stopAtFirst) {\n // Return immediately on first match\n return currentDir;\n }\n // Track deepest marker (closest to root)\n deepestMarkerPath = currentDir;\n }\n }\n\n // Check if we've reached the boundary\n if (currentDir === boundary || isFilesystemRoot(currentDir)) {\n break;\n }\n\n // Move up one directory\n const parentDir = dirname(currentDir);\n\n // Safety check: prevent infinite loop\n if (parentDir === currentDir) {\n // Reached filesystem root\n break;\n }\n\n currentDir = parentDir;\n depth++;\n }\n\n // If stopAtFirst=false and we found a marker, return deepest one\n if (!stopAtFirst && deepestMarkerPath) {\n return deepestMarkerPath;\n }\n\n // No marker found\n throw createPathfinderError(\n PathfinderErrorCode.REPOSITORY_NOT_FOUND,\n `No repository root found with markers [${markers.join(\", \")}] from ${startPath}`,\n {\n severity: \"medium\",\n context: {\n startPath: normalizedStart,\n markers,\n maxDepth,\n boundary,\n depthReached: depth,\n },\n },\n );\n}\n\n/**\n * Validate start path exists and is accessible\n *\n * @param startPath - Path to validate\n * @throws {FulmenError} INVALID_START_PATH if path doesn't exist or isn't accessible\n */\nasync function validateStartPath(startPath: string): Promise<void> {\n try {\n await access(startPath);\n const stats = await lstat(startPath);\n if (!stats.isDirectory()) {\n throw createPathfinderError(\n PathfinderErrorCode.INVALID_START_PATH,\n `Start path is not a directory: ${startPath}`,\n { severity: \"high\", context: { startPath } },\n );\n }\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n throw createPathfinderError(\n PathfinderErrorCode.INVALID_START_PATH,\n `Start path does not exist: ${startPath}`,\n { severity: \"high\", context: { startPath } },\n );\n }\n throw error;\n }\n}\n\n/**\n * Validate boundary is ancestor of start path\n *\n * @param startPath - Start path for search\n * @param boundary - Boundary ceiling\n * @throws {FulmenError} INVALID_BOUNDARY if boundary is not ancestor of startPath\n */\nfunction validateBoundary(startPath: string, boundary: string): void {\n const normalizedStart = resolve(startPath);\n const normalizedBoundary = resolve(boundary);\n\n if (!normalizedStart.startsWith(normalizedBoundary)) {\n throw createPathfinderError(\n PathfinderErrorCode.INVALID_BOUNDARY,\n `Boundary ${boundary} is not an ancestor of start path ${startPath}`,\n { severity: \"high\", context: { startPath, boundary } },\n );\n }\n}\n\n/**\n * Check if directory is filesystem root\n *\n * Detects POSIX root (/), Windows drive roots (C:\\), and UNC roots (\\\\server\\share).\n *\n * @param dir - Directory to check\n * @returns true if dir is filesystem root\n */\nfunction isFilesystemRoot(dir: string): boolean {\n const parentDir = dirname(dir);\n return parentDir === dir;\n}\n\n/**\n * Get default boundary (user home directory)\n *\n * @returns Absolute path to user home directory\n */\nfunction getDefaultBoundary(): string {\n return homedir();\n}\n\n/**\n * Check if marker exists in directory\n *\n * @param dir - Directory to check\n * @param marker - Marker file/directory name\n * @returns true if marker exists in dir\n */\nasync function markerExists(dir: string, marker: string): Promise<boolean> {\n try {\n await access(join(dir, marker));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get real path resolving symlinks\n *\n * @param path - Path to resolve\n * @returns Real path with symlinks resolved\n */\nasync function getRealPath(path: string): Promise<string> {\n try {\n return await realpath(path);\n } catch (_error) {\n // If realpath fails, return original path\n return path;\n }\n}\n","/**\n * Pathfinder validators - Schema validation using TSFulmen schema module\n *\n * Uses the existing schema module instead of creating standalone AJV instances.\n * This ensures:\n * - Telemetry automatically emitted (schema_validations, schema_validation_errors)\n * - Schemas auto-discovered from Crucible SSOT\n * - Consistent error handling with other modules\n * - Validator caching handled automatically\n */\n\nimport { compileSchemaById, validateDataBySchemaId } from \"../schema/index.js\";\nimport type { CompiledValidator, SchemaValidationResult } from \"../schema/types.js\";\nimport { createPathfinderError, PathfinderErrorCode } from \"./errors.js\";\n\n/**\n * Compile pathfinder config schema for validation\n *\n * Uses TSFulmen's schema registry to load from Crucible SSOT.\n * Schemas are cached automatically by the schema module.\n *\n * @returns Compiled validator for pathfinder configuration\n *\n * @example\n * ```typescript\n * const validator = await compileConfigSchema();\n * const result = validateData(config, validator);\n * ```\n */\nexport async function compileConfigSchema(): Promise<CompiledValidator> {\n return compileSchemaById(\"pathfinder/v1.0.0/finder-config\");\n}\n\n/**\n * Compile path result schema for validation\n *\n * @returns Compiled validator for path results\n */\nexport async function compilePathResultSchema(): Promise<CompiledValidator> {\n return compileSchemaById(\"pathfinder/v1.0.0/path-result\");\n}\n\n/**\n * Validate pathfinder configuration against Crucible schema\n *\n * Uses schema module which automatically emits telemetry:\n * - `schema_validations` counter on success\n * - `schema_validation_errors` counter on failure\n *\n * @param config - Configuration to validate\n * @returns Validation result with diagnostics\n *\n * @example\n * ```typescript\n * const result = await validateConfig({ root: '/tmp' });\n * if (!result.valid) {\n * console.error('Invalid config:', result.diagnostics);\n * }\n * ```\n */\nexport async function validateConfig(config: unknown): Promise<SchemaValidationResult> {\n return validateDataBySchemaId(config, \"pathfinder/v1.0.0/finder-config\");\n}\n\n/**\n * Validate path result against Crucible schema\n *\n * @param result - Path result to validate\n * @returns Validation result with diagnostics\n *\n * @example\n * ```typescript\n * const result = await validatePathResult({\n * relativePath: 'src/index.ts',\n * sourcePath: '/tmp/src/index.ts',\n * loaderType: 'local',\n * metadata: { size: 1234, modified: '2025-11-01T12:00:00Z' }\n * });\n * ```\n */\nexport async function validatePathResult(result: unknown): Promise<SchemaValidationResult> {\n return validateDataBySchemaId(result, \"pathfinder/v1.0.0/path-result\");\n}\n\n/**\n * Validate config and throw on failure\n *\n * Convenience wrapper that throws FulmenError on validation failure.\n *\n * @param config - Configuration to validate\n * @throws {FulmenError} With pathfinder.validation_failed code\n *\n * @example\n * ```typescript\n * try {\n * await assertValidConfig(config);\n * // Config is valid, proceed\n * } catch (error) {\n * // Handle validation error\n * }\n * ```\n */\nexport async function assertValidConfig(config: unknown): Promise<void> {\n const result = await validateConfig(config);\n\n if (!result.valid) {\n const messages = result.diagnostics.map((d) => d.message).join(\", \");\n throw createPathfinderError(\n PathfinderErrorCode.VALIDATION_FAILED,\n `Invalid pathfinder configuration: ${messages}`,\n {\n severity: \"high\",\n context: { diagnostics: result.diagnostics },\n },\n );\n }\n}\n\n/**\n * Validate path result and throw on failure\n *\n * @param result - Path result to validate\n * @throws {FulmenError} With pathfinder.validation_failed code\n *\n * @example\n * ```typescript\n * await assertValidPathResult(result);\n * ```\n */\nexport async function assertValidPathResult(result: unknown): Promise<void> {\n const validationResult = await validatePathResult(result);\n\n if (!validationResult.valid) {\n const messages = validationResult.diagnostics.map((d) => d.message).join(\", \");\n throw createPathfinderError(\n PathfinderErrorCode.VALIDATION_FAILED,\n `Invalid path result: ${messages}`,\n {\n severity: \"high\",\n context: { diagnostics: validationResult.diagnostics },\n },\n );\n }\n}\n","/**\n * Pathfinder - Enterprise filesystem traversal with checksums and observability\n *\n * Provides filesystem discovery with pattern matching, ignore files, optional checksums,\n * and comprehensive observability through structured errors and telemetry.\n *\n * @example Basic usage\n * ```typescript\n * import { Pathfinder } from '@fulmenhq/tsfulmen/pathfinder';\n *\n * const finder = new Pathfinder();\n *\n * const results = await finder.find({\n * root: './src',\n * include: ['*.ts'],\n * followSymlinks: false,\n * });\n * ```\n *\n * @example Convenience helpers\n * ```typescript\n * import { findConfigFiles, findSchemaFiles } from '@fulmenhq/tsfulmen/pathfinder';\n *\n * const configs = await findConfigFiles('./config');\n * const schemas = await findSchemaFiles('./schemas');\n * ```\n *\n * @module pathfinder\n */\n\nexport const VERSION = \"0.1.0\";\n\n// Checksum helpers\nexport { calculateChecksum, calculateChecksumsBatch } from \"./checksum.js\";\n// Constants\nexport {\n DEFAULT_CONFIG,\n DEFAULT_IGNORE_FILES,\n DEFAULT_MAX_DEPTH,\n GitMarkers,\n GoModMarkers,\n MAX_PATH_LENGTH,\n MonorepoMarkers,\n NodeMarkers,\n PATH_SEPARATOR,\n PythonMarkers,\n} from \"./constants.js\";\n// Convenience helpers\nexport { findByExtensions, findConfigFiles, findSchemaFiles } from \"./convenience.js\";\n// Error types\nexport {\n createPathfinderError,\n PathfinderErrorCode,\n wrapPathfinderError,\n} from \"./errors.js\";\nexport type { PathfinderOptions } from \"./finder.js\";\n// Core exports\nexport { Pathfinder } from \"./finder.js\";\n// Repository root discovery\nexport { findRepositoryRoot } from \"./repoRoot.js\";\n// Types\nexport type {\n ErrorCallback,\n FileMetadata,\n FindRepoOptions,\n PathfinderConfig,\n PathfinderExecuteOptions,\n PathfinderQuery,\n PathResult,\n ProgressCallback,\n ResultCallback,\n} from \"./types.js\";\nexport {\n ChecksumAlgorithm,\n ChecksumEncoding,\n ConstraintType,\n EnforcementLevel,\n LoaderType,\n withBoundary,\n withConstraint,\n withFollowSymlinks,\n withMaxDepth,\n withStopAtFirst,\n} from \"./types.js\";\n// Validators\nexport {\n assertValidConfig,\n assertValidPathResult,\n compileConfigSchema,\n compilePathResultSchema,\n validateConfig,\n validatePathResult,\n} from \"./validators.js\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/pathfinder/types.ts","../../src/pathfinder/checksum.ts","../../src/pathfinder/constants.ts","../../src/pathfinder/errors.ts","../../src/pathfinder/safety.ts","../../src/pathfinder/ignore.ts","../../src/pathfinder/finder.ts","../../src/pathfinder/convenience.ts","../../src/pathfinder/repoRoot.ts","../../src/pathfinder/validators.ts","../../src/pathfinder/index.ts"],"names":["EnforcementLevel","ConstraintType","LoaderType","ChecksumAlgorithm","ChecksumEncoding","path","PathfinderErrorCode","fs","lstat"],"mappings":";;;;;;;;;;;;;;;AAcO,IAAK,gBAAA,qBAAAA,iBAAAA,KAAL;AAEL,EAAAA,kBAAA,QAAA,CAAA,GAAS,QAAA;AAGT,EAAAA,kBAAA,MAAA,CAAA,GAAO,MAAA;AAGP,EAAAA,kBAAA,YAAA,CAAA,GAAa,YAAA;AARH,EAAA,OAAAA,iBAAAA;AAAA,CAAA,EAAA,gBAAA,IAAA,EAAA;AAcL,IAAK,cAAA,qBAAAC,eAAAA,KAAL;AACL,EAAAA,gBAAA,YAAA,CAAA,GAAa,YAAA;AACb,EAAAA,gBAAA,WAAA,CAAA,GAAY,WAAA;AACZ,EAAAA,gBAAA,OAAA,CAAA,GAAQ,OAAA;AAHE,EAAA,OAAAA,eAAAA;AAAA,CAAA,EAAA,cAAA,IAAA,EAAA;AASL,IAAK,UAAA,qBAAAC,WAAAA,KAAL;AACL,EAAAA,YAAA,OAAA,CAAA,GAAQ,OAAA;AACR,EAAAA,YAAA,QAAA,CAAA,GAAS,QAAA;AACT,EAAAA,YAAA,OAAA,CAAA,GAAQ,OAAA;AAHE,EAAA,OAAAA,WAAAA;AAAA,CAAA,EAAA,UAAA,IAAA,EAAA;AASL,IAAK,iBAAA,qBAAAC,kBAAAA,KAAL;AACL,EAAAA,mBAAA,UAAA,CAAA,GAAW,UAAA;AACX,EAAAA,mBAAA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IAAA,MAAM,qBAAA;AAAA,MAAA,8BAAA;AAAA,MAEJ,wBAAwB,QAAQ,CAAA,CAAA;AAAA,MAChC;AAAA,QACE,QAAA,EAAU,MAAA;AAAA,QACV,OAAA,EAAS,EAAE,WAAA,EAAa,gBAAA,CAAiB,WAAA;AAAY;AACvD,KACF;AAAA,EACF;AACF;;;ACjHO,IAAM,OAAA,GAAU","file":"index.js","sourcesContent":["/**\n * Pathfinder types - Core type definitions for filesystem traversal\n *\n * Implements types aligned with Crucible schemas:\n * - schemas/crucible-ts/pathfinder/v1.0.0/finder-config.schema.json\n * - schemas/crucible-ts/pathfinder/v1.0.0/path-result.schema.json\n * - schemas/crucible-ts/pathfinder/v1.0.0/metadata.schema.json\n */\n\n/**\n * Enforcement levels for path constraints\n *\n * Controls how path constraint violations are handled during traversal.\n */\nexport enum EnforcementLevel {\n /** Reject constraint violations */\n STRICT = \"strict\",\n\n /** Log violations but continue */\n WARN = \"warn\",\n\n /** Disable constraint enforcement */\n PERMISSIVE = \"permissive\",\n}\n\n/**\n * Supported constraint types (repository/workspace/cloud)\n */\nexport enum ConstraintType {\n REPOSITORY = \"repository\",\n WORKSPACE = \"workspace\",\n CLOUD = \"cloud\",\n}\n\n/**\n * Supported loader implementations for discovery operations\n */\nexport enum LoaderType {\n LOCAL = \"local\",\n REMOTE = \"remote\",\n CLOUD = \"cloud\",\n}\n\n/**\n * Supported checksum algorithms for FulHash integration\n */\nexport enum ChecksumAlgorithm {\n XXH3_128 = \"xxh3-128\",\n SHA256 = \"sha256\",\n}\n\n/**\n * Supported checksum encodings for serialized results\n */\nexport enum ChecksumEncoding {\n HEX = \"hex\",\n}\n\n/**\n * Path constraint specification (mirrors Crucible schema)\n *\n * Encapsulates repository/workspace boundaries and enforcement behaviour.\n */\nexport interface PathConstraint {\n /** Root path for the constraint scope */\n root?: string;\n\n /** Constraint classification (repository/workspace/cloud) */\n type: ConstraintType;\n\n /** Enforcement behaviour for path violations */\n enforcementLevel: EnforcementLevel;\n}\n\n/**\n * Pathfinder configuration options (Crucible-aligned)\n *\n * Aligns with schemas/crucible-ts/pathfinder/v1.0.0/finder-config.schema.json.\n */\nexport interface PathfinderConfig {\n /** Maximum number of worker routines for traversal */\n maxWorkers?: number;\n\n /** Enable filesystem metadata/result caching */\n cacheEnabled?: boolean;\n\n /** Cache time-to-live (seconds) */\n cacheTTL?: number;\n\n /** Path constraint applied to traversal */\n constraint?: PathConstraint;\n\n /** Default loader used to resolve paths */\n loaderType?: LoaderType;\n\n /** Calculate file checksums */\n calculateChecksums?: boolean;\n\n /** Hash algorithm used for checksum calculation */\n checksumAlgorithm?: ChecksumAlgorithm;\n\n /** Encoding format for serialized checksums */\n checksumEncoding?: ChecksumEncoding;\n\n /** Honor .fulmenignore files during traversal */\n honorIgnoreFiles?: boolean;\n}\n\n/**\n * Pathfinder discovery query (Crucible-aligned)\n *\n * Matches schemas/crucible-ts/pathfinder/v1.0.0/find-query.schema.json.\n */\nexport interface PathfinderQuery {\n /** Root directory for traversal (required) */\n root: string;\n\n /** Glob include patterns (defaults to matching all files) */\n include?: string[];\n\n /** Glob exclude patterns */\n exclude?: string[];\n\n /** Maximum traversal depth (0 = unlimited) */\n maxDepth?: number;\n\n /** Follow symbolic links during traversal */\n followSymlinks?: boolean;\n\n /** Include hidden files and directories (dot-prefixed) */\n includeHidden?: boolean;\n\n /** Honor .fulmenignore files during traversal */\n honorIgnoreFiles?: boolean;\n}\n\n/**\n * File metadata returned by pathfinder\n *\n * Includes size, modification time, and optional checksum information.\n */\nexport interface FileMetadata {\n /** File size in bytes */\n size?: number;\n\n /** Last modification timestamp (ISO 8601) */\n modified?: string;\n\n /** File permissions (e.g., rwxr-xr-x or 0755) */\n permissions?: string;\n\n /** MIME type of the file */\n mimeType?: string;\n\n /** Character encoding if applicable */\n encoding?: string;\n\n /** FulHash output formatted as algorithm:hex */\n checksum?: string;\n\n /** Algorithm used for the checksum */\n checksumAlgorithm?: ChecksumAlgorithm;\n\n /** Error message when checksum calculation fails */\n checksumError?: string;\n\n /** User-defined tags associated with the result */\n tags?: string[];\n\n /** Custom metadata bag for provider-specific data */\n custom?: Record<string, unknown>;\n\n /** Whether result represents a symbolic link */\n isSymlink?: boolean;\n\n /** Target path for symbolic links */\n symlinkTarget?: string;\n\n /** Allow additional provider-specific properties */\n [key: string]: unknown;\n}\n\n/**\n * Path result returned by finder operations\n *\n * Represents a single discovered file with its metadata.\n */\nexport interface PathResult {\n /** Path relative to traversal root */\n relativePath: string;\n\n /** Absolute path to the discovered file */\n sourcePath: string;\n\n /** Logical path presented to downstream consumers */\n logicalPath?: string;\n\n /** Loader type that produced the result */\n loaderType: LoaderType;\n\n /** Provider metadata attached to the result */\n metadata?: FileMetadata;\n}\n\n/**\n * Progress callback for long-running operations\n *\n * Called for each discovered file during traversal.\n * Can be async to allow for processing or throttling.\n */\nexport type ProgressCallback = (result: PathResult) => void | Promise<void>;\n\n/**\n * Error handler callback\n *\n * Called when non-fatal errors occur during traversal.\n * Allows custom error handling without stopping the entire operation.\n */\nexport type ErrorCallback = (error: Error, path: string) => void | Promise<void>;\n\n/**\n * Result handler callback (fires for each result)\n *\n * Alternative to collecting all results in memory.\n * Process results as they're discovered.\n */\nexport type ResultCallback = (result: PathResult) => void | Promise<void>;\n\n/**\n * Execution callbacks for finder operations\n *\n * Allows callers to subscribe to progress, per-result, and recoverable errors.\n */\nexport interface PathfinderExecuteOptions {\n /** Invoked for each discovered result */\n resultCallback?: ResultCallback;\n\n /** Invoked for each discovered result (alias for resultCallback) */\n progressCallback?: ProgressCallback;\n\n /** Invoked when recoverable errors occur during traversal */\n errorCallback?: ErrorCallback;\n}\n\n/**\n * Options for repository root discovery\n *\n * Controls behavior of findRepositoryRoot() operation including\n * boundaries, max depth, symlink handling, and path constraints.\n *\n * Aligned with Crucible v0.2.15 pathfinder extension spec.\n */\nexport interface FindRepoOptions {\n /**\n * Maximum depth to search upward\n *\n * Defaults to 10. Prevents excessive traversal up the directory tree.\n */\n maxDepth?: number;\n\n /**\n * Boundary ceiling for upward search\n *\n * Stops traversal when reaching this directory.\n * Defaults to user home directory if not specified.\n * Always stops at filesystem root/drive/UNC regardless.\n */\n boundary?: string;\n\n /**\n * Stop at first marker match\n *\n * If true, returns immediately upon finding any marker.\n * If false, continues to find deepest marker (closest to filesystem root).\n * Defaults to true.\n */\n stopAtFirst?: boolean;\n\n /**\n * Path constraint for upper boundary enforcement\n *\n * If provided, prevents discovery outside this constraint.\n * Returns REPOSITORY_NOT_FOUND if constraint prevents marker hit.\n */\n constraint?: PathConstraint;\n\n /**\n * Follow symbolic links during traversal\n *\n * Defaults to false (security). If enabled, tracks visited\n * real paths to detect loops.\n */\n followSymlinks?: boolean;\n}\n\n/**\n * Helper to create FindRepoOptions with maxDepth\n *\n * @param maxDepth - Maximum depth to search upward\n * @returns FindRepoOptions with maxDepth set\n */\nexport function withMaxDepth(maxDepth: number): FindRepoOptions {\n return { maxDepth };\n}\n\n/**\n * Helper to create FindRepoOptions with boundary\n *\n * @param boundary - Boundary ceiling directory\n * @returns FindRepoOptions with boundary set\n */\nexport function withBoundary(boundary: string): FindRepoOptions {\n return { boundary };\n}\n\n/**\n * Helper to create FindRepoOptions with stopAtFirst\n *\n * @param stopAtFirst - Whether to stop at first marker\n * @returns FindRepoOptions with stopAtFirst set\n */\nexport function withStopAtFirst(stopAtFirst: boolean): FindRepoOptions {\n return { stopAtFirst };\n}\n\n/**\n * Helper to create FindRepoOptions with constraint\n *\n * @param constraint - Path constraint for upper boundary\n * @returns FindRepoOptions with constraint set\n */\nexport function withConstraint(constraint: PathConstraint): FindRepoOptions {\n return { constraint };\n}\n\n/**\n * Helper to create FindRepoOptions with followSymlinks\n *\n * @param followSymlinks - Whether to follow symbolic links\n * @returns FindRepoOptions with followSymlinks set\n */\nexport function withFollowSymlinks(followSymlinks: boolean): FindRepoOptions {\n return { followSymlinks };\n}\n","import { createReadStream } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Algorithm, createStreamHasher } from \"../fulhash/index.js\";\nimport { ChecksumAlgorithm, type FileMetadata } from \"./types.js\";\n\n/**\n * Result fragment returned when calculating a checksum.\n */\nexport type ChecksumMetadata = Pick<\n FileMetadata,\n \"checksum\" | \"checksumAlgorithm\" | \"checksumError\"\n>;\n\nfunction toFulHashAlgorithm(algorithm: ChecksumAlgorithm): Algorithm {\n switch (algorithm) {\n case ChecksumAlgorithm.SHA256:\n return Algorithm.SHA256;\n default:\n return Algorithm.XXH3_128;\n }\n}\n\n/**\n * Calculate the checksum for a single file using FulHash streaming hasher.\n *\n * Returns checksum metadata compatible with Pathfinder metadata schema.\n */\nexport async function calculateChecksum(\n filePath: string,\n algorithm: ChecksumAlgorithm,\n): Promise<ChecksumMetadata> {\n const absolutePath = path.resolve(filePath);\n\n try {\n const hasher = await createStreamHasher({ algorithm: toFulHashAlgorithm(algorithm) });\n const stream = createReadStream(absolutePath);\n\n try {\n for await (const chunk of stream) {\n hasher.update(chunk as Uint8Array);\n }\n } catch (error) {\n stream.destroy();\n throw error;\n }\n\n const digest = hasher.digest();\n\n return {\n checksum: `${algorithm}:${digest.hex}`,\n checksumAlgorithm: algorithm,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n checksumAlgorithm: algorithm,\n checksumError: message,\n };\n }\n}\n\n/**\n * Calculate checksums for a list of files with a simple concurrency limiter.\n */\nexport async function calculateChecksumsBatch(\n filePaths: string[],\n algorithm: ChecksumAlgorithm,\n concurrency: number = 1,\n): Promise<Map<string, ChecksumMetadata>> {\n const safeConcurrency = Math.max(1, Math.floor(concurrency));\n const results = new Map<string, ChecksumMetadata>();\n\n if (filePaths.length === 0) {\n return results;\n }\n\n let index = 0;\n\n const worker = async (): Promise<void> => {\n while (index < filePaths.length) {\n const currentIndex = index++;\n const filePath = filePaths[currentIndex];\n const metadata = await calculateChecksum(filePath, algorithm);\n results.set(filePath, metadata);\n }\n };\n\n const workers = Array.from({ length: Math.min(safeConcurrency, filePaths.length) }, () =>\n worker(),\n );\n await Promise.all(workers);\n\n return results;\n}\n","/**\n * Pathfinder constants - Default configuration and standard values\n */\n\nimport type { PathfinderConfig } from \"./types.js\";\nimport { ChecksumAlgorithm, ChecksumEncoding, LoaderType } from \"./types.js\";\n\n/**\n * Default Pathfinder configuration\n *\n * Provides schema-aligned defaults for optional configuration parameters.\n * Callers should override constraint.root and other deployment-specific values.\n */\nexport const DEFAULT_CONFIG: Partial<PathfinderConfig> = {\n maxWorkers: 4,\n cacheEnabled: false,\n cacheTTL: 300,\n loaderType: LoaderType.LOCAL,\n calculateChecksums: false,\n checksumAlgorithm: ChecksumAlgorithm.XXH3_128,\n checksumEncoding: ChecksumEncoding.HEX,\n honorIgnoreFiles: true,\n};\n\n/**\n * Default ignore file names (checked in order)\n *\n * Pathfinder will look for these files in each directory during traversal.\n * First match wins. .fulmenignore takes precedence over .gitignore.\n */\nexport const DEFAULT_IGNORE_FILES = [\".fulmenignore\", \".gitignore\"];\n\n/**\n * Platform-specific path separator\n *\n * Used for normalizing paths across Windows and Unix-like systems.\n */\nexport const PATH_SEPARATOR = process.platform === \"win32\" ? \"\\\\\" : \"/\";\n\n/**\n * Maximum reasonable path length\n *\n * Used for validation to prevent excessively long paths.\n * Windows MAX_PATH is 260, Unix typically 4096. Use conservative limit.\n */\nexport const MAX_PATH_LENGTH = 4096;\n\n/**\n * Default buffer size for file operations (bytes)\n *\n * Used when reading files for checksum calculation.\n */\nexport const DEFAULT_BUFFER_SIZE = 65536; // 64KB\n\n/**\n * Default maximum depth for repository root search\n *\n * Prevents excessive traversal up the directory tree.\n * Can be overridden via FindRepoOptions.\n */\nexport const DEFAULT_MAX_DEPTH = 10;\n\n/**\n * Git repository markers\n *\n * Identifies Git repositories by presence of .git directory.\n */\nexport const GitMarkers = [\".git\"];\n\n/**\n * Node.js/npm project markers (ordered by specificity)\n *\n * Identifies Node.js projects by package.json or package-lock.json.\n * Order: most specific first.\n */\nexport const NodeMarkers = [\"package.json\", \"package-lock.json\"];\n\n/**\n * Go module markers\n *\n * Identifies Go modules by go.mod file.\n */\nexport const GoModMarkers = [\"go.mod\"];\n\n/**\n * Python project markers (ordered by specificity)\n *\n * Identifies Python projects by various project files.\n * Order: most specific first.\n */\nexport const PythonMarkers = [\"pyproject.toml\", \"setup.py\", \"requirements.txt\", \"Pipfile\"];\n\n/**\n * Monorepo markers (common tools)\n *\n * Identifies monorepo roots by presence of workspace configuration files.\n * Order: most specific first.\n */\nexport const MonorepoMarkers = [\n \"lerna.json\",\n \"pnpm-workspace.yaml\",\n \"nx.json\",\n \"turbo.json\",\n \"rush.json\",\n];\n","/**\n * Pathfinder errors - Domain-specific error helpers\n *\n * Provides pathfinder-specific error codes and factory functions\n * that wrap FulmenError with appropriate metadata.\n */\n\nimport type { FulmenErrorOptions } from \"../errors/index.js\";\nimport { FulmenError } from \"../errors/index.js\";\n\n/**\n * Pathfinder error codes\n *\n * All codes prefixed with 'pathfinder.' for domain identification.\n */\nexport enum PathfinderErrorCode {\n /** Configuration validation failed */\n INVALID_CONFIG = \"pathfinder.invalid_config\",\n\n /** Root directory invalid or inaccessible */\n INVALID_ROOT = \"pathfinder.invalid_root\",\n\n /** Filesystem traversal operation failed */\n TRAVERSAL_FAILED = \"pathfinder.traversal_failed\",\n\n /** Path constraint violation detected */\n CONSTRAINT_VIOLATION = \"pathfinder.constraint_violation\",\n\n /** Checksum calculation failed */\n CHECKSUM_FAILED = \"pathfinder.checksum_failed\",\n\n /** Schema validation failed */\n VALIDATION_FAILED = \"pathfinder.validation_failed\",\n\n /** Ignore file parsing failed */\n IGNORE_FILE_ERROR = \"pathfinder.ignore_file_error\",\n\n /** Repository root not found */\n REPOSITORY_NOT_FOUND = \"pathfinder.repository_not_found\",\n\n /** Invalid start path for repository search */\n INVALID_START_PATH = \"pathfinder.invalid_start_path\",\n\n /** Invalid boundary specified */\n INVALID_BOUNDARY = \"pathfinder.invalid_boundary\",\n\n /** Traversal loop detected (cyclic symlinks) */\n TRAVERSAL_LOOP = \"pathfinder.traversal_loop\",\n\n /** Security violation detected during traversal */\n SECURITY_VIOLATION = \"pathfinder.security_violation\",\n}\n\n/**\n * Create a pathfinder-specific FulmenError\n *\n * Factory function that creates properly structured errors with\n * pathfinder domain, filesystem category, and appropriate severity.\n *\n * @param code - Pathfinder error code\n * @param message - Human-readable error message\n * @param options - Additional error options (severity, context, etc.)\n * @returns FulmenError instance with pathfinder metadata\n *\n * @example\n * ```typescript\n * throw createPathfinderError(\n * PathfinderErrorCode.INVALID_ROOT,\n * 'Root directory does not exist',\n * { severity: 'high', context: { root: '/nonexistent' } }\n * );\n * ```\n */\nexport function createPathfinderError(\n code: PathfinderErrorCode,\n message: string,\n options?: Partial<FulmenErrorOptions>,\n): FulmenError {\n return new FulmenError({\n code,\n message,\n severity: options?.severity ?? \"medium\",\n context: {\n domain: \"pathfinder\",\n category: \"filesystem\",\n ...options?.context,\n },\n ...options,\n });\n}\n\n/**\n * Wrap an existing error as a PathfinderError\n *\n * Preserves the original error as the cause while adding\n * pathfinder-specific metadata.\n *\n * @param error - Original error to wrap\n * @param code - Pathfinder error code\n * @param context - Additional context information\n * @returns FulmenError wrapping the original error\n *\n * @example\n * ```typescript\n * try {\n * await fs.readdir(dir);\n * } catch (err) {\n * throw wrapPathfinderError(\n * err,\n * PathfinderErrorCode.TRAVERSAL_FAILED,\n * { directory: dir }\n * );\n * }\n * ```\n */\nexport function wrapPathfinderError(\n error: Error,\n code: PathfinderErrorCode,\n context?: Record<string, unknown>,\n): FulmenError {\n return FulmenError.wrap(error, {\n code,\n severity: \"medium\",\n context: {\n domain: \"pathfinder\",\n category: \"filesystem\",\n ...context,\n },\n });\n}\n","/**\n * Path safety and constraint enforcement utilities\n */\n\nimport path from \"node:path\";\n\nimport { createPathfinderError, PathfinderErrorCode } from \"./errors.js\";\nimport type { PathConstraint } from \"./types.js\";\n\n/**\n * Result of evaluating a path against configured constraints.\n */\nexport interface ConstraintEvaluation {\n /** Whether the path satisfied all constraints */\n allowed: boolean;\n /** Optional reason describing the violation */\n reason?: string;\n}\n\n/**\n * Normalize a path for comparison by resolving against root.\n */\nfunction normalizeAbsolute(p: string): string {\n return path.resolve(p);\n}\n\n/**\n * Convert filesystem-relative paths to POSIX form for glob evaluation.\n */\nexport function toPosixPath(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/**\n * Determine if candidate path is contained within the provided root directory.\n *\n * @param candidate - Absolute path to check\n * @param root - Root directory that bounds traversal\n */\nexport function isPathWithinRoot(candidate: string, root: string): boolean {\n const normalizedCandidate = normalizeAbsolute(candidate);\n const normalizedRoot = normalizeAbsolute(root);\n const relative = path.relative(normalizedRoot, normalizedCandidate);\n\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\n/**\n * Evaluate a path against a configured constraint definition.\n *\n * Does not throw directly; callers should inspect {@link ConstraintEvaluation.allowed}\n * and escalate according to enforcement level.\n *\n * @param absolutePath - Absolute path being evaluated\n * @param relativePath - Path relative to discovery root (POSIX or platform-specific)\n * @param constraint - Constraint configuration (may be undefined)\n */\nexport function enforcePathConstraints(\n absolutePath: string,\n _relativePath: string,\n constraint?: PathConstraint,\n): ConstraintEvaluation {\n if (!constraint) {\n return { allowed: true };\n }\n\n const constraintRoot = constraint.root ? normalizeAbsolute(constraint.root) : undefined;\n\n if (!constraintRoot) {\n return { allowed: true };\n }\n\n const normalizedConstraintRoot = constraintRoot;\n const normalizedAbsolutePath = normalizeAbsolute(absolutePath);\n\n if (!isPathWithinRoot(normalizedAbsolutePath, normalizedConstraintRoot)) {\n return {\n allowed: false,\n reason: `Path ${normalizedAbsolutePath} escapes constraint root ${normalizedConstraintRoot}`,\n };\n }\n\n return { allowed: true };\n}\n\n/**\n * Create a constraint violation error for STRICT enforcement modes.\n *\n * @param reason - Human-readable violation reason\n * @param context - Additional error context\n */\nexport function createConstraintViolationError(\n reason: string,\n context?: Record<string, unknown>,\n): Error {\n return createPathfinderError(PathfinderErrorCode.CONSTRAINT_VIOLATION, reason, {\n severity: \"critical\",\n context,\n });\n}\n","import { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nimport picomatch from \"picomatch\";\n\nimport { DEFAULT_IGNORE_FILES } from \"./constants.js\";\nimport { toPosixPath } from \"./safety.js\";\n\ninterface CompiledRule {\n raw: string;\n negate: boolean;\n directory: boolean;\n pattern: string;\n matcher: picomatch.Matcher;\n}\n\n/**\n * `.fulmenignore` support with directory-level caching.\n *\n * Inspired by gitignore semantics: the last matching rule wins and patterns\n * prefixed with `!` re-include paths. Patterns ending with a slash apply to a\n * directory and all descendants.\n */\nexport class IgnoreMatcher {\n private readonly root: string;\n private readonly ignoreFileNames: string[];\n private readonly ruleCache = new Map<string, CompiledRule[]>();\n private readonly aggregateCache = new Map<string, CompiledRule[]>();\n\n constructor(root: string, ignoreFileNames: string[] = DEFAULT_IGNORE_FILES) {\n this.root = path.resolve(root);\n this.ignoreFileNames = ignoreFileNames;\n }\n\n /**\n * Determine whether the relative path should be ignored.\n *\n * @param absolutePath - Absolute filesystem path\n * @param relativePath - Path relative to the finder root (POSIX)\n */\n async shouldIgnore(absolutePath: string, relativePath: string): Promise<boolean> {\n const directory = path.dirname(path.resolve(absolutePath));\n const rules = await this.loadAggregateRules(directory);\n\n if (rules.length === 0) {\n return false;\n }\n\n const posixPath = toPosixPath(relativePath);\n let ignored = false;\n\n for (const rule of rules) {\n if (!this.matchesRule(rule, posixPath)) {\n continue;\n }\n\n ignored = !rule.negate;\n }\n\n return ignored;\n }\n\n private matchesRule(rule: CompiledRule, posixPath: string): boolean {\n if (rule.directory) {\n return posixPath === rule.pattern || posixPath.startsWith(`${rule.pattern}/`);\n }\n\n if (rule.matcher(posixPath)) {\n return true;\n }\n\n if (!rule.pattern.includes(\"/\")) {\n const basename = posixPath.split(\"/\").pop() ?? posixPath;\n return rule.matcher(basename);\n }\n\n return false;\n }\n\n private async loadAggregateRules(directory: string): Promise<CompiledRule[]> {\n const normalizedDirectory = this.normalizeDirectory(directory);\n\n const cachedAggregate = this.aggregateCache.get(normalizedDirectory);\n if (cachedAggregate) {\n return cachedAggregate;\n }\n\n if (!this.isWithinRoot(normalizedDirectory)) {\n this.aggregateCache.set(normalizedDirectory, []);\n return [];\n }\n\n const parentDirectory = path.dirname(normalizedDirectory);\n const parentRules =\n normalizedDirectory === this.root ? [] : await this.loadAggregateRules(parentDirectory);\n const localRules = await this.loadRulesForDirectory(normalizedDirectory);\n\n const combined = parentRules.length > 0 ? [...parentRules, ...localRules] : localRules;\n\n this.aggregateCache.set(normalizedDirectory, combined);\n return combined;\n }\n\n private async loadRulesForDirectory(directory: string): Promise<CompiledRule[]> {\n const cachedRules = this.ruleCache.get(directory);\n if (cachedRules) {\n return cachedRules;\n }\n\n const rules: CompiledRule[] = [];\n const relativePrefix = toRelativePrefix(directory, this.root);\n\n for (const fileName of this.ignoreFileNames) {\n const filePath = path.join(directory, fileName);\n\n let content: string | undefined;\n try {\n content = await fs.readFile(filePath, \"utf-8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n continue;\n }\n throw error;\n }\n\n const fileRules = this.parseRules(content, relativePrefix);\n rules.push(...fileRules);\n }\n\n this.ruleCache.set(directory, rules);\n return rules;\n }\n\n private parseRules(content: string, relativePrefix: string): CompiledRule[] {\n const compiled: CompiledRule[] = [];\n\n for (const rawLine of content.split(/\\r?\\n/)) {\n const trimmed = rawLine.trim();\n\n if (!trimmed || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n let negate = false;\n let pattern = trimmed;\n\n if (pattern.startsWith(\"!\")) {\n negate = true;\n pattern = pattern.slice(1).trim();\n if (!pattern) continue;\n }\n\n let directory = false;\n if (pattern.endsWith(\"/\")) {\n directory = true;\n pattern = pattern.slice(0, -1);\n }\n\n const normalizedPatternFromFile = pattern.replace(/\\\\/g, \"/\");\n const resolvedPattern = resolvePattern(normalizedPatternFromFile, relativePrefix);\n\n const normalizedPattern = resolvedPattern.pattern;\n directory = directory || resolvedPattern.directory;\n const matcher = picomatch(normalizedPattern, {\n dot: true,\n matchBase: !normalizedPattern.includes(\"/\"),\n });\n\n compiled.push({\n raw: rawLine,\n negate,\n directory,\n pattern: normalizedPattern,\n matcher,\n });\n }\n\n return compiled;\n }\n\n private normalizeDirectory(directory: string): string {\n return path.resolve(directory);\n }\n\n private isWithinRoot(directory: string): boolean {\n return isSubPath(directory, this.root);\n }\n}\n\nfunction isSubPath(candidate: string, root: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction toRelativePrefix(directory: string, root: string): string {\n const relative = path.relative(root, directory);\n if (!relative || relative === \".\") {\n return \"\";\n }\n\n return toPosixPath(relative);\n}\n\nfunction resolvePattern(\n pattern: string,\n relativePrefix: string,\n): {\n pattern: string;\n directory: boolean;\n} {\n let directory = false;\n let normalized = pattern;\n\n if (pattern.startsWith(\"/\")) {\n normalized = pattern.slice(1);\n } else if (relativePrefix) {\n normalized = `${relativePrefix}/${pattern}`;\n }\n\n if (normalized.endsWith(\"/\")) {\n directory = true;\n normalized = normalized.slice(0, -1);\n }\n\n return {\n pattern: normalized.replace(/\\\\/g, \"/\"),\n directory,\n };\n}\n","/**\n * Pathfinder Finder - Main traversal class (Phase 1)\n *\n * Implements secure filesystem traversal with glob-based discovery, include/exclude\n * pattern support, optional symlink following, and constraint enforcement.\n */\n\nimport type { Stats } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport fg, { type Options as FastGlobOptions } from \"fast-glob\";\n\nimport { FulmenError, generateCorrelationId } from \"../errors/index.js\";\nimport type { SeverityName } from \"../errors/severity.js\";\nimport type { Logger } from \"../logging/logger.js\";\nimport { metrics as defaultMetrics } from \"../telemetry/index.js\";\nimport type { MetricsRegistry } from \"../telemetry/registry.js\";\nimport { calculateChecksum } from \"./checksum.js\";\nimport { DEFAULT_CONFIG, DEFAULT_IGNORE_FILES } from \"./constants.js\";\nimport { createPathfinderError, PathfinderErrorCode } from \"./errors.js\";\nimport { IgnoreMatcher } from \"./ignore.js\";\nimport {\n type ConstraintEvaluation,\n enforcePathConstraints,\n isPathWithinRoot,\n toPosixPath,\n} from \"./safety.js\";\nimport type {\n PathfinderConfig,\n PathfinderExecuteOptions,\n PathfinderQuery,\n PathResult,\n} from \"./types.js\";\nimport {\n ChecksumAlgorithm,\n ChecksumEncoding,\n EnforcementLevel,\n type FileMetadata,\n LoaderType,\n} from \"./types.js\";\n\nexport interface PathfinderOptions {\n logger?: Logger;\n correlationId?: string;\n metrics?: MetricsRegistry;\n}\n\n/**\n * Resolved configuration with defaults applied.\n */\ninterface ResolvedPathfinderConfig {\n maxWorkers: number;\n cacheEnabled: boolean;\n cacheTTL: number;\n loaderType: LoaderType;\n calculateChecksums: boolean;\n checksumAlgorithm: ChecksumAlgorithm;\n checksumEncoding: ChecksumEncoding;\n constraint?: PathfinderConfig[\"constraint\"];\n honorIgnoreFiles: boolean;\n}\n\n/**\n * Normalized discovery query with absolute paths and defaults applied.\n */\ninterface NormalizedPathfinderQuery {\n /** Absolute root path retaining caller symlink semantics */\n root: string;\n /** Real path of the root (symlinks resolved) */\n realRoot: string;\n include: string[];\n exclude: string[];\n maxDepth: number;\n followSymlinks: boolean;\n includeHidden: boolean;\n honorIgnoreFiles: boolean;\n}\n\n/**\n * Pathfinder class - Filesystem traversal with pattern matching\n */\nexport class Pathfinder {\n private readonly config: ResolvedPathfinderConfig;\n private readonly logger?: Logger;\n private readonly correlationId: string;\n private readonly metrics: MetricsRegistry;\n\n constructor(config?: PathfinderConfig, options: PathfinderOptions = {}) {\n this.config = this.normalizeConfig(config);\n this.logger = options.logger;\n this.correlationId = options.correlationId ?? generateCorrelationId();\n this.metrics = options.metrics ?? defaultMetrics;\n }\n\n private log(\n level: \"debug\" | \"info\" | \"warn\" | \"error\",\n message: string,\n context?: Record<string, unknown>,\n error?: Error,\n ): void {\n if (!this.logger) return;\n\n const logContext = {\n correlation_id: this.correlationId,\n domain: \"pathfinder\",\n ...context,\n };\n\n switch (level) {\n case \"debug\":\n this.logger.debug(message, logContext);\n break;\n case \"info\":\n this.logger.info(message, logContext);\n break;\n case \"warn\":\n this.logger.warn(message, logContext);\n break;\n case \"error\":\n this.logger.error(message, error, logContext);\n break;\n }\n }\n\n private createError(\n code: PathfinderErrorCode,\n message: string,\n severity: SeverityName = \"medium\",\n context?: Record<string, unknown>,\n ): FulmenError {\n return createPathfinderError(code, message, {\n severity,\n correlation_id: this.correlationId,\n context,\n });\n }\n\n private throwError(\n code: PathfinderErrorCode,\n message: string,\n severity: SeverityName = \"medium\",\n context?: Record<string, unknown>,\n ): never {\n const error = this.createError(code, message, severity, context);\n const level = severity === \"critical\" || severity === \"high\" ? \"error\" : \"warn\";\n this.log(level, message, { code, ...context }, error);\n throw error;\n }\n\n private wrapError(\n error: unknown,\n code: PathfinderErrorCode,\n severity: SeverityName = \"medium\",\n context: Record<string, unknown> = {},\n ): FulmenError {\n const baseError =\n error instanceof Error ? error : new Error(typeof error === \"string\" ? error : String(error));\n\n if (error instanceof FulmenError) {\n return FulmenError.wrap(error, {\n severity,\n correlation_id: this.correlationId,\n context: {\n domain: \"pathfinder\",\n category: \"filesystem\",\n ...context,\n },\n });\n }\n\n return FulmenError.wrap(baseError, {\n code,\n severity,\n correlation_id: this.correlationId,\n context: {\n domain: \"pathfinder\",\n category: \"filesystem\",\n ...context,\n },\n });\n }\n\n private wrapAndLogError(\n error: unknown,\n code: PathfinderErrorCode,\n severity: SeverityName = \"medium\",\n context: Record<string, unknown> = {},\n message?: string,\n ): FulmenError {\n const wrapped = this.wrapError(error, code, severity, context);\n const logMessage = message ?? wrapped.message;\n const level = severity === \"critical\" || severity === \"high\" ? \"error\" : \"warn\";\n this.log(level, logMessage, { code, ...context }, wrapped);\n return wrapped;\n }\n\n private recordSecurityWarning(details: Record<string, unknown>, reason?: string): void {\n this.metrics.counter(\"pathfinder_security_warnings\").inc();\n this.log(\"warn\", reason ?? \"Pathfinder security warning\", details);\n }\n\n /**\n * Discover files matching the specified query.\n *\n * Collects all results in memory before returning.\n */\n async find(\n query: PathfinderQuery,\n options: PathfinderExecuteOptions = {},\n ): Promise<PathResult[]> {\n const histogram = this.metrics.histogram(\"pathfinder_find_ms\");\n const start = performance.now();\n\n try {\n const results: PathResult[] = [];\n\n for await (const result of this.iterate(query, options)) {\n results.push(result);\n }\n\n histogram.observe(performance.now() - start);\n return results;\n } catch (error) {\n histogram.observe(performance.now() - start);\n throw this.wrapAndLogError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n operation: \"find\",\n });\n }\n }\n\n async *findIterable(\n query: PathfinderQuery,\n options: PathfinderExecuteOptions = {},\n ): AsyncIterable<PathResult> {\n const histogram = this.metrics.histogram(\"pathfinder_find_ms\");\n const start = performance.now();\n\n try {\n for await (const result of this.iterate(query, options)) {\n yield result;\n }\n histogram.observe(performance.now() - start);\n } catch (error) {\n histogram.observe(performance.now() - start);\n throw this.wrapAndLogError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n operation: \"findIterable\",\n });\n }\n }\n\n /**\n * Discover files lazily via async iteration.\n */\n private async *iterate(\n query: PathfinderQuery,\n options: PathfinderExecuteOptions = {},\n ): AsyncIterable<PathResult> {\n const normalizedQuery = await this.normalizeQuery(query);\n this.validateConstraintCompatibility(normalizedQuery);\n\n const ignoreMatcher = normalizedQuery.honorIgnoreFiles\n ? new IgnoreMatcher(normalizedQuery.root)\n : undefined;\n\n const globOptions: FastGlobOptions = {\n cwd: normalizedQuery.root,\n absolute: true,\n dot: normalizedQuery.includeHidden,\n onlyFiles: true,\n followSymbolicLinks: normalizedQuery.followSymlinks,\n unique: true,\n ignore: normalizedQuery.exclude,\n };\n\n if (normalizedQuery.maxDepth > 0) {\n globOptions.deep = normalizedQuery.maxDepth;\n }\n\n let matches: string[];\n try {\n matches = await fg(normalizedQuery.include, globOptions);\n } catch (error) {\n throw this.wrapAndLogError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n root: normalizedQuery.root,\n operation: \"glob\",\n });\n }\n\n for (const candidatePath of matches) {\n const lstat = await this.safeLstat(candidatePath, options);\n if (!lstat) continue;\n\n if (lstat.isDirectory()) {\n // Should not happen with onlyFiles=true, but guard defensively\n continue;\n }\n\n if (lstat.isSymbolicLink() && !normalizedQuery.followSymlinks) {\n continue;\n }\n\n const isDefaultIgnoreFile = DEFAULT_IGNORE_FILES.includes(path.basename(candidatePath));\n if (isDefaultIgnoreFile) {\n if (normalizedQuery.honorIgnoreFiles) {\n this.log(\"debug\", \"Skipping default ignore file\", { path: candidatePath });\n continue;\n }\n\n this.log(\"debug\", \"Including default ignore file because honorIgnoreFiles is disabled\", {\n path: candidatePath,\n });\n }\n\n let evaluationPath = candidatePath;\n if (lstat.isSymbolicLink()) {\n const resolved = await this.safeRealpath(candidatePath, options);\n if (!resolved) continue;\n evaluationPath = resolved;\n }\n\n // Ensure the resolved path remains within the real root.\n if (!isPathWithinRoot(evaluationPath, normalizedQuery.realRoot)) {\n const violationContext = {\n path: evaluationPath,\n root: normalizedQuery.realRoot,\n operation: \"validatePathWithinRoot\",\n };\n this.recordSecurityWarning(\n violationContext,\n `Path ${evaluationPath} escapes discovery root ${normalizedQuery.realRoot}`,\n );\n const violationError = this.createError(\n PathfinderErrorCode.CONSTRAINT_VIOLATION,\n `Path ${evaluationPath} escapes discovery root ${normalizedQuery.realRoot}`,\n \"high\",\n violationContext,\n );\n await this.dispatchError(violationError, candidatePath, options);\n continue;\n }\n\n const relativeFromRoot = path.relative(normalizedQuery.root, candidatePath);\n if (relativeFromRoot.startsWith(\"..\") || path.isAbsolute(relativeFromRoot)) {\n const violationContext = {\n path: candidatePath,\n root: normalizedQuery.root,\n operation: \"validateRelativePath\",\n };\n this.recordSecurityWarning(\n violationContext,\n `Path ${candidatePath} is outside discovery root ${normalizedQuery.root}`,\n );\n const violationError = this.createError(\n PathfinderErrorCode.CONSTRAINT_VIOLATION,\n `Path ${candidatePath} is outside discovery root ${normalizedQuery.root}`,\n \"high\",\n violationContext,\n );\n await this.dispatchError(violationError, candidatePath, options);\n continue;\n }\n\n const relativePosix = toPosixPath(relativeFromRoot);\n if (ignoreMatcher && (await ignoreMatcher.shouldIgnore(candidatePath, relativePosix))) {\n this.log(\"debug\", \"Excluded by ignore matcher\", {\n path: candidatePath,\n relativePath: relativePosix,\n });\n continue;\n }\n\n const constraintResult = this.evaluateConstraint(evaluationPath, relativePosix);\n if (!constraintResult.allowed) {\n const enforcement = this.config.constraint?.enforcementLevel ?? EnforcementLevel.WARN;\n const message = constraintResult.reason ?? \"Path violates configured constraint\";\n const violationContext = {\n path: evaluationPath,\n relativePath: relativePosix,\n constraintRoot: this.config.constraint?.root,\n enforcement,\n };\n\n this.recordSecurityWarning(violationContext, message);\n\n const violationError = this.createError(\n PathfinderErrorCode.CONSTRAINT_VIOLATION,\n message,\n enforcement === EnforcementLevel.STRICT ? \"high\" : \"medium\",\n violationContext,\n );\n\n if (enforcement === EnforcementLevel.STRICT) {\n this.log(\"error\", message, violationContext, violationError);\n throw violationError;\n }\n\n if (enforcement === EnforcementLevel.WARN) {\n this.log(\"warn\", message, violationContext, violationError);\n if (options.errorCallback) {\n await options.errorCallback(violationError, candidatePath);\n }\n continue;\n }\n\n // Permissive mode allows the path through.\n }\n\n let statsForMetadata = lstat;\n if (evaluationPath !== candidatePath) {\n const resolvedStats = await this.safeStat(evaluationPath, options);\n statsForMetadata = resolvedStats ?? lstat;\n }\n\n const metadata = await this.buildMetadata(\n candidatePath,\n evaluationPath,\n statsForMetadata,\n lstat.isSymbolicLink(),\n );\n\n const result: PathResult = {\n relativePath: relativePosix,\n sourcePath: candidatePath,\n logicalPath: relativePosix,\n loaderType: this.config.loaderType,\n metadata,\n };\n\n await this.dispatchResult(result, options);\n yield result;\n }\n }\n\n /**\n * Normalize finder configuration by applying defaults.\n */\n private normalizeConfig(config?: PathfinderConfig): ResolvedPathfinderConfig {\n const merged: PathfinderConfig = {\n ...DEFAULT_CONFIG,\n ...config,\n };\n\n return {\n maxWorkers: merged.maxWorkers ?? 4,\n cacheEnabled: merged.cacheEnabled ?? false,\n cacheTTL: merged.cacheTTL ?? 300,\n loaderType: merged.loaderType ?? LoaderType.LOCAL,\n calculateChecksums: merged.calculateChecksums ?? false,\n checksumAlgorithm: merged.checksumAlgorithm ?? ChecksumAlgorithm.XXH3_128,\n checksumEncoding: merged.checksumEncoding ?? ChecksumEncoding.HEX,\n constraint: merged.constraint,\n honorIgnoreFiles: merged.honorIgnoreFiles ?? true,\n };\n }\n\n /**\n * Normalize a discovery query and ensure the root exists.\n */\n private async normalizeQuery(query: PathfinderQuery): Promise<NormalizedPathfinderQuery> {\n if (!query || !query.root) {\n this.throwError(\n PathfinderErrorCode.INVALID_CONFIG,\n \"Pathfinder query requires a root directory\",\n \"high\",\n { operation: \"normalizeQuery\" },\n );\n }\n\n const absoluteRoot = path.resolve(query.root);\n\n let stats: Stats;\n try {\n stats = await fs.stat(absoluteRoot);\n } catch (error) {\n throw this.wrapAndLogError(error, PathfinderErrorCode.INVALID_ROOT, \"high\", {\n root: absoluteRoot,\n operation: \"stat\",\n });\n }\n\n if (!stats.isDirectory()) {\n this.throwError(\n PathfinderErrorCode.INVALID_ROOT,\n `Pathfinder root must be a directory: ${absoluteRoot}`,\n \"high\",\n { root: absoluteRoot },\n );\n }\n\n let realRoot: string;\n try {\n realRoot = await fs.realpath(absoluteRoot);\n } catch (error) {\n throw this.wrapAndLogError(error, PathfinderErrorCode.INVALID_ROOT, \"high\", {\n root: absoluteRoot,\n operation: \"realpath\",\n });\n }\n\n const include = query.include && query.include.length > 0 ? [...query.include] : [\"**/*\"];\n const exclude = query.exclude ? [...query.exclude] : [];\n const maxDepth = query.maxDepth ?? 0;\n\n if (maxDepth < 0) {\n this.throwError(\n PathfinderErrorCode.INVALID_CONFIG,\n \"Pathfinder maxDepth must be >= 0\",\n \"high\",\n { maxDepth },\n );\n }\n\n return {\n root: absoluteRoot,\n realRoot,\n include,\n exclude,\n maxDepth,\n followSymlinks: query.followSymlinks ?? false,\n includeHidden: query.includeHidden ?? false,\n honorIgnoreFiles: query.honorIgnoreFiles ?? this.config.honorIgnoreFiles,\n };\n }\n\n /**\n * Ensure constraint root encompasses the discovery root when provided.\n */\n private validateConstraintCompatibility(query: NormalizedPathfinderQuery): void {\n const constraint = this.config.constraint;\n if (!constraint) {\n return;\n }\n\n const constraintRoot = constraint.root ? path.resolve(constraint.root) : undefined;\n if (!constraintRoot) {\n return;\n }\n\n if (!isPathWithinRoot(query.realRoot, constraintRoot)) {\n this.throwError(\n PathfinderErrorCode.INVALID_CONFIG,\n `Discovery root ${query.realRoot} must be within constraint root ${constraintRoot}`,\n \"high\",\n { root: query.realRoot, constraintRoot },\n );\n }\n }\n\n /**\n * Evaluate constraint applicability for a discovered path.\n */\n private evaluateConstraint(evaluationPath: string, relativePath: string): ConstraintEvaluation {\n return enforcePathConstraints(evaluationPath, relativePath, this.config.constraint);\n }\n\n /**\n * Invoke result/progress callbacks prior to yielding.\n */\n private async dispatchResult(\n result: PathResult,\n options: PathfinderExecuteOptions,\n ): Promise<void> {\n if (options.resultCallback) {\n await options.resultCallback(result);\n }\n\n if (options.progressCallback && options.progressCallback !== options.resultCallback) {\n await options.progressCallback(result);\n }\n }\n\n private async buildMetadata(\n originalPath: string,\n resolvedPath: string,\n stats: Stats,\n isSymlink: boolean,\n ): Promise<FileMetadata> {\n const metadata: FileMetadata = {};\n\n if (Number.isFinite(stats.size)) {\n metadata.size = stats.size;\n }\n\n if (stats.mtime instanceof Date && Number.isFinite(stats.mtime.valueOf())) {\n metadata.modified = stats.mtime.toISOString();\n }\n\n metadata.permissions = this.formatPermissions(stats.mode);\n\n if (isSymlink) {\n metadata.isSymlink = true;\n try {\n metadata.symlinkTarget = await fs.readlink(originalPath);\n } catch {\n // Ignore readlink errors; metadata remains without target\n }\n }\n\n if (this.config.calculateChecksums) {\n const algorithm = this.config.checksumAlgorithm ?? ChecksumAlgorithm.XXH3_128;\n const checksumMetadata = await calculateChecksum(resolvedPath, algorithm);\n\n if (checksumMetadata.checksumError) {\n this.log(\"warn\", \"Checksum calculation failed\", {\n path: originalPath,\n resolvedPath,\n algorithm,\n error: checksumMetadata.checksumError,\n });\n }\n\n Object.assign(metadata, checksumMetadata);\n }\n\n return metadata;\n }\n\n private formatPermissions(mode: number): string {\n const normalized = mode & 0o777;\n return normalized.toString(8).padStart(4, \"0\");\n }\n\n private async safeStat(\n targetPath: string,\n options: PathfinderExecuteOptions,\n ): Promise<Stats | undefined> {\n try {\n return await fs.stat(targetPath);\n } catch (error) {\n const wrapped = this.wrapError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n path: targetPath,\n operation: \"stat\",\n });\n await this.dispatchError(wrapped, targetPath, options);\n return undefined;\n }\n }\n\n /**\n * Invoke error callback or throw when unrecoverable.\n */\n private async dispatchError(\n error: Error,\n pathContext: string,\n options: PathfinderExecuteOptions,\n ): Promise<void> {\n const normalized =\n error instanceof FulmenError\n ? error\n : this.wrapError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n path: pathContext,\n operation: \"dispatchError\",\n });\n\n const severity = normalized.data.severity ?? \"medium\";\n const level = severity === \"critical\" || severity === \"high\" ? \"error\" : \"warn\";\n\n this.log(\n level,\n \"Pathfinder recoverable error\",\n {\n path: pathContext,\n code: normalized.data.code,\n severity,\n },\n normalized,\n );\n\n if (options.errorCallback) {\n await options.errorCallback(normalized, pathContext);\n return;\n }\n\n throw normalized;\n }\n\n /**\n * lstat wrapper that routes recoverable errors through callbacks.\n */\n private async safeLstat(\n targetPath: string,\n options: PathfinderExecuteOptions,\n ): Promise<Stats | undefined> {\n try {\n return await fs.lstat(targetPath);\n } catch (error) {\n const wrapped = this.wrapError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n path: targetPath,\n operation: \"lstat\",\n });\n await this.dispatchError(wrapped, targetPath, options);\n return undefined;\n }\n }\n\n /**\n * realpath wrapper that routes recoverable errors through callbacks.\n */\n private async safeRealpath(\n targetPath: string,\n options: PathfinderExecuteOptions,\n ): Promise<string | undefined> {\n try {\n return await fs.realpath(targetPath);\n } catch (error) {\n const wrapped = this.wrapError(error, PathfinderErrorCode.TRAVERSAL_FAILED, \"medium\", {\n path: targetPath,\n operation: \"realpath\",\n });\n await this.dispatchError(wrapped, targetPath, options);\n return undefined;\n }\n }\n}\n","import { Pathfinder } from \"./finder.js\";\nimport type { PathfinderConfig, PathfinderQuery, PathResult } from \"./types.js\";\n\nconst DEFAULT_CONFIG_EXTENSIONS = [\".yaml\", \".yml\", \".json\"];\nconst DEFAULT_SCHEMA_PATTERNS = [\"**/*.schema.json\", \"**/*.schema.yaml\"];\n\nfunction normalizeExtension(extension: string): string {\n return extension.startsWith(\".\") ? extension : `.${extension}`;\n}\n\nfunction buildIncludePatternsFromExtensions(extensions: string[]): string[] {\n return extensions.map((extension) => `**/*${normalizeExtension(extension)}`);\n}\n\nfunction createFinder(additionalConfig?: Partial<PathfinderConfig>): Pathfinder {\n return new Pathfinder(additionalConfig);\n}\n\nasync function executeFinder(finder: Pathfinder, query: PathfinderQuery): Promise<PathResult[]> {\n return finder.find(query);\n}\n\nexport async function findConfigFiles(\n root: string,\n extensions: string[] = DEFAULT_CONFIG_EXTENSIONS,\n additionalConfig?: Partial<PathfinderConfig>,\n): Promise<PathResult[]> {\n const include = buildIncludePatternsFromExtensions(extensions);\n const finder = createFinder(additionalConfig);\n\n return executeFinder(finder, {\n root,\n include,\n });\n}\n\nexport async function findSchemaFiles(\n root: string,\n additionalConfig?: Partial<PathfinderConfig>,\n): Promise<PathResult[]> {\n const finder = createFinder(additionalConfig);\n return executeFinder(finder, {\n root,\n include: DEFAULT_SCHEMA_PATTERNS,\n });\n}\n\nexport async function findByExtensions(\n root: string,\n extensions: string[],\n additionalConfig?: Partial<PathfinderConfig>,\n): Promise<PathResult[]> {\n if (extensions.length === 0) {\n return [];\n }\n\n const include = buildIncludePatternsFromExtensions(extensions);\n const finder = createFinder(additionalConfig);\n\n return executeFinder(finder, {\n root,\n include,\n });\n}\n","/**\n * Repository root discovery - Find repository markers in ancestor directories\n *\n * Implements Crucible v0.2.15 pathfinder extension for secure upward traversal.\n * Prevents data leakage with boundaries, max-depth, and path constraint enforcement.\n */\n\nimport { access, lstat, realpath } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { DEFAULT_MAX_DEPTH } from \"./constants.js\";\nimport { createPathfinderError, PathfinderErrorCode } from \"./errors.js\";\nimport type { FindRepoOptions } from \"./types.js\";\n\n/**\n * Find repository root by walking up directory tree\n *\n * Searches for marker files (e.g., .git, package.json) by traversing\n * upward from startPath, respecting boundaries and security constraints.\n *\n * **Security**: Enforces boundaries (home/explicit), max-depth, root/drive/UNC\n * ceilings, and optional path constraints. Default followSymlinks=false.\n *\n * @param startPath - Directory to start search from\n * @param markers - Array of marker files/directories to search for (e.g., [\".git\", \"package.json\"])\n * @param options - Optional configuration for boundaries, depth, and symlink handling\n * @returns Absolute path to repository root containing marker\n * @throws {FulmenError} REPOSITORY_NOT_FOUND if no marker found within constraints\n * @throws {FulmenError} INVALID_START_PATH if startPath doesn't exist or isn't accessible\n * @throws {FulmenError} INVALID_BOUNDARY if boundary is outside startPath ancestry\n * @throws {FulmenError} TRAVERSAL_LOOP if cyclic symlink detected (when followSymlinks=true)\n * @throws {FulmenError} SECURITY_VIOLATION if constraint prevents marker discovery\n *\n * @example\n * ```typescript\n * import { findRepositoryRoot, GitMarkers } from \"@fulmenhq/tsfulmen/pathfinder\";\n *\n * // Find Git repository root\n * const gitRoot = await findRepositoryRoot(process.cwd(), GitMarkers);\n *\n * // Find with custom boundary\n * const root = await findRepositoryRoot(\"./src/components\", [\".git\"], {\n * boundary: \"/home/user/projects\",\n * maxDepth: 5\n * });\n * ```\n */\nexport async function findRepositoryRoot(\n startPath: string,\n markers: string[] = [\".git\"],\n options?: FindRepoOptions,\n): Promise<string> {\n // Normalize and validate start path\n const normalizedStart = resolve(startPath);\n await validateStartPath(normalizedStart);\n\n // Apply defaults\n const maxDepth = options?.maxDepth ?? DEFAULT_MAX_DEPTH;\n const stopAtFirst = options?.stopAtFirst ?? true;\n const followSymlinks = options?.followSymlinks ?? false;\n const constraint = options?.constraint;\n\n // Determine boundary: explicit or default (home), but only if start is under it\n let boundary: string;\n if (options?.boundary) {\n boundary = resolve(options.boundary);\n // Validate explicit boundary is ancestor of start\n validateBoundary(normalizedStart, boundary);\n } else {\n // Default boundary: use home if start is under it, otherwise filesystem root\n const home = getDefaultBoundary();\n boundary = normalizedStart.startsWith(home) ? home : \"/\";\n }\n\n // Validate constraint if provided\n if (constraint?.root) {\n const constraintRoot = resolve(constraint.root);\n if (!normalizedStart.startsWith(constraintRoot)) {\n throw createPathfinderError(\n PathfinderErrorCode.SECURITY_VIOLATION,\n `Start path ${normalizedStart} is outside constraint root ${constraintRoot}`,\n { severity: \"high\", context: { startPath: normalizedStart, constraint: constraintRoot } },\n );\n }\n }\n\n // Track visited paths for loop detection (when followSymlinks=true)\n const visitedRealPaths = new Set<string>();\n\n // Track all found markers (for stopAtFirst=false)\n let deepestMarkerPath: string | null = null;\n\n let currentDir = normalizedStart;\n let depth = 0;\n\n // Walk upward until we hit a boundary\n while (depth < maxDepth) {\n // Check for cyclic symlinks (if following symlinks)\n if (followSymlinks) {\n const realPath = await getRealPath(currentDir);\n if (visitedRealPaths.has(realPath)) {\n throw createPathfinderError(\n PathfinderErrorCode.TRAVERSAL_LOOP,\n `Cyclic symlink detected at ${currentDir}`,\n { severity: \"high\", context: { currentDir, realPath, depth } },\n );\n }\n visitedRealPaths.add(realPath);\n }\n\n // Check if we're outside constraint (if provided)\n if (constraint?.root) {\n const constraintRoot = resolve(constraint.root);\n if (!currentDir.startsWith(constraintRoot)) {\n // We've walked above the constraint - stop here\n break;\n }\n }\n\n // Check for markers in current directory\n for (const marker of markers) {\n if (await markerExists(currentDir, marker)) {\n if (stopAtFirst) {\n // Return immediately on first match\n return currentDir;\n }\n // Track deepest marker (closest to root)\n deepestMarkerPath = currentDir;\n }\n }\n\n // Check if we've reached the boundary\n if (currentDir === boundary || isFilesystemRoot(currentDir)) {\n break;\n }\n\n // Move up one directory\n const parentDir = dirname(currentDir);\n\n // Safety check: prevent infinite loop\n if (parentDir === currentDir) {\n // Reached filesystem root\n break;\n }\n\n currentDir = parentDir;\n depth++;\n }\n\n // If stopAtFirst=false and we found a marker, return deepest one\n if (!stopAtFirst && deepestMarkerPath) {\n return deepestMarkerPath;\n }\n\n // No marker found\n throw createPathfinderError(\n PathfinderErrorCode.REPOSITORY_NOT_FOUND,\n `No repository root found with markers [${markers.join(\", \")}] from ${startPath}`,\n {\n severity: \"medium\",\n context: {\n startPath: normalizedStart,\n markers,\n maxDepth,\n boundary,\n depthReached: depth,\n },\n },\n );\n}\n\n/**\n * Validate start path exists and is accessible\n *\n * @param startPath - Path to validate\n * @throws {FulmenError} INVALID_START_PATH if path doesn't exist or isn't accessible\n */\nasync function validateStartPath(startPath: string): Promise<void> {\n try {\n await access(startPath);\n const stats = await lstat(startPath);\n if (!stats.isDirectory()) {\n throw createPathfinderError(\n PathfinderErrorCode.INVALID_START_PATH,\n `Start path is not a directory: ${startPath}`,\n { severity: \"high\", context: { startPath } },\n );\n }\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n throw createPathfinderError(\n PathfinderErrorCode.INVALID_START_PATH,\n `Start path does not exist: ${startPath}`,\n { severity: \"high\", context: { startPath } },\n );\n }\n throw error;\n }\n}\n\n/**\n * Validate boundary is ancestor of start path\n *\n * @param startPath - Start path for search\n * @param boundary - Boundary ceiling\n * @throws {FulmenError} INVALID_BOUNDARY if boundary is not ancestor of startPath\n */\nfunction validateBoundary(startPath: string, boundary: string): void {\n const normalizedStart = resolve(startPath);\n const normalizedBoundary = resolve(boundary);\n\n if (!normalizedStart.startsWith(normalizedBoundary)) {\n throw createPathfinderError(\n PathfinderErrorCode.INVALID_BOUNDARY,\n `Boundary ${boundary} is not an ancestor of start path ${startPath}`,\n { severity: \"high\", context: { startPath, boundary } },\n );\n }\n}\n\n/**\n * Check if directory is filesystem root\n *\n * Detects POSIX root (/), Windows drive roots (C:\\), and UNC roots (\\\\server\\share).\n *\n * @param dir - Directory to check\n * @returns true if dir is filesystem root\n */\nfunction isFilesystemRoot(dir: string): boolean {\n const parentDir = dirname(dir);\n return parentDir === dir;\n}\n\n/**\n * Get default boundary (user home directory)\n *\n * @returns Absolute path to user home directory\n */\nfunction getDefaultBoundary(): string {\n return homedir();\n}\n\n/**\n * Check if marker exists in directory\n *\n * @param dir - Directory to check\n * @param marker - Marker file/directory name\n * @returns true if marker exists in dir\n */\nasync function markerExists(dir: string, marker: string): Promise<boolean> {\n try {\n await access(join(dir, marker));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get real path resolving symlinks\n *\n * @param path - Path to resolve\n * @returns Real path with symlinks resolved\n */\nasync function getRealPath(path: string): Promise<string> {\n try {\n return await realpath(path);\n } catch (_error) {\n // If realpath fails, return original path\n return path;\n }\n}\n","/**\n * Pathfinder validators - Schema validation using TSFulmen schema module\n *\n * Uses the existing schema module instead of creating standalone AJV instances.\n * This ensures:\n * - Telemetry automatically emitted (schema_validations, schema_validation_errors)\n * - Schemas auto-discovered from Crucible SSOT\n * - Consistent error handling with other modules\n * - Validator caching handled automatically\n */\n\nimport { compileSchemaById, validateDataBySchemaId } from \"../schema/index.js\";\nimport type { CompiledValidator, SchemaValidationResult } from \"../schema/types.js\";\nimport { createPathfinderError, PathfinderErrorCode } from \"./errors.js\";\n\n/**\n * Compile pathfinder config schema for validation\n *\n * Uses TSFulmen's schema registry to load from Crucible SSOT.\n * Schemas are cached automatically by the schema module.\n *\n * @returns Compiled validator for pathfinder configuration\n *\n * @example\n * ```typescript\n * const validator = await compileConfigSchema();\n * const result = validateData(config, validator);\n * ```\n */\nexport async function compileConfigSchema(): Promise<CompiledValidator> {\n return compileSchemaById(\"pathfinder/v1.0.0/finder-config\");\n}\n\n/**\n * Compile path result schema for validation\n *\n * @returns Compiled validator for path results\n */\nexport async function compilePathResultSchema(): Promise<CompiledValidator> {\n return compileSchemaById(\"pathfinder/v1.0.0/path-result\");\n}\n\n/**\n * Validate pathfinder configuration against Crucible schema\n *\n * Uses schema module which automatically emits telemetry:\n * - `schema_validations` counter on success\n * - `schema_validation_errors` counter on failure\n *\n * @param config - Configuration to validate\n * @returns Validation result with diagnostics\n *\n * @example\n * ```typescript\n * const result = await validateConfig({ root: '/tmp' });\n * if (!result.valid) {\n * console.error('Invalid config:', result.diagnostics);\n * }\n * ```\n */\nexport async function validateConfig(config: unknown): Promise<SchemaValidationResult> {\n return validateDataBySchemaId(config, \"pathfinder/v1.0.0/finder-config\");\n}\n\n/**\n * Validate path result against Crucible schema\n *\n * @param result - Path result to validate\n * @returns Validation result with diagnostics\n *\n * @example\n * ```typescript\n * const result = await validatePathResult({\n * relativePath: 'src/index.ts',\n * sourcePath: '/tmp/src/index.ts',\n * loaderType: 'local',\n * metadata: { size: 1234, modified: '2025-11-01T12:00:00Z' }\n * });\n * ```\n */\nexport async function validatePathResult(result: unknown): Promise<SchemaValidationResult> {\n return validateDataBySchemaId(result, \"pathfinder/v1.0.0/path-result\");\n}\n\n/**\n * Validate config and throw on failure\n *\n * Convenience wrapper that throws FulmenError on validation failure.\n *\n * @param config - Configuration to validate\n * @throws {FulmenError} With pathfinder.validation_failed code\n *\n * @example\n * ```typescript\n * try {\n * await assertValidConfig(config);\n * // Config is valid, proceed\n * } catch (error) {\n * // Handle validation error\n * }\n * ```\n */\nexport async function assertValidConfig(config: unknown): Promise<void> {\n const result = await validateConfig(config);\n\n if (!result.valid) {\n const messages = result.diagnostics.map((d) => d.message).join(\", \");\n throw createPathfinderError(\n PathfinderErrorCode.VALIDATION_FAILED,\n `Invalid pathfinder configuration: ${messages}`,\n {\n severity: \"high\",\n context: { diagnostics: result.diagnostics },\n },\n );\n }\n}\n\n/**\n * Validate path result and throw on failure\n *\n * @param result - Path result to validate\n * @throws {FulmenError} With pathfinder.validation_failed code\n *\n * @example\n * ```typescript\n * await assertValidPathResult(result);\n * ```\n */\nexport async function assertValidPathResult(result: unknown): Promise<void> {\n const validationResult = await validatePathResult(result);\n\n if (!validationResult.valid) {\n const messages = validationResult.diagnostics.map((d) => d.message).join(\", \");\n throw createPathfinderError(\n PathfinderErrorCode.VALIDATION_FAILED,\n `Invalid path result: ${messages}`,\n {\n severity: \"high\",\n context: { diagnostics: validationResult.diagnostics },\n },\n );\n }\n}\n","/**\n * Pathfinder - Enterprise filesystem traversal with checksums and observability\n *\n * Provides filesystem discovery with pattern matching, ignore files, optional checksums,\n * and comprehensive observability through structured errors and telemetry.\n *\n * @example Basic usage\n * ```typescript\n * import { Pathfinder } from '@fulmenhq/tsfulmen/pathfinder';\n *\n * const finder = new Pathfinder();\n *\n * const results = await finder.find({\n * root: './src',\n * include: ['*.ts'],\n * followSymlinks: false,\n * });\n * ```\n *\n * @example Convenience helpers\n * ```typescript\n * import { findConfigFiles, findSchemaFiles } from '@fulmenhq/tsfulmen/pathfinder';\n *\n * const configs = await findConfigFiles('./config');\n * const schemas = await findSchemaFiles('./schemas');\n * ```\n *\n * @module pathfinder\n */\n\nexport const VERSION = \"0.1.0\";\n\n// Checksum helpers\nexport { calculateChecksum, calculateChecksumsBatch } from \"./checksum.js\";\n// Constants\nexport {\n DEFAULT_CONFIG,\n DEFAULT_IGNORE_FILES,\n DEFAULT_MAX_DEPTH,\n GitMarkers,\n GoModMarkers,\n MAX_PATH_LENGTH,\n MonorepoMarkers,\n NodeMarkers,\n PATH_SEPARATOR,\n PythonMarkers,\n} from \"./constants.js\";\n// Convenience helpers\nexport { findByExtensions, findConfigFiles, findSchemaFiles } from \"./convenience.js\";\n// Error types\nexport {\n createPathfinderError,\n PathfinderErrorCode,\n wrapPathfinderError,\n} from \"./errors.js\";\nexport type { PathfinderOptions } from \"./finder.js\";\n// Core exports\nexport { Pathfinder } from \"./finder.js\";\n// Repository root discovery\nexport { findRepositoryRoot } from \"./repoRoot.js\";\n// Types\nexport type {\n ErrorCallback,\n FileMetadata,\n FindRepoOptions,\n PathfinderConfig,\n PathfinderExecuteOptions,\n PathfinderQuery,\n PathResult,\n ProgressCallback,\n ResultCallback,\n} from \"./types.js\";\nexport {\n ChecksumAlgorithm,\n ChecksumEncoding,\n ConstraintType,\n EnforcementLevel,\n LoaderType,\n withBoundary,\n withConstraint,\n withFollowSymlinks,\n withMaxDepth,\n withStopAtFirst,\n} from \"./types.js\";\n// Validators\nexport {\n assertValidConfig,\n assertValidPathResult,\n compileConfigSchema,\n compilePathResultSchema,\n validateConfig,\n validatePathResult,\n} from \"./validators.js\";\n"]}
|