@wrongstack/core 0.291.0 → 0.291.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/dist/boot.d.ts.map +1 -1
- package/dist/chronicle/index.js +20 -1
- package/dist/chronicle/index.js.map +2 -2
- package/dist/chronicle/tool-adapter.d.ts.map +1 -1
- package/dist/coordination/director.d.ts +18 -0
- package/dist/coordination/director.d.ts.map +1 -1
- package/dist/coordination/fleet-spawn.d.ts.map +1 -1
- package/dist/coordination/index.js +37 -15
- package/dist/coordination/index.js.map +2 -2
- package/dist/core/agent-response.d.ts.map +1 -1
- package/dist/defaults/index.js +660 -391
- package/dist/defaults/index.js.map +4 -4
- package/dist/execution/index.js +61 -12
- package/dist/execution/index.js.map +3 -3
- package/dist/execution/tool-executor.d.ts.map +1 -1
- package/dist/hq/index.js +17 -0
- package/dist/hq/index.js.map +2 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1304 -882
- package/dist/index.js.map +4 -4
- package/dist/infrastructure/index.js +15 -10
- package/dist/infrastructure/index.js.map +2 -2
- package/dist/kernel/events/tool-events.d.ts +24 -0
- package/dist/kernel/events/tool-events.d.ts.map +1 -1
- package/dist/plugins/auto-review-plugin.d.ts +10 -0
- package/dist/plugins/auto-review-plugin.d.ts.map +1 -1
- package/dist/security/index.js +148 -0
- package/dist/security/index.js.map +3 -3
- package/dist/security/permission-policy.d.ts +8 -1
- package/dist/security/permission-policy.d.ts.map +1 -1
- package/dist/storage/config-loader.d.ts +8 -0
- package/dist/storage/config-loader.d.ts.map +1 -1
- package/dist/storage/index.js +457 -379
- package/dist/storage/index.js.map +4 -4
- package/dist/storage/provider-config-watcher.d.ts +6 -0
- package/dist/storage/provider-config-watcher.d.ts.map +1 -1
- package/dist/types/permission.d.ts +38 -0
- package/dist/types/permission.d.ts.map +1 -1
- package/dist/utils/config-backup.d.ts +20 -0
- package/dist/utils/config-backup.d.ts.map +1 -0
- package/dist/utils/index.d.ts +2 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +172 -106
- package/dist/utils/index.js.map +4 -4
- package/dist/utils/message-invariants.d.ts +12 -9
- package/dist/utils/message-invariants.d.ts.map +1 -1
- package/dist/utils/term.d.ts +6 -0
- package/dist/utils/term.d.ts.map +1 -1
- package/dist/utils/wstack-paths.d.ts +10 -0
- package/dist/utils/wstack-paths.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/chronicle/context.ts", "../../src/chronicle/identity.ts", "../../src/chronicle/file-observer.ts", "../../src/chronicle/journal.ts", "../../src/utils/atomic-write.ts", "../../src/types/errors.ts", "../../src/chronicle/types.ts", "../../src/chronicle/provider-adapter.ts", "../../src/chronicle/tool-adapter.ts", "../../src/chronicle/process-adapter.ts", "../../src/chronicle/health-monitor.ts", "../../src/chronicle/decision-adapter.ts", "../../src/chronicle/domain-adapter.ts", "../../src/chronicle/stream-adapter.ts", "../../src/chronicle/prompt-manifest.ts", "../../src/chronicle/rollup-adapter.ts", "../../src/chronicle/query.ts"],
|
|
4
|
-
"sourcesContent": ["import { randomUUID } from 'node:crypto';\nimport type { ChronicleCorrelation, ChronicleScope } from './types.js';\n\nexport interface ChronicleContext {\n scope: ChronicleScope;\n correlation: ChronicleCorrelation;\n}\n\n/** Create a root correlation context for a session, run, or background worker. */\nexport function createChronicleContext(\n scope: ChronicleScope,\n traceId: string = randomUUID(),\n): ChronicleContext {\n return {\n scope: { ...scope },\n correlation: { traceId, spanId: randomUUID() },\n };\n}\n\n/** Derive a child span without losing project/session/task attribution. */\nexport function childChronicleContext(\n parent: ChronicleContext,\n overrides: {\n scope?: Partial<ChronicleScope> | undefined;\n correlation?: Partial<Omit<ChronicleCorrelation, 'traceId'>> | undefined;\n } = {},\n): ChronicleContext {\n return {\n scope: { ...parent.scope, ...overrides.scope },\n correlation: {\n ...parent.correlation,\n ...overrides.correlation,\n traceId: parent.correlation.traceId,\n parentSpanId: parent.correlation.spanId,\n spanId: overrides.correlation?.spanId ?? randomUUID(),\n },\n };\n}\n", "import { createHash } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\nexport interface ChronicleRuntimeIdentityInput {\n globalRoot: string;\n projectId: string;\n projectDir: string;\n now?: Date | undefined;\n}\n\nexport interface ChronicleRuntimeLocation {\n installationId: string;\n machineId: string;\n projectId: string;\n journalPath: string;\n}\n\n/**\n * Resolve privacy-preserving stable IDs and a UTC daily project partition.\n * Raw host names and global paths never enter the journal envelope.\n */\nexport function resolveChronicleRuntimeLocation(\n input: ChronicleRuntimeIdentityInput,\n): ChronicleRuntimeLocation {\n const day = (input.now ?? new Date()).toISOString().slice(0, 10);\n return {\n installationId: stableId('installation', path.resolve(input.globalRoot)),\n machineId: stableId('machine', `${os.hostname()}\\0${os.platform()}\\0${os.arch()}`),\n projectId: input.projectId,\n journalPath: path.join(input.projectDir, 'chronicle', `${day}.events.jsonl`),\n };\n}\n\nfunction stableId(prefix: string, value: string): string {\n return `${prefix}_${createHash('sha256').update(value).digest('hex').slice(0, 24)}`;\n}\n", "import { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\ninterface FileFingerprint {\n size: number;\n mtimeMs: number;\n hash?: string | undefined;\n}\n\ninterface RecentToolMutation {\n at: number;\n toolUseId: string;\n toolName: string;\n agentId?: string | undefined;\n}\n\nexport interface ChronicleFileObserverOptions {\n projectRoot: string;\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n events?: EventBus | undefined;\n debounceMs?: number | undefined;\n maxHashBytes?: number | undefined;\n excludedDirectories?: readonly string[] | undefined;\n onError?: ((error: unknown) => void) | undefined;\n}\n\nexport interface ChronicleFileObserver {\n close(): Promise<void>;\n readonly watchedFiles: number;\n}\n\nconst DEFAULT_EXCLUDED = ['.git', '.wrongstack', 'node_modules', 'dist', 'coverage', '.temp_files'];\n\n/** Observe editor/user/external process mutations that bypass WrongStack tools. */\nexport async function startChronicleFileObserver(\n options: ChronicleFileObserverOptions,\n): Promise<ChronicleFileObserver> {\n const root = path.resolve(options.projectRoot);\n const excluded = new Set(options.excludedDirectories ?? DEFAULT_EXCLUDED);\n const debounceMs = options.debounceMs ?? 120;\n const maxHashBytes = options.maxHashBytes ?? 8 * 1024 * 1024;\n const known = await scanProject(root, excluded, maxHashBytes, options.onError);\n const recentToolMutations = new Map<string, RecentToolMutation>();\n const offToolProgress = options.events?.on('tool.progress', (event) => {\n if (event.event.type !== 'file_changed' || !event.event.path) return;\n const absolute = path.isAbsolute(event.event.path)\n ? path.normalize(event.event.path)\n : path.resolve(root, event.event.path);\n const relative = normalizeRelative(path.relative(root, absolute));\n if (relative.startsWith('../') || isExcluded(relative, excluded)) return;\n recentToolMutations.set(relative, {\n at: Date.now(),\n toolUseId: event.id,\n toolName: event.name,\n agentId: event.agentId,\n });\n });\n const pending = new Set<string>();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let flushTail: Promise<void> = Promise.resolve();\n\n const schedule = (filename: string | Buffer | null): void => {\n if (closed) return;\n if (filename === null) {\n // Some platforms omit the filename. A bounded full rescan recovers the\n // facts instead of silently losing an external mutation.\n pending.add('*');\n } else {\n const relative = normalizeRelative(String(filename));\n if (!relative || isExcluded(relative, excluded)) return;\n pending.add(relative);\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n const paths = [...pending];\n pending.clear();\n flushTail = flushTail.then(() => reconcile(paths)).catch((error) => options.onError?.(error));\n }, debounceMs);\n };\n\n const reconcile = async (changedPaths: string[]): Promise<void> => {\n const candidates = changedPaths.includes('*')\n ? unionKeys(known, await scanProject(root, excluded, maxHashBytes, options.onError))\n : changedPaths;\n const changes: Array<{\n relative: string;\n before?: FileFingerprint | undefined;\n after?: FileFingerprint | undefined;\n }> = [];\n for (const relative of candidates) {\n const before = known.get(relative);\n const after = await fingerprint(path.join(root, relative), maxHashBytes);\n if (sameFingerprint(before, after)) continue;\n changes.push({ relative, before, after });\n }\n\n // Atomic saves and renames commonly arrive as delete+create. Matching the\n // last-known content hash preserves resource lineage when the OS provides\n // only generic \"rename\" notifications.\n const deleted = changes.filter((change) => change.before && !change.after);\n const created = changes.filter((change) => !change.before && change.after);\n const consumed = new Set<string>();\n for (const from of deleted) {\n const match = created.find((to) =>\n !consumed.has(to.relative) &&\n from.before?.hash !== undefined &&\n from.before.hash === to.after?.hash,\n );\n if (!match) continue;\n consumed.add(from.relative);\n consumed.add(match.relative);\n known.delete(from.relative);\n known.set(match.relative, match.after!);\n await recordMutation(options, 'file.external.renamed', match.relative, match.after, {\n operation: 'rename',\n previousPath: from.relative,\n previousResourceId: resourceId(from.relative),\n actor: 'external',\n }, mutationAttribution(match.relative, recentToolMutations));\n }\n\n for (const change of changes) {\n if (consumed.has(change.relative)) continue;\n if (!change.after) {\n known.delete(change.relative);\n await recordMutation(options, 'file.external.deleted', change.relative, change.before, {\n operation: 'delete',\n actor: 'external',\n previousHash: change.before?.hash,\n previousSize: change.before?.size,\n }, mutationAttribution(change.relative, recentToolMutations));\n } else if (!change.before) {\n known.set(change.relative, change.after);\n await recordMutation(options, 'file.external.created', change.relative, change.after, {\n operation: 'write',\n actor: 'external',\n }, mutationAttribution(change.relative, recentToolMutations));\n } else {\n known.set(change.relative, change.after);\n await recordMutation(options, 'file.external.modified', change.relative, change.after, {\n operation: 'edit',\n actor: 'external',\n previousHash: change.before.hash,\n previousSize: change.before.size,\n }, mutationAttribution(change.relative, recentToolMutations));\n }\n }\n };\n\n let watcher: fs.FSWatcher;\n try {\n watcher = fs.watch(root, { recursive: true, persistent: false }, (_eventType, filename) => schedule(filename));\n } catch (error) {\n options.onError?.(error);\n throw error;\n }\n watcher.on('error', (error) => options.onError?.(error));\n\n return {\n get watchedFiles() {\n return known.size;\n },\n async close() {\n if (closed) return;\n closed = true;\n offToolProgress?.();\n watcher.close();\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n const paths = [...pending];\n pending.clear();\n if (paths.length > 0) flushTail = flushTail.then(() => reconcile(paths));\n }\n await flushTail;\n },\n };\n}\n\nasync function recordMutation(\n options: ChronicleFileObserverOptions,\n eventType: string,\n relativePath: string,\n state: FileFingerprint | undefined,\n attributes: Record<string, unknown>,\n attribution?: RecentToolMutation | undefined,\n): Promise<void> {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const operation = attributes['operation'] as 'write' | 'edit' | 'delete' | 'rename';\n options.events?.emit('file.activity', {\n filePath: path.join(options.projectRoot, relativePath),\n operation,\n phase: 'changed',\n source: attribution ? 'tool' : 'external',\n at: Date.now(),\n sessionId: context.scope.sessionId,\n traceId: context.correlation.traceId,\n agentId: attribution?.agentId ?? context.scope.agentId,\n ...(attribution ? { toolUseId: attribution.toolUseId, toolName: attribution.toolName } : {}),\n });\n const input: ChronicleEventInput = {\n eventType: attribution ? eventType.replace('.external.', '.tool.') : eventType,\n scope: context.scope,\n correlation: {\n ...context.correlation,\n ...(attribution ? { toolCallId: attribution.toolUseId } : {}),\n },\n outcome: 'success',\n resource: {\n kind: 'file',\n id: resourceId(relativePath),\n path: normalizeRelative(relativePath),\n ...(state?.hash ? { contentHashAfter: state.hash } : {}),\n },\n attributes: {\n ...attributes,\n actor: attribution ? 'agent' : attributes['actor'],\n source: attribution ? 'tool' : 'external',\n toolName: attribution?.toolName,\n size: state?.size,\n mtimeMs: state?.mtimeMs,\n observedBy: 'fs.watch',\n },\n };\n await options.journal.append(input);\n}\n\nfunction mutationAttribution(\n relativePath: string,\n recent: Map<string, RecentToolMutation>,\n): RecentToolMutation | undefined {\n const value = recent.get(relativePath);\n if (!value) return undefined;\n recent.delete(relativePath);\n return Date.now() - value.at <= 2_000 ? value : undefined;\n}\n\nasync function scanProject(\n root: string,\n excluded: ReadonlySet<string>,\n maxHashBytes: number,\n onError?: ((error: unknown) => void) | undefined,\n): Promise<Map<string, FileFingerprint>> {\n const result = new Map<string, FileFingerprint>();\n const dirs = [''];\n while (dirs.length > 0) {\n const relativeDir = dirs.pop()!;\n try {\n const entries = await fsp.readdir(path.join(root, relativeDir), { withFileTypes: true });\n for (const entry of entries) {\n const relative = normalizeRelative(path.join(relativeDir, entry.name));\n if (entry.isDirectory()) {\n if (!excluded.has(entry.name)) dirs.push(relative);\n } else if (entry.isFile()) {\n const value = await fingerprint(path.join(root, relative), maxHashBytes);\n if (value) result.set(relative, value);\n }\n }\n } catch (error) {\n onError?.(error);\n }\n }\n return result;\n}\n\nasync function fingerprint(filePath: string, maxHashBytes: number): Promise<FileFingerprint | undefined> {\n try {\n const stat = await fsp.stat(filePath);\n if (!stat.isFile()) return undefined;\n const base: FileFingerprint = { size: stat.size, mtimeMs: stat.mtimeMs };\n if (stat.size <= maxHashBytes) {\n base.hash = createHash('sha256').update(await fsp.readFile(filePath)).digest('hex');\n }\n return base;\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\nfunction sameFingerprint(a: FileFingerprint | undefined, b: FileFingerprint | undefined): boolean {\n if (!a || !b) return a === b;\n if (a.hash !== undefined && b.hash !== undefined) return a.hash === b.hash;\n return a.size === b.size && a.mtimeMs === b.mtimeMs;\n}\n\nfunction isExcluded(relative: string, excluded: ReadonlySet<string>): boolean {\n return normalizeRelative(relative).split('/').some((segment) => excluded.has(segment));\n}\n\nfunction normalizeRelative(value: string): string {\n return value.replaceAll('\\\\', '/').replace(/^\\.\\//, '');\n}\n\nfunction resourceId(relativePath: string): string {\n return `file_${createHash('sha256').update(normalizeRelative(relativePath)).digest('hex').slice(0, 24)}`;\n}\n\nfunction unionKeys(a: ReadonlyMap<string, unknown>, b: ReadonlyMap<string, unknown>): string[] {\n return [...new Set([...a.keys(), ...b.keys()])];\n}\n", "import { createHash, randomUUID } from 'node:crypto';\r\nimport * as fs from 'node:fs/promises';\r\nimport * as path from 'node:path';\r\nimport { atomicWrite, ensureDir, withFileLock } from '../utils/atomic-write.js';\r\nimport {\r\n CHRONICLE_SCHEMA_VERSION,\r\n type ChronicleEvent,\r\n type ChronicleEventInput,\r\n type ChronicleVerifyResult,\r\n} from './types.js';\r\n\r\nconst GENESIS_HASH = '0'.repeat(64);\r\nconst DEFAULT_MAX_PARTITION_BYTES = 100 * 1024 * 1024;\r\nconst DEFAULT_ROTATION_WINDOW_MS = 60 * 60 * 1000;\r\nconst RETENTION_CHECKPOINT_VERSION = 1;\r\n\r\ninterface ChronicleRetentionCheckpoint {\r\n version: typeof RETENTION_CHECKPOINT_VERSION;\r\n sequence: number;\r\n hash: string;\r\n}\r\n\r\nexport interface ChronicleJournalOptions {\r\n filePath: string;\r\n now?: (() => Date) | undefined;\r\n monotonicNow?: (() => bigint) | undefined;\r\n idFactory?: (() => string) | undefined;\r\n maxPending?: number | undefined;\r\n batchWindowMs?: number | undefined;\r\n maxPartitionSizeBytes?: number | undefined;\r\n rotationWindowMs?: number | undefined;\r\n retentionDays?: number | undefined;\r\n autoPurgeIntervalMs?: number | undefined;\r\n}\r\nexport interface ChronicleJournalStats {\r\n acceptedEvents: number; persistedEvents: number; rejectedEvents: number; failedEvents: number;\r\n batches: number; pendingEvents: number; maxObservedPending: number; largestBatch: number;\r\n lastBatchDurationMs?: number | undefined;\r\n partitionRolls: number;\r\n}\r\nexport interface ChroniclePurgeOptions {\r\n retentionDays: number;\r\n dryRun?: boolean | undefined;\r\n files?: string[] | undefined;\r\n}\r\nexport interface ChroniclePurgeResult {\r\n deletedCount: number;\r\n deletedBytes: number;\r\n skippedCount: number;\r\n errors: Array<{ file: string; reason: string }>;\r\n candidates?: string[] | undefined;\r\n}\r\n\r\nexport class ChronicleJournal {\r\n private readonly basePath: string;\r\n private readonly now: () => Date;\r\n private readonly monotonicNow: () => bigint;\r\n private readonly idFactory: () => string;\r\n private readonly maxPending: number;\r\n private readonly batchWindowMs: number;\r\n private readonly maxPartitionSizeBytes: number;\r\n private readonly rotationWindowMs: number;\r\n private readonly retentionDays: number;\r\n private readonly autoPurgeIntervalMs: number;\r\n private pending: Array<{ input: ChronicleEventInput; resolve: (event: ChronicleEvent) => void; reject: (error: unknown) => void; }> = [];\r\n private drainPromise: Promise<void> | undefined;\r\n private drainScheduled = false;\r\n private drainTimer: ReturnType<typeof setTimeout> | undefined;\r\n private readonly counters = { acceptedEvents: 0, persistedEvents: 0, rejectedEvents: 0, failedEvents: 0, batches: 0, maxObservedPending: 0, largestBatch: 0, partitionRolls: 0 };\r\n private lastBatchDurationMs: number | undefined;\r\n private partitionIndex = 0;\r\n private partitionStartedAt: number;\r\n private lastSequence = 0;\r\n private lastHash: string = GENESIS_HASH;\r\n private lastAutoPurgeAt = 0;\r\n\r\n constructor(options: ChronicleJournalOptions) {\r\n this.basePath = path.resolve(options.filePath);\r\n this.now = options.now ?? (() => new Date());\r\n this.monotonicNow = options.monotonicNow ?? (() => process.hrtime.bigint());\r\n this.idFactory = options.idFactory ?? randomUUID;\r\n this.maxPending = Math.max(1, options.maxPending ?? 100_000);\r\n this.batchWindowMs = Math.max(0, options.batchWindowMs ?? 5);\r\n this.maxPartitionSizeBytes = options.maxPartitionSizeBytes ?? DEFAULT_MAX_PARTITION_BYTES;\r\n this.rotationWindowMs = options.rotationWindowMs ?? DEFAULT_ROTATION_WINDOW_MS;\r\n this.retentionDays = options.retentionDays && Number.isFinite(options.retentionDays) && options.retentionDays > 0 ? options.retentionDays : 0;\r\n this.autoPurgeIntervalMs = Math.max(0, options.autoPurgeIntervalMs ?? 3_600_000);\r\n this.partitionStartedAt = Date.now();\r\n }\r\n\r\n get path(): string { return this.partitionIndex === 0 ? this.basePath : rotatedPath(this.basePath, this.partitionIndex); }\r\n\r\n stats(): ChronicleJournalStats {\r\n return { ...this.counters, pendingEvents: this.pending.length, ...(this.lastBatchDurationMs !== undefined ? { lastBatchDurationMs: this.lastBatchDurationMs } : {}) };\r\n }\r\n\r\n append(input: ChronicleEventInput): Promise<ChronicleEvent> {\r\n if (this.pending.length >= this.maxPending) { this.counters.rejectedEvents++; return Promise.reject(new Error(`Chronicle backpressure limit reached (${this.maxPending} pending events)`)); }\r\n const promise = new Promise<ChronicleEvent>((resolve, reject) => { this.pending.push({ input, resolve, reject }); });\r\n this.counters.acceptedEvents++;\r\n this.counters.maxObservedPending = Math.max(this.counters.maxObservedPending, this.pending.length);\r\n this.scheduleDrain();\r\n return promise;\r\n }\r\n\r\n async readAll(): Promise<ChronicleEvent[]> {\r\n await this.flush();\r\n const files = await collectPartitions(this.basePath);\r\n const entries: ChronicleEvent[] = [];\r\n for (const file of files) entries.push(...(await readEntriesStrict(file)));\r\n return entries;\r\n }\r\n\r\n async flush(): Promise<void> {\r\n if (this.drainTimer) { clearTimeout(this.drainTimer); this.drainTimer = undefined; this.drainScheduled = false; }\r\n while (this.pending.length > 0 || this.drainPromise) {\r\n if (this.pending.length > 0 && !this.drainPromise) this.startDrain();\r\n await this.drainPromise;\r\n }\r\n }\r\n\r\n async verify(): Promise<ChronicleVerifyResult> {\r\n await this.flush();\r\n const files = await collectPartitions(this.basePath);\r\n const checkpointResult = await readRetentionCheckpoint(this.basePath);\r\n if (checkpointResult.error) return { ok: false, entries: 0, brokenAt: 0, reason: checkpointResult.error };\r\n return verifyPartitionFiles(files, checkpointResult.checkpoint);\r\n }\r\n\r\n async purge(options: ChroniclePurgeOptions): Promise<ChroniclePurgeResult> {\r\n await this.flush();\r\n if (!Number.isFinite(options.retentionDays) || options.retentionDays <= 0) {\r\n throw new TypeError('Chronicle retentionDays must be a positive finite number');\r\n }\r\n await this.refreshStateFromDisk();\r\n const cutoff = Date.now() - options.retentionDays * 86400000;\r\n const activePath = path.resolve(this.path);\r\n const errors: ChroniclePurgeResult['errors'] = [];\r\n let dc = 0, db = 0, sc = 0;\r\n const suppliedFiles = options.files === undefined\r\n ? await collectJournalPartitions(this.basePath)\r\n : [...options.files];\r\n const eligible = new Set<string>();\r\n for (const suppliedPath of new Set(suppliedFiles)) {\r\n const file = path.resolve(suppliedPath);\r\n if (!isJournalPartition(file, path.dirname(this.basePath), this.basePath)) {\r\n errors.push({ file: suppliedPath, reason: 'not a Chronicle journal partition in this journal directory' });\r\n sc++;\r\n continue;\r\n }\r\n if (file === activePath) { sc++; continue; }\r\n let mtimeMs: number;\r\n try {\r\n const fileStat = await fs.lstat(file);\r\n if (!fileStat.isFile()) { sc++; continue; }\r\n mtimeMs = fileStat.mtimeMs;\r\n } catch (error) { if (isNotFound(error)) continue; errors.push({ file, reason: errorMessage(error) }); sc++; continue; }\r\n if (mtimeMs > cutoff) { sc++; continue; }\r\n eligible.add(file);\r\n }\r\n\r\n const candidates: string[] = [];\r\n const allPartitions = await collectJournalPartitions(this.basePath);\r\n for (const family of groupPartitionsByFamily(allPartitions).values()) {\r\n for (const file of family) {\r\n if (file === activePath || !eligible.has(file)) break;\r\n candidates.push(file);\r\n eligible.delete(file);\r\n }\r\n }\r\n sc += eligible.size;\r\n\r\n if (!options.dryRun) {\r\n for (const file of candidates) {\r\n try {\r\n const familyBase = partitionFamilyBase(file);\r\n let deletedBytes: number | undefined;\r\n await withFileLock(familyBase, async () => {\r\n const fileStat = await fs.lstat(file);\r\n if (!fileStat.isFile() || fileStat.mtimeMs > cutoff) return;\r\n const entries = await readEntriesStrict(file);\r\n const checkpointResult = await readRetentionCheckpoint(familyBase);\r\n if (checkpointResult.error) throw new Error(checkpointResult.error);\r\n const checkpoint = checkpointResult.checkpoint;\r\n const nextCheckpoint = verifyRetainedPrefix(entries, checkpoint);\r\n if (!nextCheckpoint) throw new Error('partition does not extend the trusted Chronicle chain');\r\n if (nextCheckpoint.sequence > (checkpoint?.sequence ?? 0)) {\r\n await writeRetentionCheckpoint(familyBase, nextCheckpoint);\r\n }\r\n deletedBytes = fileStat.size;\r\n await fs.unlink(file);\r\n });\r\n if (deletedBytes === undefined) { sc++; break; }\r\n db += deletedBytes;\r\n dc++;\r\n } catch (error) {\r\n errors.push({ file, reason: errorMessage(error) });\r\n sc++;\r\n // Candidates form an oldest-first prefix. Do not advance the\r\n // checkpoint beyond a partition that could not be removed: if its\r\n // checkpoint-covered bytes remain on disk, verify() must still be\r\n // able to anchor and validate them against that checkpoint.\r\n break;\r\n }\r\n }\r\n }\r\n return { deletedCount: dc, deletedBytes: db, skippedCount: sc, errors, ...(options.dryRun ? { candidates } : {}) };\r\n }\r\n\r\n private async maybeAutoPurge(): Promise<void> {\r\n if (this.retentionDays <= 0) return;\r\n const n = Date.now();\r\n if (n - this.lastAutoPurgeAt < this.autoPurgeIntervalMs) return;\r\n this.lastAutoPurgeAt = n;\r\n try { await this.purge({ retentionDays: this.retentionDays }); } catch { /* best-effort */ }\r\n }\r\n\r\n private scheduleDrain(): void {\r\n if (this.drainScheduled || this.drainPromise) return;\r\n this.drainScheduled = true;\r\n this.drainTimer = setTimeout(() => { this.drainTimer = undefined; this.drainScheduled = false; this.startDrain(); }, this.batchWindowMs);\r\n }\r\n\r\n private startDrain(): void {\r\n if (this.drainPromise || this.pending.length === 0) return;\r\n const batch = this.pending.splice(0);\r\n const drain = this.persistBatch(batch);\r\n this.drainPromise = drain.finally(() => { this.drainPromise = undefined; if (this.pending.length > 0) this.scheduleDrain(); });\r\n }\r\n\r\n private async refreshStateFromDisk(): Promise<void> {\r\n const files = await collectPartitions(this.basePath);\r\n const latest = files[files.length - 1] ?? this.basePath;\r\n this.partitionIndex = partitionIndex(latest, this.basePath);\r\n const entry = await readLastEntry(latest);\r\n const checkpointResult = await readRetentionCheckpoint(this.basePath);\r\n if (checkpointResult.error) throw new Error(checkpointResult.error);\r\n const checkpoint = checkpointResult.checkpoint;\r\n this.lastSequence = entry?.sequence ?? checkpoint?.sequence ?? 0;\r\n this.lastHash = entry?.hash ?? checkpoint?.hash ?? GENESIS_HASH;\r\n try { this.partitionStartedAt = (await fs.stat(latest)).birthtimeMs; } catch { this.partitionStartedAt = Date.now(); }\r\n }\r\n\r\n private async checkRotation(): Promise<void> {\r\n if (this.partitionIndex === 0 && this.lastSequence === 0) return;\r\n if (Number.isFinite(this.rotationWindowMs) && Date.now() - this.partitionStartedAt >= this.rotationWindowMs) { this.rotate(); return; }\r\n if (Number.isFinite(this.maxPartitionSizeBytes)) { try { if ((await fs.stat(this.path)).size >= this.maxPartitionSizeBytes) this.rotate(); } catch { /* ok */ } }\r\n }\r\n\r\n private rotate(): void { this.partitionIndex++; this.partitionStartedAt = Date.now(); this.counters.partitionRolls++; }\r\n\r\n private async persistBatch(batch: typeof this.pending): Promise<void> {\r\n const started = performance.now();\r\n this.counters.batches++;\r\n this.counters.largestBatch = Math.max(this.counters.largestBatch, batch.length);\r\n try {\r\n await ensureDir(path.dirname(this.basePath));\r\n let recorded: ChronicleEvent[] = [];\r\n await withFileLock(this.basePath, async () => {\r\n await this.refreshStateFromDisk();\r\n await this.checkRotation();\r\n const cp = this.path;\r\n let prev: { sequence: number; hash: string } | undefined = this.lastSequence > 0 ? { sequence: this.lastSequence, hash: this.lastHash } : undefined;\r\n recorded = batch.map(({ input }) => {\r\n const instant = this.now().toISOString();\r\n const ni = removeUndefined(input) as unknown as ChronicleEventInput;\r\n const uh = { ...ni, occurredAt: input.occurredAt ?? instant, monotonicNs: input.monotonicNs ?? this.monotonicNow().toString(), schemaVersion: CHRONICLE_SCHEMA_VERSION, eventId: this.idFactory(), observedAt: instant, persistedAt: instant, sequence: (prev?.sequence ?? 0) + 1, previousHash: prev?.hash ?? GENESIS_HASH };\r\n const event: ChronicleEvent = { ...uh, hash: hashValue(uh) };\r\n prev = event;\r\n return event;\r\n });\r\n await fs.appendFile(cp, recorded.map((e) => JSON.stringify(e)).join('\\n') + '\\n', 'utf8');\r\n });\r\n const last = recorded[recorded.length - 1]!;\r\n this.lastSequence = last.sequence;\r\n this.lastHash = last.hash;\r\n batch.forEach((item, i) => { item.resolve(recorded[i]!); });\r\n this.counters.persistedEvents += batch.length;\r\n void this.maybeAutoPurge();\r\n } catch (error) {\r\n this.counters.failedEvents += batch.length;\r\n batch.forEach((item) => { item.reject(error); });\r\n } finally { this.lastBatchDurationMs = performance.now() - started; }\r\n }\r\n}\r\n\r\nfunction rotatedPath(basePath: string, index: number): string {\r\n const dir = path.dirname(basePath);\r\n const ext = path.extname(basePath);\r\n const base = path.basename(basePath, ext);\r\n return path.join(dir, `${base}.${String(index).padStart(5, '0')}${ext}`);\r\n}\r\n\r\nasync function collectPartitions(basePath: string): Promise<string[]> {\r\n const dir = path.dirname(basePath);\r\n const ext = path.extname(basePath);\r\n const base = path.basename(basePath, ext);\r\n const pattern = new RegExp(`^${escapeRegex(base)}(?:\\\\.\\\\d{5})?${escapeRegex(ext)}$`);\r\n const result: string[] = [];\r\n try {\r\n const entries = await fs.readdir(dir, { withFileTypes: true });\r\n for (const entry of entries) if (entry.isFile() && pattern.test(entry.name)) result.push(path.join(dir, entry.name));\r\n } catch { /* ok */ }\r\n const baseFile = path.join(dir, base + ext);\r\n const rotated = result.filter((file) => file !== baseFile).sort((left, right) => parseIndex(left, base, ext) - parseIndex(right, base, ext));\r\n return [baseFile, ...rotated];\r\n}\r\n\r\nasync function collectJournalPartitions(basePath: string): Promise<string[]> {\r\n const directory = path.dirname(basePath);\r\n const result: string[] = [];\r\n try {\r\n const entries = await fs.readdir(directory, { withFileTypes: true });\r\n for (const entry of entries) {\r\n const file = path.join(directory, entry.name);\r\n if (entry.isFile() && isJournalPartition(file, directory, basePath)) result.push(file);\r\n }\r\n } catch { /* ok */ }\r\n return result.sort(compareJournalPartitions);\r\n}\r\n\r\nfunction isJournalPartition(filePath: string, directory: string, basePath?: string): boolean {\r\n if (path.dirname(path.resolve(filePath)) !== path.resolve(directory)) return false;\r\n const fileName = path.basename(filePath);\r\n if (!basePath) return false;\r\n const baseName = path.basename(basePath);\r\n const dailyFamily = /^\\d{4}-\\d{2}-\\d{2}\\.events(?:\\.\\d{5})?\\.jsonl$/;\r\n if (/^\\d{4}-\\d{2}-\\d{2}\\.events\\.jsonl$/.test(baseName)) return dailyFamily.test(fileName);\r\n return partitionFamilyBase(path.resolve(filePath)) === partitionFamilyBase(path.resolve(basePath));\r\n}\r\n\r\nfunction compareJournalPartitions(left: string, right: string): number {\r\n const pattern = /^(.*\\.events)(?:\\.(\\d{5}))?\\.jsonl$/;\r\n const leftMatch = pattern.exec(path.basename(left));\r\n const rightMatch = pattern.exec(path.basename(right));\r\n const familyOrder = (leftMatch?.[1] ?? left).localeCompare(rightMatch?.[1] ?? right);\r\n return familyOrder || Number(leftMatch?.[2] ?? 0) - Number(rightMatch?.[2] ?? 0);\r\n}\r\n\r\nfunction groupPartitionsByFamily(files: string[]): Map<string, string[]> {\r\n const groups = new Map<string, string[]>();\r\n for (const file of files) {\r\n const family = partitionFamilyBase(file);\r\n const group = groups.get(family) ?? [];\r\n group.push(file);\r\n groups.set(family, group);\r\n }\r\n return groups;\r\n}\r\n\r\nfunction partitionFamilyBase(filePath: string): string {\r\n return filePath.replace(/\\.\\d{5}(?=\\.jsonl$)/, '');\r\n}\r\n\r\nfunction retentionCheckpointPath(basePath: string): string {\r\n return `${partitionFamilyBase(basePath)}.retention.json`;\r\n}\r\n\r\nfunction verifyRetainedPrefix(\r\n entries: ChronicleEvent[],\r\n checkpoint: ChronicleRetentionCheckpoint | undefined,\r\n): ChronicleRetentionCheckpoint | undefined {\r\n if (entries.length === 0) return undefined;\r\n let sequence = checkpoint?.sequence ?? 0;\r\n let hash = checkpoint?.hash ?? GENESIS_HASH;\r\n let advanced = false;\r\n for (const entry of entries) {\r\n if (entry.sequence <= sequence) continue;\r\n if (entry.sequence !== sequence + 1 || entry.previousHash !== hash) return undefined;\r\n const { hash: recordedHash, ...content } = entry;\r\n if (hashValue(content) !== recordedHash) return undefined;\r\n sequence = entry.sequence;\r\n hash = recordedHash;\r\n advanced = true;\r\n }\r\n if (!advanced) return checkpoint;\r\n return { version: RETENTION_CHECKPOINT_VERSION, sequence, hash };\r\n}\r\n\r\nasync function verifyPartitionFiles(\r\n files: string[],\r\n checkpoint: ChronicleRetentionCheckpoint | undefined,\r\n): Promise<ChronicleVerifyResult> {\r\n const checkpointSequence = checkpoint?.sequence ?? 0;\r\n let previousHash = checkpoint?.hash ?? GENESIS_HASH;\r\n let entries = 0;\r\n let lastSequence = checkpointSequence;\r\n let coveredPrevious: ChronicleEvent | undefined;\r\n for (const file of files) {\r\n let chunk: ChronicleEvent[];\r\n try { chunk = await readEntriesStrict(file); } catch (error) { return { ok: false, entries, brokenAt: entries, reason: errorMessage(error) }; }\r\n for (const entry of chunk) {\r\n const { hash: recordedHash, ...content } = entry;\r\n if (entry.sequence <= checkpointSequence) {\r\n // A checkpoint can be durably renamed just before its source\r\n // partition fails to unlink. Such retained bytes are still evidence:\r\n // validate them rather than treating every covered sequence as absent.\r\n if (hashValue(content) !== recordedHash) return { ok: false, entries, brokenAt: entries, reason: 'entry hash mismatch' };\r\n if (coveredPrevious && entry.sequence !== coveredPrevious.sequence + 1) {\r\n return { ok: false, entries, brokenAt: entries, reason: `sequence ${entry.sequence} is not ${coveredPrevious.sequence + 1}` };\r\n }\r\n if (coveredPrevious && entry.previousHash !== coveredPrevious.hash) {\r\n return { ok: false, entries, brokenAt: entries, reason: 'previous hash mismatch' };\r\n }\r\n if (entry.sequence === checkpointSequence && recordedHash !== checkpoint?.hash) {\r\n return { ok: false, entries, brokenAt: entries, reason: 'retention checkpoint hash mismatch' };\r\n }\r\n coveredPrevious = entry;\r\n continue;\r\n }\r\n const index = entries++;\r\n if (entry.sequence !== lastSequence + 1) return { ok: false, entries, brokenAt: index, reason: `sequence ${entry.sequence} is not ${lastSequence + 1}` };\r\n if (entry.previousHash !== previousHash) return { ok: false, entries, brokenAt: index, reason: 'previous hash mismatch' };\r\n if (hashValue(content) !== recordedHash) return { ok: false, entries, brokenAt: index, reason: 'entry hash mismatch' };\r\n previousHash = recordedHash;\r\n lastSequence = entry.sequence;\r\n }\r\n }\r\n if (\r\n coveredPrevious &&\r\n (coveredPrevious.sequence !== checkpointSequence || coveredPrevious.hash !== checkpoint?.hash)\r\n ) {\r\n return { ok: false, entries, brokenAt: entries, reason: 'retention checkpoint hash mismatch' };\r\n }\r\n return { ok: true, entries, lastSequence, lastHash: previousHash };\r\n}\r\n\r\nasync function readRetentionCheckpoint(basePath: string): Promise<{\r\n checkpoint?: ChronicleRetentionCheckpoint | undefined;\r\n error?: string | undefined;\r\n}> {\r\n const checkpointPath = retentionCheckpointPath(basePath);\r\n let raw: string;\r\n try { raw = await fs.readFile(checkpointPath, 'utf8'); } catch (error) {\r\n return isNotFound(error) ? {} : { error: `cannot read retention checkpoint: ${errorMessage(error)}` };\r\n }\r\n try {\r\n const parsed = JSON.parse(raw) as Partial<ChronicleRetentionCheckpoint>;\r\n if (parsed.version !== RETENTION_CHECKPOINT_VERSION || !Number.isSafeInteger(parsed.sequence) || (parsed.sequence ?? -1) < 0 || !isHash(parsed.hash)) {\r\n return { error: 'invalid Chronicle retention checkpoint' };\r\n }\r\n return { checkpoint: parsed as ChronicleRetentionCheckpoint };\r\n } catch { return { error: 'invalid Chronicle retention checkpoint JSON' }; }\r\n}\r\n\r\nasync function writeRetentionCheckpoint(basePath: string, checkpoint: ChronicleRetentionCheckpoint): Promise<void> {\r\n await atomicWrite(retentionCheckpointPath(basePath), `${JSON.stringify(checkpoint)}\\n`, { mode: 0o600 });\r\n}\r\n\r\nfunction isHash(value: unknown): value is string {\r\n return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);\r\n}\r\n\r\nfunction parseIndex(filePath: string, base: string, ext: string): number {\r\n const suffix = path.basename(filePath).slice(base.length + 1, -ext.length);\r\n return suffix ? parseInt(suffix, 10) : 0;\r\n}\r\n\r\nfunction partitionIndex(filePath: string, basePath: string): number {\r\n const ext = path.extname(basePath);\r\n return parseIndex(filePath, path.basename(basePath, ext), ext);\r\n}\r\n\r\nfunction escapeRegex(text: string): string { return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); }\r\n\r\nasync function readLastEntry(filePath: string): Promise<ChronicleEvent | undefined> {\r\n let handle: fs.FileHandle;\r\n try { handle = await fs.open(filePath, 'r'); } catch (error) { if (isNotFound(error)) return undefined; throw error; }\r\n try {\r\n const size = (await handle.stat()).size;\r\n let position = size, suffix = '';\r\n while (position > 0) {\r\n const length = Math.min(65536, position);\r\n position -= length;\r\n const buf = Buffer.allocUnsafe(length);\r\n await handle.read(buf, 0, length, position);\r\n suffix = buf.toString('utf8') + suffix;\r\n const lines = suffix.split('\\n');\r\n const start = position === 0 ? 0 : 1;\r\n for (let i = lines.length - 1; i >= start; i--) {\r\n const trimmed = lines[i]!.trim();\r\n if (!trimmed) continue;\r\n try { return JSON.parse(trimmed) as ChronicleEvent; } catch { /* scan earlier */ }\r\n }\r\n suffix = lines[0] ?? '';\r\n }\r\n return undefined;\r\n } finally { await handle.close(); }\r\n}\r\n\r\nasync function readEntriesStrict(filePath: string): Promise<ChronicleEvent[]> {\r\n let raw: string;\r\n try { raw = await fs.readFile(filePath, 'utf8'); } catch (error) { if (isNotFound(error)) return []; throw error; }\r\n const entries: ChronicleEvent[] = [];\r\n const lines = raw.split('\\n');\r\n for (let i = 0; i < lines.length; i++) {\r\n const trimmed = lines[i]!.trim();\r\n if (!trimmed) continue;\r\n try { entries.push(JSON.parse(trimmed) as ChronicleEvent); } catch { throw new Error(`invalid JSON at line ${i + 1} in ${path.basename(filePath)}`); }\r\n }\r\n return entries;\r\n}\r\n\r\nfunction hashValue(value: unknown): string { return createHash('sha256').update(stableStringify(value), 'utf8').digest('hex'); }\r\nfunction stableStringify(value: unknown): string {\r\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\r\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\r\n const obj = value as Record<string, unknown>;\r\n return `{${Object.keys(obj).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')}}`;\r\n}\r\nfunction removeUndefined(value: unknown): unknown {\r\n if (Array.isArray(value)) return value.map((item) => item === undefined ? null : removeUndefined(item));\r\n if (value === null || typeof value !== 'object') return value;\r\n const result: Record<string, unknown> = {};\r\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) if (item !== undefined) result[key] = removeUndefined(item);\r\n return result;\r\n}\r\nfunction isNotFound(error: unknown): boolean { return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'; }\r\nfunction errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); }\r\n\r\nexport { GENESIS_HASH };\r\n", "import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport { watch as watchDir } from 'node:fs';\nimport type { FSWatcher } from 'node:fs';\nimport * as path from 'node:path';\nimport { FsError } from '../types/errors.js';\n\nexport interface AtomicWriteOptions {\n mode?: number | undefined;\n encoding?: BufferEncoding | undefined;\n}\n\nexport interface FileLockOptions {\n timeoutMs?: number | undefined;\n staleMs?: number | undefined;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists \u2014 extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n // P3 #20 (before-release.md): on Windows, fs.rename (MoveFileExW) does\n // not preserve Unix permission bits \u2014 the chmod above applies to the tmp\n // file, but the rename may reset the destination's mode to the Windows\n // default. Re-apply the mode after rename on win32 so an edited file\n // keeps its executable bit (or any non-default permission). On POSIX,\n // rename preserves metadata so this is a no-op (chmod is idempotent and\n // cheap), but we gate it on win32 to avoid the extra stat+chmod on the\n // common path.\n if (mode !== undefined && process.platform === 'win32') {\n try {\n await fs.chmod(targetPath, mode);\n } catch {\n // Best-effort: a transient EPERM (antivirus lock) should not fail\n // the write \u2014 the content is already on disk.\n }\n }\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\nexport async function withFileLock<T>(\n targetPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const lockPath = path.join(dir, `.${path.basename(targetPath)}.lock`);\n // A lock holder can be scheduled out for several seconds when the full test\n // suite (or a busy workstation) is spawning many child processes. Five\n // seconds was short enough to turn ordinary contention into a dropped\n // best-effort index write. Keep the wait bounded, but leave enough headroom\n // for the holder to resume and release before stale-lock recovery applies.\n const timeoutMs = opts.timeoutMs ?? 15_000;\n const staleMs = opts.staleMs ?? 30_000;\n const started = Date.now();\n let handle: fs.FileHandle | undefined;\n\n for (;;) {\n try {\n handle = await fs.open(lockPath, 'wx');\n await handle.writeFile(`${process.pid}:${Date.now()}`);\n break;\n } catch (err) {\n // If fs.open succeeded but handle.writeFile threw (e.g. ENOSPC, EIO),\n // `handle` owns an open exclusive lock file. Close the handle and remove\n // the orphan lock so the next iteration (or a peer) can acquire it\n // without timing out on the stale-lock window or dead-looping on EEXIST.\n if (handle) {\n await handle.close().catch(() => {});\n await fs.unlink(lockPath).catch(() => {});\n handle = undefined;\n }\n const code = (err as NodeJS.ErrnoException).code;\n // ENOENT means the directory was deleted (e.g. by concurrent cleanup).\n // Recreate it and retry acquiring the lock.\n if (code === 'ENOENT') {\n await fs.mkdir(dir, { recursive: true });\n continue;\n }\n if (code !== 'EEXIST' && code !== 'EPERM') throw err;\n try {\n const stat = await fs.stat(lockPath);\n if (Date.now() - stat.mtimeMs > staleMs) {\n await fs.unlink(lockPath);\n continue;\n }\n } catch {\n continue;\n }\n const elapsed = Date.now() - started;\n if (elapsed >= timeoutMs) {\n throw new FsError({\n message: `Timed out waiting for file lock: ${targetPath}`,\n code: 'FS_ATOMIC_WRITE_FAILED',\n path: targetPath,\n context: { timeoutMs },\n });\n }\n // Wait for the lock to be released, using a filesystem watcher for\n // nearly-instant wake-up instead of polling. The watcher is best-effort:\n // a safety timeout fires at most every 100ms so we don't busy-wait.\n await waitForLockRelease(lockPath, timeoutMs - elapsed);\n }\n }\n\n try {\n return await fn();\n } finally {\n try {\n await handle?.close();\n } catch {\n // ignore\n }\n try {\n await fs.unlink(lockPath);\n } catch {\n // ignore\n }\n }\n}\n\n/**\n * Watch a lock file's parent directory for the file being removed (unlinked),\n * which signals that the lock holder has released it. A safety timeout caps\n * the wait so the overall `withFileLock` timeout is always respected.\n *\n * Uses a bounded safety interval (up to 100ms) so even if `fs.watch` is\n * unavailable or misses the event, we never busy-wait at 25ms fixed polling.\n */\nasync function waitForLockRelease(lockPath: string, remainingMs: number): Promise<void> {\n const parentDir = path.dirname(lockPath);\n const lockName = path.basename(lockPath);\n const intervalMs = Math.min(remainingMs, 100);\n\n return new Promise<void>((resolve) => {\n let settled = false;\n let watcher: FSWatcher | null = null;\n\n // Safety timer \u2014 always fires, even if fs.watch is unavailable.\n const timer = setTimeout(() => {\n settled = true;\n watcher?.close();\n resolve();\n }, intervalMs);\n\n try {\n watcher = watchDir(parentDir, (eventType, filename) => {\n if (settled) return;\n // 'rename' fires on unlink on most platforms; 'change' is a\n // conservative fallback for environments that only emit 'change'.\n if (filename === lockName && (eventType === 'rename' || eventType === 'change')) {\n settled = true;\n clearTimeout(timer);\n watcher?.close();\n resolve();\n }\n });\n } catch {\n // fs.watch not supported (e.g. some container environments, network\n // filesystems). Clear the safety timer and fall back to a single\n // short delay \u2014 the caller's loop will retry on the next iteration.\n clearTimeout(timer);\n if (!settled) {\n settled = true;\n setTimeout(resolve, Math.min(remainingMs, 25));\n }\n return;\n }\n\n // Re-check lock existence after setting up the watch to close the race\n // where the lock was released between our last EEXIST check and now.\n fs.access(lockPath).then(\n () => {\n // Lock still exists \u2014 the watch (or safety timer) will resolve.\n },\n () => {\n // Lock was already released \u2014 respond immediately.\n if (!settled) {\n settled = true;\n clearTimeout(timer);\n watcher?.close();\n resolve();\n }\n },\n );\n });\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient \u2014 retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n", "import { toErrorMessage } from '../utils/index.js';\n\n/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// \u2500\u2500 Error codes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // SDD (Spec-Driven Development)\n SDD_VALIDATION_FAILED: 'SDD_VALIDATION_FAILED',\n SDD_PARSE_FAILED: 'SDD_PARSE_FAILED',\n SDD_INVALID_STATE: 'SDD_INVALID_STATE',\n SDD_NOT_READY: 'SDD_NOT_READY',\n // General\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n PARSE_FAILED: 'PARSE_FAILED',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` \u2014 no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'sdd'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// \u2500\u2500 Base error class \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown> | undefined;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity | undefined;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// \u2500\u2500 Specific error classes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Tool execution errors \u2014 thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors \u2014 thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = toErrorMessage(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * SDD (Spec-Driven Development) errors \u2014 spec validation, parsing, and\n * state machine violations in the AISpecBuilder, TaskFlow, and TaskTracker.\n */\nexport class SddError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'SDD_VALIDATION_FAILED' | 'SDD_PARSE_FAILED' | 'SDD_INVALID_STATE' | 'SDD_NOT_READY'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'sdd',\n severity: opts.code === ERROR_CODES.SDD_PARSE_FAILED ? 'warning' : 'error',\n recoverable: opts.code === ERROR_CODES.SDD_NOT_READY,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'SddError';\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n/**\n * HTTP fetch error \u2014 thrown when a network request returns a non-OK status.\n * Carries the response status so {@link classifyToolError} can branch on it\n * (429 \u2192 transient, 404 \u2192 not_found, 401 \u2192 permission) without duck-typing\n * the error via `'response' in err`.\n *\n * P3 #18 (before-release.md): the previous `'response' in err` check caught\n * any Error with a `response` property, including custom errors, proxy\n * objects, or mocked errors in tests. `instanceof FetchError` is reliable.\n *\n * Tools and providers that make HTTP requests and need the executor to\n * classify their failures should throw `new FetchError({ status, message })`\n * instead of a bare `Error` with an ad-hoc `response` field.\n */\nexport class FetchError extends WrongStackError {\n readonly status: number;\n\n constructor(opts: {\n message: string;\n status: number;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.VALIDATION_ERROR,\n subsystem: 'general',\n severity: 'error',\n recoverable: opts.status === 429 || opts.status >= 500,\n context: { status: opts.status, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FetchError';\n this.status = opts.status;\n }\n}\n\n/**\n * Tool input validation error \u2014 thrown when a tool's input fails a validation\n * check that the JSON Schema cannot express (e.g. `old_string === new_string`\n * in edit, or a cross-field invariant). Use this instead of a bare\n * `throw new Error('...validation...')` so {@link classifyToolError} can\n * match on `instanceof` rather than a locale-dependent message substring.\n *\n * P2 #6 (before-release.md): the previous `err.message.includes('validation')`\n * check misclassified any error whose message happened to contain \"validation\"\n * (e.g. a third-party \"input validation timeout\") as a VALIDATION error.\n *\n * Named `ToolValidationError` (not `ValidationError`) to avoid colliding with\n * the existing `ValidationError` interface exported by json-schema-validate.ts\n * (a validation-result shape, not an Error subclass).\n */\nexport class ToolValidationError extends WrongStackError {\n constructor(opts: {\n message: string;\n /** Field path or tool name that failed validation, for diagnostics. */\n field?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.VALIDATION_ERROR,\n subsystem: 'general',\n severity: 'error',\n recoverable: false,\n context: { field: opts.field, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolValidationError';\n }\n}\n\n/**\n * Response / payload parse error \u2014 thrown when an upstream HTTP response,\n * file, or data structure is well-formed at the transport layer (HTTP 200,\n * valid JSON) but is missing required fields or has an unexpected shape.\n *\n * Distinct from `ConfigError(CONFIG_PARSE_FAILED)` (which is specifically\n * for config-file parsing) and `FetchError` (which covers HTTP non-OK\n * responses). `ParseError` fills the gap: the request succeeded but the\n * response body couldn't be interpreted.\n *\n * Common sites: OAuth token responses missing `access_token`, device-code\n * responses missing `device_code`, registry responses with unexpected\n * schemas.\n */\nexport class ParseError extends WrongStackError {\n readonly source?: string | undefined;\n\n constructor(opts: {\n message: string;\n /**\n * What was being parsed \u2014 e.g. `'oauth-token-response'`,\n * `'device-code-response'`. Lets consumers distinguish parse failures\n * from different upstream APIs without parsing the message.\n */\n source?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.PARSE_FAILED,\n subsystem: 'general',\n severity: 'error',\n recoverable: false,\n context: { source: opts.source, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ParseError';\n this.source = opts.source;\n }\n}\n\n// \u2500\u2500 Type guards \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n\nexport function isToolValidationError(err: unknown): err is ToolValidationError {\n return err instanceof ToolValidationError;\n}\n\nexport function isFetchError(err: unknown): err is FetchError {\n return err instanceof FetchError;\n}\n\nexport function isParseError(err: unknown): err is ParseError {\n return err instanceof ParseError;\n}\n\nexport function isSddError(err: unknown): err is SddError {\n return err instanceof SddError;\n}\n", "/** Schema version for the first durable WrongStack Chronicle event envelope. */\nexport const CHRONICLE_SCHEMA_VERSION = 1 as const;\n\nexport type ChronicleOutcome =\n | 'started'\n | 'success'\n | 'failure'\n | 'cancelled'\n | 'denied'\n | 'abandoned'\n | 'unknown';\n\n/** Stable identities used to project one event into global and project views. */\nexport interface ChronicleScope {\n installationId: string;\n machineId: string;\n projectId?: string | undefined;\n repositoryId?: string | undefined;\n workspaceId?: string | undefined;\n worktreeId?: string | undefined;\n sessionId?: string | undefined;\n turnId?: string | undefined;\n iterationId?: string | undefined;\n agentId?: string | undefined;\n goalId?: string | undefined;\n planId?: string | undefined;\n taskId?: string | undefined;\n kanbanBoardId?: string | undefined;\n}\n\nexport interface ChronicleCorrelation {\n traceId: string;\n spanId: string;\n parentSpanId?: string | undefined;\n logicalRequestId?: string | undefined;\n attemptId?: string | undefined;\n toolCallId?: string | undefined;\n}\n\nexport interface ChronicleRuntimeIdentity {\n providerId?: string | undefined;\n modelId?: string | undefined;\n modelRevision?: string | undefined;\n processId?: number | undefined;\n parentProcessId?: number | undefined;\n}\n\nexport interface ChronicleResourceRef {\n kind: 'file' | 'symbol' | 'memory' | 'task' | 'kanban' | 'process' | 'network' | 'artifact' | 'other';\n id: string;\n path?: string | undefined;\n lineStart?: number | undefined;\n lineEnd?: number | undefined;\n contentHashBefore?: string | undefined;\n contentHashAfter?: string | undefined;\n}\n\nexport interface ChronicleEventInput {\n eventType: string;\n scope: ChronicleScope;\n correlation: ChronicleCorrelation;\n runtime?: ChronicleRuntimeIdentity | undefined;\n resource?: ChronicleResourceRef | undefined;\n outcome?: ChronicleOutcome | undefined;\n durationNs?: string | undefined;\n occurredAt?: string | undefined;\n monotonicNs?: string | undefined;\n attributes?: Record<string, unknown> | undefined;\n tags?: Record<string, string> | undefined;\n}\n\n/**\n * Lossless durable envelope. All wall-clock timestamps are UTC ISO-8601;\n * monotonicNs is used for elapsed-time ordering inside one process.\n */\nexport interface ChronicleEvent extends ChronicleEventInput {\n schemaVersion: typeof CHRONICLE_SCHEMA_VERSION;\n eventId: string;\n observedAt: string;\n persistedAt: string;\n sequence: number;\n previousHash: string;\n hash: string;\n}\n\nexport type ChronicleVerifyResult =\n | { ok: true; entries: number; lastSequence: number; lastHash: string }\n | { ok: false; entries: number; brokenAt: number; reason: string };\n", "import type { EventBus, EventMap } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleProviderAdapterOptions {\n events: EventBus;\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\n/** Persist provider attempt facts without coupling the provider runner to storage. */\nexport function wireProviderAttemptsToChronicle(options: ChronicleProviderAdapterOptions): () => void {\n const unsubs = [\n options.events.on('provider.attempt.started', (event) => persist(options, event, {\n eventType: 'provider.attempt.started',\n outcome: 'started',\n occurredAt: event.startedAt,\n })),\n options.events.on('provider.attempt.completed', (event) => persist(options, event, {\n eventType: 'provider.attempt.completed',\n outcome: 'success',\n occurredAt: event.endedAt,\n durationNs: millisecondsToNanoseconds(event.durationMs),\n })),\n options.events.on('provider.attempt.failed', (event) => persist(options, event, {\n eventType: 'provider.attempt.failed',\n outcome: 'failure',\n occurredAt: event.endedAt,\n durationNs: millisecondsToNanoseconds(event.durationMs),\n })),\n ];\n return () => unsubs.forEach((unsubscribe) => { unsubscribe(); });\n}\n\ntype ProviderAttemptEvent =\n | EventMap['provider.attempt.started']\n | EventMap['provider.attempt.completed']\n | EventMap['provider.attempt.failed'];\n\nfunction persist(\n options: ChronicleProviderAdapterOptions,\n event: ProviderAttemptEvent,\n base: Pick<ChronicleEventInput, 'eventType' | 'outcome' | 'occurredAt' | 'durationNs'>,\n): void {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const input: ChronicleEventInput = {\n ...base,\n scope: {\n ...context.scope,\n sessionId: event.sessionId,\n ...(event.agentId ? { agentId: event.agentId } : {}),\n },\n correlation: {\n ...context.correlation,\n ...(event.traceId ? { traceId: event.traceId } : {}),\n logicalRequestId: event.logicalRequestId,\n attemptId: event.attemptId,\n },\n runtime: { providerId: event.providerId, modelId: event.model },\n attributes: providerAttributes(event),\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n}\n\nfunction providerAttributes(event: ProviderAttemptEvent): Record<string, unknown> {\n const { sessionId: _sessionId, traceId: _traceId, agentId: _agentId, providerId: _providerId,\n model: _model, logicalRequestId: _logicalRequestId, attemptId: _attemptId, ...attributes } = event;\n return attributes;\n}\n\nfunction millisecondsToNanoseconds(durationMs: number): string {\n return Math.round(durationMs * 1_000_000).toString();\n}\n", "import { createHash } from 'node:crypto';\nimport type { EventBus, EventMap } from '../kernel/events.js';\nimport type { SecretScrubber } from '../types/secret-scrubber.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput, ChronicleResourceRef } from './types.js';\n\nexport interface ChronicleToolAdapterOptions {\n events: EventBus;\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n scrubber: SecretScrubber;\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\n/** Persist the complete tool lifecycle plus resource edges discovered in results. */\nexport function wireToolsToChronicle(options: ChronicleToolAdapterOptions): () => void {\n const unsubs = [\n options.events.on('tool.started', (event) => {\n const input = scrubValue(options.scrubber, event.input);\n persist(options, event, {\n eventType: 'tool.started',\n outcome: 'started',\n attributes: {\n toolName: event.name,\n input,\n inputHash: hashText(input),\n },\n });\n }),\n options.events.on('tool.executed', (event) => {\n const output = options.scrubber.scrub(event.output ?? '');\n persist(options, event, {\n eventType: 'tool.executed',\n outcome: event.ok ? 'success' : 'failure',\n durationNs: millisecondsToNanoseconds(event.durationMs),\n attributes: {\n toolName: event.name,\n ok: event.ok,\n outputPreview: output,\n outputHash: hashText(output),\n outputBytes: event.outputBytes,\n outputTokens: event.outputTokens,\n outputLines: event.outputLines,\n metadata: event.metadata,\n },\n });\n persistEvidenceEdges(options, event);\n }),\n options.events.on('tool.failed', (event) => persist(options, event, {\n eventType: 'tool.failed',\n outcome: 'failure',\n durationNs: millisecondsToNanoseconds(event.durationMs),\n attributes: {\n toolName: event.name,\n category: event.category,\n retryable: event.retryable,\n detail: event.detail,\n errorCode: event.errorCode,\n errorSubsystem: event.errorSubsystem,\n errorSeverity: event.errorSeverity,\n },\n })),\n options.events.on('tool.progress', (event) => {\n if (event.event.type !== 'file_changed') return;\n const resource = progressResource(event);\n persist(options, event, {\n eventType: 'file.mutation.observed',\n outcome: 'started',\n ...(resource ? { resource } : {}),\n attributes: {\n toolName: event.name,\n progressType: event.event.type,\n text: options.scrubber.scrub(event.event.text ?? ''),\n data: scrubValue(options.scrubber, event.event.data),\n operation: event.event.operation,\n },\n });\n }),\n ];\n return () => unsubs.forEach((unsubscribe) => { unsubscribe(); });\n}\n\ntype ToolCorrelationEvent = {\n sessionId?: string | undefined;\n traceId?: string | undefined;\n agentId?: string | undefined;\n id?: string | undefined;\n name: string;\n};\n\nfunction persist(\n options: ChronicleToolAdapterOptions,\n event: ToolCorrelationEvent,\n fields: Pick<ChronicleEventInput, 'eventType' | 'outcome'> &\n Partial<Pick<ChronicleEventInput, 'durationNs' | 'resource' | 'attributes'>>,\n): void {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const input: ChronicleEventInput = {\n ...fields,\n scope: {\n ...context.scope,\n ...(event.sessionId ? { sessionId: event.sessionId } : {}),\n ...(event.agentId ? { agentId: event.agentId } : {}),\n },\n correlation: {\n ...context.correlation,\n ...(event.traceId ? { traceId: event.traceId } : {}),\n ...(event.id ? { toolCallId: event.id } : {}),\n },\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n}\n\nfunction persistEvidenceEdges(\n options: ChronicleToolAdapterOptions,\n event: EventMap['tool.executed'],\n): void {\n const metadata = event.metadata;\n if (!metadata) return;\n for (const file of metadata.files) {\n persist(options, event, {\n eventType: 'tool.resource.observed',\n outcome: event.ok ? 'success' : 'failure',\n resource: { kind: 'file', id: resourceId('file', file), path: file },\n attributes: { relation: 'observed', toolName: event.name, evidenceStatus: metadata.status },\n });\n }\n for (const symbol of metadata.symbols) {\n persist(options, event, {\n eventType: 'tool.resource.observed',\n outcome: event.ok ? 'success' : 'failure',\n resource: { kind: 'symbol', id: resourceId('symbol', symbol) },\n attributes: { relation: 'observed', toolName: event.name, symbol },\n });\n }\n for (const command of metadata.commands) {\n persist(options, event, {\n eventType: 'tool.resource.observed',\n outcome: event.ok ? 'success' : 'failure',\n resource: { kind: 'process', id: resourceId('command', command) },\n attributes: { relation: 'invoked', toolName: event.name, command: options.scrubber.scrub(command) },\n });\n }\n}\n\nfunction progressResource(event: EventMap['tool.progress']): ChronicleResourceRef | undefined {\n if (event.event.type !== 'file_changed' || !event.event.path) return undefined;\n return {\n kind: 'file',\n id: resourceId('file', event.event.path),\n path: event.event.path,\n ...(event.event.line !== undefined ? { lineStart: event.event.line } : {}),\n ...(event.event.endLine !== undefined ? { lineEnd: event.event.endLine } : {}),\n };\n}\n\nfunction scrubValue(scrubber: SecretScrubber, value: unknown): string {\n if (value === undefined) return '';\n try {\n return scrubber.scrub(JSON.stringify(value));\n } catch {\n return scrubber.scrub(String(value));\n }\n}\n\nfunction resourceId(kind: string, value: string): string {\n return `${kind}_${hashText(value).slice(0, 24)}`;\n}\n\nfunction hashText(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction millisecondsToNanoseconds(durationMs: number): string {\n return Math.round(durationMs * 1_000_000).toString();\n}\n", "import { createHash } from 'node:crypto';\nimport type { EventBus, EventMap } from '../kernel/events.js';\nimport type { SecretScrubber } from '../types/secret-scrubber.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleProcessAdapterOptions {\n events: EventBus;\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n scrubber: SecretScrubber;\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\nexport function wireProcessesToChronicle(options: ChronicleProcessAdapterOptions): () => void {\n const unsubs = [\n options.events.on('process.started', (event) => persist(options, event, {\n eventType: 'process.started',\n outcome: 'started',\n occurredAt: event.startedAt,\n attributes: {\n command: options.scrubber.scrub(event.command),\n args: event.args.map((arg) => options.scrubber.scrub(arg)),\n cwd: event.cwd,\n parentPid: event.parentPid,\n background: event.background,\n },\n })),\n options.events.on('process.completed', (event) => persist(options, event, {\n eventType: 'process.completed',\n outcome: event.exitCode === 0 ? 'success' : event.timedOut ? 'cancelled' : 'failure',\n occurredAt: event.endedAt,\n durationNs: Math.round(event.durationMs * 1_000_000).toString(),\n attributes: {\n exitCode: event.exitCode,\n signal: event.signal,\n stdoutBytes: event.stdoutBytes,\n stderrBytes: event.stderrBytes,\n timedOut: event.timedOut,\n },\n })),\n ];\n return () => unsubs.forEach((unsubscribe) => { unsubscribe(); });\n}\n\ntype ProcessEvent =\n | EventMap['process.started']\n | EventMap['process.completed'];\n\nfunction persist(\n options: ChronicleProcessAdapterOptions,\n event: ProcessEvent,\n fields: Pick<ChronicleEventInput, 'eventType' | 'outcome' | 'occurredAt'> &\n Partial<Pick<ChronicleEventInput, 'durationNs' | 'attributes'>>,\n): void {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const processKey = `${event.sessionId}\\0${event.pid ?? 'unknown'}\\0${event.toolCallId}`;\n const input: ChronicleEventInput = {\n ...fields,\n scope: {\n ...context.scope,\n sessionId: event.sessionId,\n ...(event.agentId ? { agentId: event.agentId } : {}),\n },\n correlation: {\n ...context.correlation,\n ...(event.traceId ? { traceId: event.traceId } : {}),\n toolCallId: event.toolCallId,\n },\n runtime: {\n ...(event.pid !== undefined ? { processId: event.pid } : {}),\n ...('parentPid' in event ? { parentProcessId: event.parentPid } : {}),\n },\n resource: {\n kind: 'process',\n id: `process_${createHash('sha256').update(processKey).digest('hex').slice(0, 24)}`,\n },\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n}\n", "import { monitorEventLoopDelay, performance } from 'node:perf_hooks';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\n\nexport interface ChronicleHealthMonitorOptions {\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n intervalMs?: number | undefined;\n onPersistError?: ((error: unknown) => void) | undefined;\n}\n\n/** Low-frequency self-observation proving that telemetry is not starving the runtime. */\nexport function startChronicleHealthMonitor(options: ChronicleHealthMonitorOptions): () => void {\n const intervalMs = Math.max(5_000, options.intervalMs ?? 30_000);\n const delay = monitorEventLoopDelay({ resolution: 20 });\n delay.enable();\n let previousCpu = process.cpuUsage();\n let previousElu = performance.eventLoopUtilization();\n\n const sample = (): void => {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const memory = process.memoryUsage();\n const cpu = process.cpuUsage(previousCpu);\n previousCpu = process.cpuUsage();\n const elu = performance.eventLoopUtilization(previousElu);\n previousElu = performance.eventLoopUtilization();\n const journalBeforeSample = options.journal.stats();\n void options.journal.append({\n eventType: 'runtime.health.sampled', scope: context.scope, correlation: context.correlation,\n runtime: { processId: process.pid, parentProcessId: process.ppid }, outcome: 'success',\n resource: { kind: 'process', id: `process:${process.pid}` },\n attributes: {\n uptimeSeconds: process.uptime(),\n eventLoop: { utilization: elu.utilization, activeMs: elu.active, idleMs: elu.idle,\n delayMeanMs: Number(delay.mean) / 1e6, delayP95Ms: Number(delay.percentile(95)) / 1e6,\n delayMaxMs: Number(delay.max) / 1e6 },\n cpu: { userMicros: cpu.user, systemMicros: cpu.system },\n memory: { rssBytes: memory.rss, heapTotalBytes: memory.heapTotal,\n heapUsedBytes: memory.heapUsed, externalBytes: memory.external, arrayBuffersBytes: memory.arrayBuffers },\n chronicle: journalBeforeSample,\n },\n }).catch((error) => options.onPersistError?.(error));\n delay.reset();\n };\n\n const timer = setInterval(sample, intervalMs);\n timer.unref?.();\n return () => { clearInterval(timer); delay.disable(); };\n}\n", "import { createHash } from 'node:crypto';\nimport type { BrainDecision, BrainDecisionRequest } from '../coordination/brain.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleDecisionAdapterOptions {\n events: EventBus; journal: ChronicleJournal; context: ChronicleContext | (() => ChronicleContext);\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\n/** Decision provenance without persisting raw questions, context or rationale. */\nexport function wireDecisionsToChronicle(options: ChronicleDecisionAdapterOptions): () => void {\n const write = (eventType: string, at: number, sessionId: string | undefined, requestId: string,\n attributes: Record<string, unknown>, outcome: ChronicleEventInput['outcome']): void => {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const input: ChronicleEventInput = { eventType, occurredAt: new Date(at).toISOString(), outcome,\n scope: { ...context.scope, ...(sessionId ? { sessionId } : {}) }, correlation: context.correlation,\n resource: { kind: 'other', id: `decision:${requestId}` }, attributes: { decisionId: requestId, ...attributes } };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n };\n const requestAttrs = (request: BrainDecisionRequest) => ({ source: request.source, risk: request.risk,\n fallback: request.fallback, questionHash: hash(request.question), contextHash: hash(request.context),\n optionCount: request.options?.length ?? 0,\n options: request.options?.map((option) => ({ id: option.id, risk: option.risk,\n recommended: option.recommended ?? false, labelHash: hash(option.label), consequenceHash: hash(option.consequence) })) });\n const decisionAttrs = (decision: BrainDecision) => ({ type: decision.type,\n ...('optionId' in decision && decision.optionId ? { optionId: decision.optionId } : {}),\n contentHash: hash('text' in decision ? decision.text : 'prompt' in decision ? decision.prompt : decision.reason),\n rationaleHash: hash('rationale' in decision ? decision.rationale : undefined) });\n\n const offs = [\n options.events.on('brain.decision_requested', (e) => write('decision.requested', e.at, e.sessionId, e.request.id, requestAttrs(e.request), 'started')),\n options.events.on('brain.decision_answered', (e) => write('decision.resolved', e.at, e.sessionId, e.request.id, { ...requestAttrs(e.request), ...decisionAttrs(e.decision), resolver: 'brain' }, 'success')),\n options.events.on('brain.decision_ask_human', (e) => write('decision.escalated', e.at, e.sessionId, e.request.id, { ...requestAttrs(e.request), ...decisionAttrs(e.decision) }, 'started')),\n options.events.on('brain.decision_denied', (e) => write('decision.denied', e.at, e.sessionId, e.request.id, { ...requestAttrs(e.request), ...decisionAttrs(e.decision) }, 'denied')),\n options.events.on('brain.human_answered', (e) => write('decision.human_answered', e.at, e.sessionId, e.id, { resolver: 'human', optionId: e.optionId, denied: e.deny ?? false, answerHash: hash(e.text) }, e.deny ? 'denied' : 'success')),\n options.events.on('brain.outcome', (e) => write('decision.outcome_observed', e.at, e.sessionId, e.requestId, { observedOutcome: e.outcome, detailHash: hash(e.detail) }, e.outcome)),\n ];\n return () => offs.forEach((off) => { off(); });\n}\n\nfunction hash(value: string | undefined): string | undefined {\n return value ? createHash('sha256').update(value).digest('hex') : undefined;\n}\n", "import { createHash } from 'node:crypto';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput, ChronicleOutcome, ChronicleResourceRef } from './types.js';\n\nexport interface ChronicleDomainAdapterOptions {\n events: EventBus; journal: ChronicleJournal; context: ChronicleContext | (() => ChronicleContext);\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\nconst SPECIALIZED = [\n /^provider\\.attempt\\./, /^tool\\./, /^process\\./, /^brain\\.decision_/,\n /^brain\\.human_answered$/, /^brain\\.outcome$/, /^file\\.activity$/,\n /^provider\\.(?:text_delta|thinking_delta)$/,\n /^(?:ctx\\.pct|subagent\\.ctx_pct|countdown\\.tick|coordinator\\.stats)$/,\n];\n/**\n * Only domains that can improve coding decisions, provenance, reliability or\n * resource/cost control belong in Chronicle. UI presence, navigation and other\n * product-engagement events are intentionally not captured by this bridge.\n */\nconst CODING_SIGNAL = [\n /^(?:agent|subagent|delegate|fleet)\\./,\n /^(?:session|iteration|context|compaction|checkpoint|in_flight)\\./,\n /^(?:memory|storage|trust)\\./,\n /^(?:sdd|worktree)\\./,\n /^(?:brain|token|budget|concurrency)\\./,\n /^(?:provider|mcp|network)\\./,\n /^error$/,\n];\nconst SENSITIVE_KEY = /(content|text|prompt|question|rationale|reason|detail|summary|description|context|input|output|error|message|secret|token|password|key)$/i;\nconst PRESERVE_STRING_KEY = /(^|_)(id|status|state|kind|type|source|model|provider|phase|risk|fallback|path|name|role|sha|branch|mode)$/i;\n/** Known metadata arrays that carry unbounded accumulated state (mail, tool\n * history, commands). Chronicle only needs the most recent entries. */\nconst TRUNCATED_ARRAYS = new Set(['recentMail', 'recentTools', 'recentCommands']);\nconst TRUNCATED_ARRAY_MAX = 5;\n/** General array cap \u2014 enough for agent lists, file lists etc. without\n * allowing unbounded growth through any array-shaped event field. */\nconst DEFAULT_ARRAY_MAX = 20;\n\n/** Allowlisted coding-signal bridge for domains not owned by a richer adapter. */\nexport function wireDomainEventsToChronicle(options: ChronicleDomainAdapterOptions): () => void {\n return options.events.onAny((eventName, payload) => {\n if (SPECIALIZED.some((pattern) => pattern.test(eventName))) return;\n if (!CODING_SIGNAL.some((pattern) => pattern.test(eventName))) return;\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const record = objectPayload(payload);\n const sessionId = stringField(record, 'sessionId');\n const agentId = stringField(record, 'agentId') ?? stringField(record, 'subagentId');\n const taskId = stringField(record, 'taskId');\n const input: ChronicleEventInput = {\n eventType: eventName,\n occurredAt: eventTime(record),\n scope: { ...context.scope, ...(sessionId ? { sessionId } : {}), ...(agentId ? { agentId } : {}), ...(taskId ? { taskId } : {}) },\n correlation: {\n ...context.correlation,\n ...(stringField(record, 'traceId') ? { traceId: stringField(record, 'traceId')! } : {}),\n ...(stringField(record, 'toolCallId') ? { toolCallId: stringField(record, 'toolCallId') } : {}),\n ...(stringField(record, 'attemptId') ? { attemptId: stringField(record, 'attemptId') } : {}),\n ...(stringField(record, 'logicalRequestId') ? { logicalRequestId: stringField(record, 'logicalRequestId') } : {}),\n },\n outcome: inferOutcome(eventName, record),\n runtime: {\n ...(stringField(record, 'providerId') ?? stringField(record, 'provider') ? { providerId: stringField(record, 'providerId') ?? stringField(record, 'provider') } : {}),\n ...(stringField(record, 'modelId') ?? stringField(record, 'model') ? { modelId: stringField(record, 'modelId') ?? stringField(record, 'model') } : {}),\n },\n resource: inferResource(record),\n attributes: sanitize(record) as Record<string, unknown>,\n tags: { collector: 'eventbus-domain', family: eventName.split('.')[0] ?? 'unknown' },\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n });\n}\n\nfunction objectPayload(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' ? value as Record<string, unknown> : { value };\n}\nfunction stringField(value: Record<string, unknown>, key: string): string | undefined {\n return typeof value[key] === 'string' ? value[key] as string : undefined;\n}\nfunction eventTime(value: Record<string, unknown>): string | undefined {\n const raw = value.at ?? value.ts ?? value.timestamp;\n if (typeof raw === 'number' && Number.isFinite(raw)) return new Date(raw).toISOString();\n if (typeof raw === 'string' && Number.isFinite(Date.parse(raw))) return new Date(raw).toISOString();\n return undefined;\n}\nfunction inferOutcome(name: string, payload: Record<string, unknown>): ChronicleOutcome {\n if (payload.ok === false || /(?:failed|error|damaged|conflict|deadlock|denied|rejected|blocked)$/.test(name)) return 'failure';\n if (/(?:started|starting|retrying|threshold_reached)$/.test(name)) return 'started';\n if (/(?:cancelled|aborted)$/.test(name)) return 'cancelled';\n if (/(?:completed|finished|committed|merged|written|persisted|accepted|recovered|verified|connected|success)$/.test(name) || payload.ok === true) return 'success';\n return 'unknown';\n}\nfunction inferResource(payload: Record<string, unknown>): ChronicleResourceRef | undefined {\n const candidates: Array<[ChronicleResourceRef['kind'], string, unknown]> = [\n ['memory', 'memoryId', payload.memoryId], ['task', 'taskId', payload.taskId],\n ['kanban', 'boardId', payload.boardId ?? payload.runId], ['artifact', 'worktreeId', payload.worktreeId ?? payload.handleId],\n ['file', 'path', payload.filePath ?? payload.path], ['other', 'agentId', payload.agentId ?? payload.subagentId],\n ['network', 'serverAddress', payload.serverAddress],\n ['other', 'sessionId', payload.sessionId],\n ];\n const found = candidates.find(([, , value]) => typeof value === 'string' && value.length > 0);\n if (!found) return undefined;\n const [kind, label, value] = found as [ChronicleResourceRef['kind'], string, string];\n return { kind, id: `${label}:${value}`, ...(kind === 'file' ? { path: value } : {}) };\n}\n\nfunction sanitize(value: unknown, key = '', depth = 0, seen = new WeakSet<object>()): unknown {\n if (value === null || typeof value === 'boolean' || typeof value === 'number') return value;\n if (typeof value === 'bigint') return value.toString();\n if (typeof value === 'function') return { type: 'function' };\n if (typeof value === 'string') {\n if (PRESERVE_STRING_KEY.test(key) && !SENSITIVE_KEY.test(key)) return value.slice(0, 512);\n if (SENSITIVE_KEY.test(key)) return { hash: digest(value), length: value.length, redacted: true };\n return value.length <= 256 ? value : { hash: digest(value), length: value.length, truncated: true };\n }\n if (typeof value !== 'object') return String(value);\n if (seen.has(value)) return { circular: true };\n if (depth >= 5) return { hash: digest(safeString(value)), depthLimited: true };\n seen.add(value);\n if (Array.isArray(value)) {\n const cap = TRUNCATED_ARRAYS.has(key) ? TRUNCATED_ARRAY_MAX : DEFAULT_ARRAY_MAX;\n const items = value.slice(0, cap).map((item) => sanitize(item, key, depth + 1, seen));\n return value.length > cap ? { items, total: value.length, truncated: true } : items;\n }\n const output: Record<string, unknown> = {};\n const entries = Object.entries(value as Record<string, unknown>);\n for (const [childKey, child] of entries.slice(0, 100)) {\n if (childKey === 'ctx' || childKey === 'provider' || childKey === 'resolve' || childKey === 'extend' || childKey === 'deny') continue;\n output[childKey] = sanitize(child, childKey, depth + 1, seen);\n }\n if (entries.length > 100) output._truncatedKeys = entries.length - 100;\n return output;\n}\nfunction safeString(value: unknown): string { try { return JSON.stringify(value) ?? String(value); } catch { return String(value); } }\nfunction digest(value: string): string { return createHash('sha256').update(value).digest('hex'); }\n", "import { createHash, type Hash } from 'node:crypto';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleStreamAdapterOptions {\n events: EventBus; journal: ChronicleJournal; context: ChronicleContext | (() => ChronicleContext);\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\ninterface StreamState {\n sessionId?: string; agentId?: string; attemptId: string; logicalRequestId: string; providerId: string; model: string;\n startedAtMs: number; firstChunkAtMs?: number; lastChunkAtMs?: number;\n textChunks: number; textBytes: number; thinkingChunks: number; thinkingBytes: number;\n textHash: Hash; thinkingHash: Hash;\n}\n\n/** Aggregates high-frequency streaming deltas without dropping their volume/timing/content identity. */\nexport function wireProviderStreamsToChronicle(options: ChronicleStreamAdapterOptions): () => void {\n const states = new Map<string, StreamState>();\n const key = (sessionId: string | undefined, agentId: string | undefined) => `${sessionId ?? '__default__'}\\0${agentId ?? '__leader__'}`;\n const update = (sessionId: string | undefined, agentId: string | undefined, text: string, thinking: boolean): void => {\n const state = states.get(key(sessionId, agentId));\n if (!state) return;\n const now = Date.now(); const bytes = Buffer.byteLength(text);\n state.firstChunkAtMs ??= now; state.lastChunkAtMs = now;\n if (thinking) { state.thinkingChunks++; state.thinkingBytes += bytes; state.thinkingHash.update(text); }\n else { state.textChunks++; state.textBytes += bytes; state.textHash.update(text); }\n };\n const flush = (sessionId: string | undefined, agentId: string | undefined, outcome: 'success' | 'failure'): void => {\n const state = states.get(key(sessionId, agentId)); if (!state) return; states.delete(key(sessionId, agentId));\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const endedAtMs = Date.now();\n const input: ChronicleEventInput = { eventType: 'provider.stream.summarized', outcome,\n scope: { ...context.scope, ...(state.sessionId ? { sessionId: state.sessionId } : {}), ...(state.agentId ? { agentId: state.agentId } : {}) },\n correlation: { ...context.correlation, attemptId: state.attemptId, logicalRequestId: state.logicalRequestId },\n runtime: { providerId: state.providerId, modelId: state.model },\n durationNs: String(Math.max(0, endedAtMs - state.startedAtMs) * 1_000_000),\n attributes: { textChunks: state.textChunks, textBytes: state.textBytes,\n thinkingChunks: state.thinkingChunks, thinkingBytes: state.thinkingBytes,\n textHash: state.textHash.digest('hex'), thinkingHash: state.thinkingHash.digest('hex'),\n firstChunkLatencyMs: state.firstChunkAtMs === undefined ? undefined : state.firstChunkAtMs - state.startedAtMs,\n streamActiveMs: state.firstChunkAtMs === undefined || state.lastChunkAtMs === undefined ? 0 : state.lastChunkAtMs - state.firstChunkAtMs },\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n };\n const offs = [\n options.events.on('provider.attempt.started', (event) => states.set(key(event.sessionId,event.agentId), {\n sessionId: event.sessionId, ...(event.agentId ? { agentId:event.agentId } : {}), attemptId: event.attemptId, logicalRequestId: event.logicalRequestId,\n providerId: event.providerId, model: event.model, startedAtMs: Date.parse(event.startedAt),\n textChunks: 0, textBytes: 0, thinkingChunks: 0, thinkingBytes: 0,\n textHash: createHash('sha256'), thinkingHash: createHash('sha256'),\n })),\n options.events.on('provider.text_delta', (event) => update(event.sessionId, event.ctx.agentId, event.text, false)),\n options.events.on('provider.thinking_delta', (event) => update(event.sessionId, event.ctx.agentId, event.text, true)),\n options.events.on('provider.attempt.completed', (event) => flush(event.sessionId, event.agentId, 'success')),\n options.events.on('provider.attempt.failed', (event) => flush(event.sessionId, event.agentId, 'failure')),\n ];\n return () => { for (const state of [...states.values()]) flush(state.sessionId, state.agentId, 'failure'); offs.forEach((off) => { off(); }); };\n}\n", "import { createHash } from 'node:crypto';\nimport type { ContentBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport type { Request } from '../types/provider.js';\n\nexport interface ChroniclePromptManifest {\n manifestId: string;\n messageCount: number; estimatedMessageTokens: number; contentBytes: number;\n roleCounts: Record<string, number>; blockCounts: Record<string, number>;\n system: { blockCount: number; bytes: number; hash: string };\n messages: Array<{ index: number; role: string; bytes: number; estimatedTokens?: number; hash: string; blocks: Record<string, number> }>;\n tools: { count: number; estimatedDefinitionTokens: number; manifestHash: string; names: string[]; mutating: number; destructive: number };\n request: Record<string, unknown>;\n}\n\n/** Content-addressed prompt composition manifest; raw prompt/tool prose never leaves this function. */\nexport function createChroniclePromptManifest(request: Request): ChroniclePromptManifest {\n const roleCounts: Record<string, number> = {}, blockCounts: Record<string, number> = {};\n const messages = request.messages.map((message, index) => messageSummary(message, index, roleCounts, blockCounts));\n const systemText = (request.system ?? []).map((block) => block.text).join('\\n');\n const toolRecords = (request.tools ?? []).map((tool) => ({ name: tool.name, schemaHash: hash(stable(tool.inputSchema)),\n permission: tool.permission, mutating: tool.mutating, riskTier: tool.riskTier, capabilities: tool.capabilities,\n estimatedTokens: tool._estDefTokens ?? 0 }));\n const core = { systemHash: hash(systemText), messages: messages.map(({ hash: contentHash, ...rest }) => ({ ...rest, contentHash })), tools: toolRecords,\n model: request.model, maxTokens: request.maxTokens, temperature: request.temperature, topP: request.topP,\n topK: request.topK, seed: request.seed, toolChoice: request.toolChoice, reasoning: request.reasoning,\n cache: request.cache, responseFormat: request.responseFormat?.type };\n return {\n manifestId: `prompt_${hash(stable(core))}`,\n messageCount: messages.length,\n estimatedMessageTokens: messages.reduce((sum, message) => sum + (message.estimatedTokens ?? 0), 0),\n contentBytes: messages.reduce((sum, message) => sum + message.bytes, 0) + Buffer.byteLength(systemText),\n roleCounts, blockCounts,\n system: { blockCount: request.system?.length ?? 0, bytes: Buffer.byteLength(systemText), hash: hash(systemText) },\n messages,\n tools: { count: toolRecords.length, estimatedDefinitionTokens: toolRecords.reduce((sum, tool) => sum + tool.estimatedTokens, 0),\n manifestHash: hash(stable(toolRecords)), names: toolRecords.map((tool) => tool.name),\n mutating: toolRecords.filter((tool) => tool.mutating).length,\n destructive: toolRecords.filter((tool) => tool.riskTier === 'destructive').length },\n request: { maxTokens: request.maxTokens, temperature: request.temperature, topP: request.topP, topK: request.topK,\n frequencyPenalty: request.frequencyPenalty, presencePenalty: request.presencePenalty, seed: request.seed,\n candidateCount: request.candidateCount, logprobs: request.logprobs, topLogprobs: request.topLogprobs,\n stopSequenceCount: request.stopSequences?.length ?? 0, toolChoice: request.toolChoice,\n reasoning: request.reasoning, cache: request.cache, responseFormat: request.responseFormat?.type,\n safetySettingCount: request.safetySettings?.length ?? 0, userHash: request.user ? hash(request.user) : undefined },\n };\n}\n\nfunction messageSummary(message: Message, index: number, roles: Record<string, number>, totals: Record<string, number>) {\n roles[message.role] = (roles[message.role] ?? 0) + 1;\n const blocks = typeof message.content === 'string' ? { text: 1 } : countBlocks(message.content);\n for (const [type, count] of Object.entries(blocks)) totals[type] = (totals[type] ?? 0) + count;\n const content = contentIdentity(message.content);\n return { index, role: message.role, bytes: content.bytes,\n ...(message._estTokens !== undefined ? { estimatedTokens: message._estTokens } : {}), hash: content.hash, blocks };\n}\nfunction countBlocks(blocks: ContentBlock[]): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const block of blocks) counts[block.type] = (counts[block.type] ?? 0) + 1;\n return counts;\n}\nfunction hash(value: string): string { return createHash('sha256').update(value).digest('hex'); }\nfunction contentIdentity(content: Message['content']): { hash: string; bytes: number } {\n if (typeof content === 'string') return { hash: hash(content), bytes: Buffer.byteLength(content) };\n const digest = createHash('sha256'); let bytes = 0;\n const add = (value: string | undefined) => { if (!value) return; digest.update(value); bytes += Buffer.byteLength(value); };\n for (const block of content) {\n add(block.type);\n if (block.type === 'text') add(block.text);\n else if (block.type === 'thinking') { add(block.thinking); add(block.signature); }\n else if (block.type === 'tool_use') { add(block.id); add(block.name); add(stable(block.input)); }\n else if (block.type === 'tool_result') { add(block.tool_use_id); add(block.name); add(block.content); add(String(block.is_error ?? false)); }\n else if (block.type === 'image') { add(block.source.type); add(block.source.media_type); add(block.source.url); add(block.source.data); }\n }\n return { hash: digest.digest('hex'), bytes };\n}\nfunction stable(value: unknown): string {\n if (value === undefined) return 'undefined';\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;\n return `{${Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => `${JSON.stringify(key)}:${stable(child)}`).join(',')}}`;\n}\n", "import { createHash } from 'node:crypto';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleRollupAdapterOptions {\n events: EventBus; journal: ChronicleJournal; context: ChronicleContext | (() => ChronicleContext);\n windowMs?: number; onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\ninterface Bucket { signal: string; sessionId?: string; agentId?: string; toolCallId?: string;\n dimensions: Record<string, string>; startedAt: number; updatedAt: number; count: number;\n metrics: Record<string, { sum: number; min: number; max: number; last: number }>;\n categories: Record<string, number>; digest: ReturnType<typeof createHash> }\n\n/** Converts high-frequency ephemeral signals into bounded window aggregates before persistence. */\nexport function wireRollupsToChronicle(options: ChronicleRollupAdapterOptions): () => void {\n const buckets = new Map<string, Bucket>(); const windowMs = Math.max(1_000, options.windowMs ?? 10_000);\n const bucket = (key: string, seed: Omit<Bucket, 'startedAt'|'updatedAt'|'count'|'metrics'|'categories'|'digest'>) => {\n let value = buckets.get(key); if (!value) { const now = Date.now(); value = { ...seed, startedAt: now, updatedAt: now,\n count: 0, metrics: {}, categories: {}, digest: createHash('sha256') }; buckets.set(key, value); } return value;\n };\n const sample = (target: Bucket, values: Record<string, number>, category?: string, digest?: string) => {\n target.count++; target.updatedAt = Date.now();\n for (const [name, value] of Object.entries(values)) { const metric = target.metrics[name];\n target.metrics[name] = metric ? { sum: metric.sum + value, min: Math.min(metric.min, value), max: Math.max(metric.max, value), last: value }\n : { sum: value, min: value, max: value, last: value }; }\n if (category) target.categories[category] = (target.categories[category] ?? 0) + 1;\n if (digest) target.digest.update(digest);\n };\n const flush = (key: string) => { const value = buckets.get(key); if (!value || value.count === 0) return; buckets.delete(key);\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const stats = Object.fromEntries(Object.entries(value.metrics).map(([name, metric]) => [name, { ...metric, avg: metric.sum / value.count }]));\n const input: ChronicleEventInput = { eventType: 'metrics.rollup', outcome: 'success', occurredAt: new Date(value.updatedAt).toISOString(),\n scope: { ...context.scope, ...(value.sessionId ? { sessionId: value.sessionId } : {}), ...(value.agentId ? { agentId: value.agentId } : {}) },\n correlation: { ...context.correlation, ...(value.toolCallId ? { toolCallId: value.toolCallId } : {}) },\n durationNs: String(Math.max(0, value.updatedAt - value.startedAt) * 1_000_000),\n attributes: { signal: value.signal, windowStart: new Date(value.startedAt).toISOString(), windowEnd: new Date(value.updatedAt).toISOString(),\n samples: value.count, dimensions: value.dimensions, stats, categories: value.categories, digest: value.digest.digest('hex'), rawEventsRetained: false } };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n };\n const gauge = (signal: string, event: Record<string, unknown>, dimension?: string) => { const sessionId = text(event.sessionId);\n const dimensionValue = dimension ? text(event[dimension]) : undefined; const key = `${signal}\\0${sessionId ?? ''}\\0${dimensionValue ?? ''}`;\n const target = bucket(key, { signal, ...(sessionId ? { sessionId } : {}), ...(dimensionValue ? { agentId: dimensionValue } : {}), dimensions: dimensionValue && dimension ? { [dimension]: dimensionValue } : {} });\n sample(target, Object.fromEntries(Object.entries(event).filter(([, value]) => typeof value === 'number')) as Record<string, number>); };\n const offs = [\n options.events.on('process.output', (event) => { const key = `process.output\\0${event.sessionId}\\0${event.toolCallId}\\0${event.pid ?? ''}\\0${event.stream}`;\n const target = bucket(key, { signal: 'process.output', sessionId: event.sessionId, ...(event.agentId ? { agentId: event.agentId } : {}), toolCallId: event.toolCallId,\n dimensions: { stream: event.stream, toolName: event.toolName, pid: String(event.pid ?? '') } }); sample(target, { bytes: event.bytes }, event.stream, event.chunkHash); }),\n options.events.on('process.completed', (event) => { for (const key of [...buckets.keys()]) if (key.startsWith(`process.output\\0${event.sessionId}\\0${event.toolCallId}\\0`)) flush(key); }),\n options.events.on('tool.progress', (event) => { if (event.event.type === 'file_changed') return; const key = `tool.progress\\0${event.sessionId ?? ''}\\0${event.id}`;\n const target = bucket(key, { signal: 'tool.progress', ...(event.sessionId ? { sessionId: event.sessionId } : {}), ...(event.agentId ? { agentId: event.agentId } : {}), toolCallId: event.id, dimensions: { toolName: event.name } });\n sample(target, { textBytes: Buffer.byteLength(event.event.text ?? '') }, event.event.type, safeDigest(event.event)); }),\n options.events.on('tool.executed', (event) => flush(`tool.progress\\0${event.sessionId ?? ''}\\0${event.id ?? ''}`)),\n options.events.on('tool.failed', (event) => flush(`tool.progress\\0${event.sessionId}\\0${event.id}`)),\n options.events.on('ctx.pct', (event) => gauge('ctx.pct', event)),\n options.events.on('subagent.ctx_pct', (event) => gauge('subagent.ctx_pct', event, 'subagentId')),\n options.events.on('countdown.tick', (event) => gauge('countdown.tick', event)),\n options.events.on('coordinator.stats', (event) => gauge('coordinator.stats', event)),\n ];\n const timer = setInterval(() => { const cutoff = Date.now() - windowMs; for (const [key, value] of buckets) if (value.updatedAt <= cutoff) flush(key); }, windowMs);\n timer.unref?.();\n return () => { clearInterval(timer); for (const key of [...buckets.keys()]) flush(key); offs.forEach((off) => { off(); }); };\n}\nfunction text(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined; }\nfunction safeDigest(value: unknown): string { try { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); } catch { return 'unhashable'; } }\n", "import { createHash } from 'node:crypto';\nimport { createReadStream } from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { createInterface } from 'node:readline';\nimport type { ChronicleEvent, ChronicleOutcome, ChronicleResourceRef } from './types.js';\n\nexport interface ChronicleQuery {\n eventId?: string;\n eventTypes?: string[]; outcomes?: ChronicleOutcome[]; from?: string; to?: string;\n projectId?: string; sessionId?: string; agentId?: string; taskId?: string;\n providerId?: string; modelId?: string; traceId?: string; logicalRequestId?: string;\n attemptId?: string; toolCallId?: string; resourceKind?: ChronicleResourceRef['kind'];\n resourceId?: string; path?: string; line?: number; tags?: Record<string, string>;\n attributes?: Record<string, unknown>; text?: string; order?: 'asc' | 'desc';\n limit?: number; cursor?: string;\n}\n\nexport interface ChronicleQueryResult {\n events: ChronicleEvent[]; total: number; nextCursor?: string;\n scannedEvents: number; sourceFiles: number; invalidLines: number;\n summary: ChronicleSummary;\n}\n\n/** Derived once from all matching events; never from the paginated UI sample. */\nexport interface ChronicleSummary {\n logicalRequests: number; modelAttempts: number; completedAttempts: number; failedAttempts: number;\n scheduledRetries: number; fallbacks: number; providers: number; models: number;\n inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number;\n estimatedCostUsd: number;\n providerAvgDurationMs: number; providerP95DurationMs: number;\n toolCalls: number; completedTools: number; failedTools: number; toolAvgDurationMs: number;\n processes: number; failedProcesses: number; fileEvents: number; uniqueFiles: number;\n agentEvents: number; uniqueAgents: number; decisions: number; escalations: number;\n failures: number; cancellations: number;\n families: Record<ChronicleSignalFamily, number>;\n failuresByFamily: Record<ChronicleSignalFamily, number>;\n}\nexport type ChronicleSignalFamily = 'llm'|'agent'|'tool'|'file'|'memory'|'task'|'decision'|'runtime';\n\nexport type ChronicleFacet = 'eventType' | 'outcome' | 'projectId' | 'sessionId' |\n 'agentId' | 'taskId' | 'providerId' | 'modelId' | 'resourceKind' | 'resourcePath' | 'toolCallId';\nexport interface ChronicleFacetValue { value: string; count: number }\nexport type ChronicleRelationKind = 'parent_span' | 'trace' | 'tool_call' | 'logical_request' |\n 'attempt' | 'decision' | 'network_request' | 'prompt_manifest' | 'resource_lineage';\nexport interface ChronicleGraphEdge { from: string; to: string; kind: ChronicleRelationKind; confidence: 'explicit' | 'correlated' | 'inferred' }\nexport interface ChronicleGraphResult { nodes: ChronicleEvent[]; edges: ChronicleGraphEdge[]; truncated: boolean }\n\ninterface ChronicleOrderKey {\n occurredAt: string;\n persistedAt: string;\n sequence: number;\n eventId: string;\n}\n\ninterface ChronicleSnapshotEntry {\n id: string;\n size: number;\n}\n\ninterface ChronicleCursor {\n version: 1;\n order: 'asc' | 'desc';\n queryHash: string;\n after: ChronicleOrderKey;\n snapshot: ChronicleSnapshotEntry[];\n}\n\ninterface SnapshotFile extends ChronicleSnapshotEntry {\n file: string;\n}\n\nconst MAX_CURSOR_SNAPSHOT_ENTRIES = 10_000;\n\n// \u2500\u2500 Streaming line-by-line reader \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction streamLines(filePath: string, maxBytes?: number): AsyncIterableIterator<string> {\n const stream = createReadStream(filePath, {\n encoding: 'utf8',\n highWaterMark: 256 * 1024,\n ...(maxBytes !== undefined ? { end: maxBytes - 1 } : {}),\n });\n const rl = createInterface({ input: stream, crlfDelay: Infinity });\n return rl[Symbol.asyncIterator]() as AsyncIterableIterator<string>;\n}\n\n// \u2500\u2500 Streaming query engine (no pre-loaded events) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Queryable projection over immutable Chronicle JSONL partitions.\n * Events are streamed on demand \u2014 no full-file load into memory. */\nexport class ChronicleQueryEngine {\n private readonly partitionFiles: string[];\n\n private constructor(\n files: string[],\n readonly diagnostics: { sourceFiles: number; invalidLines: number },\n ) {\n this.partitionFiles = files;\n }\n\n static async fromDirectory(directory: string): Promise<ChronicleQueryEngine> {\n const files = await findPartitions(path.resolve(directory));\n return new ChronicleQueryEngine(files, { sourceFiles: files.length, invalidLines: 0 });\n }\n\n static async fromFiles(files: string[]): Promise<ChronicleQueryEngine> {\n return new ChronicleQueryEngine(files, { sourceFiles: files.length, invalidLines: 0 });\n }\n\n /** Stream all partitions, filter, and return the requested page + summary. */\n async query(query: ChronicleQuery = {}): Promise<ChronicleQueryResult> {\n const order = query.order ?? 'desc';\n const limit = Math.max(1, Math.min(query.limit ?? 100, 10_000));\n const queryHash = hashQuery(query);\n const cursor = decodeCursor(query.cursor, order, queryHash);\n const snapshotFiles = cursor\n ? await resolveSnapshotFiles(this.partitionFiles, cursor.snapshot)\n : await captureSnapshot(this.partitionFiles);\n const files = order === 'asc' ? snapshotFiles : snapshotFiles.slice().reverse();\n const summaryAcc = createSummaryAccumulator();\n const orderedCandidates: ChronicleEvent[] = [];\n const pageOrder = (left: ChronicleEvent, right: ChronicleEvent) =>\n compareEvents(left, right) * (order === 'asc' ? 1 : -1);\n let totalCount = 0;\n let remainingCount = 0;\n let scannedEvents = 0;\n let invalidLines = 0;\n\n for (const snapshotFile of files) {\n try {\n if (snapshotFile.size === 0) continue;\n const lines = order === 'asc'\n ? streamLines(snapshotFile.file, snapshotFile.size)\n : reverseLines(snapshotFile.file, snapshotFile.size);\n\n for await (const line of lines) {\n if (!line.trim()) continue;\n let event: ChronicleEvent;\n try {\n event = JSON.parse(line) as ChronicleEvent;\n if (!isChronicleEvent(event)) { invalidLines++; continue; }\n } catch { invalidLines++; continue; }\n scannedEvents++;\n\n if (!matches(event, query)) continue;\n totalCount++;\n updateSummary(summaryAcc, event);\n\n if (cursor && compareEventToKey(event, cursor.after) * (order === 'asc' ? 1 : -1) <= 0) {\n continue;\n }\n remainingCount++;\n\n // Keyset pagination retains only this page's best `limit` matches.\n // Cursor depth and journal size therefore cannot grow page memory.\n const insertionIndex = findInsertionIndex(orderedCandidates, event, pageOrder);\n if (insertionIndex < limit) {\n orderedCandidates.splice(insertionIndex, 0, event);\n if (orderedCandidates.length > limit) orderedCandidates.pop();\n }\n }\n } catch {\n // Skip unreadable partitions\n }\n }\n\n const pageEvents = orderedCandidates;\n const lastEvent = pageEvents.at(-1);\n\n return {\n events: pageEvents,\n total: totalCount,\n summary: finalizeSummary(summaryAcc),\n ...(lastEvent && pageEvents.length < remainingCount\n ? { nextCursor: encodeCursor({\n version: 1,\n order,\n queryHash,\n after: orderKey(lastEvent),\n snapshot: snapshotFiles.map(({ id, size }) => ({ id, size })),\n }) } : {}),\n scannedEvents,\n sourceFiles: snapshotFiles.length,\n invalidLines,\n };\n }\n\n /** Stream all partitions and compute facet value counts. */\n async facet(field: ChronicleFacet, query: ChronicleQuery = {}, limit = 100): Promise<ChronicleFacetValue[]> {\n const counts = new Map<string, number>();\n let invalidLines = 0;\n for (const file of this.partitionFiles) {\n try {\n for await (const line of streamLines(file)) {\n if (!line.trim()) continue;\n let event: ChronicleEvent;\n try {\n event = JSON.parse(line) as ChronicleEvent;\n if (!isChronicleEvent(event)) { invalidLines++; continue; }\n } catch { invalidLines++; continue; }\n if (!matches(event, query)) continue;\n const value = facetValue(event, field);\n if (value !== undefined) counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n } catch { /* skip unreadable */ }\n }\n this.diagnostics.invalidLines = invalidLines;\n return [...counts]\n .map(([value, count]) => ({ value, count }))\n .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value))\n .slice(0, Math.max(0, limit));\n }\n\n /** Expand explicit and typed correlation edges; temporal proximity alone never creates causality. */\n async graph(seed: ChronicleQuery = {}, hops = 2, maxNodes = 1_000): Promise<ChronicleGraphResult> {\n const nodeLimit = Math.max(0, Math.floor(maxNodes));\n const selected = new Map<string, ChronicleEvent>();\n let seedCount = 0;\n\n // Pass 1 retains only the bounded seed set.\n for await (const event of streamEvents(this.partitionFiles)) {\n if (!matches(event, seed)) continue;\n seedCount++;\n if (selected.size < nodeLimit) selected.set(event.eventId, event);\n }\n\n let frontier = [...selected.values()];\n const depthLimit = Math.max(0, Math.min(hops, 10));\n for (let depth = 0; depth < depthLimit && frontier.length > 0 && selected.size < nodeLimit; depth++) {\n const frontierKeys = new Set(frontier.flatMap((event) => relationKeys(event).map((relation) => relation.key)));\n const next: ChronicleEvent[] = [];\n\n // Each hop is another streaming pass. Only related nodes up to maxNodes\n // are retained, so journal size cannot determine graph memory usage.\n for await (const event of streamEvents(this.partitionFiles)) {\n if (selected.has(event.eventId)) continue;\n if (!relationKeys(event).some((relation) => frontierKeys.has(relation.key))) continue;\n selected.set(event.eventId, event);\n next.push(event);\n if (selected.size >= nodeLimit) break;\n }\n frontier = next;\n }\n\n const nodes = [...selected.values()].sort(compareEvents);\n const byKey = new Map<string, ChronicleEvent[]>();\n for (const node of nodes) for (const relation of relationKeys(node)) {\n const related = byKey.get(relation.key) ?? [];\n related.push(node);\n byKey.set(relation.key, related);\n }\n\n const edges: ChronicleGraphEdge[] = [];\n const seen = new Set<string>();\n for (const node of nodes) for (const relation of relationKeys(node)) for (const candidate of byKey.get(relation.key) ?? []) {\n if (candidate.eventId === node.eventId) continue;\n const [from, to] = compareEvents(node, candidate) <= 0 ? [node, candidate] : [candidate, node];\n const id = `${from.eventId}:${to.eventId}:${relation.kind}`;\n if (!seen.has(id)) { seen.add(id); edges.push({ from: from.eventId, to: to.eventId, kind: relation.kind, confidence: relation.confidence }); }\n }\n return { nodes, edges, truncated: seedCount > nodeLimit || selected.size >= nodeLimit };\n }\n}\n\nasync function* streamEvents(files: readonly string[]): AsyncGenerator<ChronicleEvent> {\n for (const file of files) {\n try {\n for await (const line of streamLines(file)) {\n if (!line.trim()) continue;\n try {\n const event = JSON.parse(line) as ChronicleEvent;\n if (isChronicleEvent(event)) yield event;\n } catch { /* skip invalid lines */ }\n }\n } catch { /* skip unreadable partitions */ }\n }\n}\n\n// \u2500\u2500 Reverse line reader (reads a file from end to start) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function* reverseLines(filePath: string, maxBytes?: number): AsyncGenerator<string> {\n const CHUNK = 64 * 1024;\n const NEWLINE = 0x0a;\n let handle: fs.FileHandle;\n try { handle = await fs.open(filePath, 'r'); } catch { return; }\n try {\n const fileSize = (await handle.stat()).size;\n const size = Math.min(fileSize, maxBytes ?? fileSize);\n let position = size;\n let suffix = Buffer.alloc(0);\n while (position > 0) {\n const length = Math.min(CHUNK, position);\n position -= length;\n const buffer = Buffer.allocUnsafe(length);\n await handle.read(buffer, 0, length, position);\n const data = suffix.length === 0 ? buffer : Buffer.concat([buffer, suffix]);\n let lineEnd = data.length;\n let firstNewline = -1;\n for (let index = data.length - 1; index >= 0; index--) {\n if (data[index] !== NEWLINE) continue;\n const trimmed = data.subarray(index + 1, lineEnd).toString('utf8').trim();\n if (trimmed) yield trimmed;\n lineEnd = index;\n firstNewline = index;\n }\n suffix = firstNewline >= 0 ? Buffer.from(data.subarray(0, firstNewline)) : data;\n }\n const trimmed = suffix.toString('utf8').trim();\n if (trimmed) yield trimmed;\n } finally { await handle.close(); }\n}\n\n// \u2500\u2500 Running summary accumulator (replaces scan-then-summarize) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface SummaryAcc {\n logicalRequestIds: Set<string>;\n modelAttempts: number; completedAttempts: number; failedAttempts: number;\n scheduledRetries: number; fallbacks: number;\n providers: Set<string>; models: Set<string>;\n inputTokens: number; outputTokens: number;\n cacheReadTokens: number; cacheWriteTokens: number;\n costByScope: Map<string, { cost: number; event: ChronicleEvent }>;\n providerDurations: number[];\n toolCalls: number; completedTools: number; failedTools: number;\n toolDurations: number[];\n processes: number; failedProcesses: number;\n fileEvents: number; uniqueFiles: Set<string>;\n agentEvents: number; uniqueAgents: Set<string>;\n decisions: number; escalations: number;\n failures: number; cancellations: number;\n families: Record<ChronicleSignalFamily, number>;\n failuresByFamily: Record<ChronicleSignalFamily, number>;\n /** One-per-scope token.accounted cost snapshot. Updated when a later\n * token.accounted event has a later timestamp for the same scope. */\n}\n\nfunction createSummaryAccumulator(): SummaryAcc {\n return {\n logicalRequestIds: new Set(), modelAttempts: 0, completedAttempts: 0, failedAttempts: 0,\n scheduledRetries: 0, fallbacks: 0, providers: new Set(), models: new Set(),\n inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0,\n costByScope: new Map(), providerDurations: [],\n toolCalls: 0, completedTools: 0, failedTools: 0, toolDurations: [],\n processes: 0, failedProcesses: 0,\n fileEvents: 0, uniqueFiles: new Set(), agentEvents: 0, uniqueAgents: new Set(),\n decisions: 0, escalations: 0, failures: 0, cancellations: 0,\n families: { llm: 0, agent: 0, tool: 0, file: 0, memory: 0, task: 0, decision: 0, runtime: 0 },\n failuresByFamily: { llm: 0, agent: 0, tool: 0, file: 0, memory: 0, task: 0, decision: 0, runtime: 0 },\n };\n}\n\nfunction updateSummary(acc: SummaryAcc, event: ChronicleEvent): void {\n // Families\n const family = signalFamily(event);\n acc.families[family]++;\n if (isTerminalFailure(event)) acc.failuresByFamily[family]++;\n\n // Running counts per event type\n if (event.correlation.logicalRequestId) acc.logicalRequestIds.add(event.correlation.logicalRequestId);\n if (event.runtime?.providerId) acc.providers.add(event.runtime.providerId);\n if (event.runtime?.modelId) acc.models.add(event.runtime.modelId);\n\n if (event.eventType === 'provider.attempt.started') acc.modelAttempts++;\n else if (event.eventType === 'provider.attempt.completed') {\n acc.completedAttempts++;\n acc.inputTokens += numberAt(event, 'usage.input');\n acc.outputTokens += numberAt(event, 'usage.output');\n acc.cacheReadTokens += numberAt(event, 'usage.cacheRead');\n acc.cacheWriteTokens += numberAt(event, 'usage.cacheWrite');\n const dur = durationMs(event);\n if (dur > 0) acc.providerDurations.push(dur);\n } else if (event.eventType === 'provider.attempt.failed') {\n acc.failedAttempts++;\n if (event.attributes?.retryScheduled === true) acc.scheduledRetries++;\n const dur = durationMs(event);\n if (dur > 0) acc.providerDurations.push(dur);\n } else if (event.eventType === 'provider.fallback') acc.fallbacks++;\n else if (event.eventType === 'tool.started') acc.toolCalls++;\n else if (event.eventType === 'tool.executed') {\n acc.completedTools++;\n const dur = durationMs(event);\n if (dur > 0) acc.toolDurations.push(dur);\n } else if (event.eventType === 'tool.failed') {\n acc.failedTools++;\n const dur = durationMs(event);\n if (dur > 0) acc.toolDurations.push(dur);\n } else if (event.eventType === 'process.started') acc.processes++;\n else if (event.eventType === 'process.completed' && event.outcome === 'failure') acc.failedProcesses++;\n else if (event.eventType === 'decision.requested') acc.decisions++;\n else if (event.eventType === 'decision.escalated') acc.escalations++;\n\n // Token accounted \u2014 keep the latest finite snapshot per scope. Zero is a\n // meaningful reset, and compareEvents makes ties independent of scan order.\n if (event.eventType === 'token.accounted') {\n const cost = readPath(event.attributes ?? {}, 'cost.total');\n if (typeof cost === 'number' && Number.isFinite(cost)) {\n const key = scopeKey(event);\n const existing = acc.costByScope.get(key);\n if (!existing || compareEvents(event, existing.event) > 0) {\n acc.costByScope.set(key, { cost, event });\n }\n }\n }\n\n // File evidence\n if (event.resource?.kind === 'file' || event.eventType.startsWith('file.')) {\n acc.fileEvents++;\n if (event.resource?.path) acc.uniqueFiles.add(event.resource.path);\n }\n\n // Agent events\n if (family === 'agent') acc.agentEvents++;\n if (event.scope.agentId) acc.uniqueAgents.add(event.scope.agentId);\n\n // Terminal failures and cancellations\n if (isTerminalFailure(event)) acc.failures++;\n if (event.outcome === 'cancelled' || event.outcome === 'abandoned') acc.cancellations++;\n}\n\nfunction finalizeSummary(acc: SummaryAcc): ChronicleSummary {\n const sortedProviderDurations = acc.providerDurations.slice().sort((a, b) => a - b);\n const sortedToolDurations = acc.toolDurations.slice().sort((a, b) => a - b);\n const totalCost = [...acc.costByScope.values()].reduce((sum, entry) => sum + entry.cost, 0);\n return {\n logicalRequests: acc.logicalRequestIds.size,\n modelAttempts: acc.modelAttempts,\n completedAttempts: acc.completedAttempts,\n failedAttempts: acc.failedAttempts,\n scheduledRetries: acc.scheduledRetries,\n fallbacks: acc.fallbacks,\n providers: acc.providers.size,\n models: acc.models.size,\n inputTokens: acc.inputTokens,\n outputTokens: acc.outputTokens,\n cacheReadTokens: acc.cacheReadTokens,\n cacheWriteTokens: acc.cacheWriteTokens,\n estimatedCostUsd: totalCost,\n providerAvgDurationMs: average(sortedProviderDurations),\n providerP95DurationMs: percentile(sortedProviderDurations, 0.95),\n toolCalls: acc.toolCalls,\n completedTools: acc.completedTools,\n failedTools: acc.failedTools,\n toolAvgDurationMs: average(sortedToolDurations),\n processes: acc.processes,\n failedProcesses: acc.failedProcesses,\n fileEvents: acc.fileEvents,\n uniqueFiles: acc.uniqueFiles.size,\n agentEvents: acc.agentEvents,\n uniqueAgents: acc.uniqueAgents.size,\n decisions: acc.decisions,\n escalations: acc.escalations,\n failures: acc.failures,\n cancellations: acc.cancellations,\n families: acc.families,\n failuresByFamily: acc.failuresByFamily,\n };\n}\n\n// \u2500\u2500 Partition discovery (no pre-loading) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The partition files list is stored on the prototype for legacy callers\n * that reference engine.partitionFiles directly. */\nObject.defineProperty(ChronicleQueryEngine.prototype, 'partitionFiles', {\n get() { throw new Error('ChronicleQueryEngine no longer loads events on construction. Use async query().'); },\n set(this: ChronicleQueryEngine, _val: string[]) {\n // Allow fromFiles/fromDirectory to attach the list for graph()\n Object.defineProperty(this, 'partitionFiles', { value: _val, writable: false, configurable: false });\n },\n});\n\nasync function findPartitions(root: string): Promise<string[]> {\n const result: string[] = [];\n const partitionName = /^(.*\\.events)(?:\\.(\\d{5}))?\\.jsonl$/;\n const visit = async (directory: string): Promise<void> => {\n let entries: import('node:fs').Dirent[];\n try { entries = await fs.readdir(directory, { withFileTypes: true }); } catch { return; }\n for (const entry of entries) {\n const full = path.join(directory, entry.name);\n if (entry.isDirectory()) await visit(full);\n else if (entry.isFile() && partitionName.test(entry.name)) result.push(full);\n }\n };\n await visit(root);\n return result.sort((left, right) => {\n const leftMatch = partitionName.exec(path.basename(left));\n const rightMatch = partitionName.exec(path.basename(right));\n const leftGroup = path.join(path.dirname(left), leftMatch?.[1] ?? left);\n const rightGroup = path.join(path.dirname(right), rightMatch?.[1] ?? right);\n const groupOrder = leftGroup.localeCompare(rightGroup);\n if (groupOrder !== 0) return groupOrder;\n return Number(leftMatch?.[2] ?? 0) - Number(rightMatch?.[2] ?? 0);\n });\n}\n\n// \u2500\u2500 Helper functions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction numberAt(event: ChronicleEvent, dotPath: string): number {\n const value = readPath(event.attributes ?? {}, dotPath);\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction durationMs(event: ChronicleEvent): number {\n const value = Number(event.durationNs ?? 0) / 1_000_000;\n return Number.isFinite(value) ? value : 0;\n}\n\nfunction average(values: number[]): number {\n return values.length ? values.reduce((sum, v) => sum + v, 0) / values.length : 0;\n}\n\nfunction percentile(sorted: number[], quantile: number): number {\n return sorted.length ? sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * quantile) - 1))]! : 0;\n}\n\nfunction scopeKey(event: ChronicleEvent): string {\n return `${event.scope.projectId ?? ''}\\0${event.scope.sessionId ?? ''}\\0${event.scope.agentId ?? ''}`;\n}\n\nfunction signalFamily(event: ChronicleEvent): ChronicleSignalFamily {\n if (event.eventType.startsWith('decision.') || event.eventType.startsWith('brain.')) return 'decision';\n if (event.resource?.kind === 'file' || event.resource?.kind === 'symbol' || /^(?:file|worktree)\\./.test(event.eventType)) return 'file';\n if (/^(?:provider|token|context|ctx|compaction)\\./.test(event.eventType)) return 'llm';\n if (/^(?:agent|subagent|delegate|fleet|concurrency)\\./.test(event.eventType)) return 'agent';\n if (/^(?:tool|process|mcp|network)\\./.test(event.eventType)) return 'tool';\n if (/^(?:memory|storage|trust)\\./.test(event.eventType)) return 'memory';\n if (/^(?:sdd|task|kanban|checkpoint|session|iteration|in_flight)\\./.test(event.eventType)) return 'task';\n return 'runtime';\n}\n\nfunction isTerminalFailure(event: ChronicleEvent): boolean {\n if (event.eventType === 'provider.attempt.failed') return event.attributes?.retryScheduled !== true;\n return event.eventType === 'tool.failed' ||\n (event.eventType === 'process.completed' && event.outcome === 'failure') ||\n /^(?:agent\\.run\\.error|sdd\\.task\\.failed|compaction\\.failed|network\\.request\\.failed)$/.test(event.eventType);\n}\n\nfunction relationKeys(event: ChronicleEvent): Array<{ key: string; kind: ChronicleRelationKind; confidence: ChronicleGraphEdge['confidence'] }> {\n const result: Array<{ key: string; kind: ChronicleRelationKind; confidence: ChronicleGraphEdge['confidence'] }> = [];\n const add = (kind: ChronicleRelationKind, value: unknown, confidence: ChronicleGraphEdge['confidence']) => {\n if (typeof value === 'string' && value) result.push({ key: `${kind}:${value}`, kind, confidence });\n };\n add('trace', event.correlation.traceId, 'correlated');\n add('tool_call', event.correlation.toolCallId, 'explicit');\n add('logical_request', event.correlation.logicalRequestId, 'explicit');\n add('attempt', event.correlation.attemptId, 'explicit');\n add('decision', event.attributes?.decisionId, 'explicit');\n add('network_request', event.attributes?.requestId, 'explicit');\n add('prompt_manifest', (event.attributes?.promptManifest as Record<string, unknown> | undefined)?.manifestId, 'explicit');\n add('resource_lineage', event.resource?.id, 'inferred');\n if (event.correlation.parentSpanId) add('parent_span', event.correlation.parentSpanId, 'explicit');\n add('parent_span', event.correlation.spanId, 'explicit');\n return result;\n}\n\nfunction matches(event: ChronicleEvent, query: ChronicleQuery): boolean {\n if (query.eventId && event.eventId !== query.eventId) return false;\n if (query.eventTypes && !query.eventTypes.includes(event.eventType)) return false;\n if (query.outcomes && (!event.outcome || !query.outcomes.includes(event.outcome))) return false;\n const occurredAt = event.occurredAt ?? event.observedAt;\n if (query.from && occurredAt < query.from || query.to && occurredAt > query.to) return false;\n if (!equal(query.projectId, event.scope.projectId) || !equal(query.sessionId, event.scope.sessionId)) return false;\n if (!equal(query.agentId, event.scope.agentId) || !equal(query.taskId, event.scope.taskId)) return false;\n if (!equal(query.providerId, event.runtime?.providerId) || !equal(query.modelId, event.runtime?.modelId)) return false;\n if (!equal(query.traceId, event.correlation.traceId) || !equal(query.logicalRequestId, event.correlation.logicalRequestId)) return false;\n if (!equal(query.attemptId, event.correlation.attemptId) || !equal(query.toolCallId, event.correlation.toolCallId)) return false;\n if (!equal(query.resourceKind, event.resource?.kind) || !equal(query.resourceId, event.resource?.id)) return false;\n if (query.path && normalize(event.resource?.path) !== normalize(query.path)) return false;\n if (query.line !== undefined && !lineContains(event, query.line)) return false;\n if (query.tags && !objectContains(event.tags, query.tags)) return false;\n if (query.attributes && !objectContains(event.attributes, query.attributes)) return false;\n if (query.text && !JSON.stringify(event).toLocaleLowerCase().includes(query.text.toLocaleLowerCase())) return false;\n return true;\n}\n\nfunction equal<T>(expected: T | undefined, actual: T | undefined): boolean { return expected === undefined || expected === actual; }\nfunction normalize(value: string | undefined): string | undefined { return value?.replaceAll('\\\\', '/').toLocaleLowerCase(); }\nfunction lineContains(event: ChronicleEvent, line: number): boolean {\n const start = event.resource?.lineStart; const end = event.resource?.lineEnd ?? start;\n return start !== undefined && end !== undefined && line >= start && line <= end;\n}\nfunction objectContains(actual: Record<string, unknown> | undefined, expected: Record<string, unknown>): boolean {\n return Boolean(actual && Object.entries(expected).every(([key, value]) => deepEqual(readPath(actual, key), value)));\n}\nfunction readPath(value: Record<string, unknown>, key: string): unknown {\n return key.split('.').reduce<unknown>((current, part) => current && typeof current === 'object'\n ? (current as Record<string, unknown>)[part] : undefined, value);\n}\nfunction deepEqual(left: unknown, right: unknown): boolean { return JSON.stringify(left) === JSON.stringify(right); }\nfunction findInsertionIndex(\n events: readonly ChronicleEvent[],\n event: ChronicleEvent,\n compare: (left: ChronicleEvent, right: ChronicleEvent) => number,\n): number {\n let low = 0;\n let high = events.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (compare(events[middle]!, event) <= 0) low = middle + 1;\n else high = middle;\n }\n return low;\n}\nfunction compareEvents(a: ChronicleEvent, b: ChronicleEvent): number {\n return compareEventToKey(a, orderKey(b));\n}\nfunction compareEventToKey(event: ChronicleEvent, key: ChronicleOrderKey): number {\n return (event.occurredAt ?? event.observedAt).localeCompare(key.occurredAt) ||\n event.persistedAt.localeCompare(key.persistedAt) || event.sequence - key.sequence ||\n event.eventId.localeCompare(key.eventId);\n}\nfunction orderKey(event: ChronicleEvent): ChronicleOrderKey {\n return {\n occurredAt: event.occurredAt ?? event.observedAt,\n persistedAt: event.persistedAt,\n sequence: event.sequence,\n eventId: event.eventId,\n };\n}\nfunction hashQuery(query: ChronicleQuery): string {\n const { cursor: _cursor, limit: _limit, order: _order, ...filters } = query;\n return createHash('sha256').update(stableStringify(filters), 'utf8').digest('base64url');\n}\nfunction encodeCursor(cursor: ChronicleCursor): string {\n return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');\n}\nfunction decodeCursor(\n encoded: string | undefined,\n order: 'asc' | 'desc',\n queryHash: string,\n): ChronicleCursor | undefined {\n if (!encoded) return undefined;\n if (encoded.length > 1_000_000) throw new Error('Invalid Chronicle cursor');\n try {\n const parsed = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as unknown;\n if (!isCursor(parsed) || parsed.order !== order || parsed.queryHash !== queryHash) {\n throw new Error('cursor does not match the query');\n }\n return parsed;\n } catch (error) {\n throw new Error(`Invalid Chronicle cursor: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\nfunction isCursor(value: unknown): value is ChronicleCursor {\n if (!value || typeof value !== 'object') return false;\n const cursor = value as Partial<ChronicleCursor>;\n const after = cursor.after as Partial<ChronicleOrderKey> | undefined;\n if (cursor.version !== 1 || (cursor.order !== 'asc' && cursor.order !== 'desc') ||\n typeof cursor.queryHash !== 'string' || !after ||\n typeof after.occurredAt !== 'string' || typeof after.persistedAt !== 'string' ||\n !Number.isSafeInteger(after.sequence) || typeof after.eventId !== 'string' ||\n !Array.isArray(cursor.snapshot) || cursor.snapshot.length > MAX_CURSOR_SNAPSHOT_ENTRIES) return false;\n\n const snapshotIds = new Set<string>();\n for (const entry of cursor.snapshot) {\n if (!entry || typeof entry.id !== 'string' || !entry.id ||\n !Number.isSafeInteger(entry.size) || entry.size < 0 || snapshotIds.has(entry.id)) return false;\n snapshotIds.add(entry.id);\n }\n return true;\n}\nasync function captureSnapshot(files: readonly string[]): Promise<SnapshotFile[]> {\n if (files.length > MAX_CURSOR_SNAPSHOT_ENTRIES) {\n throw new Error('Chronicle snapshot contains too many partitions');\n }\n return Promise.all(files.map(async (file) => {\n let size = 0;\n try { size = (await fs.stat(file)).size; } catch { /* preserve missing source as empty */ }\n return { file, id: fileId(file), size };\n }));\n}\nasync function resolveSnapshotFiles(\n files: readonly string[],\n snapshot: readonly ChronicleSnapshotEntry[],\n): Promise<SnapshotFile[]> {\n const currentFiles = new Map(files.map((file) => [fileId(file), file]));\n return Promise.all(snapshot.map(async (entry) => {\n const file = currentFiles.get(entry.id);\n if (!file) throw new Error('Chronicle cursor snapshot has expired');\n let currentSize: number;\n try { currentSize = (await fs.stat(file)).size; } catch { throw new Error('Chronicle cursor snapshot has expired'); }\n if (currentSize < entry.size) throw new Error('Chronicle cursor snapshot has expired');\n return { file, ...entry };\n }));\n}\nfunction fileId(file: string): string {\n return createHash('sha256').update(path.resolve(file), 'utf8').digest('base64url');\n}\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const object = value as Record<string, unknown>;\n return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`).join(',')}}`;\n}\nfunction isChronicleEvent(value: unknown): value is ChronicleEvent {\n if (!isRecord(value) || !isRecord(value.scope) || !isRecord(value.correlation)) return false;\n return value.schemaVersion === 1 &&\n typeof value.eventId === 'string' && typeof value.eventType === 'string' &&\n typeof value.occurredAt === 'string' && typeof value.observedAt === 'string' &&\n typeof value.persistedAt === 'string' && Number.isSafeInteger(value.sequence) &&\n (value.sequence as number) >= 0 && typeof value.previousHash === 'string' &&\n typeof value.hash === 'string' && typeof value.scope.installationId === 'string' &&\n typeof value.scope.machineId === 'string' && optionalStrings(value.scope, [\n 'projectId', 'repositoryId', 'workspaceId', 'worktreeId', 'sessionId', 'turnId',\n 'iterationId', 'agentId', 'goalId', 'planId', 'taskId', 'kanbanBoardId',\n ]) && typeof value.correlation.traceId === 'string' &&\n typeof value.correlation.spanId === 'string' && optionalStrings(value.correlation, [\n 'parentSpanId', 'logicalRequestId', 'attemptId', 'toolCallId',\n ]) && isRuntime(value.runtime) && isResource(value.resource) &&\n (value.attributes === undefined || isRecord(value.attributes)) &&\n (value.tags === undefined || isStringRecord(value.tags));\n}\nfunction isRuntime(value: unknown): boolean {\n return value === undefined || isRecord(value) &&\n optionalStrings(value, ['providerId', 'modelId', 'modelRevision']) &&\n optionalFiniteNumbers(value, ['processId', 'parentProcessId']);\n}\nfunction isResource(value: unknown): boolean {\n if (value === undefined) return true;\n if (!isRecord(value) || !['file', 'symbol', 'memory', 'task', 'kanban', 'process',\n 'network', 'artifact', 'other'].includes(String(value.kind)) || typeof value.id !== 'string') return false;\n return optionalStrings(value, ['path', 'contentHashBefore', 'contentHashAfter']) &&\n optionalFiniteNumbers(value, ['lineStart', 'lineEnd']);\n}\nfunction optionalStrings(value: Record<string, unknown>, keys: readonly string[]): boolean {\n return keys.every((key) => value[key] === undefined || typeof value[key] === 'string');\n}\nfunction optionalFiniteNumbers(value: Record<string, unknown>, keys: readonly string[]): boolean {\n return keys.every((key) => value[key] === undefined || typeof value[key] === 'number' && Number.isFinite(value[key]));\n}\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n return isRecord(value) && Object.values(value).every((entry) => typeof entry === 'string');\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\nfunction facetValue(event: ChronicleEvent, field: ChronicleFacet): string | undefined {\n const values: Record<ChronicleFacet, string | undefined> = {\n eventType: event.eventType, outcome: event.outcome, projectId: event.scope.projectId,\n sessionId: event.scope.sessionId, agentId: event.scope.agentId, taskId: event.scope.taskId,\n providerId: event.runtime?.providerId, modelId: event.runtime?.modelId,\n resourceKind: event.resource?.kind, resourcePath: event.resource?.path,\n toolCallId: event.correlation.toolCallId,\n };\n return values[field];\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,kBAAkB;AASpB,SAAS,uBACd,OACA,UAAkB,WAAW,GACX;AAClB,SAAO;AAAA,IACL,OAAO,EAAE,GAAG,MAAM;AAAA,IAClB,aAAa,EAAE,SAAS,QAAQ,WAAW,EAAE;AAAA,EAC/C;AACF;AAGO,SAAS,sBACd,QACA,YAGI,CAAC,GACa;AAClB,SAAO;AAAA,IACL,OAAO,EAAE,GAAG,OAAO,OAAO,GAAG,UAAU,MAAM;AAAA,IAC7C,aAAa;AAAA,MACX,GAAG,OAA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;AACA,SAAS,SAAS,OAAkD;AAClE,SAAO,QAAQ,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,CAAC;AAC5E;AACA,SAAS,WAAW,OAAuB,OAA2C;AACpF,QAAM,SAAqD;AAAA,IACzD,WAAW,MAAM;AAAA,IAAW,SAAS,MAAM;AAAA,IAAS,WAAW,MAAM,MAAM;AAAA,IAC3E,WAAW,MAAM,MAAM;AAAA,IAAW,SAAS,MAAM,MAAM;AAAA,IAAS,QAAQ,MAAM,MAAM;AAAA,IACpF,YAAY,MAAM,SAAS;AAAA,IAAY,SAAS,MAAM,SAAS;AAAA,IAC/D,cAAc,MAAM,UAAU;AAAA,IAAM,cAAc,MAAM,UAAU;AAAA,IAClE,YAAY,MAAM,YAAY;AAAA,EAChC;AACA,SAAO,OAAO,KAAK;AACrB;",
|
|
4
|
+
"sourcesContent": ["import { randomUUID } from 'node:crypto';\nimport type { ChronicleCorrelation, ChronicleScope } from './types.js';\n\nexport interface ChronicleContext {\n scope: ChronicleScope;\n correlation: ChronicleCorrelation;\n}\n\n/** Create a root correlation context for a session, run, or background worker. */\nexport function createChronicleContext(\n scope: ChronicleScope,\n traceId: string = randomUUID(),\n): ChronicleContext {\n return {\n scope: { ...scope },\n correlation: { traceId, spanId: randomUUID() },\n };\n}\n\n/** Derive a child span without losing project/session/task attribution. */\nexport function childChronicleContext(\n parent: ChronicleContext,\n overrides: {\n scope?: Partial<ChronicleScope> | undefined;\n correlation?: Partial<Omit<ChronicleCorrelation, 'traceId'>> | undefined;\n } = {},\n): ChronicleContext {\n return {\n scope: { ...parent.scope, ...overrides.scope },\n correlation: {\n ...parent.correlation,\n ...overrides.correlation,\n traceId: parent.correlation.traceId,\n parentSpanId: parent.correlation.spanId,\n spanId: overrides.correlation?.spanId ?? randomUUID(),\n },\n };\n}\n", "import { createHash } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\nexport interface ChronicleRuntimeIdentityInput {\n globalRoot: string;\n projectId: string;\n projectDir: string;\n now?: Date | undefined;\n}\n\nexport interface ChronicleRuntimeLocation {\n installationId: string;\n machineId: string;\n projectId: string;\n journalPath: string;\n}\n\n/**\n * Resolve privacy-preserving stable IDs and a UTC daily project partition.\n * Raw host names and global paths never enter the journal envelope.\n */\nexport function resolveChronicleRuntimeLocation(\n input: ChronicleRuntimeIdentityInput,\n): ChronicleRuntimeLocation {\n const day = (input.now ?? new Date()).toISOString().slice(0, 10);\n return {\n installationId: stableId('installation', path.resolve(input.globalRoot)),\n machineId: stableId('machine', `${os.hostname()}\\0${os.platform()}\\0${os.arch()}`),\n projectId: input.projectId,\n journalPath: path.join(input.projectDir, 'chronicle', `${day}.events.jsonl`),\n };\n}\n\nfunction stableId(prefix: string, value: string): string {\n return `${prefix}_${createHash('sha256').update(value).digest('hex').slice(0, 24)}`;\n}\n", "import { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\ninterface FileFingerprint {\n size: number;\n mtimeMs: number;\n hash?: string | undefined;\n}\n\ninterface RecentToolMutation {\n at: number;\n toolUseId: string;\n toolName: string;\n agentId?: string | undefined;\n}\n\nexport interface ChronicleFileObserverOptions {\n projectRoot: string;\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n events?: EventBus | undefined;\n debounceMs?: number | undefined;\n maxHashBytes?: number | undefined;\n excludedDirectories?: readonly string[] | undefined;\n onError?: ((error: unknown) => void) | undefined;\n}\n\nexport interface ChronicleFileObserver {\n close(): Promise<void>;\n readonly watchedFiles: number;\n}\n\nconst DEFAULT_EXCLUDED = ['.git', '.wrongstack', 'node_modules', 'dist', 'coverage', '.temp_files'];\n\n/** Observe editor/user/external process mutations that bypass WrongStack tools. */\nexport async function startChronicleFileObserver(\n options: ChronicleFileObserverOptions,\n): Promise<ChronicleFileObserver> {\n const root = path.resolve(options.projectRoot);\n const excluded = new Set(options.excludedDirectories ?? DEFAULT_EXCLUDED);\n const debounceMs = options.debounceMs ?? 120;\n const maxHashBytes = options.maxHashBytes ?? 8 * 1024 * 1024;\n const known = await scanProject(root, excluded, maxHashBytes, options.onError);\n const recentToolMutations = new Map<string, RecentToolMutation>();\n const offToolProgress = options.events?.on('tool.progress', (event) => {\n if (event.event.type !== 'file_changed' || !event.event.path) return;\n const absolute = path.isAbsolute(event.event.path)\n ? path.normalize(event.event.path)\n : path.resolve(root, event.event.path);\n const relative = normalizeRelative(path.relative(root, absolute));\n if (relative.startsWith('../') || isExcluded(relative, excluded)) return;\n recentToolMutations.set(relative, {\n at: Date.now(),\n toolUseId: event.id,\n toolName: event.name,\n agentId: event.agentId,\n });\n });\n const pending = new Set<string>();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n let flushTail: Promise<void> = Promise.resolve();\n\n const schedule = (filename: string | Buffer | null): void => {\n if (closed) return;\n if (filename === null) {\n // Some platforms omit the filename. A bounded full rescan recovers the\n // facts instead of silently losing an external mutation.\n pending.add('*');\n } else {\n const relative = normalizeRelative(String(filename));\n if (!relative || isExcluded(relative, excluded)) return;\n pending.add(relative);\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n const paths = [...pending];\n pending.clear();\n flushTail = flushTail.then(() => reconcile(paths)).catch((error) => options.onError?.(error));\n }, debounceMs);\n };\n\n const reconcile = async (changedPaths: string[]): Promise<void> => {\n const candidates = changedPaths.includes('*')\n ? unionKeys(known, await scanProject(root, excluded, maxHashBytes, options.onError))\n : changedPaths;\n const changes: Array<{\n relative: string;\n before?: FileFingerprint | undefined;\n after?: FileFingerprint | undefined;\n }> = [];\n for (const relative of candidates) {\n const before = known.get(relative);\n const after = await fingerprint(path.join(root, relative), maxHashBytes);\n if (sameFingerprint(before, after)) continue;\n changes.push({ relative, before, after });\n }\n\n // Atomic saves and renames commonly arrive as delete+create. Matching the\n // last-known content hash preserves resource lineage when the OS provides\n // only generic \"rename\" notifications.\n const deleted = changes.filter((change) => change.before && !change.after);\n const created = changes.filter((change) => !change.before && change.after);\n const consumed = new Set<string>();\n for (const from of deleted) {\n const match = created.find((to) =>\n !consumed.has(to.relative) &&\n from.before?.hash !== undefined &&\n from.before.hash === to.after?.hash,\n );\n if (!match) continue;\n consumed.add(from.relative);\n consumed.add(match.relative);\n known.delete(from.relative);\n known.set(match.relative, match.after!);\n await recordMutation(options, 'file.external.renamed', match.relative, match.after, {\n operation: 'rename',\n previousPath: from.relative,\n previousResourceId: resourceId(from.relative),\n actor: 'external',\n }, mutationAttribution(match.relative, recentToolMutations));\n }\n\n for (const change of changes) {\n if (consumed.has(change.relative)) continue;\n if (!change.after) {\n known.delete(change.relative);\n await recordMutation(options, 'file.external.deleted', change.relative, change.before, {\n operation: 'delete',\n actor: 'external',\n previousHash: change.before?.hash,\n previousSize: change.before?.size,\n }, mutationAttribution(change.relative, recentToolMutations));\n } else if (!change.before) {\n known.set(change.relative, change.after);\n await recordMutation(options, 'file.external.created', change.relative, change.after, {\n operation: 'write',\n actor: 'external',\n }, mutationAttribution(change.relative, recentToolMutations));\n } else {\n known.set(change.relative, change.after);\n await recordMutation(options, 'file.external.modified', change.relative, change.after, {\n operation: 'edit',\n actor: 'external',\n previousHash: change.before.hash,\n previousSize: change.before.size,\n }, mutationAttribution(change.relative, recentToolMutations));\n }\n }\n };\n\n let watcher: fs.FSWatcher;\n try {\n watcher = fs.watch(root, { recursive: true, persistent: false }, (_eventType, filename) => schedule(filename));\n } catch (error) {\n options.onError?.(error);\n throw error;\n }\n watcher.on('error', (error) => options.onError?.(error));\n\n return {\n get watchedFiles() {\n return known.size;\n },\n async close() {\n if (closed) return;\n closed = true;\n offToolProgress?.();\n watcher.close();\n if (timer) {\n clearTimeout(timer);\n timer = undefined;\n const paths = [...pending];\n pending.clear();\n if (paths.length > 0) flushTail = flushTail.then(() => reconcile(paths));\n }\n await flushTail;\n },\n };\n}\n\nasync function recordMutation(\n options: ChronicleFileObserverOptions,\n eventType: string,\n relativePath: string,\n state: FileFingerprint | undefined,\n attributes: Record<string, unknown>,\n attribution?: RecentToolMutation | undefined,\n): Promise<void> {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const operation = attributes['operation'] as 'write' | 'edit' | 'delete' | 'rename';\n options.events?.emit('file.activity', {\n filePath: path.join(options.projectRoot, relativePath),\n operation,\n phase: 'changed',\n source: attribution ? 'tool' : 'external',\n at: Date.now(),\n sessionId: context.scope.sessionId,\n traceId: context.correlation.traceId,\n agentId: attribution?.agentId ?? context.scope.agentId,\n ...(attribution ? { toolUseId: attribution.toolUseId, toolName: attribution.toolName } : {}),\n });\n const input: ChronicleEventInput = {\n eventType: attribution ? eventType.replace('.external.', '.tool.') : eventType,\n scope: context.scope,\n correlation: {\n ...context.correlation,\n ...(attribution ? { toolCallId: attribution.toolUseId } : {}),\n },\n outcome: 'success',\n resource: {\n kind: 'file',\n id: resourceId(relativePath),\n path: normalizeRelative(relativePath),\n ...(state?.hash ? { contentHashAfter: state.hash } : {}),\n },\n attributes: {\n ...attributes,\n actor: attribution ? 'agent' : attributes['actor'],\n source: attribution ? 'tool' : 'external',\n toolName: attribution?.toolName,\n size: state?.size,\n mtimeMs: state?.mtimeMs,\n observedBy: 'fs.watch',\n },\n };\n await options.journal.append(input);\n}\n\nfunction mutationAttribution(\n relativePath: string,\n recent: Map<string, RecentToolMutation>,\n): RecentToolMutation | undefined {\n const value = recent.get(relativePath);\n if (!value) return undefined;\n recent.delete(relativePath);\n return Date.now() - value.at <= 2_000 ? value : undefined;\n}\n\nasync function scanProject(\n root: string,\n excluded: ReadonlySet<string>,\n maxHashBytes: number,\n onError?: ((error: unknown) => void) | undefined,\n): Promise<Map<string, FileFingerprint>> {\n const result = new Map<string, FileFingerprint>();\n const dirs = [''];\n while (dirs.length > 0) {\n const relativeDir = dirs.pop()!;\n try {\n const entries = await fsp.readdir(path.join(root, relativeDir), { withFileTypes: true });\n for (const entry of entries) {\n const relative = normalizeRelative(path.join(relativeDir, entry.name));\n if (entry.isDirectory()) {\n if (!excluded.has(entry.name)) dirs.push(relative);\n } else if (entry.isFile()) {\n const value = await fingerprint(path.join(root, relative), maxHashBytes);\n if (value) result.set(relative, value);\n }\n }\n } catch (error) {\n onError?.(error);\n }\n }\n return result;\n}\n\nasync function fingerprint(filePath: string, maxHashBytes: number): Promise<FileFingerprint | undefined> {\n try {\n const stat = await fsp.stat(filePath);\n if (!stat.isFile()) return undefined;\n const base: FileFingerprint = { size: stat.size, mtimeMs: stat.mtimeMs };\n if (stat.size <= maxHashBytes) {\n base.hash = createHash('sha256').update(await fsp.readFile(filePath)).digest('hex');\n }\n return base;\n } catch (error) {\n if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\nfunction sameFingerprint(a: FileFingerprint | undefined, b: FileFingerprint | undefined): boolean {\n if (!a || !b) return a === b;\n if (a.hash !== undefined && b.hash !== undefined) return a.hash === b.hash;\n return a.size === b.size && a.mtimeMs === b.mtimeMs;\n}\n\nfunction isExcluded(relative: string, excluded: ReadonlySet<string>): boolean {\n return normalizeRelative(relative).split('/').some((segment) => excluded.has(segment));\n}\n\nfunction normalizeRelative(value: string): string {\n return value.replaceAll('\\\\', '/').replace(/^\\.\\//, '');\n}\n\nfunction resourceId(relativePath: string): string {\n return `file_${createHash('sha256').update(normalizeRelative(relativePath)).digest('hex').slice(0, 24)}`;\n}\n\nfunction unionKeys(a: ReadonlyMap<string, unknown>, b: ReadonlyMap<string, unknown>): string[] {\n return [...new Set([...a.keys(), ...b.keys()])];\n}\n", "import { createHash, randomUUID } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { atomicWrite, ensureDir, withFileLock } from '../utils/atomic-write.js';\nimport {\n CHRONICLE_SCHEMA_VERSION,\n type ChronicleEvent,\n type ChronicleEventInput,\n type ChronicleVerifyResult,\n} from './types.js';\n\nconst GENESIS_HASH = '0'.repeat(64);\nconst DEFAULT_MAX_PARTITION_BYTES = 100 * 1024 * 1024;\nconst DEFAULT_ROTATION_WINDOW_MS = 60 * 60 * 1000;\nconst RETENTION_CHECKPOINT_VERSION = 1;\n\ninterface ChronicleRetentionCheckpoint {\n version: typeof RETENTION_CHECKPOINT_VERSION;\n sequence: number;\n hash: string;\n}\n\nexport interface ChronicleJournalOptions {\n filePath: string;\n now?: (() => Date) | undefined;\n monotonicNow?: (() => bigint) | undefined;\n idFactory?: (() => string) | undefined;\n maxPending?: number | undefined;\n batchWindowMs?: number | undefined;\n maxPartitionSizeBytes?: number | undefined;\n rotationWindowMs?: number | undefined;\n retentionDays?: number | undefined;\n autoPurgeIntervalMs?: number | undefined;\n}\nexport interface ChronicleJournalStats {\n acceptedEvents: number; persistedEvents: number; rejectedEvents: number; failedEvents: number;\n batches: number; pendingEvents: number; maxObservedPending: number; largestBatch: number;\n lastBatchDurationMs?: number | undefined;\n partitionRolls: number;\n}\nexport interface ChroniclePurgeOptions {\n retentionDays: number;\n dryRun?: boolean | undefined;\n files?: string[] | undefined;\n}\nexport interface ChroniclePurgeResult {\n deletedCount: number;\n deletedBytes: number;\n skippedCount: number;\n errors: Array<{ file: string; reason: string }>;\n candidates?: string[] | undefined;\n}\n\nexport class ChronicleJournal {\n private readonly basePath: string;\n private readonly now: () => Date;\n private readonly monotonicNow: () => bigint;\n private readonly idFactory: () => string;\n private readonly maxPending: number;\n private readonly batchWindowMs: number;\n private readonly maxPartitionSizeBytes: number;\n private readonly rotationWindowMs: number;\n private readonly retentionDays: number;\n private readonly autoPurgeIntervalMs: number;\n private pending: Array<{ input: ChronicleEventInput; resolve: (event: ChronicleEvent) => void; reject: (error: unknown) => void; }> = [];\n private drainPromise: Promise<void> | undefined;\n private drainScheduled = false;\n private drainTimer: ReturnType<typeof setTimeout> | undefined;\n private readonly counters = { acceptedEvents: 0, persistedEvents: 0, rejectedEvents: 0, failedEvents: 0, batches: 0, maxObservedPending: 0, largestBatch: 0, partitionRolls: 0 };\n private lastBatchDurationMs: number | undefined;\n private partitionIndex = 0;\n private partitionStartedAt: number;\n private lastSequence = 0;\n private lastHash: string = GENESIS_HASH;\n private lastAutoPurgeAt = 0;\n\n constructor(options: ChronicleJournalOptions) {\n this.basePath = path.resolve(options.filePath);\n this.now = options.now ?? (() => new Date());\n this.monotonicNow = options.monotonicNow ?? (() => process.hrtime.bigint());\n this.idFactory = options.idFactory ?? randomUUID;\n this.maxPending = Math.max(1, options.maxPending ?? 100_000);\n this.batchWindowMs = Math.max(0, options.batchWindowMs ?? 5);\n this.maxPartitionSizeBytes = options.maxPartitionSizeBytes ?? DEFAULT_MAX_PARTITION_BYTES;\n this.rotationWindowMs = options.rotationWindowMs ?? DEFAULT_ROTATION_WINDOW_MS;\n this.retentionDays = options.retentionDays && Number.isFinite(options.retentionDays) && options.retentionDays > 0 ? options.retentionDays : 0;\n this.autoPurgeIntervalMs = Math.max(0, options.autoPurgeIntervalMs ?? 3_600_000);\n this.partitionStartedAt = Date.now();\n }\n\n get path(): string { return this.partitionIndex === 0 ? this.basePath : rotatedPath(this.basePath, this.partitionIndex); }\n\n stats(): ChronicleJournalStats {\n return { ...this.counters, pendingEvents: this.pending.length, ...(this.lastBatchDurationMs !== undefined ? { lastBatchDurationMs: this.lastBatchDurationMs } : {}) };\n }\n\n append(input: ChronicleEventInput): Promise<ChronicleEvent> {\n if (this.pending.length >= this.maxPending) { this.counters.rejectedEvents++; return Promise.reject(new Error(`Chronicle backpressure limit reached (${this.maxPending} pending events)`)); }\n const promise = new Promise<ChronicleEvent>((resolve, reject) => { this.pending.push({ input, resolve, reject }); });\n this.counters.acceptedEvents++;\n this.counters.maxObservedPending = Math.max(this.counters.maxObservedPending, this.pending.length);\n this.scheduleDrain();\n return promise;\n }\n\n async readAll(): Promise<ChronicleEvent[]> {\n await this.flush();\n const files = await collectPartitions(this.basePath);\n const entries: ChronicleEvent[] = [];\n for (const file of files) entries.push(...(await readEntriesStrict(file)));\n return entries;\n }\n\n async flush(): Promise<void> {\n if (this.drainTimer) { clearTimeout(this.drainTimer); this.drainTimer = undefined; this.drainScheduled = false; }\n while (this.pending.length > 0 || this.drainPromise) {\n if (this.pending.length > 0 && !this.drainPromise) this.startDrain();\n await this.drainPromise;\n }\n }\n\n async verify(): Promise<ChronicleVerifyResult> {\n await this.flush();\n const files = await collectPartitions(this.basePath);\n const checkpointResult = await readRetentionCheckpoint(this.basePath);\n if (checkpointResult.error) return { ok: false, entries: 0, brokenAt: 0, reason: checkpointResult.error };\n return verifyPartitionFiles(files, checkpointResult.checkpoint);\n }\n\n async purge(options: ChroniclePurgeOptions): Promise<ChroniclePurgeResult> {\n await this.flush();\n if (!Number.isFinite(options.retentionDays) || options.retentionDays <= 0) {\n throw new TypeError('Chronicle retentionDays must be a positive finite number');\n }\n await this.refreshStateFromDisk();\n const cutoff = Date.now() - options.retentionDays * 86400000;\n const activePath = path.resolve(this.path);\n const errors: ChroniclePurgeResult['errors'] = [];\n let dc = 0, db = 0, sc = 0;\n const suppliedFiles = options.files === undefined\n ? await collectJournalPartitions(this.basePath)\n : [...options.files];\n const eligible = new Set<string>();\n for (const suppliedPath of new Set(suppliedFiles)) {\n const file = path.resolve(suppliedPath);\n if (!isJournalPartition(file, path.dirname(this.basePath), this.basePath)) {\n errors.push({ file: suppliedPath, reason: 'not a Chronicle journal partition in this journal directory' });\n sc++;\n continue;\n }\n if (file === activePath) { sc++; continue; }\n let mtimeMs: number;\n try {\n const fileStat = await fs.lstat(file);\n if (!fileStat.isFile()) { sc++; continue; }\n mtimeMs = fileStat.mtimeMs;\n } catch (error) { if (isNotFound(error)) continue; errors.push({ file, reason: errorMessage(error) }); sc++; continue; }\n if (mtimeMs > cutoff) { sc++; continue; }\n eligible.add(file);\n }\n\n const candidates: string[] = [];\n const allPartitions = await collectJournalPartitions(this.basePath);\n for (const family of groupPartitionsByFamily(allPartitions).values()) {\n for (const file of family) {\n if (file === activePath || !eligible.has(file)) break;\n candidates.push(file);\n eligible.delete(file);\n }\n }\n sc += eligible.size;\n\n if (!options.dryRun) {\n for (const file of candidates) {\n try {\n const familyBase = partitionFamilyBase(file);\n let deletedBytes: number | undefined;\n await withFileLock(familyBase, async () => {\n const fileStat = await fs.lstat(file);\n if (!fileStat.isFile() || fileStat.mtimeMs > cutoff) return;\n const entries = await readEntriesStrict(file);\n const checkpointResult = await readRetentionCheckpoint(familyBase);\n if (checkpointResult.error) throw new Error(checkpointResult.error);\n const checkpoint = checkpointResult.checkpoint;\n const nextCheckpoint = verifyRetainedPrefix(entries, checkpoint);\n if (!nextCheckpoint) throw new Error('partition does not extend the trusted Chronicle chain');\n if (nextCheckpoint.sequence > (checkpoint?.sequence ?? 0)) {\n await writeRetentionCheckpoint(familyBase, nextCheckpoint);\n }\n deletedBytes = fileStat.size;\n await fs.unlink(file);\n });\n if (deletedBytes === undefined) { sc++; break; }\n db += deletedBytes;\n dc++;\n } catch (error) {\n errors.push({ file, reason: errorMessage(error) });\n sc++;\n // Candidates form an oldest-first prefix. Do not advance the\n // checkpoint beyond a partition that could not be removed: if its\n // checkpoint-covered bytes remain on disk, verify() must still be\n // able to anchor and validate them against that checkpoint.\n break;\n }\n }\n }\n return { deletedCount: dc, deletedBytes: db, skippedCount: sc, errors, ...(options.dryRun ? { candidates } : {}) };\n }\n\n private async maybeAutoPurge(): Promise<void> {\n if (this.retentionDays <= 0) return;\n const n = Date.now();\n if (n - this.lastAutoPurgeAt < this.autoPurgeIntervalMs) return;\n this.lastAutoPurgeAt = n;\n try { await this.purge({ retentionDays: this.retentionDays }); } catch { /* best-effort */ }\n }\n\n private scheduleDrain(): void {\n if (this.drainScheduled || this.drainPromise) return;\n this.drainScheduled = true;\n this.drainTimer = setTimeout(() => { this.drainTimer = undefined; this.drainScheduled = false; this.startDrain(); }, this.batchWindowMs);\n }\n\n private startDrain(): void {\n if (this.drainPromise || this.pending.length === 0) return;\n const batch = this.pending.splice(0);\n const drain = this.persistBatch(batch);\n this.drainPromise = drain.finally(() => { this.drainPromise = undefined; if (this.pending.length > 0) this.scheduleDrain(); });\n }\n\n private async refreshStateFromDisk(): Promise<void> {\n const files = await collectPartitions(this.basePath);\n const latest = files[files.length - 1] ?? this.basePath;\n this.partitionIndex = partitionIndex(latest, this.basePath);\n const entry = await readLastEntry(latest);\n const checkpointResult = await readRetentionCheckpoint(this.basePath);\n if (checkpointResult.error) throw new Error(checkpointResult.error);\n const checkpoint = checkpointResult.checkpoint;\n this.lastSequence = entry?.sequence ?? checkpoint?.sequence ?? 0;\n this.lastHash = entry?.hash ?? checkpoint?.hash ?? GENESIS_HASH;\n try { this.partitionStartedAt = (await fs.stat(latest)).birthtimeMs; } catch { this.partitionStartedAt = Date.now(); }\n }\n\n private async checkRotation(): Promise<void> {\n if (this.partitionIndex === 0 && this.lastSequence === 0) return;\n if (Number.isFinite(this.rotationWindowMs) && Date.now() - this.partitionStartedAt >= this.rotationWindowMs) { this.rotate(); return; }\n if (Number.isFinite(this.maxPartitionSizeBytes)) { try { if ((await fs.stat(this.path)).size >= this.maxPartitionSizeBytes) this.rotate(); } catch { /* ok */ } }\n }\n\n private rotate(): void { this.partitionIndex++; this.partitionStartedAt = Date.now(); this.counters.partitionRolls++; }\n\n private async persistBatch(batch: typeof this.pending): Promise<void> {\n const started = performance.now();\n this.counters.batches++;\n this.counters.largestBatch = Math.max(this.counters.largestBatch, batch.length);\n try {\n await ensureDir(path.dirname(this.basePath));\n let recorded: ChronicleEvent[] = [];\n await withFileLock(this.basePath, async () => {\n await this.refreshStateFromDisk();\n await this.checkRotation();\n const cp = this.path;\n let prev: { sequence: number; hash: string } | undefined = this.lastSequence > 0 ? { sequence: this.lastSequence, hash: this.lastHash } : undefined;\n recorded = batch.map(({ input }) => {\n const instant = this.now().toISOString();\n const ni = removeUndefined(input) as unknown as ChronicleEventInput;\n const uh = { ...ni, occurredAt: input.occurredAt ?? instant, monotonicNs: input.monotonicNs ?? this.monotonicNow().toString(), schemaVersion: CHRONICLE_SCHEMA_VERSION, eventId: this.idFactory(), observedAt: instant, persistedAt: instant, sequence: (prev?.sequence ?? 0) + 1, previousHash: prev?.hash ?? GENESIS_HASH };\n const event: ChronicleEvent = { ...uh, hash: hashValue(uh) };\n prev = event;\n return event;\n });\n await fs.appendFile(cp, recorded.map((e) => JSON.stringify(e)).join('\\n') + '\\n', 'utf8');\n });\n const last = recorded[recorded.length - 1]!;\n this.lastSequence = last.sequence;\n this.lastHash = last.hash;\n batch.forEach((item, i) => { item.resolve(recorded[i]!); });\n this.counters.persistedEvents += batch.length;\n void this.maybeAutoPurge();\n } catch (error) {\n this.counters.failedEvents += batch.length;\n batch.forEach((item) => { item.reject(error); });\n } finally { this.lastBatchDurationMs = performance.now() - started; }\n }\n}\n\nfunction rotatedPath(basePath: string, index: number): string {\n const dir = path.dirname(basePath);\n const ext = path.extname(basePath);\n const base = path.basename(basePath, ext);\n return path.join(dir, `${base}.${String(index).padStart(5, '0')}${ext}`);\n}\n\nasync function collectPartitions(basePath: string): Promise<string[]> {\n const dir = path.dirname(basePath);\n const ext = path.extname(basePath);\n const base = path.basename(basePath, ext);\n const pattern = new RegExp(`^${escapeRegex(base)}(?:\\\\.\\\\d{5})?${escapeRegex(ext)}$`);\n const result: string[] = [];\n try {\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) if (entry.isFile() && pattern.test(entry.name)) result.push(path.join(dir, entry.name));\n } catch { /* ok */ }\n const baseFile = path.join(dir, base + ext);\n const rotated = result.filter((file) => file !== baseFile).sort((left, right) => parseIndex(left, base, ext) - parseIndex(right, base, ext));\n return [baseFile, ...rotated];\n}\n\nasync function collectJournalPartitions(basePath: string): Promise<string[]> {\n const directory = path.dirname(basePath);\n const result: string[] = [];\n try {\n const entries = await fs.readdir(directory, { withFileTypes: true });\n for (const entry of entries) {\n const file = path.join(directory, entry.name);\n if (entry.isFile() && isJournalPartition(file, directory, basePath)) result.push(file);\n }\n } catch { /* ok */ }\n return result.sort(compareJournalPartitions);\n}\n\nfunction isJournalPartition(filePath: string, directory: string, basePath?: string): boolean {\n if (path.dirname(path.resolve(filePath)) !== path.resolve(directory)) return false;\n const fileName = path.basename(filePath);\n if (!basePath) return false;\n const baseName = path.basename(basePath);\n const dailyFamily = /^\\d{4}-\\d{2}-\\d{2}\\.events(?:\\.\\d{5})?\\.jsonl$/;\n if (/^\\d{4}-\\d{2}-\\d{2}\\.events\\.jsonl$/.test(baseName)) return dailyFamily.test(fileName);\n return partitionFamilyBase(path.resolve(filePath)) === partitionFamilyBase(path.resolve(basePath));\n}\n\nfunction compareJournalPartitions(left: string, right: string): number {\n const pattern = /^(.*\\.events)(?:\\.(\\d{5}))?\\.jsonl$/;\n const leftMatch = pattern.exec(path.basename(left));\n const rightMatch = pattern.exec(path.basename(right));\n const familyOrder = (leftMatch?.[1] ?? left).localeCompare(rightMatch?.[1] ?? right);\n return familyOrder || Number(leftMatch?.[2] ?? 0) - Number(rightMatch?.[2] ?? 0);\n}\n\nfunction groupPartitionsByFamily(files: string[]): Map<string, string[]> {\n const groups = new Map<string, string[]>();\n for (const file of files) {\n const family = partitionFamilyBase(file);\n const group = groups.get(family) ?? [];\n group.push(file);\n groups.set(family, group);\n }\n return groups;\n}\n\nfunction partitionFamilyBase(filePath: string): string {\n return filePath.replace(/\\.\\d{5}(?=\\.jsonl$)/, '');\n}\n\nfunction retentionCheckpointPath(basePath: string): string {\n return `${partitionFamilyBase(basePath)}.retention.json`;\n}\n\nfunction verifyRetainedPrefix(\n entries: ChronicleEvent[],\n checkpoint: ChronicleRetentionCheckpoint | undefined,\n): ChronicleRetentionCheckpoint | undefined {\n if (entries.length === 0) return undefined;\n let sequence = checkpoint?.sequence ?? 0;\n let hash = checkpoint?.hash ?? GENESIS_HASH;\n let advanced = false;\n for (const entry of entries) {\n if (entry.sequence <= sequence) continue;\n if (entry.sequence !== sequence + 1 || entry.previousHash !== hash) return undefined;\n const { hash: recordedHash, ...content } = entry;\n if (hashValue(content) !== recordedHash) return undefined;\n sequence = entry.sequence;\n hash = recordedHash;\n advanced = true;\n }\n if (!advanced) return checkpoint;\n return { version: RETENTION_CHECKPOINT_VERSION, sequence, hash };\n}\n\nasync function verifyPartitionFiles(\n files: string[],\n checkpoint: ChronicleRetentionCheckpoint | undefined,\n): Promise<ChronicleVerifyResult> {\n const checkpointSequence = checkpoint?.sequence ?? 0;\n let previousHash = checkpoint?.hash ?? GENESIS_HASH;\n let entries = 0;\n let lastSequence = checkpointSequence;\n let coveredPrevious: ChronicleEvent | undefined;\n for (const file of files) {\n let chunk: ChronicleEvent[];\n try { chunk = await readEntriesStrict(file); } catch (error) { return { ok: false, entries, brokenAt: entries, reason: errorMessage(error) }; }\n for (const entry of chunk) {\n const { hash: recordedHash, ...content } = entry;\n if (entry.sequence <= checkpointSequence) {\n // A checkpoint can be durably renamed just before its source\n // partition fails to unlink. Such retained bytes are still evidence:\n // validate them rather than treating every covered sequence as absent.\n if (hashValue(content) !== recordedHash) return { ok: false, entries, brokenAt: entries, reason: 'entry hash mismatch' };\n if (coveredPrevious && entry.sequence !== coveredPrevious.sequence + 1) {\n return { ok: false, entries, brokenAt: entries, reason: `sequence ${entry.sequence} is not ${coveredPrevious.sequence + 1}` };\n }\n if (coveredPrevious && entry.previousHash !== coveredPrevious.hash) {\n return { ok: false, entries, brokenAt: entries, reason: 'previous hash mismatch' };\n }\n if (entry.sequence === checkpointSequence && recordedHash !== checkpoint?.hash) {\n return { ok: false, entries, brokenAt: entries, reason: 'retention checkpoint hash mismatch' };\n }\n coveredPrevious = entry;\n continue;\n }\n const index = entries++;\n if (entry.sequence !== lastSequence + 1) return { ok: false, entries, brokenAt: index, reason: `sequence ${entry.sequence} is not ${lastSequence + 1}` };\n if (entry.previousHash !== previousHash) return { ok: false, entries, brokenAt: index, reason: 'previous hash mismatch' };\n if (hashValue(content) !== recordedHash) return { ok: false, entries, brokenAt: index, reason: 'entry hash mismatch' };\n previousHash = recordedHash;\n lastSequence = entry.sequence;\n }\n }\n if (\n coveredPrevious &&\n (coveredPrevious.sequence !== checkpointSequence || coveredPrevious.hash !== checkpoint?.hash)\n ) {\n return { ok: false, entries, brokenAt: entries, reason: 'retention checkpoint hash mismatch' };\n }\n return { ok: true, entries, lastSequence, lastHash: previousHash };\n}\n\nasync function readRetentionCheckpoint(basePath: string): Promise<{\n checkpoint?: ChronicleRetentionCheckpoint | undefined;\n error?: string | undefined;\n}> {\n const checkpointPath = retentionCheckpointPath(basePath);\n let raw: string;\n try { raw = await fs.readFile(checkpointPath, 'utf8'); } catch (error) {\n return isNotFound(error) ? {} : { error: `cannot read retention checkpoint: ${errorMessage(error)}` };\n }\n try {\n const parsed = JSON.parse(raw) as Partial<ChronicleRetentionCheckpoint>;\n if (parsed.version !== RETENTION_CHECKPOINT_VERSION || !Number.isSafeInteger(parsed.sequence) || (parsed.sequence ?? -1) < 0 || !isHash(parsed.hash)) {\n return { error: 'invalid Chronicle retention checkpoint' };\n }\n return { checkpoint: parsed as ChronicleRetentionCheckpoint };\n } catch { return { error: 'invalid Chronicle retention checkpoint JSON' }; }\n}\n\nasync function writeRetentionCheckpoint(basePath: string, checkpoint: ChronicleRetentionCheckpoint): Promise<void> {\n await atomicWrite(retentionCheckpointPath(basePath), `${JSON.stringify(checkpoint)}\\n`, { mode: 0o600 });\n}\n\nfunction isHash(value: unknown): value is string {\n return typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);\n}\n\nfunction parseIndex(filePath: string, base: string, ext: string): number {\n const suffix = path.basename(filePath).slice(base.length + 1, -ext.length);\n return suffix ? parseInt(suffix, 10) : 0;\n}\n\nfunction partitionIndex(filePath: string, basePath: string): number {\n const ext = path.extname(basePath);\n return parseIndex(filePath, path.basename(basePath, ext), ext);\n}\n\nfunction escapeRegex(text: string): string { return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); }\n\nasync function readLastEntry(filePath: string): Promise<ChronicleEvent | undefined> {\n let handle: fs.FileHandle;\n try { handle = await fs.open(filePath, 'r'); } catch (error) { if (isNotFound(error)) return undefined; throw error; }\n try {\n const size = (await handle.stat()).size;\n let position = size, suffix = '';\n while (position > 0) {\n const length = Math.min(65536, position);\n position -= length;\n const buf = Buffer.allocUnsafe(length);\n await handle.read(buf, 0, length, position);\n suffix = buf.toString('utf8') + suffix;\n const lines = suffix.split('\\n');\n const start = position === 0 ? 0 : 1;\n for (let i = lines.length - 1; i >= start; i--) {\n const trimmed = lines[i]!.trim();\n if (!trimmed) continue;\n try { return JSON.parse(trimmed) as ChronicleEvent; } catch { /* scan earlier */ }\n }\n suffix = lines[0] ?? '';\n }\n return undefined;\n } finally { await handle.close(); }\n}\n\nasync function readEntriesStrict(filePath: string): Promise<ChronicleEvent[]> {\n let raw: string;\n try { raw = await fs.readFile(filePath, 'utf8'); } catch (error) { if (isNotFound(error)) return []; throw error; }\n const entries: ChronicleEvent[] = [];\n const lines = raw.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i]!.trim();\n if (!trimmed) continue;\n try { entries.push(JSON.parse(trimmed) as ChronicleEvent); } catch { throw new Error(`invalid JSON at line ${i + 1} in ${path.basename(filePath)}`); }\n }\n return entries;\n}\n\nfunction hashValue(value: unknown): string { return createHash('sha256').update(stableStringify(value), 'utf8').digest('hex'); }\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const obj = value as Record<string, unknown>;\n return `{${Object.keys(obj).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')}}`;\n}\nfunction removeUndefined(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => item === undefined ? null : removeUndefined(item));\n if (value === null || typeof value !== 'object') return value;\n const result: Record<string, unknown> = {};\n for (const [key, item] of Object.entries(value as Record<string, unknown>)) if (item !== undefined) result[key] = removeUndefined(item);\n return result;\n}\nfunction isNotFound(error: unknown): boolean { return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'; }\nfunction errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); }\n\nexport { GENESIS_HASH };\n", "import { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs/promises';\nimport { watch as watchDir } from 'node:fs';\nimport type { FSWatcher } from 'node:fs';\nimport * as path from 'node:path';\nimport { FsError } from '../types/errors.js';\n\nexport interface AtomicWriteOptions {\n mode?: number | undefined;\n encoding?: BufferEncoding | undefined;\n}\n\nexport interface FileLockOptions {\n timeoutMs?: number | undefined;\n staleMs?: number | undefined;\n}\n\nexport async function atomicWrite(\n targetPath: string,\n content: string | Uint8Array,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const tmp = path.join(dir, `.${path.basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n\n // Write content to tmp first; 'wx' ensures exclusive creation (fails if\n // tmp already exists \u2014 extremely unlikely with 6-byte random suffix).\n try {\n if (typeof content === 'string') {\n await fs.writeFile(tmp, content, { flag: 'wx', encoding: opts.encoding ?? 'utf8' });\n } else {\n await fs.writeFile(tmp, content, { flag: 'wx' });\n }\n try {\n const fh = await fs.open(tmp, 'r+');\n try {\n await fh.sync();\n } finally {\n await fh.close();\n }\n } catch {\n // fsync best-effort\n }\n // Now safely read mode from target (if it exists) and apply to tmp before rename.\n // Prefer opts.mode for new files; for existing files preserve their mode.\n let mode: number | undefined;\n try {\n const stat = await fs.stat(targetPath);\n mode = stat.mode & 0o777;\n } catch {\n mode = opts.mode;\n }\n if (mode !== undefined) {\n await fs.chmod(tmp, mode);\n }\n await renameWithRetry(tmp, targetPath);\n // P3 #20 (before-release.md): on Windows, fs.rename (MoveFileExW) does\n // not preserve Unix permission bits \u2014 the chmod above applies to the tmp\n // file, but the rename may reset the destination's mode to the Windows\n // default. Re-apply the mode after rename on win32 so an edited file\n // keeps its executable bit (or any non-default permission). On POSIX,\n // rename preserves metadata so this is a no-op (chmod is idempotent and\n // cheap), but we gate it on win32 to avoid the extra stat+chmod on the\n // common path.\n if (mode !== undefined && process.platform === 'win32') {\n try {\n await fs.chmod(targetPath, mode);\n } catch {\n // Best-effort: a transient EPERM (antivirus lock) should not fail\n // the write \u2014 the content is already on disk.\n }\n }\n } catch (err) {\n try {\n await fs.unlink(tmp);\n } catch {\n // ignore cleanup error\n }\n throw err;\n }\n}\n\nexport async function ensureDir(dir: string): Promise<void> {\n await fs.mkdir(dir, { recursive: true });\n}\n\nexport async function withFileLock<T>(\n targetPath: string,\n fn: () => Promise<T>,\n opts: FileLockOptions = {},\n): Promise<T> {\n const dir = path.dirname(targetPath);\n await fs.mkdir(dir, { recursive: true });\n const lockPath = path.join(dir, `.${path.basename(targetPath)}.lock`);\n // A lock holder can be scheduled out for several seconds when the full test\n // suite (or a busy workstation) is spawning many child processes. Five\n // seconds was short enough to turn ordinary contention into a dropped\n // best-effort index write. Keep the wait bounded, but leave enough headroom\n // for the holder to resume and release before stale-lock recovery applies.\n const timeoutMs = opts.timeoutMs ?? 15_000;\n const staleMs = opts.staleMs ?? 30_000;\n const started = Date.now();\n let handle: fs.FileHandle | undefined;\n\n for (;;) {\n try {\n handle = await fs.open(lockPath, 'wx');\n await handle.writeFile(`${process.pid}:${Date.now()}`);\n break;\n } catch (err) {\n // If fs.open succeeded but handle.writeFile threw (e.g. ENOSPC, EIO),\n // `handle` owns an open exclusive lock file. Close the handle and remove\n // the orphan lock so the next iteration (or a peer) can acquire it\n // without timing out on the stale-lock window or dead-looping on EEXIST.\n if (handle) {\n await handle.close().catch(() => {});\n await fs.unlink(lockPath).catch(() => {});\n handle = undefined;\n }\n const code = (err as NodeJS.ErrnoException).code;\n // ENOENT means the directory was deleted (e.g. by concurrent cleanup).\n // Recreate it and retry acquiring the lock.\n if (code === 'ENOENT') {\n await fs.mkdir(dir, { recursive: true });\n continue;\n }\n if (code !== 'EEXIST' && code !== 'EPERM') throw err;\n try {\n const stat = await fs.stat(lockPath);\n if (Date.now() - stat.mtimeMs > staleMs) {\n await fs.unlink(lockPath);\n continue;\n }\n } catch {\n continue;\n }\n const elapsed = Date.now() - started;\n if (elapsed >= timeoutMs) {\n throw new FsError({\n message: `Timed out waiting for file lock: ${targetPath}`,\n code: 'FS_ATOMIC_WRITE_FAILED',\n path: targetPath,\n context: { timeoutMs },\n });\n }\n // Wait for the lock to be released, using a filesystem watcher for\n // nearly-instant wake-up instead of polling. The watcher is best-effort:\n // a safety timeout fires at most every 100ms so we don't busy-wait.\n await waitForLockRelease(lockPath, timeoutMs - elapsed);\n }\n }\n\n try {\n return await fn();\n } finally {\n try {\n await handle?.close();\n } catch {\n // ignore\n }\n try {\n await fs.unlink(lockPath);\n } catch {\n // ignore\n }\n }\n}\n\n/**\n * Watch a lock file's parent directory for the file being removed (unlinked),\n * which signals that the lock holder has released it. A safety timeout caps\n * the wait so the overall `withFileLock` timeout is always respected.\n *\n * Uses a bounded safety interval (up to 100ms) so even if `fs.watch` is\n * unavailable or misses the event, we never busy-wait at 25ms fixed polling.\n */\nasync function waitForLockRelease(lockPath: string, remainingMs: number): Promise<void> {\n const parentDir = path.dirname(lockPath);\n const lockName = path.basename(lockPath);\n const intervalMs = Math.min(remainingMs, 100);\n\n return new Promise<void>((resolve) => {\n let settled = false;\n let watcher: FSWatcher | null = null;\n\n // Safety timer \u2014 always fires, even if fs.watch is unavailable.\n const timer = setTimeout(() => {\n settled = true;\n watcher?.close();\n resolve();\n }, intervalMs);\n\n try {\n watcher = watchDir(parentDir, (eventType, filename) => {\n if (settled) return;\n // 'rename' fires on unlink on most platforms; 'change' is a\n // conservative fallback for environments that only emit 'change'.\n if (filename === lockName && (eventType === 'rename' || eventType === 'change')) {\n settled = true;\n clearTimeout(timer);\n watcher?.close();\n resolve();\n }\n });\n } catch {\n // fs.watch not supported (e.g. some container environments, network\n // filesystems). Clear the safety timer and fall back to a single\n // short delay \u2014 the caller's loop will retry on the next iteration.\n clearTimeout(timer);\n if (!settled) {\n settled = true;\n setTimeout(resolve, Math.min(remainingMs, 25));\n }\n return;\n }\n\n // Re-check lock existence after setting up the watch to close the race\n // where the lock was released between our last EEXIST check and now.\n fs.access(lockPath).then(\n () => {\n // Lock still exists \u2014 the watch (or safety timer) will resolve.\n },\n () => {\n // Lock was already released \u2014 respond immediately.\n if (!settled) {\n settled = true;\n clearTimeout(timer);\n watcher?.close();\n resolve();\n }\n },\n );\n });\n}\n\n// On Windows, fs.rename over an existing file can fail with EPERM/EBUSY/EACCES\n// when antivirus, file indexers, editor file watchers, or a concurrent writer\n// briefly hold a handle on the destination. These are transient \u2014 retry with a\n// short backoff before giving up. POSIX renames are atomic and won't hit this.\nconst TRANSIENT_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY']);\n\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n if (process.platform !== 'win32') {\n await fs.rename(from, to);\n return;\n }\n const delays = [10, 25, 60, 120, 250];\n let lastErr: unknown;\n for (let i = 0; i <= delays.length; i++) {\n try {\n await fs.rename(from, to);\n return;\n } catch (err) {\n lastErr = err;\n const code = (err as NodeJS.ErrnoException)?.code;\n if (!code || !TRANSIENT_RENAME_CODES.has(code) || i === delays.length) {\n throw err;\n }\n await new Promise((resolve) => setTimeout(resolve, delays[i]));\n }\n }\n throw lastErr;\n}\n", "import { toErrorMessage } from '../utils/index.js';\n\n/**\n * WrongStack error hierarchy.\n *\n * Every error thrown by the framework is a `WrongStackError` with a\n * machine-readable `code`, a `subsystem` tag, and a `severity` level.\n * This lets consumers (CLI, TUI, plugins, tests) branch on structured\n * data instead of parsing error messages.\n */\n\n// \u2500\u2500 Error codes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Machine-readable error codes as frozen constants.\n *\n * Use `ERROR_CODES.X` instead of raw string literals for:\n * - IDE autocomplete and compile-time validation\n * - Safe refactoring (rename updates all usages)\n * - Plugin extensibility (extend the object to add custom codes)\n *\n * The `ErrorCode` type is derived from this object, so adding a new\n * code here automatically updates the type without extra changes.\n */\nexport const ERROR_CODES = {\n // Provider\n PROVIDER_RATE_LIMITED: 'PROVIDER_RATE_LIMITED',\n PROVIDER_AUTH_FAILED: 'PROVIDER_AUTH_FAILED',\n PROVIDER_OVERLOADED: 'PROVIDER_OVERLOADED',\n PROVIDER_INVALID_REQUEST: 'PROVIDER_INVALID_REQUEST',\n PROVIDER_SERVER_ERROR: 'PROVIDER_SERVER_ERROR',\n PROVIDER_NETWORK_ERROR: 'PROVIDER_NETWORK_ERROR',\n PROVIDER_CONTEXT_OVERFLOW: 'PROVIDER_CONTEXT_OVERFLOW',\n // Tool\n TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n TOOL_PERMISSION_DENIED: 'TOOL_PERMISSION_DENIED',\n TOOL_EXECUTION_FAILED: 'TOOL_EXECUTION_FAILED',\n TOOL_TIMEOUT: 'TOOL_TIMEOUT',\n TOOL_INPUT_INVALID: 'TOOL_INPUT_INVALID',\n // Config\n CONFIG_INVALID: 'CONFIG_INVALID',\n CONFIG_NOT_FOUND: 'CONFIG_NOT_FOUND',\n CONFIG_PARSE_FAILED: 'CONFIG_PARSE_FAILED',\n CONFIG_MIGRATION_NEEDED: 'CONFIG_MIGRATION_NEEDED',\n // Plugin\n PLUGIN_LOAD_FAILED: 'PLUGIN_LOAD_FAILED',\n PLUGIN_API_MISMATCH: 'PLUGIN_API_MISMATCH',\n PLUGIN_MISSING_DEPENDENCY: 'PLUGIN_MISSING_DEPENDENCY',\n // Agent\n AGENT_ITERATION_LIMIT: 'AGENT_ITERATION_LIMIT',\n AGENT_CONTEXT_OVERFLOW: 'AGENT_CONTEXT_OVERFLOW',\n AGENT_ABORTED: 'AGENT_ABORTED',\n AGENT_RUN_FAILED: 'AGENT_RUN_FAILED',\n // Session\n SESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n SESSION_CORRUPTED: 'SESSION_CORRUPTED',\n SESSION_WRITE_FAILED: 'SESSION_WRITE_FAILED',\n // Container / Registry\n CONTAINER_TOKEN_ALREADY_BOUND: 'CONTAINER_TOKEN_ALREADY_BOUND',\n CONTAINER_TOKEN_NOT_BOUND: 'CONTAINER_TOKEN_NOT_BOUND',\n CONTAINER_CIRCULAR_DEPENDENCY: 'CONTAINER_CIRCULAR_DEPENDENCY',\n REGISTRY_DUPLICATE: 'REGISTRY_DUPLICATE',\n REGISTRY_NOT_FOUND: 'REGISTRY_NOT_FOUND',\n REGISTRY_INVALID: 'REGISTRY_INVALID',\n // File system\n FS_READ_FAILED: 'FS_READ_FAILED',\n FS_WRITE_FAILED: 'FS_WRITE_FAILED',\n FS_MKDIR_FAILED: 'FS_MKDIR_FAILED',\n FS_DELETE_FAILED: 'FS_DELETE_FAILED',\n FS_ATOMIC_WRITE_FAILED: 'FS_ATOMIC_WRITE_FAILED',\n // SDD (Spec-Driven Development)\n SDD_VALIDATION_FAILED: 'SDD_VALIDATION_FAILED',\n SDD_PARSE_FAILED: 'SDD_PARSE_FAILED',\n SDD_INVALID_STATE: 'SDD_INVALID_STATE',\n SDD_NOT_READY: 'SDD_NOT_READY',\n // General\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n PARSE_FAILED: 'PARSE_FAILED',\n UNKNOWN: 'UNKNOWN',\n} as const;\n\n/**\n * Union type derived from `ERROR_CODES`. Using `typeof ERROR_CODES[keyof typeof ERROR_CODES]`\n * instead of a string literal union means TypeScript auto-updates the type whenever\n * a new code is added to `ERROR_CODES` \u2014 no need to keep two lists in sync.\n */\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\nexport type ErrorSubsystem =\n | 'provider'\n | 'tool'\n | 'config'\n | 'plugin'\n | 'agent'\n | 'session'\n | 'sdd'\n | 'container'\n | 'fs'\n | 'general';\nexport type ErrorSeverity = 'fatal' | 'error' | 'warning';\n\n// \u2500\u2500 Base error class \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport class WrongStackError extends Error {\n readonly code: ErrorCode;\n readonly subsystem: ErrorSubsystem;\n readonly severity: ErrorSeverity;\n readonly recoverable: boolean;\n readonly context?: Record<string, unknown> | undefined;\n\n constructor(opts: {\n message: string;\n code: ErrorCode;\n subsystem: ErrorSubsystem;\n severity?: ErrorSeverity | undefined;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super(opts.message, { cause: opts.cause });\n this.name = 'WrongStackError';\n this.code = opts.code;\n this.subsystem = opts.subsystem;\n this.severity = opts.severity ?? 'error';\n this.recoverable = opts.recoverable ?? false;\n this.context = opts.context;\n }\n\n /**\n * Render a one-line user-facing description.\n * Subclasses should override for domain-specific formatting.\n */\n describe(): string {\n const ctx = this.context ? ` ${formatContext(this.context)}` : '';\n return `${this.code}: ${this.message}${ctx}`;\n }\n}\n\nfunction formatContext(ctx: Record<string, unknown>): string {\n const parts = Object.entries(ctx)\n .filter(([, v]) => v !== undefined)\n .slice(0, 3)\n .map(([k, v]) => `${k}=${String(v)}`);\n return parts.length > 0 ? `[${parts.join(' ')}]` : '';\n}\n\n// \u2500\u2500 Specific error classes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Tool execution errors \u2014 thrown by ToolExecutor and individual tools.\n */\nexport class ToolError extends WrongStackError {\n readonly toolName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n | 'TOOL_NOT_FOUND'\n | 'TOOL_PERMISSION_DENIED'\n | 'TOOL_EXECUTION_FAILED'\n | 'TOOL_TIMEOUT'\n | 'TOOL_INPUT_INVALID'\n >;\n toolName: string;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'tool',\n recoverable: opts.recoverable,\n context: { tool: opts.toolName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolError';\n this.toolName = opts.toolName;\n }\n}\n\n/**\n * Config loading / validation errors.\n */\nexport class ConfigError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'CONFIG_INVALID' | 'CONFIG_NOT_FOUND' | 'CONFIG_PARSE_FAILED' | 'CONFIG_MIGRATION_NEEDED'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'config',\n severity: 'fatal',\n recoverable: false,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'ConfigError';\n }\n}\n\n/**\n * Plugin loading / lifecycle errors.\n */\nexport class PluginError extends WrongStackError {\n readonly pluginName: string;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'PLUGIN_LOAD_FAILED' | 'PLUGIN_API_MISMATCH' | 'PLUGIN_MISSING_DEPENDENCY'\n >;\n pluginName: string;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'plugin',\n severity: 'error',\n recoverable: opts.code === ERROR_CODES.PLUGIN_MISSING_DEPENDENCY,\n context: { plugin: opts.pluginName, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'PluginError';\n this.pluginName = opts.pluginName;\n }\n}\n\n/**\n * Agent runtime errors \u2014 thrown by Agent.run when a non-WrongStackError\n * escapes the inner loop, so callers always see a structured error.\n */\nexport class AgentError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'AGENT_ITERATION_LIMIT' | 'AGENT_CONTEXT_OVERFLOW' | 'AGENT_ABORTED' | 'AGENT_RUN_FAILED'\n >;\n recoverable?: boolean | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'agent',\n severity: opts.code === ERROR_CODES.AGENT_ABORTED ? 'warning' : 'error',\n recoverable: opts.recoverable ?? opts.code === ERROR_CODES.AGENT_ITERATION_LIMIT,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'AgentError';\n }\n}\n\n/**\n * Wrap an arbitrary thrown value into a `WrongStackError` so the caller\n * always gets a structured error. Pass-throughs WrongStackError instances\n * unchanged; raw `Error`s and primitives get an `AGENT_RUN_FAILED` wrapper\n * with the original preserved as `cause`.\n */\nexport function toWrongStackError(\n err: unknown,\n code: Extract<ErrorCode, 'AGENT_RUN_FAILED' | 'AGENT_ABORTED' | 'UNKNOWN'> = ERROR_CODES.AGENT_RUN_FAILED,\n): WrongStackError {\n if (err instanceof WrongStackError) return err;\n const message = toErrorMessage(err);\n return new AgentError({\n message,\n code: code === 'UNKNOWN' ? ERROR_CODES.AGENT_RUN_FAILED : code,\n cause: err,\n });\n}\n\n/**\n * Session storage errors.\n */\nexport class SessionError extends WrongStackError {\n readonly sessionId?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<ErrorCode, 'SESSION_NOT_FOUND' | 'SESSION_CORRUPTED' | 'SESSION_WRITE_FAILED'>;\n sessionId?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'session',\n severity: opts.code === ERROR_CODES.SESSION_WRITE_FAILED ? 'error' : 'warning',\n recoverable: opts.code !== ERROR_CODES.SESSION_CORRUPTED,\n context: { sessionId: opts.sessionId, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'SessionError';\n this.sessionId = opts.sessionId;\n }\n}\n\n/**\n * SDD (Spec-Driven Development) errors \u2014 spec validation, parsing, and\n * state machine violations in the AISpecBuilder, TaskFlow, and TaskTracker.\n */\nexport class SddError extends WrongStackError {\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'SDD_VALIDATION_FAILED' | 'SDD_PARSE_FAILED' | 'SDD_INVALID_STATE' | 'SDD_NOT_READY'\n >;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'sdd',\n severity: opts.code === ERROR_CODES.SDD_PARSE_FAILED ? 'warning' : 'error',\n recoverable: opts.code === ERROR_CODES.SDD_NOT_READY,\n context: opts.context,\n cause: opts.cause,\n });\n this.name = 'SddError';\n }\n}\n\n/**\n * File system operation errors.\n */\nexport class FsError extends WrongStackError {\n readonly path?: string | undefined;\n\n constructor(opts: {\n message: string;\n code: Extract<\n ErrorCode,\n 'FS_READ_FAILED' | 'FS_WRITE_FAILED' | 'FS_MKDIR_FAILED' | 'FS_DELETE_FAILED' | 'FS_ATOMIC_WRITE_FAILED'\n >;\n path?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: opts.code,\n subsystem: 'fs',\n severity: 'error',\n recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,\n context: { path: opts.path, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FsError';\n this.path = opts.path;\n }\n}\n\n/**\n * HTTP fetch error \u2014 thrown when a network request returns a non-OK status.\n * Carries the response status so {@link classifyToolError} can branch on it\n * (429 \u2192 transient, 404 \u2192 not_found, 401 \u2192 permission) without duck-typing\n * the error via `'response' in err`.\n *\n * P3 #18 (before-release.md): the previous `'response' in err` check caught\n * any Error with a `response` property, including custom errors, proxy\n * objects, or mocked errors in tests. `instanceof FetchError` is reliable.\n *\n * Tools and providers that make HTTP requests and need the executor to\n * classify their failures should throw `new FetchError({ status, message })`\n * instead of a bare `Error` with an ad-hoc `response` field.\n */\nexport class FetchError extends WrongStackError {\n readonly status: number;\n\n constructor(opts: {\n message: string;\n status: number;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.VALIDATION_ERROR,\n subsystem: 'general',\n severity: 'error',\n recoverable: opts.status === 429 || opts.status >= 500,\n context: { status: opts.status, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'FetchError';\n this.status = opts.status;\n }\n}\n\n/**\n * Tool input validation error \u2014 thrown when a tool's input fails a validation\n * check that the JSON Schema cannot express (e.g. `old_string === new_string`\n * in edit, or a cross-field invariant). Use this instead of a bare\n * `throw new Error('...validation...')` so {@link classifyToolError} can\n * match on `instanceof` rather than a locale-dependent message substring.\n *\n * P2 #6 (before-release.md): the previous `err.message.includes('validation')`\n * check misclassified any error whose message happened to contain \"validation\"\n * (e.g. a third-party \"input validation timeout\") as a VALIDATION error.\n *\n * Named `ToolValidationError` (not `ValidationError`) to avoid colliding with\n * the existing `ValidationError` interface exported by json-schema-validate.ts\n * (a validation-result shape, not an Error subclass).\n */\nexport class ToolValidationError extends WrongStackError {\n constructor(opts: {\n message: string;\n /** Field path or tool name that failed validation, for diagnostics. */\n field?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.VALIDATION_ERROR,\n subsystem: 'general',\n severity: 'error',\n recoverable: false,\n context: { field: opts.field, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ToolValidationError';\n }\n}\n\n/**\n * Response / payload parse error \u2014 thrown when an upstream HTTP response,\n * file, or data structure is well-formed at the transport layer (HTTP 200,\n * valid JSON) but is missing required fields or has an unexpected shape.\n *\n * Distinct from `ConfigError(CONFIG_PARSE_FAILED)` (which is specifically\n * for config-file parsing) and `FetchError` (which covers HTTP non-OK\n * responses). `ParseError` fills the gap: the request succeeded but the\n * response body couldn't be interpreted.\n *\n * Common sites: OAuth token responses missing `access_token`, device-code\n * responses missing `device_code`, registry responses with unexpected\n * schemas.\n */\nexport class ParseError extends WrongStackError {\n readonly source?: string | undefined;\n\n constructor(opts: {\n message: string;\n /**\n * What was being parsed \u2014 e.g. `'oauth-token-response'`,\n * `'device-code-response'`. Lets consumers distinguish parse failures\n * from different upstream APIs without parsing the message.\n */\n source?: string | undefined;\n context?: Record<string, unknown> | undefined;\n cause?: unknown | undefined;\n }) {\n super({\n message: opts.message,\n code: ERROR_CODES.PARSE_FAILED,\n subsystem: 'general',\n severity: 'error',\n recoverable: false,\n context: { source: opts.source, ...opts.context },\n cause: opts.cause,\n });\n this.name = 'ParseError';\n this.source = opts.source;\n }\n}\n\n// \u2500\u2500 Type guards \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function isWrongStackError(err: unknown): err is WrongStackError {\n return err instanceof WrongStackError;\n}\n\nexport function isToolError(err: unknown): err is ToolError {\n return err instanceof ToolError;\n}\n\nexport function isConfigError(err: unknown): err is ConfigError {\n return err instanceof ConfigError;\n}\n\nexport function isPluginError(err: unknown): err is PluginError {\n return err instanceof PluginError;\n}\n\nexport function isSessionError(err: unknown): err is SessionError {\n return err instanceof SessionError;\n}\n\nexport function isAgentError(err: unknown): err is AgentError {\n return err instanceof AgentError;\n}\n\nexport function isFsError(err: unknown): err is FsError {\n return err instanceof FsError;\n}\n\nexport function isToolValidationError(err: unknown): err is ToolValidationError {\n return err instanceof ToolValidationError;\n}\n\nexport function isFetchError(err: unknown): err is FetchError {\n return err instanceof FetchError;\n}\n\nexport function isParseError(err: unknown): err is ParseError {\n return err instanceof ParseError;\n}\n\nexport function isSddError(err: unknown): err is SddError {\n return err instanceof SddError;\n}\n", "/** Schema version for the first durable WrongStack Chronicle event envelope. */\nexport const CHRONICLE_SCHEMA_VERSION = 1 as const;\n\nexport type ChronicleOutcome =\n | 'started'\n | 'success'\n | 'failure'\n | 'cancelled'\n | 'denied'\n | 'abandoned'\n | 'unknown';\n\n/** Stable identities used to project one event into global and project views. */\nexport interface ChronicleScope {\n installationId: string;\n machineId: string;\n projectId?: string | undefined;\n repositoryId?: string | undefined;\n workspaceId?: string | undefined;\n worktreeId?: string | undefined;\n sessionId?: string | undefined;\n turnId?: string | undefined;\n iterationId?: string | undefined;\n agentId?: string | undefined;\n goalId?: string | undefined;\n planId?: string | undefined;\n taskId?: string | undefined;\n kanbanBoardId?: string | undefined;\n}\n\nexport interface ChronicleCorrelation {\n traceId: string;\n spanId: string;\n parentSpanId?: string | undefined;\n logicalRequestId?: string | undefined;\n attemptId?: string | undefined;\n toolCallId?: string | undefined;\n}\n\nexport interface ChronicleRuntimeIdentity {\n providerId?: string | undefined;\n modelId?: string | undefined;\n modelRevision?: string | undefined;\n processId?: number | undefined;\n parentProcessId?: number | undefined;\n}\n\nexport interface ChronicleResourceRef {\n kind: 'file' | 'symbol' | 'memory' | 'task' | 'kanban' | 'process' | 'network' | 'artifact' | 'other';\n id: string;\n path?: string | undefined;\n lineStart?: number | undefined;\n lineEnd?: number | undefined;\n contentHashBefore?: string | undefined;\n contentHashAfter?: string | undefined;\n}\n\nexport interface ChronicleEventInput {\n eventType: string;\n scope: ChronicleScope;\n correlation: ChronicleCorrelation;\n runtime?: ChronicleRuntimeIdentity | undefined;\n resource?: ChronicleResourceRef | undefined;\n outcome?: ChronicleOutcome | undefined;\n durationNs?: string | undefined;\n occurredAt?: string | undefined;\n monotonicNs?: string | undefined;\n attributes?: Record<string, unknown> | undefined;\n tags?: Record<string, string> | undefined;\n}\n\n/**\n * Lossless durable envelope. All wall-clock timestamps are UTC ISO-8601;\n * monotonicNs is used for elapsed-time ordering inside one process.\n */\nexport interface ChronicleEvent extends ChronicleEventInput {\n schemaVersion: typeof CHRONICLE_SCHEMA_VERSION;\n eventId: string;\n observedAt: string;\n persistedAt: string;\n sequence: number;\n previousHash: string;\n hash: string;\n}\n\nexport type ChronicleVerifyResult =\n | { ok: true; entries: number; lastSequence: number; lastHash: string }\n | { ok: false; entries: number; brokenAt: number; reason: string };\n", "import type { EventBus, EventMap } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleProviderAdapterOptions {\n events: EventBus;\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\n/** Persist provider attempt facts without coupling the provider runner to storage. */\nexport function wireProviderAttemptsToChronicle(options: ChronicleProviderAdapterOptions): () => void {\n const unsubs = [\n options.events.on('provider.attempt.started', (event) => persist(options, event, {\n eventType: 'provider.attempt.started',\n outcome: 'started',\n occurredAt: event.startedAt,\n })),\n options.events.on('provider.attempt.completed', (event) => persist(options, event, {\n eventType: 'provider.attempt.completed',\n outcome: 'success',\n occurredAt: event.endedAt,\n durationNs: millisecondsToNanoseconds(event.durationMs),\n })),\n options.events.on('provider.attempt.failed', (event) => persist(options, event, {\n eventType: 'provider.attempt.failed',\n outcome: 'failure',\n occurredAt: event.endedAt,\n durationNs: millisecondsToNanoseconds(event.durationMs),\n })),\n ];\n return () => unsubs.forEach((unsubscribe) => { unsubscribe(); });\n}\n\ntype ProviderAttemptEvent =\n | EventMap['provider.attempt.started']\n | EventMap['provider.attempt.completed']\n | EventMap['provider.attempt.failed'];\n\nfunction persist(\n options: ChronicleProviderAdapterOptions,\n event: ProviderAttemptEvent,\n base: Pick<ChronicleEventInput, 'eventType' | 'outcome' | 'occurredAt' | 'durationNs'>,\n): void {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const input: ChronicleEventInput = {\n ...base,\n scope: {\n ...context.scope,\n sessionId: event.sessionId,\n ...(event.agentId ? { agentId: event.agentId } : {}),\n },\n correlation: {\n ...context.correlation,\n ...(event.traceId ? { traceId: event.traceId } : {}),\n logicalRequestId: event.logicalRequestId,\n attemptId: event.attemptId,\n },\n runtime: { providerId: event.providerId, modelId: event.model },\n attributes: providerAttributes(event),\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n}\n\nfunction providerAttributes(event: ProviderAttemptEvent): Record<string, unknown> {\n const { sessionId: _sessionId, traceId: _traceId, agentId: _agentId, providerId: _providerId,\n model: _model, logicalRequestId: _logicalRequestId, attemptId: _attemptId, ...attributes } = event;\n return attributes;\n}\n\nfunction millisecondsToNanoseconds(durationMs: number): string {\n return Math.round(durationMs * 1_000_000).toString();\n}\n", "import { createHash } from 'node:crypto';\nimport type { EventBus, EventMap } from '../kernel/events.js';\nimport type { SecretScrubber } from '../types/secret-scrubber.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput, ChronicleResourceRef } from './types.js';\n\nexport interface ChronicleToolAdapterOptions {\n events: EventBus;\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n scrubber: SecretScrubber;\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\n/** Persist the complete tool lifecycle plus resource edges discovered in results. */\nexport function wireToolsToChronicle(options: ChronicleToolAdapterOptions): () => void {\n const unsubs = [\n options.events.on('tool.started', (event) => {\n const input = scrubValue(options.scrubber, event.input);\n persist(options, event, {\n eventType: 'tool.started',\n outcome: 'started',\n attributes: {\n toolName: event.name,\n input,\n inputHash: hashText(input),\n },\n });\n }),\n options.events.on('permission.evaluated', (event) => {\n persist(options, event, {\n eventType: 'permission.evaluated',\n outcome: event.effectiveDecision === 'deny' ? 'denied' : 'success',\n attributes: {\n toolName: event.name,\n inputHash: event.inputHash,\n policyDecision: event.policyDecision,\n effectiveDecision: event.effectiveDecision,\n decisionSource: event.decisionSource,\n reason: event.reason ? options.scrubber.scrub(event.reason) : undefined,\n riskTier: event.riskTier,\n yoloEnabled: event.yoloEnabled,\n boundaryDecision: event.boundaryDecision,\n boundaryReason: event.boundaryReason\n ? options.scrubber.scrub(event.boundaryReason)\n : undefined,\n capabilityDowngraded: event.capabilityDowngraded,\n },\n });\n }),\n options.events.on('tool.executed', (event) => {\n const output = options.scrubber.scrub(event.output ?? '');\n persist(options, event, {\n eventType: 'tool.executed',\n outcome: event.ok ? 'success' : 'failure',\n durationNs: millisecondsToNanoseconds(event.durationMs),\n attributes: {\n toolName: event.name,\n ok: event.ok,\n outputPreview: output,\n outputHash: hashText(output),\n outputBytes: event.outputBytes,\n outputTokens: event.outputTokens,\n outputLines: event.outputLines,\n metadata: event.metadata,\n },\n });\n persistEvidenceEdges(options, event);\n }),\n options.events.on('tool.failed', (event) => persist(options, event, {\n eventType: 'tool.failed',\n outcome: 'failure',\n durationNs: millisecondsToNanoseconds(event.durationMs),\n attributes: {\n toolName: event.name,\n category: event.category,\n retryable: event.retryable,\n detail: event.detail,\n errorCode: event.errorCode,\n errorSubsystem: event.errorSubsystem,\n errorSeverity: event.errorSeverity,\n },\n })),\n options.events.on('tool.progress', (event) => {\n if (event.event.type !== 'file_changed') return;\n const resource = progressResource(event);\n persist(options, event, {\n eventType: 'file.mutation.observed',\n outcome: 'started',\n ...(resource ? { resource } : {}),\n attributes: {\n toolName: event.name,\n progressType: event.event.type,\n text: options.scrubber.scrub(event.event.text ?? ''),\n data: scrubValue(options.scrubber, event.event.data),\n operation: event.event.operation,\n },\n });\n }),\n ];\n return () => unsubs.forEach((unsubscribe) => { unsubscribe(); });\n}\n\ntype ToolCorrelationEvent = {\n sessionId?: string | undefined;\n traceId?: string | undefined;\n agentId?: string | undefined;\n id?: string | undefined;\n name: string;\n};\n\nfunction persist(\n options: ChronicleToolAdapterOptions,\n event: ToolCorrelationEvent,\n fields: Pick<ChronicleEventInput, 'eventType' | 'outcome'> &\n Partial<Pick<ChronicleEventInput, 'durationNs' | 'resource' | 'attributes'>>,\n): void {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const input: ChronicleEventInput = {\n ...fields,\n scope: {\n ...context.scope,\n ...(event.sessionId ? { sessionId: event.sessionId } : {}),\n ...(event.agentId ? { agentId: event.agentId } : {}),\n },\n correlation: {\n ...context.correlation,\n ...(event.traceId ? { traceId: event.traceId } : {}),\n ...(event.id ? { toolCallId: event.id } : {}),\n },\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n}\n\nfunction persistEvidenceEdges(\n options: ChronicleToolAdapterOptions,\n event: EventMap['tool.executed'],\n): void {\n const metadata = event.metadata;\n if (!metadata) return;\n for (const file of metadata.files) {\n persist(options, event, {\n eventType: 'tool.resource.observed',\n outcome: event.ok ? 'success' : 'failure',\n resource: { kind: 'file', id: resourceId('file', file), path: file },\n attributes: { relation: 'observed', toolName: event.name, evidenceStatus: metadata.status },\n });\n }\n for (const symbol of metadata.symbols) {\n persist(options, event, {\n eventType: 'tool.resource.observed',\n outcome: event.ok ? 'success' : 'failure',\n resource: { kind: 'symbol', id: resourceId('symbol', symbol) },\n attributes: { relation: 'observed', toolName: event.name, symbol },\n });\n }\n for (const command of metadata.commands) {\n persist(options, event, {\n eventType: 'tool.resource.observed',\n outcome: event.ok ? 'success' : 'failure',\n resource: { kind: 'process', id: resourceId('command', command) },\n attributes: { relation: 'invoked', toolName: event.name, command: options.scrubber.scrub(command) },\n });\n }\n}\n\nfunction progressResource(event: EventMap['tool.progress']): ChronicleResourceRef | undefined {\n if (event.event.type !== 'file_changed' || !event.event.path) return undefined;\n return {\n kind: 'file',\n id: resourceId('file', event.event.path),\n path: event.event.path,\n ...(event.event.line !== undefined ? { lineStart: event.event.line } : {}),\n ...(event.event.endLine !== undefined ? { lineEnd: event.event.endLine } : {}),\n };\n}\n\nfunction scrubValue(scrubber: SecretScrubber, value: unknown): string {\n if (value === undefined) return '';\n try {\n return scrubber.scrub(JSON.stringify(value));\n } catch {\n return scrubber.scrub(String(value));\n }\n}\n\nfunction resourceId(kind: string, value: string): string {\n return `${kind}_${hashText(value).slice(0, 24)}`;\n}\n\nfunction hashText(value: string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nfunction millisecondsToNanoseconds(durationMs: number): string {\n return Math.round(durationMs * 1_000_000).toString();\n}\n", "import { createHash } from 'node:crypto';\nimport type { EventBus, EventMap } from '../kernel/events.js';\nimport type { SecretScrubber } from '../types/secret-scrubber.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleProcessAdapterOptions {\n events: EventBus;\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n scrubber: SecretScrubber;\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\nexport function wireProcessesToChronicle(options: ChronicleProcessAdapterOptions): () => void {\n const unsubs = [\n options.events.on('process.started', (event) => persist(options, event, {\n eventType: 'process.started',\n outcome: 'started',\n occurredAt: event.startedAt,\n attributes: {\n command: options.scrubber.scrub(event.command),\n args: event.args.map((arg) => options.scrubber.scrub(arg)),\n cwd: event.cwd,\n parentPid: event.parentPid,\n background: event.background,\n },\n })),\n options.events.on('process.completed', (event) => persist(options, event, {\n eventType: 'process.completed',\n outcome: event.exitCode === 0 ? 'success' : event.timedOut ? 'cancelled' : 'failure',\n occurredAt: event.endedAt,\n durationNs: Math.round(event.durationMs * 1_000_000).toString(),\n attributes: {\n exitCode: event.exitCode,\n signal: event.signal,\n stdoutBytes: event.stdoutBytes,\n stderrBytes: event.stderrBytes,\n timedOut: event.timedOut,\n },\n })),\n ];\n return () => unsubs.forEach((unsubscribe) => { unsubscribe(); });\n}\n\ntype ProcessEvent =\n | EventMap['process.started']\n | EventMap['process.completed'];\n\nfunction persist(\n options: ChronicleProcessAdapterOptions,\n event: ProcessEvent,\n fields: Pick<ChronicleEventInput, 'eventType' | 'outcome' | 'occurredAt'> &\n Partial<Pick<ChronicleEventInput, 'durationNs' | 'attributes'>>,\n): void {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const processKey = `${event.sessionId}\\0${event.pid ?? 'unknown'}\\0${event.toolCallId}`;\n const input: ChronicleEventInput = {\n ...fields,\n scope: {\n ...context.scope,\n sessionId: event.sessionId,\n ...(event.agentId ? { agentId: event.agentId } : {}),\n },\n correlation: {\n ...context.correlation,\n ...(event.traceId ? { traceId: event.traceId } : {}),\n toolCallId: event.toolCallId,\n },\n runtime: {\n ...(event.pid !== undefined ? { processId: event.pid } : {}),\n ...('parentPid' in event ? { parentProcessId: event.parentPid } : {}),\n },\n resource: {\n kind: 'process',\n id: `process_${createHash('sha256').update(processKey).digest('hex').slice(0, 24)}`,\n },\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n}\n", "import { monitorEventLoopDelay, performance } from 'node:perf_hooks';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\n\nexport interface ChronicleHealthMonitorOptions {\n journal: ChronicleJournal;\n context: ChronicleContext | (() => ChronicleContext);\n intervalMs?: number | undefined;\n onPersistError?: ((error: unknown) => void) | undefined;\n}\n\n/** Low-frequency self-observation proving that telemetry is not starving the runtime. */\nexport function startChronicleHealthMonitor(options: ChronicleHealthMonitorOptions): () => void {\n const intervalMs = Math.max(5_000, options.intervalMs ?? 30_000);\n const delay = monitorEventLoopDelay({ resolution: 20 });\n delay.enable();\n let previousCpu = process.cpuUsage();\n let previousElu = performance.eventLoopUtilization();\n\n const sample = (): void => {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const memory = process.memoryUsage();\n const cpu = process.cpuUsage(previousCpu);\n previousCpu = process.cpuUsage();\n const elu = performance.eventLoopUtilization(previousElu);\n previousElu = performance.eventLoopUtilization();\n const journalBeforeSample = options.journal.stats();\n void options.journal.append({\n eventType: 'runtime.health.sampled', scope: context.scope, correlation: context.correlation,\n runtime: { processId: process.pid, parentProcessId: process.ppid }, outcome: 'success',\n resource: { kind: 'process', id: `process:${process.pid}` },\n attributes: {\n uptimeSeconds: process.uptime(),\n eventLoop: { utilization: elu.utilization, activeMs: elu.active, idleMs: elu.idle,\n delayMeanMs: Number(delay.mean) / 1e6, delayP95Ms: Number(delay.percentile(95)) / 1e6,\n delayMaxMs: Number(delay.max) / 1e6 },\n cpu: { userMicros: cpu.user, systemMicros: cpu.system },\n memory: { rssBytes: memory.rss, heapTotalBytes: memory.heapTotal,\n heapUsedBytes: memory.heapUsed, externalBytes: memory.external, arrayBuffersBytes: memory.arrayBuffers },\n chronicle: journalBeforeSample,\n },\n }).catch((error) => options.onPersistError?.(error));\n delay.reset();\n };\n\n const timer = setInterval(sample, intervalMs);\n timer.unref?.();\n return () => { clearInterval(timer); delay.disable(); };\n}\n", "import { createHash } from 'node:crypto';\nimport type { BrainDecision, BrainDecisionRequest } from '../coordination/brain.js';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleDecisionAdapterOptions {\n events: EventBus; journal: ChronicleJournal; context: ChronicleContext | (() => ChronicleContext);\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\n/** Decision provenance without persisting raw questions, context or rationale. */\nexport function wireDecisionsToChronicle(options: ChronicleDecisionAdapterOptions): () => void {\n const write = (eventType: string, at: number, sessionId: string | undefined, requestId: string,\n attributes: Record<string, unknown>, outcome: ChronicleEventInput['outcome']): void => {\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const input: ChronicleEventInput = { eventType, occurredAt: new Date(at).toISOString(), outcome,\n scope: { ...context.scope, ...(sessionId ? { sessionId } : {}) }, correlation: context.correlation,\n resource: { kind: 'other', id: `decision:${requestId}` }, attributes: { decisionId: requestId, ...attributes } };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n };\n const requestAttrs = (request: BrainDecisionRequest) => ({ source: request.source, risk: request.risk,\n fallback: request.fallback, questionHash: hash(request.question), contextHash: hash(request.context),\n optionCount: request.options?.length ?? 0,\n options: request.options?.map((option) => ({ id: option.id, risk: option.risk,\n recommended: option.recommended ?? false, labelHash: hash(option.label), consequenceHash: hash(option.consequence) })) });\n const decisionAttrs = (decision: BrainDecision) => ({ type: decision.type,\n ...('optionId' in decision && decision.optionId ? { optionId: decision.optionId } : {}),\n contentHash: hash('text' in decision ? decision.text : 'prompt' in decision ? decision.prompt : decision.reason),\n rationaleHash: hash('rationale' in decision ? decision.rationale : undefined) });\n\n const offs = [\n options.events.on('brain.decision_requested', (e) => write('decision.requested', e.at, e.sessionId, e.request.id, requestAttrs(e.request), 'started')),\n options.events.on('brain.decision_answered', (e) => write('decision.resolved', e.at, e.sessionId, e.request.id, { ...requestAttrs(e.request), ...decisionAttrs(e.decision), resolver: 'brain' }, 'success')),\n options.events.on('brain.decision_ask_human', (e) => write('decision.escalated', e.at, e.sessionId, e.request.id, { ...requestAttrs(e.request), ...decisionAttrs(e.decision) }, 'started')),\n options.events.on('brain.decision_denied', (e) => write('decision.denied', e.at, e.sessionId, e.request.id, { ...requestAttrs(e.request), ...decisionAttrs(e.decision) }, 'denied')),\n options.events.on('brain.human_answered', (e) => write('decision.human_answered', e.at, e.sessionId, e.id, { resolver: 'human', optionId: e.optionId, denied: e.deny ?? false, answerHash: hash(e.text) }, e.deny ? 'denied' : 'success')),\n options.events.on('brain.outcome', (e) => write('decision.outcome_observed', e.at, e.sessionId, e.requestId, { observedOutcome: e.outcome, detailHash: hash(e.detail) }, e.outcome)),\n ];\n return () => offs.forEach((off) => { off(); });\n}\n\nfunction hash(value: string | undefined): string | undefined {\n return value ? createHash('sha256').update(value).digest('hex') : undefined;\n}\n", "import { createHash } from 'node:crypto';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput, ChronicleOutcome, ChronicleResourceRef } from './types.js';\n\nexport interface ChronicleDomainAdapterOptions {\n events: EventBus; journal: ChronicleJournal; context: ChronicleContext | (() => ChronicleContext);\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\n\nconst SPECIALIZED = [\n /^provider\\.attempt\\./, /^tool\\./, /^process\\./, /^brain\\.decision_/,\n /^brain\\.human_answered$/, /^brain\\.outcome$/, /^file\\.activity$/,\n /^provider\\.(?:text_delta|thinking_delta)$/,\n /^(?:ctx\\.pct|subagent\\.ctx_pct|countdown\\.tick|coordinator\\.stats)$/,\n];\n/**\n * Only domains that can improve coding decisions, provenance, reliability or\n * resource/cost control belong in Chronicle. UI presence, navigation and other\n * product-engagement events are intentionally not captured by this bridge.\n */\nconst CODING_SIGNAL = [\n /^(?:agent|subagent|delegate|fleet)\\./,\n /^(?:session|iteration|context|compaction|checkpoint|in_flight)\\./,\n /^(?:memory|storage|trust)\\./,\n /^(?:sdd|worktree)\\./,\n /^(?:brain|token|budget|concurrency)\\./,\n /^(?:provider|mcp|network)\\./,\n /^error$/,\n];\nconst SENSITIVE_KEY = /(content|text|prompt|question|rationale|reason|detail|summary|description|context|input|output|error|message|secret|token|password|key)$/i;\nconst PRESERVE_STRING_KEY = /(^|_)(id|status|state|kind|type|source|model|provider|phase|risk|fallback|path|name|role|sha|branch|mode)$/i;\n/** Known metadata arrays that carry unbounded accumulated state (mail, tool\n * history, commands). Chronicle only needs the most recent entries. */\nconst TRUNCATED_ARRAYS = new Set(['recentMail', 'recentTools', 'recentCommands']);\nconst TRUNCATED_ARRAY_MAX = 5;\n/** General array cap \u2014 enough for agent lists, file lists etc. without\n * allowing unbounded growth through any array-shaped event field. */\nconst DEFAULT_ARRAY_MAX = 20;\n\n/** Allowlisted coding-signal bridge for domains not owned by a richer adapter. */\nexport function wireDomainEventsToChronicle(options: ChronicleDomainAdapterOptions): () => void {\n return options.events.onAny((eventName, payload) => {\n if (SPECIALIZED.some((pattern) => pattern.test(eventName))) return;\n if (!CODING_SIGNAL.some((pattern) => pattern.test(eventName))) return;\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const record = objectPayload(payload);\n const sessionId = stringField(record, 'sessionId');\n const agentId = stringField(record, 'agentId') ?? stringField(record, 'subagentId');\n const taskId = stringField(record, 'taskId');\n const input: ChronicleEventInput = {\n eventType: eventName,\n occurredAt: eventTime(record),\n scope: { ...context.scope, ...(sessionId ? { sessionId } : {}), ...(agentId ? { agentId } : {}), ...(taskId ? { taskId } : {}) },\n correlation: {\n ...context.correlation,\n ...(stringField(record, 'traceId') ? { traceId: stringField(record, 'traceId')! } : {}),\n ...(stringField(record, 'toolCallId') ? { toolCallId: stringField(record, 'toolCallId') } : {}),\n ...(stringField(record, 'attemptId') ? { attemptId: stringField(record, 'attemptId') } : {}),\n ...(stringField(record, 'logicalRequestId') ? { logicalRequestId: stringField(record, 'logicalRequestId') } : {}),\n },\n outcome: inferOutcome(eventName, record),\n runtime: {\n ...(stringField(record, 'providerId') ?? stringField(record, 'provider') ? { providerId: stringField(record, 'providerId') ?? stringField(record, 'provider') } : {}),\n ...(stringField(record, 'modelId') ?? stringField(record, 'model') ? { modelId: stringField(record, 'modelId') ?? stringField(record, 'model') } : {}),\n },\n resource: inferResource(record),\n attributes: sanitize(record) as Record<string, unknown>,\n tags: { collector: 'eventbus-domain', family: eventName.split('.')[0] ?? 'unknown' },\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n });\n}\n\nfunction objectPayload(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' ? value as Record<string, unknown> : { value };\n}\nfunction stringField(value: Record<string, unknown>, key: string): string | undefined {\n return typeof value[key] === 'string' ? value[key] as string : undefined;\n}\nfunction eventTime(value: Record<string, unknown>): string | undefined {\n const raw = value.at ?? value.ts ?? value.timestamp;\n if (typeof raw === 'number' && Number.isFinite(raw)) return new Date(raw).toISOString();\n if (typeof raw === 'string' && Number.isFinite(Date.parse(raw))) return new Date(raw).toISOString();\n return undefined;\n}\nfunction inferOutcome(name: string, payload: Record<string, unknown>): ChronicleOutcome {\n if (payload.ok === false || /(?:failed|error|damaged|conflict|deadlock|denied|rejected|blocked)$/.test(name)) return 'failure';\n if (/(?:started|starting|retrying|threshold_reached)$/.test(name)) return 'started';\n if (/(?:cancelled|aborted)$/.test(name)) return 'cancelled';\n if (/(?:completed|finished|committed|merged|written|persisted|accepted|recovered|verified|connected|success)$/.test(name) || payload.ok === true) return 'success';\n return 'unknown';\n}\nfunction inferResource(payload: Record<string, unknown>): ChronicleResourceRef | undefined {\n const candidates: Array<[ChronicleResourceRef['kind'], string, unknown]> = [\n ['memory', 'memoryId', payload.memoryId], ['task', 'taskId', payload.taskId],\n ['kanban', 'boardId', payload.boardId ?? payload.runId], ['artifact', 'worktreeId', payload.worktreeId ?? payload.handleId],\n ['file', 'path', payload.filePath ?? payload.path], ['other', 'agentId', payload.agentId ?? payload.subagentId],\n ['network', 'serverAddress', payload.serverAddress],\n ['other', 'sessionId', payload.sessionId],\n ];\n const found = candidates.find(([, , value]) => typeof value === 'string' && value.length > 0);\n if (!found) return undefined;\n const [kind, label, value] = found as [ChronicleResourceRef['kind'], string, string];\n return { kind, id: `${label}:${value}`, ...(kind === 'file' ? { path: value } : {}) };\n}\n\nfunction sanitize(value: unknown, key = '', depth = 0, seen = new WeakSet<object>()): unknown {\n if (value === null || typeof value === 'boolean' || typeof value === 'number') return value;\n if (typeof value === 'bigint') return value.toString();\n if (typeof value === 'function') return { type: 'function' };\n if (typeof value === 'string') {\n if (PRESERVE_STRING_KEY.test(key) && !SENSITIVE_KEY.test(key)) return value.slice(0, 512);\n if (SENSITIVE_KEY.test(key)) return { hash: digest(value), length: value.length, redacted: true };\n return value.length <= 256 ? value : { hash: digest(value), length: value.length, truncated: true };\n }\n if (typeof value !== 'object') return String(value);\n if (seen.has(value)) return { circular: true };\n if (depth >= 5) return { hash: digest(safeString(value)), depthLimited: true };\n seen.add(value);\n if (Array.isArray(value)) {\n const cap = TRUNCATED_ARRAYS.has(key) ? TRUNCATED_ARRAY_MAX : DEFAULT_ARRAY_MAX;\n const items = value.slice(0, cap).map((item) => sanitize(item, key, depth + 1, seen));\n return value.length > cap ? { items, total: value.length, truncated: true } : items;\n }\n const output: Record<string, unknown> = {};\n const entries = Object.entries(value as Record<string, unknown>);\n for (const [childKey, child] of entries.slice(0, 100)) {\n if (childKey === 'ctx' || childKey === 'provider' || childKey === 'resolve' || childKey === 'extend' || childKey === 'deny') continue;\n output[childKey] = sanitize(child, childKey, depth + 1, seen);\n }\n if (entries.length > 100) output._truncatedKeys = entries.length - 100;\n return output;\n}\nfunction safeString(value: unknown): string { try { return JSON.stringify(value) ?? String(value); } catch { return String(value); } }\nfunction digest(value: string): string { return createHash('sha256').update(value).digest('hex'); }\n", "import { createHash, type Hash } from 'node:crypto';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleStreamAdapterOptions {\n events: EventBus; journal: ChronicleJournal; context: ChronicleContext | (() => ChronicleContext);\n onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\ninterface StreamState {\n sessionId?: string; agentId?: string; attemptId: string; logicalRequestId: string; providerId: string; model: string;\n startedAtMs: number; firstChunkAtMs?: number; lastChunkAtMs?: number;\n textChunks: number; textBytes: number; thinkingChunks: number; thinkingBytes: number;\n textHash: Hash; thinkingHash: Hash;\n}\n\n/** Aggregates high-frequency streaming deltas without dropping their volume/timing/content identity. */\nexport function wireProviderStreamsToChronicle(options: ChronicleStreamAdapterOptions): () => void {\n const states = new Map<string, StreamState>();\n const key = (sessionId: string | undefined, agentId: string | undefined) => `${sessionId ?? '__default__'}\\0${agentId ?? '__leader__'}`;\n const update = (sessionId: string | undefined, agentId: string | undefined, text: string, thinking: boolean): void => {\n const state = states.get(key(sessionId, agentId));\n if (!state) return;\n const now = Date.now(); const bytes = Buffer.byteLength(text);\n state.firstChunkAtMs ??= now; state.lastChunkAtMs = now;\n if (thinking) { state.thinkingChunks++; state.thinkingBytes += bytes; state.thinkingHash.update(text); }\n else { state.textChunks++; state.textBytes += bytes; state.textHash.update(text); }\n };\n const flush = (sessionId: string | undefined, agentId: string | undefined, outcome: 'success' | 'failure'): void => {\n const state = states.get(key(sessionId, agentId)); if (!state) return; states.delete(key(sessionId, agentId));\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const endedAtMs = Date.now();\n const input: ChronicleEventInput = { eventType: 'provider.stream.summarized', outcome,\n scope: { ...context.scope, ...(state.sessionId ? { sessionId: state.sessionId } : {}), ...(state.agentId ? { agentId: state.agentId } : {}) },\n correlation: { ...context.correlation, attemptId: state.attemptId, logicalRequestId: state.logicalRequestId },\n runtime: { providerId: state.providerId, modelId: state.model },\n durationNs: String(Math.max(0, endedAtMs - state.startedAtMs) * 1_000_000),\n attributes: { textChunks: state.textChunks, textBytes: state.textBytes,\n thinkingChunks: state.thinkingChunks, thinkingBytes: state.thinkingBytes,\n textHash: state.textHash.digest('hex'), thinkingHash: state.thinkingHash.digest('hex'),\n firstChunkLatencyMs: state.firstChunkAtMs === undefined ? undefined : state.firstChunkAtMs - state.startedAtMs,\n streamActiveMs: state.firstChunkAtMs === undefined || state.lastChunkAtMs === undefined ? 0 : state.lastChunkAtMs - state.firstChunkAtMs },\n };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n };\n const offs = [\n options.events.on('provider.attempt.started', (event) => states.set(key(event.sessionId,event.agentId), {\n sessionId: event.sessionId, ...(event.agentId ? { agentId:event.agentId } : {}), attemptId: event.attemptId, logicalRequestId: event.logicalRequestId,\n providerId: event.providerId, model: event.model, startedAtMs: Date.parse(event.startedAt),\n textChunks: 0, textBytes: 0, thinkingChunks: 0, thinkingBytes: 0,\n textHash: createHash('sha256'), thinkingHash: createHash('sha256'),\n })),\n options.events.on('provider.text_delta', (event) => update(event.sessionId, event.ctx.agentId, event.text, false)),\n options.events.on('provider.thinking_delta', (event) => update(event.sessionId, event.ctx.agentId, event.text, true)),\n options.events.on('provider.attempt.completed', (event) => flush(event.sessionId, event.agentId, 'success')),\n options.events.on('provider.attempt.failed', (event) => flush(event.sessionId, event.agentId, 'failure')),\n ];\n return () => { for (const state of [...states.values()]) flush(state.sessionId, state.agentId, 'failure'); offs.forEach((off) => { off(); }); };\n}\n", "import { createHash } from 'node:crypto';\nimport type { ContentBlock } from '../types/blocks.js';\nimport type { Message } from '../types/messages.js';\nimport type { Request } from '../types/provider.js';\n\nexport interface ChroniclePromptManifest {\n manifestId: string;\n messageCount: number; estimatedMessageTokens: number; contentBytes: number;\n roleCounts: Record<string, number>; blockCounts: Record<string, number>;\n system: { blockCount: number; bytes: number; hash: string };\n messages: Array<{ index: number; role: string; bytes: number; estimatedTokens?: number; hash: string; blocks: Record<string, number> }>;\n tools: { count: number; estimatedDefinitionTokens: number; manifestHash: string; names: string[]; mutating: number; destructive: number };\n request: Record<string, unknown>;\n}\n\n/** Content-addressed prompt composition manifest; raw prompt/tool prose never leaves this function. */\nexport function createChroniclePromptManifest(request: Request): ChroniclePromptManifest {\n const roleCounts: Record<string, number> = {}, blockCounts: Record<string, number> = {};\n const messages = request.messages.map((message, index) => messageSummary(message, index, roleCounts, blockCounts));\n const systemText = (request.system ?? []).map((block) => block.text).join('\\n');\n const toolRecords = (request.tools ?? []).map((tool) => ({ name: tool.name, schemaHash: hash(stable(tool.inputSchema)),\n permission: tool.permission, mutating: tool.mutating, riskTier: tool.riskTier, capabilities: tool.capabilities,\n estimatedTokens: tool._estDefTokens ?? 0 }));\n const core = { systemHash: hash(systemText), messages: messages.map(({ hash: contentHash, ...rest }) => ({ ...rest, contentHash })), tools: toolRecords,\n model: request.model, maxTokens: request.maxTokens, temperature: request.temperature, topP: request.topP,\n topK: request.topK, seed: request.seed, toolChoice: request.toolChoice, reasoning: request.reasoning,\n cache: request.cache, responseFormat: request.responseFormat?.type };\n return {\n manifestId: `prompt_${hash(stable(core))}`,\n messageCount: messages.length,\n estimatedMessageTokens: messages.reduce((sum, message) => sum + (message.estimatedTokens ?? 0), 0),\n contentBytes: messages.reduce((sum, message) => sum + message.bytes, 0) + Buffer.byteLength(systemText),\n roleCounts, blockCounts,\n system: { blockCount: request.system?.length ?? 0, bytes: Buffer.byteLength(systemText), hash: hash(systemText) },\n messages,\n tools: { count: toolRecords.length, estimatedDefinitionTokens: toolRecords.reduce((sum, tool) => sum + tool.estimatedTokens, 0),\n manifestHash: hash(stable(toolRecords)), names: toolRecords.map((tool) => tool.name),\n mutating: toolRecords.filter((tool) => tool.mutating).length,\n destructive: toolRecords.filter((tool) => tool.riskTier === 'destructive').length },\n request: { maxTokens: request.maxTokens, temperature: request.temperature, topP: request.topP, topK: request.topK,\n frequencyPenalty: request.frequencyPenalty, presencePenalty: request.presencePenalty, seed: request.seed,\n candidateCount: request.candidateCount, logprobs: request.logprobs, topLogprobs: request.topLogprobs,\n stopSequenceCount: request.stopSequences?.length ?? 0, toolChoice: request.toolChoice,\n reasoning: request.reasoning, cache: request.cache, responseFormat: request.responseFormat?.type,\n safetySettingCount: request.safetySettings?.length ?? 0, userHash: request.user ? hash(request.user) : undefined },\n };\n}\n\nfunction messageSummary(message: Message, index: number, roles: Record<string, number>, totals: Record<string, number>) {\n roles[message.role] = (roles[message.role] ?? 0) + 1;\n const blocks = typeof message.content === 'string' ? { text: 1 } : countBlocks(message.content);\n for (const [type, count] of Object.entries(blocks)) totals[type] = (totals[type] ?? 0) + count;\n const content = contentIdentity(message.content);\n return { index, role: message.role, bytes: content.bytes,\n ...(message._estTokens !== undefined ? { estimatedTokens: message._estTokens } : {}), hash: content.hash, blocks };\n}\nfunction countBlocks(blocks: ContentBlock[]): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const block of blocks) counts[block.type] = (counts[block.type] ?? 0) + 1;\n return counts;\n}\nfunction hash(value: string): string { return createHash('sha256').update(value).digest('hex'); }\nfunction contentIdentity(content: Message['content']): { hash: string; bytes: number } {\n if (typeof content === 'string') return { hash: hash(content), bytes: Buffer.byteLength(content) };\n const digest = createHash('sha256'); let bytes = 0;\n const add = (value: string | undefined) => { if (!value) return; digest.update(value); bytes += Buffer.byteLength(value); };\n for (const block of content) {\n add(block.type);\n if (block.type === 'text') add(block.text);\n else if (block.type === 'thinking') { add(block.thinking); add(block.signature); }\n else if (block.type === 'tool_use') { add(block.id); add(block.name); add(stable(block.input)); }\n else if (block.type === 'tool_result') { add(block.tool_use_id); add(block.name); add(block.content); add(String(block.is_error ?? false)); }\n else if (block.type === 'image') { add(block.source.type); add(block.source.media_type); add(block.source.url); add(block.source.data); }\n }\n return { hash: digest.digest('hex'), bytes };\n}\nfunction stable(value: unknown): string {\n if (value === undefined) return 'undefined';\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`;\n return `{${Object.entries(value as Record<string, unknown>).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => `${JSON.stringify(key)}:${stable(child)}`).join(',')}}`;\n}\n", "import { createHash } from 'node:crypto';\nimport type { EventBus } from '../kernel/events.js';\nimport type { ChronicleContext } from './context.js';\nimport type { ChronicleJournal } from './journal.js';\nimport type { ChronicleEventInput } from './types.js';\n\nexport interface ChronicleRollupAdapterOptions {\n events: EventBus; journal: ChronicleJournal; context: ChronicleContext | (() => ChronicleContext);\n windowMs?: number; onPersistError?: ((error: unknown, event: ChronicleEventInput) => void) | undefined;\n}\ninterface Bucket { signal: string; sessionId?: string; agentId?: string; toolCallId?: string;\n dimensions: Record<string, string>; startedAt: number; updatedAt: number; count: number;\n metrics: Record<string, { sum: number; min: number; max: number; last: number }>;\n categories: Record<string, number>; digest: ReturnType<typeof createHash> }\n\n/** Converts high-frequency ephemeral signals into bounded window aggregates before persistence. */\nexport function wireRollupsToChronicle(options: ChronicleRollupAdapterOptions): () => void {\n const buckets = new Map<string, Bucket>(); const windowMs = Math.max(1_000, options.windowMs ?? 10_000);\n const bucket = (key: string, seed: Omit<Bucket, 'startedAt'|'updatedAt'|'count'|'metrics'|'categories'|'digest'>) => {\n let value = buckets.get(key); if (!value) { const now = Date.now(); value = { ...seed, startedAt: now, updatedAt: now,\n count: 0, metrics: {}, categories: {}, digest: createHash('sha256') }; buckets.set(key, value); } return value;\n };\n const sample = (target: Bucket, values: Record<string, number>, category?: string, digest?: string) => {\n target.count++; target.updatedAt = Date.now();\n for (const [name, value] of Object.entries(values)) { const metric = target.metrics[name];\n target.metrics[name] = metric ? { sum: metric.sum + value, min: Math.min(metric.min, value), max: Math.max(metric.max, value), last: value }\n : { sum: value, min: value, max: value, last: value }; }\n if (category) target.categories[category] = (target.categories[category] ?? 0) + 1;\n if (digest) target.digest.update(digest);\n };\n const flush = (key: string) => { const value = buckets.get(key); if (!value || value.count === 0) return; buckets.delete(key);\n const context = typeof options.context === 'function' ? options.context() : options.context;\n const stats = Object.fromEntries(Object.entries(value.metrics).map(([name, metric]) => [name, { ...metric, avg: metric.sum / value.count }]));\n const input: ChronicleEventInput = { eventType: 'metrics.rollup', outcome: 'success', occurredAt: new Date(value.updatedAt).toISOString(),\n scope: { ...context.scope, ...(value.sessionId ? { sessionId: value.sessionId } : {}), ...(value.agentId ? { agentId: value.agentId } : {}) },\n correlation: { ...context.correlation, ...(value.toolCallId ? { toolCallId: value.toolCallId } : {}) },\n durationNs: String(Math.max(0, value.updatedAt - value.startedAt) * 1_000_000),\n attributes: { signal: value.signal, windowStart: new Date(value.startedAt).toISOString(), windowEnd: new Date(value.updatedAt).toISOString(),\n samples: value.count, dimensions: value.dimensions, stats, categories: value.categories, digest: value.digest.digest('hex'), rawEventsRetained: false } };\n void options.journal.append(input).catch((error) => options.onPersistError?.(error, input));\n };\n const gauge = (signal: string, event: Record<string, unknown>, dimension?: string) => { const sessionId = text(event.sessionId);\n const dimensionValue = dimension ? text(event[dimension]) : undefined; const key = `${signal}\\0${sessionId ?? ''}\\0${dimensionValue ?? ''}`;\n const target = bucket(key, { signal, ...(sessionId ? { sessionId } : {}), ...(dimensionValue ? { agentId: dimensionValue } : {}), dimensions: dimensionValue && dimension ? { [dimension]: dimensionValue } : {} });\n sample(target, Object.fromEntries(Object.entries(event).filter(([, value]) => typeof value === 'number')) as Record<string, number>); };\n const offs = [\n options.events.on('process.output', (event) => { const key = `process.output\\0${event.sessionId}\\0${event.toolCallId}\\0${event.pid ?? ''}\\0${event.stream}`;\n const target = bucket(key, { signal: 'process.output', sessionId: event.sessionId, ...(event.agentId ? { agentId: event.agentId } : {}), toolCallId: event.toolCallId,\n dimensions: { stream: event.stream, toolName: event.toolName, pid: String(event.pid ?? '') } }); sample(target, { bytes: event.bytes }, event.stream, event.chunkHash); }),\n options.events.on('process.completed', (event) => { for (const key of [...buckets.keys()]) if (key.startsWith(`process.output\\0${event.sessionId}\\0${event.toolCallId}\\0`)) flush(key); }),\n options.events.on('tool.progress', (event) => { if (event.event.type === 'file_changed') return; const key = `tool.progress\\0${event.sessionId ?? ''}\\0${event.id}`;\n const target = bucket(key, { signal: 'tool.progress', ...(event.sessionId ? { sessionId: event.sessionId } : {}), ...(event.agentId ? { agentId: event.agentId } : {}), toolCallId: event.id, dimensions: { toolName: event.name } });\n sample(target, { textBytes: Buffer.byteLength(event.event.text ?? '') }, event.event.type, safeDigest(event.event)); }),\n options.events.on('tool.executed', (event) => flush(`tool.progress\\0${event.sessionId ?? ''}\\0${event.id ?? ''}`)),\n options.events.on('tool.failed', (event) => flush(`tool.progress\\0${event.sessionId}\\0${event.id}`)),\n options.events.on('ctx.pct', (event) => gauge('ctx.pct', event)),\n options.events.on('subagent.ctx_pct', (event) => gauge('subagent.ctx_pct', event, 'subagentId')),\n options.events.on('countdown.tick', (event) => gauge('countdown.tick', event)),\n options.events.on('coordinator.stats', (event) => gauge('coordinator.stats', event)),\n ];\n const timer = setInterval(() => { const cutoff = Date.now() - windowMs; for (const [key, value] of buckets) if (value.updatedAt <= cutoff) flush(key); }, windowMs);\n timer.unref?.();\n return () => { clearInterval(timer); for (const key of [...buckets.keys()]) flush(key); offs.forEach((off) => { off(); }); };\n}\nfunction text(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined; }\nfunction safeDigest(value: unknown): string { try { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); } catch { return 'unhashable'; } }\n", "import { createHash } from 'node:crypto';\nimport { createReadStream } from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { createInterface } from 'node:readline';\nimport type { ChronicleEvent, ChronicleOutcome, ChronicleResourceRef } from './types.js';\n\nexport interface ChronicleQuery {\n eventId?: string;\n eventTypes?: string[]; outcomes?: ChronicleOutcome[]; from?: string; to?: string;\n projectId?: string; sessionId?: string; agentId?: string; taskId?: string;\n providerId?: string; modelId?: string; traceId?: string; logicalRequestId?: string;\n attemptId?: string; toolCallId?: string; resourceKind?: ChronicleResourceRef['kind'];\n resourceId?: string; path?: string; line?: number; tags?: Record<string, string>;\n attributes?: Record<string, unknown>; text?: string; order?: 'asc' | 'desc';\n limit?: number; cursor?: string;\n}\n\nexport interface ChronicleQueryResult {\n events: ChronicleEvent[]; total: number; nextCursor?: string;\n scannedEvents: number; sourceFiles: number; invalidLines: number;\n summary: ChronicleSummary;\n}\n\n/** Derived once from all matching events; never from the paginated UI sample. */\nexport interface ChronicleSummary {\n logicalRequests: number; modelAttempts: number; completedAttempts: number; failedAttempts: number;\n scheduledRetries: number; fallbacks: number; providers: number; models: number;\n inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number;\n estimatedCostUsd: number;\n providerAvgDurationMs: number; providerP95DurationMs: number;\n toolCalls: number; completedTools: number; failedTools: number; toolAvgDurationMs: number;\n processes: number; failedProcesses: number; fileEvents: number; uniqueFiles: number;\n agentEvents: number; uniqueAgents: number; decisions: number; escalations: number;\n failures: number; cancellations: number;\n families: Record<ChronicleSignalFamily, number>;\n failuresByFamily: Record<ChronicleSignalFamily, number>;\n}\nexport type ChronicleSignalFamily = 'llm'|'agent'|'tool'|'file'|'memory'|'task'|'decision'|'runtime';\n\nexport type ChronicleFacet = 'eventType' | 'outcome' | 'projectId' | 'sessionId' |\n 'agentId' | 'taskId' | 'providerId' | 'modelId' | 'resourceKind' | 'resourcePath' | 'toolCallId';\nexport interface ChronicleFacetValue { value: string; count: number }\nexport type ChronicleRelationKind = 'parent_span' | 'trace' | 'tool_call' | 'logical_request' |\n 'attempt' | 'decision' | 'network_request' | 'prompt_manifest' | 'resource_lineage';\nexport interface ChronicleGraphEdge { from: string; to: string; kind: ChronicleRelationKind; confidence: 'explicit' | 'correlated' | 'inferred' }\nexport interface ChronicleGraphResult { nodes: ChronicleEvent[]; edges: ChronicleGraphEdge[]; truncated: boolean }\n\ninterface ChronicleOrderKey {\n occurredAt: string;\n persistedAt: string;\n sequence: number;\n eventId: string;\n}\n\ninterface ChronicleSnapshotEntry {\n id: string;\n size: number;\n}\n\ninterface ChronicleCursor {\n version: 1;\n order: 'asc' | 'desc';\n queryHash: string;\n after: ChronicleOrderKey;\n snapshot: ChronicleSnapshotEntry[];\n}\n\ninterface SnapshotFile extends ChronicleSnapshotEntry {\n file: string;\n}\n\nconst MAX_CURSOR_SNAPSHOT_ENTRIES = 10_000;\n\n// \u2500\u2500 Streaming line-by-line reader \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction streamLines(filePath: string, maxBytes?: number): AsyncIterableIterator<string> {\n const stream = createReadStream(filePath, {\n encoding: 'utf8',\n highWaterMark: 256 * 1024,\n ...(maxBytes !== undefined ? { end: maxBytes - 1 } : {}),\n });\n const rl = createInterface({ input: stream, crlfDelay: Infinity });\n return rl[Symbol.asyncIterator]() as AsyncIterableIterator<string>;\n}\n\n// \u2500\u2500 Streaming query engine (no pre-loaded events) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Queryable projection over immutable Chronicle JSONL partitions.\n * Events are streamed on demand \u2014 no full-file load into memory. */\nexport class ChronicleQueryEngine {\n private readonly partitionFiles: string[];\n\n private constructor(\n files: string[],\n readonly diagnostics: { sourceFiles: number; invalidLines: number },\n ) {\n this.partitionFiles = files;\n }\n\n static async fromDirectory(directory: string): Promise<ChronicleQueryEngine> {\n const files = await findPartitions(path.resolve(directory));\n return new ChronicleQueryEngine(files, { sourceFiles: files.length, invalidLines: 0 });\n }\n\n static async fromFiles(files: string[]): Promise<ChronicleQueryEngine> {\n return new ChronicleQueryEngine(files, { sourceFiles: files.length, invalidLines: 0 });\n }\n\n /** Stream all partitions, filter, and return the requested page + summary. */\n async query(query: ChronicleQuery = {}): Promise<ChronicleQueryResult> {\n const order = query.order ?? 'desc';\n const limit = Math.max(1, Math.min(query.limit ?? 100, 10_000));\n const queryHash = hashQuery(query);\n const cursor = decodeCursor(query.cursor, order, queryHash);\n const snapshotFiles = cursor\n ? await resolveSnapshotFiles(this.partitionFiles, cursor.snapshot)\n : await captureSnapshot(this.partitionFiles);\n const files = order === 'asc' ? snapshotFiles : snapshotFiles.slice().reverse();\n const summaryAcc = createSummaryAccumulator();\n const orderedCandidates: ChronicleEvent[] = [];\n const pageOrder = (left: ChronicleEvent, right: ChronicleEvent) =>\n compareEvents(left, right) * (order === 'asc' ? 1 : -1);\n let totalCount = 0;\n let remainingCount = 0;\n let scannedEvents = 0;\n let invalidLines = 0;\n\n for (const snapshotFile of files) {\n try {\n if (snapshotFile.size === 0) continue;\n const lines = order === 'asc'\n ? streamLines(snapshotFile.file, snapshotFile.size)\n : reverseLines(snapshotFile.file, snapshotFile.size);\n\n for await (const line of lines) {\n if (!line.trim()) continue;\n let event: ChronicleEvent;\n try {\n event = JSON.parse(line) as ChronicleEvent;\n if (!isChronicleEvent(event)) { invalidLines++; continue; }\n } catch { invalidLines++; continue; }\n scannedEvents++;\n\n if (!matches(event, query)) continue;\n totalCount++;\n updateSummary(summaryAcc, event);\n\n if (cursor && compareEventToKey(event, cursor.after) * (order === 'asc' ? 1 : -1) <= 0) {\n continue;\n }\n remainingCount++;\n\n // Keyset pagination retains only this page's best `limit` matches.\n // Cursor depth and journal size therefore cannot grow page memory.\n const insertionIndex = findInsertionIndex(orderedCandidates, event, pageOrder);\n if (insertionIndex < limit) {\n orderedCandidates.splice(insertionIndex, 0, event);\n if (orderedCandidates.length > limit) orderedCandidates.pop();\n }\n }\n } catch {\n // Skip unreadable partitions\n }\n }\n\n const pageEvents = orderedCandidates;\n const lastEvent = pageEvents.at(-1);\n\n return {\n events: pageEvents,\n total: totalCount,\n summary: finalizeSummary(summaryAcc),\n ...(lastEvent && pageEvents.length < remainingCount\n ? { nextCursor: encodeCursor({\n version: 1,\n order,\n queryHash,\n after: orderKey(lastEvent),\n snapshot: snapshotFiles.map(({ id, size }) => ({ id, size })),\n }) } : {}),\n scannedEvents,\n sourceFiles: snapshotFiles.length,\n invalidLines,\n };\n }\n\n /** Stream all partitions and compute facet value counts. */\n async facet(field: ChronicleFacet, query: ChronicleQuery = {}, limit = 100): Promise<ChronicleFacetValue[]> {\n const counts = new Map<string, number>();\n let invalidLines = 0;\n for (const file of this.partitionFiles) {\n try {\n for await (const line of streamLines(file)) {\n if (!line.trim()) continue;\n let event: ChronicleEvent;\n try {\n event = JSON.parse(line) as ChronicleEvent;\n if (!isChronicleEvent(event)) { invalidLines++; continue; }\n } catch { invalidLines++; continue; }\n if (!matches(event, query)) continue;\n const value = facetValue(event, field);\n if (value !== undefined) counts.set(value, (counts.get(value) ?? 0) + 1);\n }\n } catch { /* skip unreadable */ }\n }\n this.diagnostics.invalidLines = invalidLines;\n return [...counts]\n .map(([value, count]) => ({ value, count }))\n .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value))\n .slice(0, Math.max(0, limit));\n }\n\n /** Expand explicit and typed correlation edges; temporal proximity alone never creates causality. */\n async graph(seed: ChronicleQuery = {}, hops = 2, maxNodes = 1_000): Promise<ChronicleGraphResult> {\n const nodeLimit = Math.max(0, Math.floor(maxNodes));\n const selected = new Map<string, ChronicleEvent>();\n let seedCount = 0;\n\n // Pass 1 retains only the bounded seed set.\n for await (const event of streamEvents(this.partitionFiles)) {\n if (!matches(event, seed)) continue;\n seedCount++;\n if (selected.size < nodeLimit) selected.set(event.eventId, event);\n }\n\n let frontier = [...selected.values()];\n const depthLimit = Math.max(0, Math.min(hops, 10));\n for (let depth = 0; depth < depthLimit && frontier.length > 0 && selected.size < nodeLimit; depth++) {\n const frontierKeys = new Set(frontier.flatMap((event) => relationKeys(event).map((relation) => relation.key)));\n const next: ChronicleEvent[] = [];\n\n // Each hop is another streaming pass. Only related nodes up to maxNodes\n // are retained, so journal size cannot determine graph memory usage.\n for await (const event of streamEvents(this.partitionFiles)) {\n if (selected.has(event.eventId)) continue;\n if (!relationKeys(event).some((relation) => frontierKeys.has(relation.key))) continue;\n selected.set(event.eventId, event);\n next.push(event);\n if (selected.size >= nodeLimit) break;\n }\n frontier = next;\n }\n\n const nodes = [...selected.values()].sort(compareEvents);\n const byKey = new Map<string, ChronicleEvent[]>();\n for (const node of nodes) for (const relation of relationKeys(node)) {\n const related = byKey.get(relation.key) ?? [];\n related.push(node);\n byKey.set(relation.key, related);\n }\n\n const edges: ChronicleGraphEdge[] = [];\n const seen = new Set<string>();\n for (const node of nodes) for (const relation of relationKeys(node)) for (const candidate of byKey.get(relation.key) ?? []) {\n if (candidate.eventId === node.eventId) continue;\n const [from, to] = compareEvents(node, candidate) <= 0 ? [node, candidate] : [candidate, node];\n const id = `${from.eventId}:${to.eventId}:${relation.kind}`;\n if (!seen.has(id)) { seen.add(id); edges.push({ from: from.eventId, to: to.eventId, kind: relation.kind, confidence: relation.confidence }); }\n }\n return { nodes, edges, truncated: seedCount > nodeLimit || selected.size >= nodeLimit };\n }\n}\n\nasync function* streamEvents(files: readonly string[]): AsyncGenerator<ChronicleEvent> {\n for (const file of files) {\n try {\n for await (const line of streamLines(file)) {\n if (!line.trim()) continue;\n try {\n const event = JSON.parse(line) as ChronicleEvent;\n if (isChronicleEvent(event)) yield event;\n } catch { /* skip invalid lines */ }\n }\n } catch { /* skip unreadable partitions */ }\n }\n}\n\n// \u2500\u2500 Reverse line reader (reads a file from end to start) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function* reverseLines(filePath: string, maxBytes?: number): AsyncGenerator<string> {\n const CHUNK = 64 * 1024;\n const NEWLINE = 0x0a;\n let handle: fs.FileHandle;\n try { handle = await fs.open(filePath, 'r'); } catch { return; }\n try {\n const fileSize = (await handle.stat()).size;\n const size = Math.min(fileSize, maxBytes ?? fileSize);\n let position = size;\n let suffix = Buffer.alloc(0);\n while (position > 0) {\n const length = Math.min(CHUNK, position);\n position -= length;\n const buffer = Buffer.allocUnsafe(length);\n await handle.read(buffer, 0, length, position);\n const data = suffix.length === 0 ? buffer : Buffer.concat([buffer, suffix]);\n let lineEnd = data.length;\n let firstNewline = -1;\n for (let index = data.length - 1; index >= 0; index--) {\n if (data[index] !== NEWLINE) continue;\n const trimmed = data.subarray(index + 1, lineEnd).toString('utf8').trim();\n if (trimmed) yield trimmed;\n lineEnd = index;\n firstNewline = index;\n }\n suffix = firstNewline >= 0 ? Buffer.from(data.subarray(0, firstNewline)) : data;\n }\n const trimmed = suffix.toString('utf8').trim();\n if (trimmed) yield trimmed;\n } finally { await handle.close(); }\n}\n\n// \u2500\u2500 Running summary accumulator (replaces scan-then-summarize) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface SummaryAcc {\n logicalRequestIds: Set<string>;\n modelAttempts: number; completedAttempts: number; failedAttempts: number;\n scheduledRetries: number; fallbacks: number;\n providers: Set<string>; models: Set<string>;\n inputTokens: number; outputTokens: number;\n cacheReadTokens: number; cacheWriteTokens: number;\n costByScope: Map<string, { cost: number; event: ChronicleEvent }>;\n providerDurations: number[];\n toolCalls: number; completedTools: number; failedTools: number;\n toolDurations: number[];\n processes: number; failedProcesses: number;\n fileEvents: number; uniqueFiles: Set<string>;\n agentEvents: number; uniqueAgents: Set<string>;\n decisions: number; escalations: number;\n failures: number; cancellations: number;\n families: Record<ChronicleSignalFamily, number>;\n failuresByFamily: Record<ChronicleSignalFamily, number>;\n /** One-per-scope token.accounted cost snapshot. Updated when a later\n * token.accounted event has a later timestamp for the same scope. */\n}\n\nfunction createSummaryAccumulator(): SummaryAcc {\n return {\n logicalRequestIds: new Set(), modelAttempts: 0, completedAttempts: 0, failedAttempts: 0,\n scheduledRetries: 0, fallbacks: 0, providers: new Set(), models: new Set(),\n inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0,\n costByScope: new Map(), providerDurations: [],\n toolCalls: 0, completedTools: 0, failedTools: 0, toolDurations: [],\n processes: 0, failedProcesses: 0,\n fileEvents: 0, uniqueFiles: new Set(), agentEvents: 0, uniqueAgents: new Set(),\n decisions: 0, escalations: 0, failures: 0, cancellations: 0,\n families: { llm: 0, agent: 0, tool: 0, file: 0, memory: 0, task: 0, decision: 0, runtime: 0 },\n failuresByFamily: { llm: 0, agent: 0, tool: 0, file: 0, memory: 0, task: 0, decision: 0, runtime: 0 },\n };\n}\n\nfunction updateSummary(acc: SummaryAcc, event: ChronicleEvent): void {\n // Families\n const family = signalFamily(event);\n acc.families[family]++;\n if (isTerminalFailure(event)) acc.failuresByFamily[family]++;\n\n // Running counts per event type\n if (event.correlation.logicalRequestId) acc.logicalRequestIds.add(event.correlation.logicalRequestId);\n if (event.runtime?.providerId) acc.providers.add(event.runtime.providerId);\n if (event.runtime?.modelId) acc.models.add(event.runtime.modelId);\n\n if (event.eventType === 'provider.attempt.started') acc.modelAttempts++;\n else if (event.eventType === 'provider.attempt.completed') {\n acc.completedAttempts++;\n acc.inputTokens += numberAt(event, 'usage.input');\n acc.outputTokens += numberAt(event, 'usage.output');\n acc.cacheReadTokens += numberAt(event, 'usage.cacheRead');\n acc.cacheWriteTokens += numberAt(event, 'usage.cacheWrite');\n const dur = durationMs(event);\n if (dur > 0) acc.providerDurations.push(dur);\n } else if (event.eventType === 'provider.attempt.failed') {\n acc.failedAttempts++;\n if (event.attributes?.retryScheduled === true) acc.scheduledRetries++;\n const dur = durationMs(event);\n if (dur > 0) acc.providerDurations.push(dur);\n } else if (event.eventType === 'provider.fallback') acc.fallbacks++;\n else if (event.eventType === 'tool.started') acc.toolCalls++;\n else if (event.eventType === 'tool.executed') {\n acc.completedTools++;\n const dur = durationMs(event);\n if (dur > 0) acc.toolDurations.push(dur);\n } else if (event.eventType === 'tool.failed') {\n acc.failedTools++;\n const dur = durationMs(event);\n if (dur > 0) acc.toolDurations.push(dur);\n } else if (event.eventType === 'process.started') acc.processes++;\n else if (event.eventType === 'process.completed' && event.outcome === 'failure') acc.failedProcesses++;\n else if (event.eventType === 'decision.requested') acc.decisions++;\n else if (event.eventType === 'decision.escalated') acc.escalations++;\n\n // Token accounted \u2014 keep the latest finite snapshot per scope. Zero is a\n // meaningful reset, and compareEvents makes ties independent of scan order.\n if (event.eventType === 'token.accounted') {\n const cost = readPath(event.attributes ?? {}, 'cost.total');\n if (typeof cost === 'number' && Number.isFinite(cost)) {\n const key = scopeKey(event);\n const existing = acc.costByScope.get(key);\n if (!existing || compareEvents(event, existing.event) > 0) {\n acc.costByScope.set(key, { cost, event });\n }\n }\n }\n\n // File evidence\n if (event.resource?.kind === 'file' || event.eventType.startsWith('file.')) {\n acc.fileEvents++;\n if (event.resource?.path) acc.uniqueFiles.add(event.resource.path);\n }\n\n // Agent events\n if (family === 'agent') acc.agentEvents++;\n if (event.scope.agentId) acc.uniqueAgents.add(event.scope.agentId);\n\n // Terminal failures and cancellations\n if (isTerminalFailure(event)) acc.failures++;\n if (event.outcome === 'cancelled' || event.outcome === 'abandoned') acc.cancellations++;\n}\n\nfunction finalizeSummary(acc: SummaryAcc): ChronicleSummary {\n const sortedProviderDurations = acc.providerDurations.slice().sort((a, b) => a - b);\n const sortedToolDurations = acc.toolDurations.slice().sort((a, b) => a - b);\n const totalCost = [...acc.costByScope.values()].reduce((sum, entry) => sum + entry.cost, 0);\n return {\n logicalRequests: acc.logicalRequestIds.size,\n modelAttempts: acc.modelAttempts,\n completedAttempts: acc.completedAttempts,\n failedAttempts: acc.failedAttempts,\n scheduledRetries: acc.scheduledRetries,\n fallbacks: acc.fallbacks,\n providers: acc.providers.size,\n models: acc.models.size,\n inputTokens: acc.inputTokens,\n outputTokens: acc.outputTokens,\n cacheReadTokens: acc.cacheReadTokens,\n cacheWriteTokens: acc.cacheWriteTokens,\n estimatedCostUsd: totalCost,\n providerAvgDurationMs: average(sortedProviderDurations),\n providerP95DurationMs: percentile(sortedProviderDurations, 0.95),\n toolCalls: acc.toolCalls,\n completedTools: acc.completedTools,\n failedTools: acc.failedTools,\n toolAvgDurationMs: average(sortedToolDurations),\n processes: acc.processes,\n failedProcesses: acc.failedProcesses,\n fileEvents: acc.fileEvents,\n uniqueFiles: acc.uniqueFiles.size,\n agentEvents: acc.agentEvents,\n uniqueAgents: acc.uniqueAgents.size,\n decisions: acc.decisions,\n escalations: acc.escalations,\n failures: acc.failures,\n cancellations: acc.cancellations,\n families: acc.families,\n failuresByFamily: acc.failuresByFamily,\n };\n}\n\n// \u2500\u2500 Partition discovery (no pre-loading) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** The partition files list is stored on the prototype for legacy callers\n * that reference engine.partitionFiles directly. */\nObject.defineProperty(ChronicleQueryEngine.prototype, 'partitionFiles', {\n get() { throw new Error('ChronicleQueryEngine no longer loads events on construction. Use async query().'); },\n set(this: ChronicleQueryEngine, _val: string[]) {\n // Allow fromFiles/fromDirectory to attach the list for graph()\n Object.defineProperty(this, 'partitionFiles', { value: _val, writable: false, configurable: false });\n },\n});\n\nasync function findPartitions(root: string): Promise<string[]> {\n const result: string[] = [];\n const partitionName = /^(.*\\.events)(?:\\.(\\d{5}))?\\.jsonl$/;\n const visit = async (directory: string): Promise<void> => {\n let entries: import('node:fs').Dirent[];\n try { entries = await fs.readdir(directory, { withFileTypes: true }); } catch { return; }\n for (const entry of entries) {\n const full = path.join(directory, entry.name);\n if (entry.isDirectory()) await visit(full);\n else if (entry.isFile() && partitionName.test(entry.name)) result.push(full);\n }\n };\n await visit(root);\n return result.sort((left, right) => {\n const leftMatch = partitionName.exec(path.basename(left));\n const rightMatch = partitionName.exec(path.basename(right));\n const leftGroup = path.join(path.dirname(left), leftMatch?.[1] ?? left);\n const rightGroup = path.join(path.dirname(right), rightMatch?.[1] ?? right);\n const groupOrder = leftGroup.localeCompare(rightGroup);\n if (groupOrder !== 0) return groupOrder;\n return Number(leftMatch?.[2] ?? 0) - Number(rightMatch?.[2] ?? 0);\n });\n}\n\n// \u2500\u2500 Helper functions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction numberAt(event: ChronicleEvent, dotPath: string): number {\n const value = readPath(event.attributes ?? {}, dotPath);\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction durationMs(event: ChronicleEvent): number {\n const value = Number(event.durationNs ?? 0) / 1_000_000;\n return Number.isFinite(value) ? value : 0;\n}\n\nfunction average(values: number[]): number {\n return values.length ? values.reduce((sum, v) => sum + v, 0) / values.length : 0;\n}\n\nfunction percentile(sorted: number[], quantile: number): number {\n return sorted.length ? sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(sorted.length * quantile) - 1))]! : 0;\n}\n\nfunction scopeKey(event: ChronicleEvent): string {\n return `${event.scope.projectId ?? ''}\\0${event.scope.sessionId ?? ''}\\0${event.scope.agentId ?? ''}`;\n}\n\nfunction signalFamily(event: ChronicleEvent): ChronicleSignalFamily {\n if (/^(?:decision|brain|permission)\\./.test(event.eventType)) return 'decision';\n if (event.resource?.kind === 'file' || event.resource?.kind === 'symbol' || /^(?:file|worktree)\\./.test(event.eventType)) return 'file';\n if (/^(?:provider|token|context|ctx|compaction)\\./.test(event.eventType)) return 'llm';\n if (/^(?:agent|subagent|delegate|fleet|concurrency)\\./.test(event.eventType)) return 'agent';\n if (/^(?:tool|process|mcp|network)\\./.test(event.eventType)) return 'tool';\n if (/^(?:memory|storage|trust)\\./.test(event.eventType)) return 'memory';\n if (/^(?:sdd|task|kanban|checkpoint|session|iteration|in_flight)\\./.test(event.eventType)) return 'task';\n return 'runtime';\n}\n\nfunction isTerminalFailure(event: ChronicleEvent): boolean {\n if (event.eventType === 'provider.attempt.failed') return event.attributes?.retryScheduled !== true;\n return event.eventType === 'tool.failed' ||\n (event.eventType === 'process.completed' && event.outcome === 'failure') ||\n /^(?:agent\\.run\\.error|sdd\\.task\\.failed|compaction\\.failed|network\\.request\\.failed)$/.test(event.eventType);\n}\n\nfunction relationKeys(event: ChronicleEvent): Array<{ key: string; kind: ChronicleRelationKind; confidence: ChronicleGraphEdge['confidence'] }> {\n const result: Array<{ key: string; kind: ChronicleRelationKind; confidence: ChronicleGraphEdge['confidence'] }> = [];\n const add = (kind: ChronicleRelationKind, value: unknown, confidence: ChronicleGraphEdge['confidence']) => {\n if (typeof value === 'string' && value) result.push({ key: `${kind}:${value}`, kind, confidence });\n };\n add('trace', event.correlation.traceId, 'correlated');\n add('tool_call', event.correlation.toolCallId, 'explicit');\n add('logical_request', event.correlation.logicalRequestId, 'explicit');\n add('attempt', event.correlation.attemptId, 'explicit');\n add('decision', event.attributes?.decisionId, 'explicit');\n add('network_request', event.attributes?.requestId, 'explicit');\n add('prompt_manifest', (event.attributes?.promptManifest as Record<string, unknown> | undefined)?.manifestId, 'explicit');\n add('resource_lineage', event.resource?.id, 'inferred');\n if (event.correlation.parentSpanId) add('parent_span', event.correlation.parentSpanId, 'explicit');\n add('parent_span', event.correlation.spanId, 'explicit');\n return result;\n}\n\nfunction matches(event: ChronicleEvent, query: ChronicleQuery): boolean {\n if (query.eventId && event.eventId !== query.eventId) return false;\n if (query.eventTypes && !query.eventTypes.includes(event.eventType)) return false;\n if (query.outcomes && (!event.outcome || !query.outcomes.includes(event.outcome))) return false;\n const occurredAt = event.occurredAt ?? event.observedAt;\n if (query.from && occurredAt < query.from || query.to && occurredAt > query.to) return false;\n if (!equal(query.projectId, event.scope.projectId) || !equal(query.sessionId, event.scope.sessionId)) return false;\n if (!equal(query.agentId, event.scope.agentId) || !equal(query.taskId, event.scope.taskId)) return false;\n if (!equal(query.providerId, event.runtime?.providerId) || !equal(query.modelId, event.runtime?.modelId)) return false;\n if (!equal(query.traceId, event.correlation.traceId) || !equal(query.logicalRequestId, event.correlation.logicalRequestId)) return false;\n if (!equal(query.attemptId, event.correlation.attemptId) || !equal(query.toolCallId, event.correlation.toolCallId)) return false;\n if (!equal(query.resourceKind, event.resource?.kind) || !equal(query.resourceId, event.resource?.id)) return false;\n if (query.path && normalize(event.resource?.path) !== normalize(query.path)) return false;\n if (query.line !== undefined && !lineContains(event, query.line)) return false;\n if (query.tags && !objectContains(event.tags, query.tags)) return false;\n if (query.attributes && !objectContains(event.attributes, query.attributes)) return false;\n if (query.text && !JSON.stringify(event).toLocaleLowerCase().includes(query.text.toLocaleLowerCase())) return false;\n return true;\n}\n\nfunction equal<T>(expected: T | undefined, actual: T | undefined): boolean { return expected === undefined || expected === actual; }\nfunction normalize(value: string | undefined): string | undefined { return value?.replaceAll('\\\\', '/').toLocaleLowerCase(); }\nfunction lineContains(event: ChronicleEvent, line: number): boolean {\n const start = event.resource?.lineStart; const end = event.resource?.lineEnd ?? start;\n return start !== undefined && end !== undefined && line >= start && line <= end;\n}\nfunction objectContains(actual: Record<string, unknown> | undefined, expected: Record<string, unknown>): boolean {\n return Boolean(actual && Object.entries(expected).every(([key, value]) => deepEqual(readPath(actual, key), value)));\n}\nfunction readPath(value: Record<string, unknown>, key: string): unknown {\n return key.split('.').reduce<unknown>((current, part) => current && typeof current === 'object'\n ? (current as Record<string, unknown>)[part] : undefined, value);\n}\nfunction deepEqual(left: unknown, right: unknown): boolean { return JSON.stringify(left) === JSON.stringify(right); }\nfunction findInsertionIndex(\n events: readonly ChronicleEvent[],\n event: ChronicleEvent,\n compare: (left: ChronicleEvent, right: ChronicleEvent) => number,\n): number {\n let low = 0;\n let high = events.length;\n while (low < high) {\n const middle = (low + high) >>> 1;\n if (compare(events[middle]!, event) <= 0) low = middle + 1;\n else high = middle;\n }\n return low;\n}\nfunction compareEvents(a: ChronicleEvent, b: ChronicleEvent): number {\n return compareEventToKey(a, orderKey(b));\n}\nfunction compareEventToKey(event: ChronicleEvent, key: ChronicleOrderKey): number {\n return (event.occurredAt ?? event.observedAt).localeCompare(key.occurredAt) ||\n event.persistedAt.localeCompare(key.persistedAt) || event.sequence - key.sequence ||\n event.eventId.localeCompare(key.eventId);\n}\nfunction orderKey(event: ChronicleEvent): ChronicleOrderKey {\n return {\n occurredAt: event.occurredAt ?? event.observedAt,\n persistedAt: event.persistedAt,\n sequence: event.sequence,\n eventId: event.eventId,\n };\n}\nfunction hashQuery(query: ChronicleQuery): string {\n const { cursor: _cursor, limit: _limit, order: _order, ...filters } = query;\n return createHash('sha256').update(stableStringify(filters), 'utf8').digest('base64url');\n}\nfunction encodeCursor(cursor: ChronicleCursor): string {\n return Buffer.from(JSON.stringify(cursor), 'utf8').toString('base64url');\n}\nfunction decodeCursor(\n encoded: string | undefined,\n order: 'asc' | 'desc',\n queryHash: string,\n): ChronicleCursor | undefined {\n if (!encoded) return undefined;\n if (encoded.length > 1_000_000) throw new Error('Invalid Chronicle cursor');\n try {\n const parsed = JSON.parse(Buffer.from(encoded, 'base64url').toString('utf8')) as unknown;\n if (!isCursor(parsed) || parsed.order !== order || parsed.queryHash !== queryHash) {\n throw new Error('cursor does not match the query');\n }\n return parsed;\n } catch (error) {\n throw new Error(`Invalid Chronicle cursor: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\nfunction isCursor(value: unknown): value is ChronicleCursor {\n if (!value || typeof value !== 'object') return false;\n const cursor = value as Partial<ChronicleCursor>;\n const after = cursor.after as Partial<ChronicleOrderKey> | undefined;\n if (cursor.version !== 1 || (cursor.order !== 'asc' && cursor.order !== 'desc') ||\n typeof cursor.queryHash !== 'string' || !after ||\n typeof after.occurredAt !== 'string' || typeof after.persistedAt !== 'string' ||\n !Number.isSafeInteger(after.sequence) || typeof after.eventId !== 'string' ||\n !Array.isArray(cursor.snapshot) || cursor.snapshot.length > MAX_CURSOR_SNAPSHOT_ENTRIES) return false;\n\n const snapshotIds = new Set<string>();\n for (const entry of cursor.snapshot) {\n if (!entry || typeof entry.id !== 'string' || !entry.id ||\n !Number.isSafeInteger(entry.size) || entry.size < 0 || snapshotIds.has(entry.id)) return false;\n snapshotIds.add(entry.id);\n }\n return true;\n}\nasync function captureSnapshot(files: readonly string[]): Promise<SnapshotFile[]> {\n if (files.length > MAX_CURSOR_SNAPSHOT_ENTRIES) {\n throw new Error('Chronicle snapshot contains too many partitions');\n }\n return Promise.all(files.map(async (file) => {\n let size = 0;\n try { size = (await fs.stat(file)).size; } catch { /* preserve missing source as empty */ }\n return { file, id: fileId(file), size };\n }));\n}\nasync function resolveSnapshotFiles(\n files: readonly string[],\n snapshot: readonly ChronicleSnapshotEntry[],\n): Promise<SnapshotFile[]> {\n const currentFiles = new Map(files.map((file) => [fileId(file), file]));\n return Promise.all(snapshot.map(async (entry) => {\n const file = currentFiles.get(entry.id);\n if (!file) throw new Error('Chronicle cursor snapshot has expired');\n let currentSize: number;\n try { currentSize = (await fs.stat(file)).size; } catch { throw new Error('Chronicle cursor snapshot has expired'); }\n if (currentSize < entry.size) throw new Error('Chronicle cursor snapshot has expired');\n return { file, ...entry };\n }));\n}\nfunction fileId(file: string): string {\n return createHash('sha256').update(path.resolve(file), 'utf8').digest('base64url');\n}\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value);\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const object = value as Record<string, unknown>;\n return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(object[key])}`).join(',')}}`;\n}\nfunction isChronicleEvent(value: unknown): value is ChronicleEvent {\n if (!isRecord(value) || !isRecord(value.scope) || !isRecord(value.correlation)) return false;\n return value.schemaVersion === 1 &&\n typeof value.eventId === 'string' && typeof value.eventType === 'string' &&\n typeof value.occurredAt === 'string' && typeof value.observedAt === 'string' &&\n typeof value.persistedAt === 'string' && Number.isSafeInteger(value.sequence) &&\n (value.sequence as number) >= 0 && typeof value.previousHash === 'string' &&\n typeof value.hash === 'string' && typeof value.scope.installationId === 'string' &&\n typeof value.scope.machineId === 'string' && optionalStrings(value.scope, [\n 'projectId', 'repositoryId', 'workspaceId', 'worktreeId', 'sessionId', 'turnId',\n 'iterationId', 'agentId', 'goalId', 'planId', 'taskId', 'kanbanBoardId',\n ]) && typeof value.correlation.traceId === 'string' &&\n typeof value.correlation.spanId === 'string' && optionalStrings(value.correlation, [\n 'parentSpanId', 'logicalRequestId', 'attemptId', 'toolCallId',\n ]) && isRuntime(value.runtime) && isResource(value.resource) &&\n (value.attributes === undefined || isRecord(value.attributes)) &&\n (value.tags === undefined || isStringRecord(value.tags));\n}\nfunction isRuntime(value: unknown): boolean {\n return value === undefined || isRecord(value) &&\n optionalStrings(value, ['providerId', 'modelId', 'modelRevision']) &&\n optionalFiniteNumbers(value, ['processId', 'parentProcessId']);\n}\nfunction isResource(value: unknown): boolean {\n if (value === undefined) return true;\n if (!isRecord(value) || !['file', 'symbol', 'memory', 'task', 'kanban', 'process',\n 'network', 'artifact', 'other'].includes(String(value.kind)) || typeof value.id !== 'string') return false;\n return optionalStrings(value, ['path', 'contentHashBefore', 'contentHashAfter']) &&\n optionalFiniteNumbers(value, ['lineStart', 'lineEnd']);\n}\nfunction optionalStrings(value: Record<string, unknown>, keys: readonly string[]): boolean {\n return keys.every((key) => value[key] === undefined || typeof value[key] === 'string');\n}\nfunction optionalFiniteNumbers(value: Record<string, unknown>, keys: readonly string[]): boolean {\n return keys.every((key) => value[key] === undefined || typeof value[key] === 'number' && Number.isFinite(value[key]));\n}\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n return isRecord(value) && Object.values(value).every((entry) => typeof entry === 'string');\n}\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === 'object' && !Array.isArray(value));\n}\nfunction facetValue(event: ChronicleEvent, field: ChronicleFacet): string | undefined {\n const values: Record<ChronicleFacet, string | undefined> = {\n eventType: event.eventType, outcome: event.outcome, projectId: event.scope.projectId,\n sessionId: event.scope.sessionId, agentId: event.scope.agentId, taskId: event.scope.taskId,\n providerId: event.runtime?.providerId, modelId: event.runtime?.modelId,\n resourceKind: event.resource?.kind, resourcePath: event.resource?.path,\n toolCallId: event.correlation.toolCallId,\n };\n return values[field];\n}\n"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,kBAAkB;AASpB,SAAS,uBACd,OACA,UAAkB,WAAW,GACX;AAClB,SAAO;AAAA,IACL,OAAO,EAAE,GAAG,MAAM;AAAA,IAClB,aAAa,EAAE,SAAS,QAAQ,WAAW,EAAE;AAAA,EAC/C;AACF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6
|
"names": ["createHash", "path", "relative", "stat", "createHash", "randomUUID", "fs", "path", "fs", "path", "stat", "resolve", "randomUUID", "resolve", "hash", "text", "createHash", "durationMs", "createHash", "persist", "millisecondsToNanoseconds", "resourceId", "durationMs", "createHash", "persist", "performance", "createHash", "createHash", "value", "createHash", "text", "createHash", "hash", "digest", "createHash", "digest", "createHash", "fs", "path", "trimmed", "normalize", "stableStringify"]
|
|
7
7
|
}
|