@maximtop/opencode-debug-mode 0.1.0 → 0.1.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/plugin.ts","../src/cleanup/service.ts","../src/probes/extension-permissions.ts","../src/probes/remove.ts","../src/process/tree.ts","../src/core/constants.ts","../src/cleanup/export.ts","../src/evidence/sanitize.ts","../src/evidence/types.ts","../src/core/schemas.ts","../src/investigation/schema.ts","../src/session/paths.ts","../src/cleanup/types.ts","../src/collector/ingest.ts","../src/collector/body.ts","../src/collector/auth.ts","../src/collector/router.ts","../src/collector/server.ts","../src/core/clock.ts","../src/evidence/store.ts","../src/session/types.ts","../src/evidence/read.ts","../src/probes/helper.ts","../src/probes/registry.ts","../src/probes/types.ts","../src/probes/template.ts","../src/process/service.ts","../src/process/line-decoder.ts","../src/process/protocol.ts","../src/run/service.ts","../src/session/orphan-recovery.ts","../src/investigation/store.ts","../src/session/atomic-json.ts","../src/session/manifest-store.ts","../src/session/secret-store.ts","../src/session/registry.ts","../src/tools/cleanup-tool.ts","../src/core/result.ts","../src/tools/common.ts","../src/tools/collector-tools.ts","../src/tools/evidence-tools.ts","../src/tools/probe-tools.ts","../src/tools/run-tools.ts","../src/tools/session-tools.ts","../src/tools/state-tools.ts","../src/tools/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\nimport type { Config, Plugin } from \"@opencode-ai/plugin\"\nimport { CleanupService } from \"./cleanup/service.js\"\nimport type { FinalReportInput } from \"./cleanup/types.js\"\nimport { createIngestHandler } from \"./collector/ingest.js\"\nimport { createCollectorRouter } from \"./collector/router.js\"\nimport { CollectorServer } from \"./collector/server.js\"\nimport type { Clock } from \"./core/clock.js\"\nimport { systemClock } from \"./core/clock.js\"\nimport { TEMP_BASE_NAME } from \"./core/constants.js\"\nimport { DebugModeError } from \"./core/errors.js\"\nimport { EvidenceStore } from \"./evidence/store.js\"\nimport { addLoopbackPermission, removeLoopbackPermission } from \"./probes/extension-permissions.js\"\nimport { TransportHelper } from \"./probes/helper.js\"\nimport { ProbeRegistry } from \"./probes/registry.js\"\nimport { ProcessService } from \"./process/service.js\"\nimport { RunService } from \"./run/service.js\"\nimport { recoverOrphans } from \"./session/orphan-recovery.js\"\nimport { isContained } from \"./session/paths.js\"\nimport { type DebugSession, SessionRegistry } from \"./session/registry.js\"\nimport { createDebugTools } from \"./tools/index.js\"\n\ntype SessionServices = {\n evidence: EvidenceStore\n runs: RunService\n probes: ProbeRegistry\n process: ProcessService\n collectorServer?: CollectorServer\n collector: {\n start(input: {\n runtime: \"web\" | \"extension-background\"\n transportTargetPath?: string\n extensionManifestPath?: string\n }): Promise<{\n collectorId: string\n host: \"127.0.0.1\" | \"::1\"\n port: number\n status: string\n helperImport?: string\n helperPath?: string\n }>\n }\n cleanup: CleanupService\n}\n\nasync function updateManifest(session: DebugSession, mutate: Parameters<DebugSession[\"manifestStore\"][\"modify\"]>[0]) {\n return session.manifestStore.modify(mutate)\n}\n\nfunction terminalReport(outcome: \"abandoned\" | \"escalated\", reason: string): FinalReportInput {\n return {\n outcome,\n rootCause: reason,\n decidingEvidence: [],\n hypotheses: [],\n fix: \"No additional fix was applied during lifecycle cleanup\",\n changedFiles: [],\n verification: [\"Package-owned resources were cleaned by the lifecycle hook\"],\n }\n}\n\nexport type DebugModePluginOptions = Readonly<{\n clock?: Clock\n tempBase?: string\n}>\n\nexport function createDebugModePlugin(options: DebugModePluginOptions = {}): Plugin {\n return async (input) => {\n const prompt = await readFile(new URL(\"../assets/debug-agent.md\", import.meta.url), \"utf8\")\n const tempBase = options.tempBase ?? path.join(tmpdir(), TEMP_BASE_NAME)\n const clock = options.clock ?? systemClock\n const recovery = await recoverOrphans({ tempBase, now: clock.now() }).catch((error) => ({\n cleaned: [],\n ignored: [],\n errors: [{ directory: \"<temp-base>\", reason: error instanceof Error ? error.name : \"recovery-failed\" }],\n }))\n if (recovery.errors.length > 0) {\n await input.client.app.log({\n body: {\n service: \"opencode-debug-mode\",\n level: \"warn\",\n message: `Orphan recovery reported ${recovery.errors.length} failure(s)`,\n },\n })\n }\n const services = new Map<string, SessionServices>()\n let registry: SessionRegistry\n\n const forSession = (session: DebugSession): SessionServices => {\n const existing = services.get(session.publicId)\n if (existing !== undefined) return existing\n const evidence = new EvidenceStore(\n session.paths.evidenceFile,\n async (counters) => {\n await updateManifest(session, (manifest) => ({ ...manifest, counters })).catch(() => undefined)\n },\n clock,\n async () => (await session.manifestStore.read()).counters,\n )\n const runs = new RunService(session.manifestStore, clock, (kind) =>\n registry.acquireLeaseForSession(session, kind),\n )\n const probes = new ProbeRegistry(session.manifestStore, session.projectRoot, async (id) => {\n const state = await session.investigationStore.read()\n return state.hypotheses.some((hypothesis) => hypothesis.id === id)\n })\n const sampleCounts = new Map<string, number>()\n const processService = new ProcessService({\n session,\n runs,\n evidence,\n probes,\n acquireLease: async () => registry.acquireLeaseForSession(session, \"process\"),\n })\n let collectorServer: CollectorServer | undefined\n const collector = {\n start: async (request: {\n runtime: \"web\" | \"extension-background\"\n transportTargetPath?: string\n extensionManifestPath?: string\n }) => {\n const manifest = await session.manifestStore.read()\n if (manifest.collector !== null) throw new DebugModeError(\"COLLECTOR_EXISTS\", \"A collector is already active\")\n const ingest = createIngestHandler({\n evidence,\n validateEvent: (event) => probes.validateEvent(event),\n sample: async (event) => {\n const probe = (await session.manifestStore.read()).probes.find(\n (candidate) => candidate.id === event.probeId,\n )\n if (probe?.sampling.mode !== \"every\" || probe.sampling.n === 1) return false\n const count = (sampleCounts.get(probe.id) ?? 0) + 1\n sampleCounts.set(probe.id, count)\n return count % probe.sampling.n !== 0\n },\n })\n collectorServer = new CollectorServer(\n createCollectorRouter({\n token: session.secret,\n ingest,\n onAuthenticated: () => registry.touchSession(session),\n }),\n async () => {\n await service.cleanup.run({\n reason: \"collector-failure\",\n finalReport: terminalReport(\"escalated\", \"Collector failed\"),\n })\n },\n )\n const handle = await collectorServer.start()\n let permissionChange: Awaited<ReturnType<typeof addLoopbackPermission>> | undefined\n if (request.extensionManifestPath !== undefined) {\n if (request.runtime !== \"extension-background\") {\n await collectorServer.close()\n throw new DebugModeError(\n \"PERMISSION_MISMATCH\",\n \"Extension permissions require extension-background runtime\",\n )\n }\n const manifestPath = path.resolve(session.projectRoot, request.extensionManifestPath)\n if (!isContained(session.projectRoot, manifestPath)) {\n await collectorServer.close()\n throw new DebugModeError(\"PERMISSION_MISMATCH\", \"Extension manifest must be inside the project\")\n }\n const host = handle.host === \"::1\" ? \"[::1]\" : handle.host\n permissionChange = await addLoopbackPermission(manifestPath, `http://${host}:${handle.port}/*`)\n }\n try {\n await updateManifest(session, (value) => ({\n ...value,\n collector: {\n id: handle.id,\n host: handle.host,\n port: handle.port,\n status: \"ready\",\n startedAt: clock.now().toISOString(),\n },\n permissionChanges:\n permissionChange === undefined\n ? value.permissionChanges\n : [...value.permissionChanges, permissionChange],\n }))\n } catch (error) {\n if (permissionChange !== undefined) {\n await removeLoopbackPermission(permissionChange.manifestPath, permissionChange).catch(() => undefined)\n }\n await collectorServer.close()\n throw error\n }\n let helper: Awaited<ReturnType<TransportHelper[\"create\"]>> | undefined\n if (request.transportTargetPath !== undefined) {\n const transportHelper = new TransportHelper(session.projectRoot, async (owned) => {\n await updateManifest(session, (value) => ({\n ...value,\n ownedFiles: [...value.ownedFiles, { ...owned, kind: \"transport-helper\" }],\n }))\n })\n helper = await transportHelper.create({\n targetPath: request.transportTargetPath,\n host: handle.host,\n port: handle.port,\n token: session.secret,\n runtime: request.runtime,\n })\n }\n return {\n collectorId: handle.id,\n host: handle.host,\n port: handle.port,\n status: handle.status,\n ...(helper === undefined ? {} : { helperImport: helper.requiredImport, helperPath: helper.relativePath }),\n }\n },\n }\n const cleanup = new CleanupService(session, {\n collector: { close: async () => collectorServer?.close() },\n })\n const service: SessionServices = {\n evidence,\n runs,\n probes,\n process: processService,\n collector,\n cleanup,\n ...(collectorServer === undefined ? {} : { collectorServer }),\n }\n services.set(session.publicId, service)\n return service\n }\n\n registry = new SessionRegistry(tempBase, clock, async (session) => {\n const result = await forSession(session).cleanup.run({\n reason: \"idle-expired\",\n finalReport: terminalReport(\"abandoned\", \"Debug session expired after inactivity\"),\n })\n services.delete(session.publicId)\n if (result.status === \"partial\") {\n await input.client.app.log({\n body: {\n service: \"opencode-debug-mode\",\n level: \"warn\",\n message: \"Idle session cleanup completed with partial failures\",\n },\n })\n }\n })\n\n const tools = createDebugTools({\n registry,\n runFor: (session) => forSession(session).runs,\n processFor: (session) => forSession(session).process,\n collectorFor: (session) => forSession(session).collector,\n probesFor: (session) => forSession(session).probes,\n evidenceFor: (session) => forSession(session).evidence,\n cleanupFor: (session) => forSession(session).cleanup,\n })\n\n const logCollision = (name: string) => {\n void input.client.app.log({\n body: { service: \"opencode-debug-mode\", level: \"warn\", message: `Replacing conflicting ${name} configuration` },\n })\n }\n\n return {\n config: async (config: Config) => {\n if (config.agent?.debug !== undefined) logCollision(\"agent.debug\")\n if (config.command?.debug !== undefined) logCollision(\"command.debug\")\n config.agent ??= {}\n config.command ??= {}\n config.agent.debug = {\n mode: \"primary\",\n description: \"Hypothesis-driven runtime debugging\",\n prompt,\n }\n config.command.debug = {\n description: \"Start hypothesis-driven runtime debugging\",\n agent: \"debug\",\n template: \"$ARGUMENTS\",\n }\n },\n tool: tools,\n event: async ({ event }) => {\n if (event.type !== \"session.deleted\") return\n const trustedId = event.properties.info.id\n try {\n const session = await registry.requireOwned(trustedId)\n await forSession(session).cleanup.run({\n reason: \"session-deleted\",\n finalReport: terminalReport(\"abandoned\", \"OpenCode session was deleted\"),\n })\n registry.forgetTrusted(trustedId)\n } catch (error) {\n if (!(error instanceof DebugModeError && error.code === \"NO_ACTIVE_SESSION\")) throw error\n }\n },\n \"experimental.session.compacting\": async ({ sessionID }, output) => {\n if (await registry.hasTrusted(sessionID)) {\n output.context.push(\n \"An opencode-debug-mode investigation is active. Before any next action, call debug_state_read and reconcile its revision, phase, completed checks, evidence references, and nextAction. Do not repeat a conclusive check unless the checkpoint records invalidating evidence.\",\n )\n }\n },\n dispose: async () => {\n for (const session of registry.listActive()) {\n await forSession(session).cleanup.run({\n reason: \"plugin-dispose\",\n finalReport: terminalReport(\"abandoned\", \"OpenCode plugin was disposed\"),\n })\n }\n await registry.closeAll()\n },\n }\n }\n}\n\nexport const DebugModePlugin: Plugin = createDebugModePlugin()\n","import { spawn } from \"node:child_process\"\nimport { createHash } from \"node:crypto\"\nimport { readFile, rm } from \"node:fs/promises\"\nimport { performance } from \"node:perf_hooks\"\nimport type { z } from \"zod\"\nimport type { CollectorServer } from \"../collector/server.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { removeLoopbackPermission } from \"../probes/extension-permissions.js\"\nimport { removeOwnedProbe } from \"../probes/remove.js\"\nimport { terminateTree } from \"../process/tree.js\"\nimport type { DebugSession } from \"../session/registry.js\"\nimport type { OwnedFileManifestSchema, ProcessManifestSchema } from \"../session/types.js\"\nimport { finalizeRetainedBundle, type StagedBundle, stageRetainedBundle } from \"./export.js\"\nimport { type CleanupResult, type FinalReportInput, FinalReportInputSchema } from \"./types.js\"\n\ntype OwnedFile = z.infer<typeof OwnedFileManifestSchema>\ntype OwnedProcess = z.infer<typeof ProcessManifestSchema>\ntype ResourceResult = CleanupResult[\"resources\"][\"collector\"]\n\nexport class CleanupService {\n private running: Promise<CleanupResult> | undefined\n private completed: CleanupResult | undefined\n\n constructor(\n private readonly session: DebugSession,\n private readonly dependencies: {\n collector?: Pick<CollectorServer, \"close\">\n terminateProcess?: (process: OwnedProcess) => Promise<ResourceResult>\n removeSecret?: () => Promise<\"success\" | \"already-clean\">\n securityValues?: string[]\n } = {},\n ) {}\n\n async run(input: {\n reason: string\n finalReport: FinalReportInput\n cleanCheck?: { executable: string; args: string[]; cwd: string; timeoutMs: number }\n }): Promise<CleanupResult> {\n if (this.completed !== undefined) return this.completed\n this.running ??= this.execute(input)\n this.completed = await this.running\n return this.completed\n }\n\n private async execute(input: {\n reason: string\n finalReport: FinalReportInput\n cleanCheck?: { executable: string; args: string[]; cwd: string; timeoutMs: number }\n }): Promise<CleanupResult> {\n const started = performance.now()\n const finalReport = FinalReportInputSchema.parse(input.finalReport)\n const manifest = await this.session.manifestStore\n .modify((value) => ({\n ...value,\n status: \"cleaning\",\n cleanup: { status: \"running\", completedResources: [] },\n }))\n .catch(() => this.session.manifestStore.read())\n const state = await this.session.investigationStore.read().catch(() => undefined)\n if (state !== undefined) {\n await this.session.investigationStore\n .checkpoint(state.revision, {\n ...state,\n phase: \"cleaning\",\n cleanup: { status: \"running\", completedResources: state.cleanup.completedResources },\n })\n .catch(() => undefined)\n }\n\n let collector: ResourceResult = { status: \"skipped\", reason: \"not-running\" }\n if (manifest.collector !== null) {\n if (this.dependencies.collector === undefined)\n collector = { status: \"failed\", reason: \"collector-runtime-unavailable\" }\n else {\n try {\n await this.dependencies.collector.close()\n collector = { status: \"success\" }\n } catch {\n collector = { status: \"failed\", reason: \"collector-close-failed\" }\n }\n }\n }\n\n const processes: ResourceResult[] = []\n for (const owned of manifest.processes) {\n try {\n if (this.dependencies.terminateProcess !== undefined)\n processes.push(await this.dependencies.terminateProcess(owned))\n else if (owned.targetPid !== undefined) {\n const result = await terminateTree(owned.targetPid)\n processes.push(result.remaining ? { status: \"failed\", reason: \"process-remains\" } : { status: \"success\" })\n } else processes.push({ status: \"already-clean\" })\n } catch {\n processes.push({ status: \"failed\", reason: \"process-termination-failed\" })\n }\n }\n\n const probes: ResourceResult[] = []\n for (const probe of manifest.probes) {\n const result = await removeOwnedProbe(probe)\n probes.push({\n status: result.status === \"already-clean\" ? \"already-clean\" : result.status,\n ...(result.reason === undefined ? {} : { reason: result.reason }),\n location: probe.sourceFile,\n })\n }\n\n const permissions: ResourceResult[] = []\n for (const change of manifest.permissionChanges) {\n const result = await removeLoopbackPermission(change.manifestPath, change)\n permissions.push({\n status: result.status,\n ...(result.reason === undefined ? {} : { reason: result.reason }),\n location: change.manifestPath,\n })\n }\n\n const files: ResourceResult[] = []\n for (const owned of manifest.ownedFiles) files.push(await this.removeOwnedFile(owned))\n\n const cleanCheck = input.cleanCheck === undefined ? undefined : await this.runCleanCheck(input.cleanCheck)\n let staged: StagedBundle | undefined\n if (manifest.keepArtifacts && manifest.retentionDestination !== undefined) {\n try {\n staged = await stageRetainedBundle({\n keepArtifacts: true,\n destination: manifest.retentionDestination,\n sessionDir: manifest.sessionDir,\n evidenceFile: this.session.paths.evidenceFile,\n stateFile: this.session.paths.stateFile,\n token: this.session.secret,\n securityValues: this.dependencies.securityValues ?? [],\n finalReport,\n })\n } catch {\n files.push({ status: \"failed\", reason: \"retention-export-failed\" })\n }\n }\n\n let secret: ResourceResult\n try {\n const status = await (this.dependencies.removeSecret?.() ?? this.session.secretStore.remove())\n secret = { status }\n } catch {\n secret = { status: \"failed\", reason: \"secret-removal-failed\" }\n }\n\n let sessionDirectory: ResourceResult\n try {\n await rm(this.session.paths.sessionDir, { recursive: true, force: true })\n sessionDirectory = { status: \"success\" }\n } catch {\n sessionDirectory = { status: \"failed\", reason: \"session-directory-removal-failed\" }\n }\n\n const resources = { collector, processes, probes, permissions, files, secret, sessionDirectory }\n const failures = [collector, ...processes, ...probes, ...permissions, ...files, secret, sessionDirectory].filter(\n (result) => result.status === \"failed\",\n )\n const remainingArtifacts = failures.flatMap((result) => (result.location === undefined ? [] : [result.location]))\n const result: CleanupResult = {\n status: failures.length === 0 ? \"complete\" : \"partial\",\n reason: input.reason.slice(0, 256),\n resources,\n remainingArtifacts,\n durationMs: performance.now() - started,\n ...(cleanCheck === undefined ? {} : { cleanCheck }),\n }\n if (staged !== undefined) {\n try {\n const retained = await finalizeRetainedBundle(staged, result)\n result.retainedArtifactLocation = retained.path\n } catch (error) {\n result.status = \"partial\"\n result.resources.files.push({\n status: \"failed\",\n reason:\n error instanceof DebugModeError\n ? `retention-finalize-failed:${error.code}:${error.message}`.slice(0, 8_192)\n : \"retention-finalize-failed\",\n })\n }\n }\n return result\n }\n\n private async removeOwnedFile(owned: OwnedFile): Promise<ResourceResult> {\n try {\n const content = await readFile(owned.path)\n if (createHash(\"sha256\").update(content).digest(\"hex\") !== owned.sha256 || content.byteLength !== owned.bytes) {\n return { status: \"failed\", reason: \"owned-file-hash-mismatch\", location: owned.path }\n }\n await rm(owned.path)\n return { status: \"success\", location: owned.path }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { status: \"already-clean\", location: owned.path }\n return { status: \"failed\", reason: \"owned-file-removal-failed\", location: owned.path }\n }\n }\n\n private runCleanCheck(input: { executable: string; args: string[]; cwd: string; timeoutMs: number }) {\n const started = performance.now()\n return new Promise<NonNullable<CleanupResult[\"cleanCheck\"]>>((resolve) => {\n const child = spawn(input.executable, input.args, {\n cwd: input.cwd,\n shell: false,\n stdio: \"ignore\",\n windowsHide: true,\n })\n let timedOut = false\n const timeout = setTimeout(() => {\n timedOut = true\n child.kill(\"SIGKILL\")\n }, input.timeoutMs)\n child.once(\"exit\", (exitCode) => {\n clearTimeout(timeout)\n resolve({\n command: [input.executable, ...input.args].join(\" \").slice(0, 8_192),\n exitCode,\n timedOut,\n durationMs: performance.now() - started,\n })\n })\n child.once(\"error\", () => {\n clearTimeout(timeout)\n resolve({\n command: input.executable.slice(0, 8_192),\n exitCode: null,\n timedOut,\n durationMs: performance.now() - started,\n })\n })\n })\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\"\nimport { applyEdits, modify, type ParseError, parse } from \"jsonc-parser\"\nimport type { z } from \"zod\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport type { PermissionChangeSchema } from \"../session/types.js\"\n\nexport type PermissionChange = z.infer<typeof PermissionChangeSchema>\n\nconst LOOPBACK_MATCH = /^http:\\/\\/(?:127\\.0\\.0\\.1:\\d{1,5}|\\[::1\\]:\\d{1,5})\\/\\*$/u\nconst formatting = { tabSize: 2, insertSpaces: true, eol: \"\\n\" }\n\nfunction readManifest(text: string): Record<string, unknown> {\n const errors: ParseError[] = []\n const value = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as unknown\n if (errors.length > 0 || typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new DebugModeError(\"PERMISSION_MISMATCH\", \"Extension manifest is invalid\")\n }\n return value as Record<string, unknown>\n}\n\nfunction permissionProperty(manifest: Record<string, unknown>): \"permissions\" | \"host_permissions\" {\n if (manifest.manifest_version === 2) return \"permissions\"\n if (manifest.manifest_version === 3) return \"host_permissions\"\n throw new DebugModeError(\"PERMISSION_MISMATCH\", \"Extension manifest version must be 2 or 3\")\n}\n\nexport async function addLoopbackPermission(manifestPath: string, matchPattern: string): Promise<PermissionChange> {\n if (!LOOPBACK_MATCH.test(matchPattern)) {\n throw new DebugModeError(\"PERMISSION_MISMATCH\", \"Only an exact active loopback match pattern is allowed\")\n }\n const text = await readFile(manifestPath, \"utf8\")\n const manifest = readManifest(text)\n const property = permissionProperty(manifest)\n const current = manifest[property]\n if (current !== undefined && (!Array.isArray(current) || current.some((entry) => typeof entry !== \"string\"))) {\n throw new DebugModeError(\"PERMISSION_MISMATCH\", `Extension ${property} must be a string array`)\n }\n const permissions = (current ?? []) as string[]\n if (permissions.includes(matchPattern)) {\n return { manifestPath, property, matchPattern, addedBySession: false }\n }\n const edits = Array.isArray(current)\n ? modify(text, [property, permissions.length], matchPattern, {\n formattingOptions: formatting,\n isArrayInsertion: true,\n })\n : modify(text, [property], [matchPattern], { formattingOptions: formatting })\n await writeFile(manifestPath, applyEdits(text, edits), \"utf8\")\n return { manifestPath, property, matchPattern, addedBySession: true }\n}\n\nexport async function removeLoopbackPermission(\n manifestPath: string,\n change: PermissionChange,\n): Promise<{ status: \"success\" | \"already-clean\" | \"failed\"; reason?: string }> {\n if (!change.addedBySession) return { status: \"already-clean\" }\n let text: string\n try {\n text = await readFile(manifestPath, \"utf8\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { status: \"already-clean\" }\n return { status: \"failed\", reason: \"manifest-read-failed\" }\n }\n let manifest: Record<string, unknown>\n try {\n manifest = readManifest(text)\n } catch {\n return { status: \"failed\", reason: \"manifest-invalid\" }\n }\n if (permissionProperty(manifest) !== change.property) return { status: \"failed\", reason: \"manifest-version-changed\" }\n const current = manifest[change.property]\n if (current === undefined) return { status: \"already-clean\" }\n if (!Array.isArray(current) || current.some((entry) => typeof entry !== \"string\")) {\n return { status: \"failed\", reason: \"permission-structure-changed\" }\n }\n const matches = current.flatMap((entry, index) => (entry === change.matchPattern ? [index] : []))\n if (matches.length === 0) return { status: \"already-clean\" }\n if (matches.length !== 1) return { status: \"failed\", reason: \"permission-ambiguous\" }\n const index = matches[0]\n if (index === undefined) return { status: \"already-clean\" }\n const edits = modify(text, [change.property, index], undefined, { formattingOptions: formatting })\n await writeFile(manifestPath, applyEdits(text, edits), \"utf8\")\n return { status: \"success\" }\n}\n","import { createHash } from \"node:crypto\"\nimport { readFile, writeFile } from \"node:fs/promises\"\nimport type { ManifestProbe } from \"../session/types.js\"\n\nexport type ProbeRemovalResult =\n | { status: \"success\"; file: string; reason?: never }\n | { status: \"already-clean\"; file: string; reason?: never }\n | { status: \"failed\"; file: string; reason: string; line?: number }\n\nfunction occurrences(value: string, needle: string): number {\n if (needle.length === 0) return 0\n return value.split(needle).length - 1\n}\n\nfunction lineAt(value: string, index: number): number {\n return value.slice(0, index).split(/\\r?\\n/u).length\n}\n\nexport async function removeOwnedProbe(probe: ManifestProbe): Promise<ProbeRemovalResult> {\n for (let attempt = 0; attempt < 2; attempt += 1) {\n let source: string\n try {\n source = await readFile(probe.sourceFile, \"utf8\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { status: \"already-clean\", file: probe.sourceFile }\n return { status: \"failed\", file: probe.sourceFile, reason: \"source-read-failed\" }\n }\n const starts = occurrences(source, probe.markerStart)\n const ends = occurrences(source, probe.markerEnd)\n if (starts === 0 && ends === 0) return { status: \"already-clean\", file: probe.sourceFile }\n const startIndex = source.indexOf(probe.markerStart)\n if (starts !== 1 || ends !== 1 || startIndex < 0) {\n return {\n status: \"failed\",\n file: probe.sourceFile,\n reason: \"marker-ambiguous\",\n ...(startIndex < 0 ? {} : { line: lineAt(source, startIndex) }),\n }\n }\n if (probe.expectedBlock === undefined || probe.expectedHash === undefined) {\n return {\n status: \"failed\",\n file: probe.sourceFile,\n reason: \"marker-ownership-incomplete\",\n line: lineAt(source, startIndex),\n }\n }\n if (\n occurrences(source, probe.expectedBlock) !== 1 ||\n createHash(\"sha256\").update(probe.expectedBlock).digest(\"hex\") !== probe.expectedHash\n ) {\n return {\n status: \"failed\",\n file: probe.sourceFile,\n reason: \"marker-content-mismatch\",\n line: lineAt(source, startIndex),\n }\n }\n const current = await readFile(probe.sourceFile, \"utf8\")\n if (current !== source) continue\n const blockIndex = source.indexOf(probe.expectedBlock)\n const next = source.slice(0, blockIndex) + source.slice(blockIndex + probe.expectedBlock.length)\n await writeFile(probe.sourceFile, next, \"utf8\")\n return { status: \"success\", file: probe.sourceFile }\n }\n return { status: \"failed\", file: probe.sourceFile, reason: \"concurrent-source-change\" }\n}\n","import { spawn } from \"node:child_process\"\nimport { performance } from \"node:perf_hooks\"\nimport { LIMITS } from \"../core/constants.js\"\n\nexport type Execute = (executable: string, args: string[]) => Promise<{ exitCode: number | null }>\n\nexport type TerminationResult = Readonly<{\n graceful: boolean\n forced: boolean\n remaining: boolean\n durationMs: number\n errors: string[]\n}>\n\nconst defaultExecute: Execute = (executable, args) =>\n new Promise((resolve, reject) => {\n const child = spawn(executable, args, { shell: false, windowsHide: true, stdio: \"ignore\" })\n child.once(\"error\", reject)\n child.once(\"exit\", (exitCode) => resolve({ exitCode }))\n })\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== \"ESRCH\"\n }\n}\n\nasync function waitForExit(pid: number, milliseconds: number): Promise<boolean> {\n const deadline = performance.now() + milliseconds\n while (performance.now() < deadline) {\n if (!isAlive(pid)) return true\n await new Promise<void>((resolve) => setTimeout(resolve, 20))\n }\n return !isAlive(pid)\n}\n\nfunction safeError(error: unknown): string {\n const code = (error as NodeJS.ErrnoException).code\n return typeof code === \"string\" ? code.slice(0, 64) : \"termination-failed\"\n}\n\nexport async function terminateTree(\n targetPid: number,\n options: {\n platform?: NodeJS.Platform\n execute?: Execute\n gracefulMs?: number\n forceMs?: number\n } = {},\n): Promise<TerminationResult> {\n const started = performance.now()\n const errors: string[] = []\n let graceful = false\n let forced = false\n const platform = options.platform ?? process.platform\n const gracefulMs = options.gracefulMs ?? LIMITS.gracefulKillMs\n const forceMs = options.forceMs ?? LIMITS.forcedKillMs\n\n if (!Number.isInteger(targetPid) || targetPid <= 0) {\n return {\n graceful: false,\n forced: false,\n remaining: false,\n durationMs: performance.now() - started,\n errors: [\"invalid-pid\"],\n }\n }\n\n if (platform === \"win32\") {\n const execute = options.execute ?? defaultExecute\n try {\n const result = await execute(\"taskkill\", [\"/PID\", String(targetPid), \"/T\"])\n graceful = result.exitCode === 0\n } catch (error) {\n errors.push(safeError(error))\n }\n await waitForExit(targetPid, gracefulMs)\n try {\n const result = await execute(\"taskkill\", [\"/PID\", String(targetPid), \"/T\", \"/F\"])\n forced = result.exitCode === 0\n } catch (error) {\n errors.push(safeError(error))\n }\n await waitForExit(targetPid, forceMs)\n } else {\n try {\n process.kill(-targetPid, \"SIGTERM\")\n graceful = true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ESRCH\") {\n return { graceful: false, forced: false, remaining: false, durationMs: performance.now() - started, errors }\n }\n errors.push(safeError(error))\n }\n if (!(await waitForExit(targetPid, gracefulMs))) {\n try {\n process.kill(-targetPid, \"SIGKILL\")\n forced = true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") errors.push(safeError(error))\n }\n await waitForExit(targetPid, forceMs)\n }\n }\n\n return {\n graceful,\n forced,\n remaining: isAlive(targetPid),\n durationMs: performance.now() - started,\n errors,\n }\n}\n","export const PACKAGE_ID = \"opencode-debug-mode\" as const\nexport const MANIFEST_SCHEMA_VERSION = 1 as const\nexport const STATE_SCHEMA_VERSION = 1 as const\nexport const EVENT_SCHEMA_VERSION = 1 as const\nexport const TEMP_BASE_NAME = \"opencode-debug-mode-v1\" as const\nexport const PROCESS_EVENT_PREFIX = \"__OPENCODE_DEBUG_EVENT_V1__\" as const\n\nexport const LIMITS = Object.freeze({\n requestBytes: 64 * 1024,\n scalarBytes: 8 * 1024,\n events: 25_000,\n evidenceBytes: 25 * 1024 * 1024,\n checkpointBytes: 256 * 1024,\n eventsPerBatch: 100,\n idleMs: 30 * 60 * 1000,\n collectorReadyMs: 2_000,\n cleanupMs: 5_000,\n gracefulKillMs: 750,\n forcedKillMs: 1_500,\n noSignalIterations: 3,\n})\n","import { createHash, randomBytes } from \"node:crypto\"\nimport { createReadStream } from \"node:fs\"\nimport { appendFile, mkdir, readdir, readFile, realpath, rename, rm, writeFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { createInterface } from \"node:readline\"\nimport { PACKAGE_ID } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { sanitizeEvidenceData } from \"../evidence/sanitize.js\"\nimport { EvidenceEventSchema } from \"../evidence/types.js\"\nimport { InvestigationStateSchema } from \"../investigation/schema.js\"\nimport { isContained } from \"../session/paths.js\"\nimport { type CleanupResult, CleanupResultSchema, type FinalReportInput, FinalReportInputSchema } from \"./types.js\"\n\nexport type RetainedBundleInput = Readonly<{\n keepArtifacts: boolean\n destination?: string\n sessionDir: string\n evidenceFile: string\n stateFile: string\n token: string\n securityValues?: string[]\n finalReport: FinalReportInput\n}>\n\nexport type StagedBundle = Readonly<{\n partialPath: string\n finalPath: string\n token: string\n securityValues: string[]\n report: FinalReportInput\n eventCount: number\n}>\n\nfunction sha256(value: Buffer | string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\")\n}\n\nfunction redactKnownSecrets(value: unknown, secrets: string[]): unknown {\n if (typeof value === \"string\") {\n return secrets.reduce((text, secret) => (secret.length === 0 ? text : text.replaceAll(secret, \"[REDACTED]\")), value)\n }\n if (Array.isArray(value)) return value.map((entry) => redactKnownSecrets(entry, secrets))\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, redactKnownSecrets(entry, secrets)]))\n }\n return value\n}\n\nasync function sanitizedEvidence(source: string, destination: string): Promise<number> {\n let count = 0\n await writeFile(destination, \"\", { mode: 0o600 })\n const lines = createInterface({ input: createReadStream(source), crlfDelay: Number.POSITIVE_INFINITY })\n for await (const line of lines) {\n if (line.length === 0) continue\n const event = EvidenceEventSchema.parse(JSON.parse(line))\n const sanitized = sanitizeEvidenceData(event.data)\n await appendFile(\n destination,\n `${JSON.stringify({\n ...event,\n data: sanitized.value,\n sanitization: {\n flags: [...new Set([...event.sanitization.flags, ...sanitized.flags])].sort(),\n droppedKeys: event.sanitization.droppedKeys + sanitized.droppedKeys,\n storedBytes: sanitized.storedBytes,\n ...(sanitized.originalBytes === undefined ? {} : { originalBytes: sanitized.originalBytes }),\n },\n })}\\n`,\n { mode: 0o600 },\n )\n count += 1\n }\n return count\n}\n\nfunction renderReport(report: FinalReportInput, cleanup: CleanupResult, retainedPath: string): string {\n const hypotheses = report.hypotheses.map((value) => `- ${value.id}: ${value.status} — ${value.statement}`).join(\"\\n\")\n return `# Debug investigation report\n\nOutcome: ${report.outcome}\n\n## Root cause\n\n${report.rootCause}\n\n## Deciding evidence\n\n${report.decidingEvidence.map((value) => `- ${value}`).join(\"\\n\")}\n\n## Hypotheses\n\n${hypotheses}\n\n## Fix\n\n${report.fix}\n\nChanged files: ${report.changedFiles.join(\", \")}\n\n## Verification\n\n${report.verification.map((value) => `- ${value}`).join(\"\\n\")}\n\n## Cleanup\n\nStatus: ${cleanup.status}\n\nRetained artifact: ${retainedPath}\n`\n}\n\nexport async function stageRetainedBundle(input: RetainedBundleInput): Promise<StagedBundle> {\n if (!input.keepArtifacts || input.destination === undefined) {\n throw new DebugModeError(\"DESTINATION_REQUIRED\", \"Explicit retention is not enabled\")\n }\n let partialPath: string | undefined\n try {\n const destination = await realpath(input.destination)\n const sessionDir = await realpath(input.sessionDir)\n if (destination === sessionDir || isContained(sessionDir, destination)) {\n throw new DebugModeError(\"EXPORT_FAILED\", \"Retention destination cannot be inside the ephemeral session\")\n }\n const suffix = randomBytes(8).toString(\"hex\")\n partialPath = path.join(destination, `.partial-${PACKAGE_ID}-${suffix}`)\n const finalPath = path.join(\n destination,\n `${PACKAGE_ID}-${new Date().toISOString().replace(/[:.]/gu, \"-\")}-${suffix}`,\n )\n await mkdir(partialPath, { mode: 0o700 })\n const state = InvestigationStateSchema.parse(JSON.parse(await readFile(input.stateFile, \"utf8\")))\n const sanitizedState = InvestigationStateSchema.parse(\n sanitizeEvidenceData(redactKnownSecrets(state, [input.token, ...(input.securityValues ?? [])])).value,\n )\n await writeFile(\n path.join(partialPath, \"investigation-state.json\"),\n `${JSON.stringify(sanitizedState, null, 2)}\\n`,\n {\n mode: 0o600,\n },\n )\n const eventCount = await sanitizedEvidence(input.evidenceFile, path.join(partialPath, \"evidence.ndjson\"))\n return {\n partialPath,\n finalPath,\n token: input.token,\n securityValues: input.securityValues ?? [],\n report: FinalReportInputSchema.parse(input.finalReport),\n eventCount,\n }\n } catch (error) {\n if (partialPath !== undefined) await rm(partialPath, { recursive: true, force: true }).catch(() => undefined)\n if (error instanceof DebugModeError) throw error\n throw new DebugModeError(\"EXPORT_FAILED\", \"Retained bundle could not be staged\")\n }\n}\n\nexport async function finalizeRetainedBundle(\n staged: StagedBundle,\n cleanupInput: CleanupResult,\n): Promise<{ path: string }> {\n try {\n const cleanup = CleanupResultSchema.parse(cleanupInput)\n const report = renderReport(staged.report, cleanup, staged.finalPath)\n await writeFile(path.join(staged.partialPath, \"report.md\"), report, { mode: 0o600 })\n const publicFiles = [\"evidence.ndjson\", \"investigation-state.json\", \"report.md\"]\n const files: Record<string, { bytes: number; sha256: string }> = {}\n for (const name of publicFiles) {\n const value = await readFile(path.join(staged.partialPath, name))\n files[name] = { bytes: value.byteLength, sha256: sha256(value) }\n }\n const manifest = {\n package: PACKAGE_ID,\n schemaVersion: 1,\n createdAt: new Date().toISOString(),\n eventCount: staged.eventCount,\n files,\n }\n await writeFile(path.join(staged.partialPath, \"bundle-manifest.json\"), `${JSON.stringify(manifest, null, 2)}\\n`, {\n mode: 0o600,\n })\n for (const name of await readdir(staged.partialPath)) {\n const text = await readFile(path.join(staged.partialPath, name), \"utf8\")\n if ([staged.token, ...staged.securityValues].some((secret) => secret.length > 0 && text.includes(secret))) {\n throw new DebugModeError(\"EXPORT_FAILED\", \"Retained bundle failed its secret scan\")\n }\n }\n await rename(staged.partialPath, staged.finalPath)\n return { path: staged.finalPath }\n } catch (error) {\n await rm(staged.partialPath, { recursive: true, force: true }).catch(() => undefined)\n if (error instanceof DebugModeError) throw error\n throw new DebugModeError(\"EXPORT_FAILED\", \"Retained bundle could not be finalized\")\n }\n}\n","import { LIMITS } from \"../core/constants.js\"\nimport type { JsonValue, SanitizationFlag } from \"./types.js\"\n\nconst MAX_DEPTH = 6\nconst MAX_KEYS = 50\nconst MAX_ARRAY = 100\nconst SECRET_KEYS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"password\",\n \"passwd\",\n \"secret\",\n \"token\",\n \"access-token\",\n \"refresh-token\",\n \"api-key\",\n \"apikey\",\n \"private-key\",\n \"client-secret\",\n])\n\nexport type SanitizeResult = Readonly<{\n value: JsonValue\n flags: SanitizationFlag[]\n droppedKeys: number\n originalBytes?: number\n storedBytes: number\n}>\n\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[_\\s]+/g, \"-\")\n}\n\nfunction truncateUtf8(value: string, maximumBytes: number): string {\n if (Buffer.byteLength(value) <= maximumBytes) return value\n return Buffer.from(value)\n .subarray(0, maximumBytes)\n .toString(\"utf8\")\n .replace(/\\uFFFD$/u, \"\")\n}\n\nfunction estimateOriginalBytes(value: unknown): number | undefined {\n try {\n const serialized = JSON.stringify(value)\n return serialized === undefined ? undefined : Buffer.byteLength(serialized)\n } catch {\n return undefined\n }\n}\n\nexport function sanitizeEvidenceData(input: unknown): SanitizeResult {\n const flags = new Set<SanitizationFlag>()\n const seen = new WeakSet<object>()\n let droppedKeys = 0\n\n const visit = (value: unknown, depth: number): JsonValue => {\n if (depth > MAX_DEPTH) {\n flags.add(\"truncated\")\n return \"[TRUNCATED: depth]\"\n }\n if (value === null) return null\n if (typeof value === \"string\") {\n const truncated = truncateUtf8(value, LIMITS.scalarBytes)\n if (truncated !== value) flags.add(\"truncated\")\n return truncated\n }\n if (typeof value === \"boolean\") return value\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value\n flags.add(\"unsupported\")\n return `[${String(value)}]`\n }\n if (typeof value === \"bigint\") {\n flags.add(\"unsupported\")\n return `[BigInt ${truncateUtf8(value.toString(), 128)}]`\n }\n if (typeof value === \"undefined\") {\n flags.add(\"unsupported\")\n return \"[undefined]\"\n }\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n flags.add(\"unsupported\")\n return `[${typeof value}]`\n }\n\n if (Buffer.isBuffer(value) || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n flags.add(\"binary\")\n const length = Buffer.isBuffer(value)\n ? value.byteLength\n : value instanceof ArrayBuffer\n ? value.byteLength\n : value.byteLength\n return `[Binary ${length} bytes]`\n }\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? \"[Invalid Date]\" : value.toISOString()\n if (value instanceof RegExp) {\n flags.add(\"unsupported\")\n return truncateUtf8(value.toString(), 256)\n }\n if (value instanceof Error) {\n flags.add(\"unsupported\")\n return { name: truncateUtf8(value.name, 128), message: truncateUtf8(value.message, LIMITS.scalarBytes) }\n }\n if (seen.has(value)) {\n flags.add(\"cycle\")\n return \"[CYCLE]\"\n }\n seen.add(value)\n\n if (Array.isArray(value)) {\n if (value.length > MAX_ARRAY) {\n flags.add(\"truncated\")\n droppedKeys += value.length - MAX_ARRAY\n }\n return value.slice(0, MAX_ARRAY).map((entry) => visit(entry, depth + 1))\n }\n\n const record = value as Record<string, unknown>\n try {\n if (typeof record.nodeType === \"number\" && typeof record.nodeName === \"string\") {\n flags.add(\"unsupported\")\n return `[DOM ${truncateUtf8(record.nodeName, 128)}]`\n }\n } catch {\n flags.add(\"unsupported\")\n }\n\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n flags.add(\"unsupported\")\n return `[Unsupported ${truncateUtf8(value.constructor?.name ?? \"object\", 128)}]`\n }\n\n let keys: string[]\n try {\n keys = Object.keys(record).sort()\n } catch {\n flags.add(\"unsupported\")\n return \"[Unreadable object]\"\n }\n if (keys.length > MAX_KEYS) {\n flags.add(\"truncated\")\n droppedKeys += keys.length - MAX_KEYS\n keys = keys.slice(0, MAX_KEYS)\n }\n\n const result: Record<string, JsonValue> = {}\n for (const key of keys) {\n if (SECRET_KEYS.has(normalizeKey(key))) {\n result[key] = \"[REDACTED]\"\n flags.add(\"redacted\")\n continue\n }\n try {\n result[key] = visit(record[key], depth + 1)\n } catch {\n result[key] = \"[Unreadable property]\"\n flags.add(\"unsupported\")\n }\n }\n return result\n }\n\n const value = visit(input, 0)\n const storedBytes = Buffer.byteLength(JSON.stringify(value))\n const originalBytes = estimateOriginalBytes(input)\n return {\n value,\n flags: [...flags].sort(),\n droppedKeys,\n ...(originalBytes === undefined ? {} : { originalBytes }),\n storedBytes,\n }\n}\n","import { z } from \"zod\"\nimport { EVENT_SCHEMA_VERSION, LIMITS } from \"../core/constants.js\"\nimport { IsoTimestampSchema, OpaqueIdSchema, RunLabelSchema } from \"../core/schemas.js\"\n\nexport type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }\n\nexport const SourceLocationSchema = z\n .object({\n file: z.string().min(1).max(LIMITS.scalarBytes),\n line: z.number().int().positive(),\n column: z.number().int().positive().optional(),\n })\n .strict()\n\nexport const EventInputSchema = z\n .object({\n schemaVersion: z.literal(EVENT_SCHEMA_VERSION),\n sessionId: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n runLabel: RunLabelSchema,\n hypothesisId: OpaqueIdSchema,\n probeId: OpaqueIdSchema,\n timestamp: IsoTimestampSchema,\n message: z.string().min(1).max(LIMITS.scalarBytes),\n source: SourceLocationSchema,\n data: z.unknown().optional(),\n })\n .strict()\n\nexport const SanitizationFlagSchema = z.enum([\"redacted\", \"truncated\", \"cycle\", \"binary\", \"unsupported\"])\n\nexport const EvidenceEventSchema = z\n .object({\n schemaVersion: z.literal(EVENT_SCHEMA_VERSION),\n eventId: OpaqueIdSchema,\n receivedAt: IsoTimestampSchema,\n timestamp: IsoTimestampSchema,\n sessionId: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n runLabel: RunLabelSchema,\n hypothesisId: OpaqueIdSchema,\n probeId: OpaqueIdSchema,\n kind: z.string().min(1).max(128),\n message: z.string().min(1).max(LIMITS.scalarBytes),\n data: z.unknown(),\n source: SourceLocationSchema,\n sanitization: z\n .object({\n flags: z.array(SanitizationFlagSchema),\n droppedKeys: z.number().int().nonnegative(),\n originalBytes: z.number().int().nonnegative().optional(),\n storedBytes: z.number().int().nonnegative(),\n })\n .strict(),\n })\n .strict()\n\nexport type EventInput = z.infer<typeof EventInputSchema>\nexport type EvidenceEvent = z.infer<typeof EvidenceEventSchema>\nexport type SanitizationFlag = z.infer<typeof SanitizationFlagSchema>\n\nexport type EvidenceFilter = Readonly<{\n sessionId?: string\n runId?: string\n hypothesisId?: string\n probeId?: string\n from?: string\n to?: string\n keyword?: string\n cursor?: string\n limit?: number\n}>\n","import { z } from \"zod\"\n\nexport const OpaqueIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[A-Za-z0-9_-]+$/)\nexport const IsoTimestampSchema = z.string().datetime({ offset: true })\nexport const HexSha256Schema = z.string().regex(/^[a-f0-9]{64}$/)\nexport const RunLabelSchema = z.enum([\"pre-fix\", \"post-fix\"])\n\nexport type OpaqueId = z.infer<typeof OpaqueIdSchema>\n","import { z } from \"zod\"\nimport { LIMITS, STATE_SCHEMA_VERSION } from \"../core/constants.js\"\nimport { IsoTimestampSchema, OpaqueIdSchema, RunLabelSchema } from \"../core/schemas.js\"\n\nconst Text = z.string().max(LIMITS.scalarBytes)\nconst TextList = (maximum: number) => z.array(Text).max(maximum)\nconst EvidenceIds = z.array(OpaqueIdSchema).max(500)\n\nexport const HypothesisSchema = z\n .object({\n id: OpaqueIdSchema,\n rank: z.number().int().min(1).max(4),\n statement: Text,\n confirmationSignals: TextList(20),\n eliminationSignals: TextList(20),\n status: z.enum([\"open\", \"confirmed\", \"eliminated\"]),\n evidenceRefs: EvidenceIds,\n invalidatedBy: Text.optional(),\n })\n .strict()\n\nexport const CompletedCheckSchema = z\n .object({\n id: OpaqueIdSchema,\n summary: Text,\n interpretation: Text,\n conclusive: z.boolean(),\n evidenceRefs: EvidenceIds,\n completedAt: IsoTimestampSchema,\n invalidatedBy: Text.optional(),\n })\n .strict()\n\nexport const RunReferenceSchema = z\n .object({\n id: OpaqueIdSchema,\n label: RunLabelSchema,\n status: z.enum([\"planned\", \"running\", \"waiting\", \"completed\", \"failed\", \"timed_out\", \"cancelled\"]),\n evidenceRefs: EvidenceIds,\n })\n .strict()\n\nexport const ProbeReferenceSchema = z\n .object({\n id: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n hypothesisId: OpaqueIdSchema,\n sourceFile: Text,\n status: z.enum([\"planned\", \"registered\", \"validated\", \"active\", \"removed\", \"ambiguous\"]),\n })\n .strict()\n\nexport const DeveloperConfirmationSchema = z\n .object({ id: OpaqueIdSchema, statement: Text, confirmedAt: IsoTimestampSchema })\n .strict()\n\nexport const DecisionSchema = z\n .object({ id: OpaqueIdSchema, summary: Text, evidenceRefs: EvidenceIds, decidedAt: IsoTimestampSchema })\n .strict()\n\nexport const InvestigationStateSchema = z\n .object({\n schemaVersion: z.literal(STATE_SCHEMA_VERSION),\n revision: z.number().int().nonnegative(),\n updatedAt: IsoTimestampSchema,\n problemSummary: Text,\n expectedBehavior: Text,\n actualBehavior: Text,\n runtimeContext: z.object({ kind: z.enum([\"cli\", \"web\", \"extension\", \"other\"]), target: Text }).strict(),\n reproduction: z.object({ method: Text, requiresUser: z.boolean(), confirmed: z.boolean().nullable() }).strict(),\n successCriteria: TextList(50),\n phase: z.enum([\n \"intake\",\n \"hypotheses\",\n \"baseline\",\n \"instrumenting\",\n \"waiting_for_reproduction\",\n \"analyzing\",\n \"fixing\",\n \"verifying\",\n \"cleaning\",\n \"completed\",\n \"abandoned\",\n \"escalated\",\n ]),\n loopIteration: z.number().int().min(0).max(3),\n singleCauseEvidenceRef: OpaqueIdSchema.nullable(),\n hypotheses: z.array(HypothesisSchema).max(4),\n completedChecks: z.array(CompletedCheckSchema).max(100),\n runs: z.array(RunReferenceSchema).max(20),\n probeRefs: z.array(ProbeReferenceSchema).max(100),\n decidingEvidenceIds: EvidenceIds,\n developerConfirmations: z.array(DeveloperConfirmationSchema).max(100),\n decisions: z.array(DecisionSchema).max(100),\n nextAction: Text,\n instrumentedFiles: TextList(200),\n fixedFiles: TextList(200),\n cleanup: z\n .object({\n status: z.enum([\"not_started\", \"running\", \"complete\", \"partial\"]),\n completedResources: TextList(1_000),\n })\n .strict(),\n })\n .strict()\n\nexport type InvestigationState = z.infer<typeof InvestigationStateSchema>\n","import { lstat, mkdir, mkdtemp, realpath } from \"node:fs/promises\"\nimport path from \"node:path\"\n\nexport type SessionPaths = Readonly<{\n baseDir: string\n sessionDir: string\n projectRoot: string\n manifestFile: string\n secretFile: string\n stateFile: string\n evidenceFile: string\n}>\n\nexport function isContained(parent: string, child: string): boolean {\n const relative = path.relative(parent, child)\n return relative !== \"\" && !relative.startsWith(`..${path.sep}`) && relative !== \"..\" && !path.isAbsolute(relative)\n}\n\nexport async function createSessionPaths(tempBase: string, projectRoot: string): Promise<SessionPaths> {\n const absoluteBase = path.resolve(tempBase)\n try {\n const existing = await lstat(absoluteBase)\n if (existing.isSymbolicLink()) throw new Error(\"Temporary base must not be a symbolic link\")\n if (!existing.isDirectory()) throw new Error(\"Temporary base must be a directory\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n await mkdir(absoluteBase, { recursive: true, mode: 0o700 })\n }\n\n await realpath(absoluteBase)\n const canonicalProject = await realpath(projectRoot)\n const sessionDir = await mkdtemp(path.join(absoluteBase, \"session-\"))\n if (!isContained(absoluteBase, sessionDir)) throw new Error(\"Created session directory escaped the temporary base\")\n\n return Object.freeze({\n baseDir: absoluteBase,\n sessionDir,\n projectRoot: canonicalProject,\n manifestFile: path.join(sessionDir, \"manifest.json\"),\n secretFile: path.join(sessionDir, \"secret.bin\"),\n stateFile: path.join(sessionDir, \"investigation-state.json\"),\n evidenceFile: path.join(sessionDir, \"evidence.ndjson\"),\n })\n}\n","import { z } from \"zod\"\n\nexport const ResourceCleanupResultSchema = z\n .object({\n status: z.enum([\"success\", \"already-clean\", \"skipped\", \"failed\"]),\n reason: z.string().max(8_192).optional(),\n location: z.string().max(8_192).optional(),\n })\n .strict()\n\nexport const CleanupResultSchema = z\n .object({\n status: z.enum([\"complete\", \"partial\"]),\n reason: z.string().max(256),\n resources: z\n .object({\n collector: ResourceCleanupResultSchema,\n processes: z.array(ResourceCleanupResultSchema),\n probes: z.array(ResourceCleanupResultSchema),\n permissions: z.array(ResourceCleanupResultSchema),\n files: z.array(ResourceCleanupResultSchema),\n secret: ResourceCleanupResultSchema,\n sessionDirectory: ResourceCleanupResultSchema,\n })\n .strict(),\n remainingArtifacts: z.array(z.string().max(8_192)),\n durationMs: z.number().nonnegative(),\n cleanCheck: z\n .object({\n command: z.string().max(8_192),\n exitCode: z.number().int().nullable(),\n timedOut: z.boolean(),\n durationMs: z.number().nonnegative(),\n })\n .strict()\n .optional(),\n retainedArtifactLocation: z.string().max(8_192).optional(),\n })\n .strict()\n\nexport const FinalReportInputSchema = z\n .object({\n outcome: z.enum([\"completed\", \"unresolved\", \"abandoned\", \"escalated\"]),\n rootCause: z.string().max(8_192),\n decidingEvidence: z.array(z.string().max(8_192)).max(100),\n hypotheses: z\n .array(\n z\n .object({\n id: z.string().max(64),\n status: z.enum([\"open\", \"confirmed\", \"eliminated\"]),\n statement: z.string().max(8_192),\n })\n .strict(),\n )\n .max(4),\n fix: z.string().max(8_192),\n changedFiles: z.array(z.string().max(8_192)).max(200),\n verification: z.array(z.string().max(8_192)).max(100),\n })\n .strict()\n\nexport const FinalReportSchema = FinalReportInputSchema.extend({\n cleanup: CleanupResultSchema,\n retainedArtifactLocation: z.string().max(8_192).optional(),\n}).strict()\n\nexport type CleanupResult = z.infer<typeof CleanupResultSchema>\nexport type FinalReportInput = z.infer<typeof FinalReportInputSchema>\nexport type FinalReport = z.infer<typeof FinalReportSchema>\n","import { randomBytes } from \"node:crypto\"\nimport type { IncomingMessage, ServerResponse } from \"node:http\"\nimport { z } from \"zod\"\nimport { LIMITS } from \"../core/constants.js\"\nimport type { EvidenceStore } from \"../evidence/store.js\"\nimport { type EventInput, EventInputSchema } from \"../evidence/types.js\"\nimport { CollectorBodyError, readBoundedJsonBody } from \"./body.js\"\nimport { writeCollectorJson } from \"./router.js\"\n\nconst EventBatchSchema = z.object({ events: z.array(EventInputSchema).min(1).max(LIMITS.eventsPerBatch) }).strict()\n\nfunction errorBody(code: string, message: string, retryable = false) {\n return { ok: false, error: { code, message, retryable } }\n}\n\nexport function createIngestHandler(options: {\n evidence: EvidenceStore\n validateEvent: (event: EventInput) => Promise<EventInput>\n sample?: (event: EventInput) => boolean | Promise<boolean>\n}) {\n return async (request: IncomingMessage, response: ServerResponse, origin?: string): Promise<void> => {\n await options.evidence.countRequest()\n let body: unknown\n try {\n body = await readBoundedJsonBody(request)\n } catch (error) {\n if (error instanceof CollectorBodyError) {\n await options.evidence.recordRejected()\n writeCollectorJson(response, error.status, errorBody(error.code, error.message), origin)\n return\n }\n throw error\n }\n const parsed = EventBatchSchema.safeParse(body)\n if (!parsed.success) {\n await options.evidence.recordRejected()\n writeCollectorJson(response, 400, errorBody(\"INVALID_REQUEST\", \"Invalid event batch\"), origin)\n return\n }\n\n const validated: EventInput[] = []\n try {\n for (const event of parsed.data.events) validated.push(await options.validateEvent(event))\n } catch {\n await options.evidence.recordRejected(parsed.data.events.length)\n writeCollectorJson(response, 400, errorBody(\"INVALID_REQUEST\", \"Event ownership is invalid\"), origin)\n return\n }\n\n let accepted = 0\n let sampled = 0\n let dropped = 0\n for (const event of validated) {\n const result = await options.evidence.append(\n {\n ...event,\n eventId: `event_${randomBytes(16).toString(\"base64url\")}`,\n kind: \"probe\",\n },\n { sampled: (await options.sample?.(event)) ?? false },\n )\n if (result.status === \"accepted\") accepted += 1\n else if (result.status === \"sampled\") sampled += 1\n else if (result.status === \"dropped\") dropped += 1\n }\n writeCollectorJson(response, 202, { ok: true, accepted, sampled, dropped }, origin)\n }\n}\n","import type { IncomingMessage } from \"node:http\"\nimport { LIMITS } from \"../core/constants.js\"\n\nexport class CollectorBodyError extends Error {\n constructor(\n readonly status: 400 | 413 | 415,\n readonly code: \"INVALID_REQUEST\" | \"LIMIT_EXCEEDED\" | \"UNSUPPORTED_MEDIA_TYPE\",\n ) {\n super(code)\n }\n}\n\nexport async function readBoundedJsonBody(request: IncomingMessage): Promise<unknown> {\n const contentType = request.headers[\"content-type\"]?.split(\";\", 1)[0]?.trim().toLowerCase()\n if (contentType !== \"application/json\") throw new CollectorBodyError(415, \"UNSUPPORTED_MEDIA_TYPE\")\n const declared = request.headers[\"content-length\"]\n if (declared !== undefined) {\n if (!/^\\d+$/u.test(declared)) throw new CollectorBodyError(400, \"INVALID_REQUEST\")\n if (Number(declared) > LIMITS.requestBytes) {\n request.resume()\n throw new CollectorBodyError(413, \"LIMIT_EXCEEDED\")\n }\n }\n\n const chunks: Buffer[] = []\n let bytes = 0\n for await (const chunk of request) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n bytes += buffer.byteLength\n if (bytes > LIMITS.requestBytes) {\n request.resume()\n throw new CollectorBodyError(413, \"LIMIT_EXCEEDED\")\n }\n chunks.push(buffer)\n }\n try {\n return JSON.parse(Buffer.concat(chunks, bytes).toString(\"utf8\"))\n } catch {\n throw new CollectorBodyError(400, \"INVALID_REQUEST\")\n }\n}\n","import { createHash, timingSafeEqual } from \"node:crypto\"\nimport type { SecretStore } from \"../session/secret-store.js\"\n\nconst TOKEN = /^[A-Za-z0-9_-]{43}$/\n\nfunction decode(value: string): Buffer | undefined {\n if (!TOKEN.test(value)) return undefined\n const decoded = Buffer.from(value, \"base64url\")\n if (decoded.byteLength !== 32 || decoded.toString(\"base64url\") !== value) return undefined\n return decoded\n}\n\nexport function authenticateBearer(header: string | undefined, expectedToken: string): boolean {\n if (header === undefined || !header.startsWith(\"Bearer \") || header.indexOf(\" \", 7) !== -1) return false\n const provided = decode(header.slice(7))\n const expected = decode(expectedToken)\n if (provided === undefined || expected === undefined) return false\n const providedDigest = createHash(\"sha256\").update(provided).digest()\n const expectedDigest = createHash(\"sha256\").update(expected).digest()\n return timingSafeEqual(providedDigest, expectedDigest)\n}\n\nexport async function createCollectorCredential(store: SecretStore): Promise<string> {\n return store.create()\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\"\nimport { authenticateBearer } from \"./auth.js\"\n\nexport type IngestHandler = (request: IncomingMessage, response: ServerResponse, origin?: string) => Promise<void>\n\nconst ERROR_MESSAGES = {\n INVALID_REQUEST: \"Invalid request\",\n UNAUTHORIZED: \"Unauthorized\",\n NOT_FOUND: \"Not found\",\n METHOD_NOT_ALLOWED: \"Method not allowed\",\n COLLECTOR_DRAINING: \"Collector is draining\",\n} as const\n\nfunction baseHeaders(): Record<string, string> {\n return {\n \"Cache-Control\": \"no-store\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n }\n}\n\nfunction json(response: ServerResponse, status: number, value: unknown, headers: Record<string, string> = {}): void {\n response.writeHead(status, { ...baseHeaders(), ...headers })\n response.end(JSON.stringify(value))\n}\n\nfunction error(\n response: ServerResponse,\n status: number,\n code: keyof typeof ERROR_MESSAGES,\n retryable = false,\n headers: Record<string, string> = {},\n): void {\n json(response, status, { ok: false, error: { code, message: ERROR_MESSAGES[code], retryable } }, headers)\n}\n\nfunction validOrigin(value: string): boolean {\n if (value.length > 2_048 || /[\\s\\r\\n]/u.test(value)) return false\n return /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\/[^/]+$/u.test(value)\n}\n\nfunction preflight(request: IncomingMessage, response: ServerResponse): void {\n const origin = request.headers.origin\n const requestedMethod = request.headers[\"access-control-request-method\"]\n const rawHeaders = request.headers[\"access-control-request-headers\"] ?? \"\"\n if (\n origin === undefined ||\n !validOrigin(origin) ||\n requestedMethod !== \"POST\" ||\n typeof rawHeaders !== \"string\" ||\n rawHeaders.length > 256\n ) {\n error(response, 400, \"INVALID_REQUEST\")\n return\n }\n const requestedHeaders = rawHeaders\n .split(\",\")\n .map((value) => value.trim().toLowerCase())\n .filter(Boolean)\n if (requestedHeaders.some((value) => value !== \"authorization\" && value !== \"content-type\")) {\n error(response, 400, \"INVALID_REQUEST\")\n return\n }\n response.writeHead(204, {\n ...baseHeaders(),\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST\",\n \"Access-Control-Allow-Headers\": \"Authorization, Content-Type\",\n \"Access-Control-Max-Age\": \"600\",\n Vary: \"Origin\",\n })\n response.end()\n}\n\nexport function createCollectorRouter(options: {\n token: string\n ingest?: IngestHandler\n onAuthenticated?: () => void | Promise<void>\n}) {\n return async (\n request: IncomingMessage,\n response: ServerResponse,\n status: () => \"ready\" | \"draining\",\n ): Promise<void> => {\n const rawUrl = request.url ?? \"\"\n let url: URL\n try {\n url = new URL(rawUrl, \"http://loopback.invalid\")\n } catch {\n error(response, 404, \"NOT_FOUND\")\n return\n }\n if (url.search !== \"\") {\n error(response, 404, \"NOT_FOUND\")\n return\n }\n const pathname = url.pathname\n if (request.method === \"OPTIONS\") {\n if (pathname === \"/v1/events\") preflight(request, response)\n else error(response, 404, \"NOT_FOUND\")\n return\n }\n\n const authorization = Array.isArray(request.headers.authorization) ? undefined : request.headers.authorization\n if (!authenticateBearer(authorization, options.token)) {\n error(response, 401, \"UNAUTHORIZED\")\n return\n }\n await options.onAuthenticated?.()\n\n if (pathname === \"/v1/health\") {\n if (request.method !== \"GET\") {\n error(response, 405, \"METHOD_NOT_ALLOWED\", false, { Allow: \"GET\" })\n return\n }\n json(response, 200, { ok: true, status: status() })\n return\n }\n if (pathname === \"/v1/events\") {\n if (request.method !== \"POST\") {\n error(response, 405, \"METHOD_NOT_ALLOWED\", false, { Allow: \"OPTIONS, POST\" })\n return\n }\n if (status() === \"draining\") {\n error(response, 429, \"COLLECTOR_DRAINING\", true)\n return\n }\n if (options.ingest === undefined) {\n error(response, 400, \"INVALID_REQUEST\")\n return\n }\n const origin = request.headers.origin\n await options.ingest(request, response, typeof origin === \"string\" && validOrigin(origin) ? origin : undefined)\n return\n }\n error(response, 404, \"NOT_FOUND\")\n }\n}\n\nexport function writeCollectorJson(response: ServerResponse, status: number, value: unknown, origin?: string): void {\n json(response, status, value, origin === undefined ? {} : { \"Access-Control-Allow-Origin\": origin, Vary: \"Origin\" })\n}\n","import { randomBytes } from \"node:crypto\"\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\"\nimport type { Socket } from \"node:net\"\nimport { LIMITS } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\n\nexport type CollectorStatus = \"stopped\" | \"starting\" | \"ready\" | \"draining\" | \"failed\"\nexport type CollectorRequestHandler = (\n request: IncomingMessage,\n response: ServerResponse,\n status: () => \"ready\" | \"draining\",\n) => void | Promise<void>\n\nexport type CollectorHandle = Readonly<{\n id: string\n host: \"127.0.0.1\" | \"::1\"\n port: number\n status: \"ready\"\n close(): Promise<void>\n}>\n\nexport class CollectorServer {\n private server: Server | undefined\n private readonly sockets = new Set<Socket>()\n private state: CollectorStatus = \"stopped\"\n private handle: CollectorHandle | undefined\n private failureReported = false\n\n constructor(\n private readonly handler: CollectorRequestHandler = (_request, response) => {\n response.writeHead(404, { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" })\n response.end('{\"ok\":false,\"error\":{\"code\":\"NOT_FOUND\",\"message\":\"Not found\",\"retryable\":false}}')\n },\n private readonly onFailure?: (reason: string) => void | Promise<void>,\n ) {}\n\n async start(): Promise<CollectorHandle> {\n if (this.handle !== undefined && this.state === \"ready\") return this.handle\n if (this.state !== \"stopped\") throw new DebugModeError(\"COLLECTOR_EXISTS\", \"A collector already exists\")\n this.state = \"starting\"\n try {\n this.handle = await this.bind(\"127.0.0.1\")\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== \"EAFNOSUPPORT\" && code !== \"EADDRNOTAVAIL\") {\n this.state = \"failed\"\n throw new DebugModeError(\"LOOPBACK_BIND_FAILED\", \"The IPv4 loopback collector could not bind\")\n }\n try {\n this.handle = await this.bind(\"::1\")\n } catch {\n this.state = \"failed\"\n throw new DebugModeError(\"LOOPBACK_BIND_FAILED\", \"Neither loopback address could bind\")\n }\n }\n this.state = \"ready\"\n return this.handle\n }\n\n get status(): CollectorStatus {\n return this.state\n }\n\n async close(): Promise<void> {\n if (this.state === \"stopped\") return\n this.state = \"draining\"\n const server = this.server\n if (server === undefined) {\n this.state = \"stopped\"\n return\n }\n await Promise.race([\n new Promise<void>((resolve) => server.close(() => resolve())),\n new Promise<void>((resolve) =>\n setTimeout(() => {\n for (const socket of this.sockets) socket.destroy()\n server.closeAllConnections?.()\n resolve()\n }, 1_000),\n ),\n ])\n for (const socket of this.sockets) socket.destroy()\n this.sockets.clear()\n this.server = undefined\n this.handle = undefined\n this.state = \"stopped\"\n }\n\n private bind(host: \"127.0.0.1\" | \"::1\"): Promise<CollectorHandle> {\n return new Promise((resolve, reject) => {\n const server = createServer(\n {\n requestTimeout: 5_000,\n headersTimeout: 5_000,\n keepAliveTimeout: 1_000,\n maxHeaderSize: 16_384,\n connectionsCheckingInterval: 1_000,\n },\n (request, response) => {\n void Promise.resolve(\n this.handler(request, response, () => (this.state === \"draining\" ? \"draining\" : \"ready\")),\n ).catch(() => {\n if (!response.headersSent) response.writeHead(500, { \"Content-Type\": \"application/json\" })\n response.end('{\"ok\":false,\"error\":{\"code\":\"INTERNAL_ERROR\",\"message\":\"Request failed\",\"retryable\":false}}')\n })\n },\n )\n server.maxHeadersCount = 32\n this.server = server\n server.on(\"connection\", (socket) => {\n this.sockets.add(socket)\n socket.once(\"close\", () => this.sockets.delete(socket))\n })\n const startupTimeout = setTimeout(() => {\n cleanupStartup()\n server.close()\n const error = new Error(\"Collector startup timed out\") as NodeJS.ErrnoException\n error.code = \"ETIMEDOUT\"\n reject(error)\n }, LIMITS.collectorReadyMs)\n const startupError = (error: Error) => {\n cleanupStartup()\n server.close()\n reject(error)\n }\n const listening = () => {\n cleanupStartup()\n const address = server.address()\n if (address === null || typeof address === \"string\") {\n reject(new Error(\"Collector returned no TCP address\"))\n return\n }\n const handle: CollectorHandle = Object.freeze({\n id: `collector_${randomBytes(16).toString(\"base64url\")}`,\n host,\n port: address.port,\n status: \"ready\" as const,\n close: () => this.close(),\n })\n server.on(\"error\", () => void this.reportFailure(\"listener-error\"))\n server.on(\"close\", () => {\n if (this.state === \"ready\") void this.reportFailure(\"unexpected-close\")\n })\n resolve(handle)\n }\n const cleanupStartup = () => {\n clearTimeout(startupTimeout)\n server.off(\"error\", startupError)\n server.off(\"listening\", listening)\n }\n server.once(\"error\", startupError)\n server.once(\"listening\", listening)\n server.listen({ host, port: 0, exclusive: true })\n })\n }\n\n private async reportFailure(reason: string): Promise<void> {\n if (this.failureReported) return\n this.failureReported = true\n this.state = \"failed\"\n await this.onFailure?.(reason)\n }\n}\n","import { performance } from \"node:perf_hooks\"\n\nexport interface Clock {\n now(): Date\n monotonicMs(): number\n}\n\nexport const systemClock: Clock = Object.freeze({\n now: () => new Date(),\n monotonicMs: () => performance.now(),\n})\n","import { appendFile, stat } from \"node:fs/promises\"\nimport { z } from \"zod\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { EVENT_SCHEMA_VERSION, LIMITS } from \"../core/constants.js\"\nimport { type EvidenceCounters, EvidenceCountersSchema } from \"../session/types.js\"\nimport { readEvidence } from \"./read.js\"\nimport { sanitizeEvidenceData } from \"./sanitize.js\"\nimport { type EvidenceEvent, EvidenceEventSchema, type EvidenceFilter } from \"./types.js\"\n\nconst AppendEventSchema = EvidenceEventSchema.omit({ receivedAt: true, sanitization: true, data: true }).extend({\n schemaVersion: z.literal(EVENT_SCHEMA_VERSION),\n data: z.unknown().optional(),\n})\n\nexport type EvidenceAppendInput = z.infer<typeof AppendEventSchema>\nexport type CounterUpdate = (counters: EvidenceCounters) => void | Promise<void>\n\nexport class EvidenceStore {\n private tail: Promise<void> = Promise.resolve()\n private currentBytes = 0\n private initialized = false\n private readonly counters: EvidenceCounters = {\n accepted: 0,\n rejected: 0,\n sampled: 0,\n truncated: 0,\n dropped: 0,\n requests: 0,\n }\n\n constructor(\n private readonly filename: string,\n private readonly onCounters?: CounterUpdate,\n private readonly clock: Clock = systemClock,\n private readonly loadCounters?: () => Promise<EvidenceCounters>,\n ) {}\n\n async append(\n input: EvidenceAppendInput,\n options: { sampled?: boolean } = {},\n ): Promise<{ status: \"accepted\" | \"sampled\" | \"dropped\" | \"rejected\"; event?: EvidenceEvent }> {\n return this.exclusive(async () => {\n await this.initialize()\n if (options.sampled === true) {\n await this.increment(\"sampled\")\n return { status: \"sampled\" }\n }\n\n const parsed = AppendEventSchema.safeParse(input)\n if (!parsed.success) {\n await this.increment(\"rejected\")\n return { status: \"rejected\" }\n }\n if (this.counters.accepted >= LIMITS.events) {\n await this.increment(\"dropped\")\n return { status: \"dropped\" }\n }\n\n const sanitized = sanitizeEvidenceData(parsed.data.data)\n const event = EvidenceEventSchema.parse({\n ...parsed.data,\n data: sanitized.value,\n receivedAt: this.clock.now().toISOString(),\n sanitization: {\n flags: sanitized.flags,\n droppedKeys: sanitized.droppedKeys,\n storedBytes: sanitized.storedBytes,\n ...(sanitized.originalBytes === undefined ? {} : { originalBytes: sanitized.originalBytes }),\n },\n })\n const line = `${JSON.stringify(event)}\\n`\n const bytes = Buffer.byteLength(line)\n if (this.currentBytes + bytes > LIMITS.evidenceBytes) {\n await this.increment(\"dropped\")\n return { status: \"dropped\" }\n }\n\n try {\n await appendFile(this.filename, line, { encoding: \"utf8\", mode: 0o600 })\n } catch (error) {\n await this.increment(\"rejected\")\n throw error\n }\n this.currentBytes += bytes\n await this.increment(\"accepted\")\n if (sanitized.flags.includes(\"truncated\")) await this.increment(\"truncated\")\n return { status: \"accepted\", event }\n })\n }\n\n async read(filter: EvidenceFilter = {}) {\n await this.initialize()\n const page = await readEvidence(this.filename, filter)\n return { ...page, counters: EvidenceCountersSchema.parse(this.counters) }\n }\n\n snapshotCounters(): EvidenceCounters {\n return EvidenceCountersSchema.parse(this.counters)\n }\n\n async countRequest(): Promise<void> {\n await this.exclusive(async () => {\n await this.initialize()\n await this.increment(\"requests\")\n })\n }\n\n async recordRejected(count = 1): Promise<void> {\n await this.exclusive(async () => {\n await this.initialize()\n for (let index = 0; index < count; index += 1) await this.increment(\"rejected\")\n })\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) return\n if (this.loadCounters !== undefined) {\n Object.assign(this.counters, EvidenceCountersSchema.parse(await this.loadCounters()))\n }\n try {\n this.currentBytes = (await stat(this.filename)).size\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n this.initialized = true\n }\n\n private async increment(field: keyof EvidenceCounters): Promise<void> {\n this.counters[field] += 1\n await this.onCounters?.(EvidenceCountersSchema.parse(this.counters))\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n const previous = this.tail\n let release!: () => void\n this.tail = new Promise<void>((resolve) => {\n release = resolve\n })\n await previous\n try {\n return await operation()\n } finally {\n release()\n }\n }\n}\n","import { z } from \"zod\"\nimport { LIMITS, MANIFEST_SCHEMA_VERSION, PACKAGE_ID } from \"../core/constants.js\"\nimport { HexSha256Schema, IsoTimestampSchema, OpaqueIdSchema, RunLabelSchema } from \"../core/schemas.js\"\n\nexport const EvidenceCountersSchema = z\n .object({\n accepted: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative(),\n sampled: z.number().int().nonnegative(),\n truncated: z.number().int().nonnegative(),\n dropped: z.number().int().nonnegative(),\n requests: z.number().int().nonnegative(),\n })\n .strict()\n\nexport const CollectorManifestSchema = z\n .object({\n id: OpaqueIdSchema,\n host: z.enum([\"127.0.0.1\", \"::1\"]),\n port: z.number().int().min(1).max(65_535),\n status: z.enum([\"starting\", \"ready\", \"draining\", \"stopped\", \"failed\"]),\n startedAt: IsoTimestampSchema,\n stoppedAt: IsoTimestampSchema.optional(),\n })\n .strict()\n\nexport const RunManifestSchema = z\n .object({\n id: OpaqueIdSchema,\n label: RunLabelSchema,\n reproduction: z.string().max(LIMITS.scalarBytes),\n status: z.enum([\"planned\", \"running\", \"waiting\", \"completed\", \"failed\", \"timed_out\", \"cancelled\"]),\n createdAt: IsoTimestampSchema,\n completedAt: IsoTimestampSchema.optional(),\n })\n .strict()\n\nexport const ProcessManifestSchema = z\n .object({\n id: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n commandSummary: z.string().max(LIMITS.scalarBytes),\n supervisorPid: z.number().int().positive().optional(),\n targetPid: z.number().int().positive().optional(),\n ownerNonceHash: HexSha256Schema,\n status: z.enum([\"starting\", \"running\", \"exited\", \"timed_out\", \"cancelled\", \"terminated\", \"failed\"]),\n startedAt: IsoTimestampSchema,\n completedAt: IsoTimestampSchema.optional(),\n exitCode: z.number().int().nullable().optional(),\n signal: z.string().max(64).nullable().optional(),\n })\n .strict()\n\nexport const ProbeManifestSchema = z\n .object({\n id: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n hypothesisId: OpaqueIdSchema,\n sourceFile: z.string().min(1),\n sourceLine: z.number().int().positive(),\n sourceColumn: z.number().int().positive().optional(),\n message: z.string().min(1).max(LIMITS.scalarBytes),\n transport: z.enum([\"process\", \"http-web\", \"extension-background\", \"extension-content\"]),\n captures: z\n .array(z.object({ label: z.string().min(1).max(128), path: z.string().min(1).max(512) }).strict())\n .max(20),\n sampling: z.discriminatedUnion(\"mode\", [\n z.object({ mode: z.literal(\"every\"), n: z.number().int().min(1).max(10_000) }).strict(),\n z.object({ mode: z.literal(\"aggregate\"), windowMs: z.number().int().min(100).max(60_000) }).strict(),\n ]),\n status: z.enum([\"planned\", \"registered\", \"validated\", \"active\", \"removed\", \"ambiguous\"]),\n validationStatus: z.enum([\"pending\", \"validated\", \"failed\"]),\n markerStart: z.string().min(1),\n markerEnd: z.string().min(1),\n expectedBlock: z.string().optional(),\n expectedHash: HexSha256Schema.optional(),\n })\n .strict()\n\nexport const OwnedFileManifestSchema = z\n .object({\n path: z.string().min(1),\n sha256: HexSha256Schema,\n bytes: z.number().int().nonnegative(),\n kind: z.enum([\"transport-helper\", \"temporary\"]),\n })\n .strict()\n\nexport const PermissionChangeSchema = z\n .object({\n manifestPath: z.string().min(1),\n property: z.enum([\"permissions\", \"host_permissions\"]),\n matchPattern: z.string().min(1),\n addedBySession: z.boolean(),\n })\n .strict()\n\nexport const CleanupProgressSchema = z\n .object({\n status: z.enum([\"not_started\", \"running\", \"complete\", \"partial\"]),\n completedResources: z.array(z.string().max(256)).max(10_000),\n })\n .strict()\n\nexport const ManifestSchema = z\n .object({\n package: z.literal(PACKAGE_ID),\n schemaVersion: z.literal(MANIFEST_SCHEMA_VERSION),\n revision: z.number().int().nonnegative(),\n sessionId: OpaqueIdSchema,\n trustedSessionHash: HexSha256Schema,\n projectRoot: z.string().min(1),\n sessionDir: z.string().min(1),\n status: z.enum([\"active\", \"cleaning\", \"cleaned\", \"partial\"]),\n createdAt: IsoTimestampSchema,\n lastActivityAt: IsoTimestampSchema,\n expiresAt: IsoTimestampSchema,\n waitingForReproduction: z.boolean(),\n keepArtifacts: z.boolean(),\n retentionDestination: z.string().min(1).optional(),\n collector: CollectorManifestSchema.nullable(),\n runs: z.array(RunManifestSchema),\n processes: z.array(ProcessManifestSchema),\n probes: z.array(ProbeManifestSchema),\n ownedFiles: z.array(OwnedFileManifestSchema),\n permissionChanges: z.array(PermissionChangeSchema),\n counters: EvidenceCountersSchema,\n cleanup: CleanupProgressSchema,\n })\n .strict()\n\nexport type CleanupManifest = z.infer<typeof ManifestSchema>\nexport type ManifestProbe = z.infer<typeof ProbeManifestSchema>\nexport type ManifestRun = z.infer<typeof RunManifestSchema>\nexport type EvidenceCounters = z.infer<typeof EvidenceCountersSchema>\n","import { createReadStream } from \"node:fs\"\nimport { type EvidenceEvent, EvidenceEventSchema, type EvidenceFilter } from \"./types.js\"\n\nexport type EvidencePage = Readonly<{\n events: EvidenceEvent[]\n nextCursor: string | null\n trailingPartialLine: boolean\n invalidLines: number\n}>\n\nfunction matches(event: EvidenceEvent, filter: EvidenceFilter): boolean {\n if (filter.sessionId !== undefined && event.sessionId !== filter.sessionId) return false\n if (filter.runId !== undefined && event.runId !== filter.runId) return false\n if (filter.hypothesisId !== undefined && event.hypothesisId !== filter.hypothesisId) return false\n if (filter.probeId !== undefined && event.probeId !== filter.probeId) return false\n if (filter.from !== undefined && event.timestamp < filter.from) return false\n if (filter.to !== undefined && event.timestamp > filter.to) return false\n if (filter.keyword !== undefined && !JSON.stringify(event).toLowerCase().includes(filter.keyword.toLowerCase()))\n return false\n return true\n}\n\nexport async function readEvidence(filename: string, filter: EvidenceFilter = {}): Promise<EvidencePage> {\n const limit = Math.min(Math.max(filter.limit ?? 100, 1), 100)\n const start = filter.cursor === undefined ? 0 : Number(filter.cursor)\n if (!Number.isSafeInteger(start) || start < 0) throw new Error(\"Evidence cursor is invalid\")\n\n const events: EvidenceEvent[] = []\n let invalidLines = 0\n let trailingPartialLine = false\n let buffer = Buffer.alloc(0)\n let offset = start\n let nextCursor: string | null = null\n const stream = createReadStream(filename, { start })\n\n try {\n for await (const chunk of stream) {\n buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)])\n while (true) {\n const newline = buffer.indexOf(0x0a)\n if (newline < 0) break\n const line = buffer.subarray(0, newline)\n buffer = buffer.subarray(newline + 1)\n offset += newline + 1\n if (line.byteLength === 0) continue\n try {\n const event = EvidenceEventSchema.parse(JSON.parse(line.toString(\"utf8\")))\n if (matches(event, filter)) {\n events.push(event)\n if (events.length >= limit) {\n nextCursor = String(offset)\n stream.destroy()\n return { events, nextCursor, trailingPartialLine: false, invalidLines }\n }\n }\n } catch {\n invalidLines += 1\n }\n }\n }\n trailingPartialLine = buffer.byteLength > 0\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n } finally {\n stream.destroy()\n }\n return { events, nextCursor, trailingPartialLine, invalidLines }\n}\n","import { createHash } from \"node:crypto\"\nimport { mkdir, realpath, writeFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { isContained } from \"../session/paths.js\"\n\nexport type TransportHelperResult = Readonly<{\n relativePath: string\n requiredImport: string\n sha256: string\n bytes: number\n}>\n\nfunction helperSource(options: { endpoint: string; token: string; extensionBackground: boolean }): string {\n const listener = options.extensionBackground\n ? `\nconst runtime = globalThis.browser?.runtime ?? globalThis.chrome?.runtime\nruntime?.onMessage?.addListener((message) => {\n if (message?.type === \"opencode-debug-event\") __opencodeDebugEmit(message.event)\n})\n`\n : \"\"\n return `const endpoint = ${JSON.stringify(options.endpoint)}\nconst authorization = ${JSON.stringify(`Bearer ${options.token}`)}\nconst queue = []\nlet sending = false\nlet dropped = 0\n\nfunction bound(value, depth = 0) {\n if (depth > 6) return \"[TRUNCATED]\"\n if (typeof value === \"string\") return value.slice(0, 8192)\n if (Array.isArray(value)) return value.slice(0, 100).map((item) => bound(item, depth + 1))\n if (value && typeof value === \"object\") {\n return Object.fromEntries(Object.keys(value).sort().slice(0, 50).map((key) => [key, bound(value[key], depth + 1)]))\n }\n return value\n}\n\nexport function __opencodeDebugEmit(event) {\n if (queue.length >= 100) { dropped += 1; return }\n queue.push(bound(event))\n void flush()\n}\n\nasync function flush() {\n if (sending) return\n sending = true\n try {\n while (queue.length > 0) {\n const events = queue.splice(0, 100)\n if (dropped > 0) { events.push({ ...events[0], message: \"dropped events\", data: { dropped } }); dropped = 0 }\n const response = await fetch(endpoint, {\n method: \"POST\",\n credentials: \"omit\",\n headers: { Authorization: authorization, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ events }),\n })\n if (!response.ok) break\n }\n } catch {\n // Runtime evidence transport is best effort and never affects target behavior.\n } finally {\n sending = false\n }\n}\n${listener}`\n}\n\nexport class TransportHelper {\n constructor(\n private readonly projectRoot: string,\n private readonly recordOwnedFile?: (value: { path: string; sha256: string; bytes: number }) => void | Promise<void>,\n ) {}\n\n async create(options: {\n targetPath: string\n host: \"127.0.0.1\" | \"::1\"\n port: number\n token: string\n runtime: \"web\" | \"extension-background\"\n }): Promise<TransportHelperResult> {\n const canonicalRoot = await realpath(this.projectRoot)\n const absoluteTarget = path.resolve(canonicalRoot, options.targetPath)\n if (!isContained(canonicalRoot, absoluteTarget)) {\n throw new DebugModeError(\"HELPER_PATH_UNSAFE\", \"Transport helper must remain inside the project\")\n }\n const parent = path.dirname(absoluteTarget)\n await mkdir(parent, { recursive: true })\n if ((await realpath(parent)) !== parent) {\n throw new DebugModeError(\"HELPER_PATH_UNSAFE\", \"Transport helper parent is not canonical\")\n }\n const endpointHost = options.host === \"::1\" ? \"[::1]\" : options.host\n const source = helperSource({\n endpoint: `http://${endpointHost}:${options.port}/v1/events`,\n token: options.token,\n extensionBackground: options.runtime === \"extension-background\",\n })\n await writeFile(absoluteTarget, source, { flag: \"wx\", mode: 0o600 })\n const bytes = Buffer.byteLength(source)\n const sha256 = createHash(\"sha256\").update(source).digest(\"hex\")\n await this.recordOwnedFile?.({ path: absoluteTarget, sha256, bytes })\n const relativePath = `./${path.relative(canonicalRoot, absoluteTarget).split(path.sep).join(\"/\")}`\n return {\n relativePath,\n requiredImport: `import { __opencodeDebugEmit } from ${JSON.stringify(relativePath)}`,\n sha256,\n bytes,\n }\n }\n}\n","import { createHash, randomBytes } from \"node:crypto\"\nimport { readFile, realpath } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport type { EventInput } from \"../evidence/types.js\"\nimport type { ManifestStore } from \"../session/manifest-store.js\"\nimport { isContained } from \"../session/paths.js\"\nimport type { CleanupManifest, ManifestProbe } from \"../session/types.js\"\nimport { createProbeTemplate } from \"./template.js\"\nimport { type ProbePlanInput, SAFE_CAPTURE } from \"./types.js\"\n\nconst SUPPORTED_EXTENSIONS = new Set([\".js\", \".jsx\", \".ts\", \".tsx\", \".mjs\", \".cjs\"])\n\nfunction probeId(): string {\n return `probe_${randomBytes(16).toString(\"base64url\")}`\n}\n\nfunction sha256(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\")\n}\n\nfunction markerLines(sessionId: string, input: ProbePlanInput, id: string) {\n const ownership = `opencode-debug-mode session=${sessionId} run=${input.runId} hypothesis=${input.hypothesisId} probe=${id}`\n return { start: `/* DEBUG-START ${ownership} */`, end: `/* DEBUG-END ${ownership} */` }\n}\n\nexport class ProbeRegistry {\n constructor(\n private readonly store: ManifestStore,\n private readonly projectRoot: string,\n private readonly hasHypothesis: (id: string) => Promise<boolean>,\n ) {}\n\n async plan(input: ProbePlanInput): Promise<ManifestProbe & { markerBlock: string }> {\n const manifest = await this.store.read()\n if (!manifest.runs.some((run) => run.id === input.runId))\n throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n if (!(await this.hasHypothesis(input.hypothesisId))) {\n throw new DebugModeError(\"STATE_INVALID\", \"Hypothesis was not found in the checkpoint\")\n }\n if (!Number.isInteger(input.sourceLine) || input.sourceLine < 1) {\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Source line must be one-based\")\n }\n if (input.message.length < 1 || Buffer.byteLength(input.message) > 8_192) {\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Probe message is invalid\")\n }\n if (input.captures.length > 20 || input.captures.some((capture) => !SAFE_CAPTURE.test(capture.path))) {\n throw new DebugModeError(\"UNSAFE_CAPTURE\", \"Probe capture path is unsafe\")\n }\n\n const absoluteSource = path.resolve(this.projectRoot, input.sourceFile)\n if (!isContained(this.projectRoot, absoluteSource)) {\n throw new DebugModeError(\"HELPER_PATH_UNSAFE\", \"Probe source is outside the project\")\n }\n if (!SUPPORTED_EXTENSIONS.has(path.extname(absoluteSource).toLowerCase())) {\n throw new DebugModeError(\"UNSUPPORTED_LANGUAGE\", \"Only JavaScript and TypeScript probes are supported\")\n }\n const canonicalSource = await realpath(absoluteSource)\n if (!isContained(this.projectRoot, canonicalSource)) {\n throw new DebugModeError(\"HELPER_PATH_UNSAFE\", \"Probe source resolves outside the project\")\n }\n\n const id = probeId()\n const markers = markerLines(manifest.sessionId, input, id)\n const run = manifest.runs.find((candidate) => candidate.id === input.runId)\n if (run === undefined) throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n const markerBlock =\n input.markerBlock ??\n createProbeTemplate({\n sessionId: manifest.sessionId,\n runId: input.runId,\n runLabel: run.label,\n hypothesisId: input.hypothesisId,\n probeId: id,\n sourceFile: path.relative(this.projectRoot, canonicalSource),\n sourceLine: input.sourceLine,\n message: input.message,\n captures: input.captures,\n transport: input.transport,\n sampling: input.sampling,\n }).markerBlock\n const probe: ManifestProbe = {\n id,\n runId: input.runId,\n hypothesisId: input.hypothesisId,\n sourceFile: canonicalSource,\n sourceLine: input.sourceLine,\n ...(input.sourceColumn === undefined ? {} : { sourceColumn: input.sourceColumn }),\n message: input.message,\n transport: input.transport,\n captures: input.captures,\n sampling: input.sampling,\n status: \"planned\",\n validationStatus: \"pending\",\n markerStart: markers.start,\n markerEnd: markers.end,\n expectedBlock: markerBlock,\n }\n await this.update(manifest, (value) => ({ ...value, probes: [...value.probes, probe] }))\n return { ...probe, markerBlock }\n }\n\n async register(id: string): Promise<ManifestProbe> {\n const manifest = await this.store.read()\n const probe = manifest.probes.find((candidate) => candidate.id === id)\n if (probe === undefined) throw new DebugModeError(\"MARKER_MISSING\", \"Probe was not planned\")\n if (probe.expectedBlock === undefined)\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Probe marker content is unavailable\")\n const source = await readFile(probe.sourceFile, \"utf8\")\n const occurrences = source.split(probe.expectedBlock).length - 1\n if (occurrences === 0) throw new DebugModeError(\"MARKER_MISSING\", \"Owned probe marker is missing\")\n if (occurrences !== 1) throw new DebugModeError(\"MARKER_MISMATCH\", \"Owned probe marker is not unique\")\n const updated: ManifestProbe = {\n ...probe,\n expectedHash: sha256(probe.expectedBlock),\n status: \"registered\",\n validationStatus: \"pending\",\n }\n await this.update(manifest, (value) => ({\n ...value,\n probes: value.probes.map((candidate) => (candidate.id === id ? updated : candidate)),\n }))\n return updated\n }\n\n async validate(probeIds: string[]): Promise<void> {\n const manifest = await this.store.read()\n if (probeIds.some((id) => !manifest.probes.some((probe) => probe.id === id && probe.status === \"registered\"))) {\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Only registered probes can be validated\")\n }\n await this.update(manifest, (value) => ({\n ...value,\n probes: value.probes.map((probe) =>\n probeIds.includes(probe.id)\n ? { ...probe, status: \"validated\" as const, validationStatus: \"validated\" as const }\n : probe,\n ),\n }))\n }\n\n async requireValidatedForRun(runId: string): Promise<void> {\n const manifest = await this.store.read()\n if (manifest.probes.some((probe) => probe.runId === runId && probe.validationStatus !== \"validated\")) {\n throw new DebugModeError(\"PROBE_NOT_VALIDATED\", \"Every active probe must pass an instrumentation check\")\n }\n }\n\n async validateEvent(input: EventInput): Promise<EventInput> {\n const manifest = await this.store.read()\n const probe = manifest.probes.find((candidate) => candidate.id === input.probeId)\n const run = manifest.runs.find((candidate) => candidate.id === input.runId)\n if (\n probe === undefined ||\n run === undefined ||\n input.sessionId !== manifest.sessionId ||\n probe.runId !== input.runId ||\n probe.hypothesisId !== input.hypothesisId ||\n run.label !== input.runLabel\n ) {\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Runtime event ownership does not match the registered probe\")\n }\n return {\n ...input,\n source: {\n file: path.relative(this.projectRoot, probe.sourceFile),\n line: probe.sourceLine,\n ...(probe.sourceColumn === undefined ? {} : { column: probe.sourceColumn }),\n },\n }\n }\n\n private async update(\n _manifest: CleanupManifest,\n mutate: (value: CleanupManifest) => CleanupManifest,\n ): Promise<CleanupManifest> {\n return this.store.modify(mutate)\n }\n}\n","export const SAFE_CAPTURE = /^[A-Za-z_$][\\w$]*(?:(?:\\.|\\?\\.)[A-Za-z_$][\\w$]*)*$/\n\nexport type ProbeTransport = \"process\" | \"http-web\" | \"extension-background\" | \"extension-content\"\nexport type ProbeSampling = { mode: \"every\"; n: number } | { mode: \"aggregate\"; windowMs: number }\n\nexport type ProbePlanInput = Readonly<{\n runId: string\n hypothesisId: string\n sourceFile: string\n sourceLine: number\n sourceColumn?: number\n message: string\n captures: Array<{ label: string; path: string }>\n transport: ProbeTransport\n sampling: ProbeSampling\n markerBlock?: string\n}>\n","import { PROCESS_EVENT_PREFIX } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { type ProbeSampling, type ProbeTransport, SAFE_CAPTURE } from \"./types.js\"\n\nexport type ProbeTemplateInput = Readonly<{\n sessionId: string\n runId: string\n runLabel: \"pre-fix\" | \"post-fix\"\n hypothesisId: string\n probeId: string\n sourceFile: string\n sourceLine: number\n message: string\n captures: Array<{ label: string; path: string }>\n transport: ProbeTransport\n sampling: ProbeSampling\n contentAdapter?: \"chrome.runtime.sendMessage\" | \"browser.runtime.sendMessage\" | \"wrapper.sendMessage\"\n}>\n\nexport function createProbeTemplate(input: ProbeTemplateInput): { markerBlock: string } {\n if (input.captures.some((capture) => !SAFE_CAPTURE.test(capture.path))) {\n throw new DebugModeError(\"UNSAFE_CAPTURE\", \"Probe capture path is unsafe\")\n }\n const ownership = `opencode-debug-mode session=${input.sessionId} run=${input.runId} hypothesis=${input.hypothesisId} probe=${input.probeId}`\n const data = input.captures.map((capture) => `${JSON.stringify(capture.label)}: ${capture.path}`).join(\", \")\n const event = `{\n schemaVersion: 1,\n sessionId: ${JSON.stringify(input.sessionId)},\n runId: ${JSON.stringify(input.runId)},\n runLabel: ${JSON.stringify(input.runLabel)},\n hypothesisId: ${JSON.stringify(input.hypothesisId)},\n probeId: ${JSON.stringify(input.probeId)},\n timestamp: new Date().toISOString(),\n message: ${JSON.stringify(input.message)},\n source: { file: ${JSON.stringify(input.sourceFile)}, line: ${input.sourceLine} },\n data: { ${data} },\n}`\n let emission: string\n if (input.transport === \"process\") {\n emission = `void ((event) => process.stderr.write(${JSON.stringify(PROCESS_EVENT_PREFIX)} + JSON.stringify(event) + \"\\\\n\"))(${event})`\n } else if (input.transport === \"extension-content\") {\n const adapter = input.contentAdapter ?? \"chrome.runtime.sendMessage\"\n emission = `void ${adapter}({ type: \"opencode-debug-event\", event: ${event} })`\n } else {\n emission = `void __opencodeDebugEmit(${event})`\n }\n return {\n markerBlock: `/* DEBUG-START ${ownership} */\\n${emission}\\n/* DEBUG-END ${ownership} */`,\n }\n}\n","import { type ChildProcess, fork } from \"node:child_process\"\nimport { createHash, randomBytes } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport type { z } from \"zod\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { EVENT_SCHEMA_VERSION } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport type { EvidenceStore } from \"../evidence/store.js\"\nimport { EventInputSchema } from \"../evidence/types.js\"\nimport type { ProbeRegistry } from \"../probes/registry.js\"\nimport type { RunService } from \"../run/service.js\"\nimport type { DebugSession } from \"../session/registry.js\"\nimport type { CleanupManifest, ProcessManifestSchema } from \"../session/types.js\"\nimport { type DecodedProcessRecord, ProcessLineDecoder, type ProcessStream } from \"./line-decoder.js\"\nimport { parseChildMessage } from \"./protocol.js\"\n\ntype OwnedProcess = z.infer<typeof ProcessManifestSchema>\n\nexport type ProcessCaptureInput = Readonly<{\n runId: string\n executable: string\n args: string[]\n cwd: string\n env: Record<string, string>\n timeoutMs: number\n probeIds?: string[]\n purpose?: \"instrumentation-check\" | \"reproduction\" | \"verification\"\n signal?: AbortSignal\n}>\n\nexport type ProcessCaptureResult = Readonly<{\n processId: string\n runId: string\n exitCode: number | null\n signal: string | null\n timedOut: boolean\n durationMs: number\n stdoutEvents: number\n stderrEvents: number\n probeEvents: number\n}>\n\nfunction generatedId(prefix: string): string {\n return `${prefix}${randomBytes(16).toString(\"base64url\")}`\n}\n\nfunction defaultSupervisorPath(): string {\n const directory = path.dirname(fileURLToPath(import.meta.url))\n const bundled = path.join(directory, \"process-supervisor.js\")\n if (existsSync(bundled)) return bundled\n return path.resolve(directory, \"../../dist/process-supervisor.js\")\n}\n\nexport class ProcessService {\n constructor(\n private readonly dependencies: {\n session: DebugSession\n runs: RunService\n evidence: EvidenceStore\n acquireLease: () => Promise<() => void>\n probes?: ProbeRegistry\n supervisorPath?: string\n clock?: Clock\n },\n ) {}\n\n async capture(input: ProcessCaptureInput): Promise<ProcessCaptureResult> {\n const run = await this.dependencies.runs.require(input.runId)\n const release = await this.dependencies.acquireLease()\n const clock = this.dependencies.clock ?? systemClock\n const startedAt = clock.monotonicMs()\n const decoder = new ProcessLineDecoder({ maxLineBytes: 8_192 })\n let stdoutEvents = 0\n let stderrEvents = 0\n let probeEvents = 0\n let writes: Promise<void> = Promise.resolve()\n let startedUpdate: Promise<void> = Promise.resolve()\n let child: ChildProcess | undefined\n const processId = generatedId(\"process_\")\n const ownerNonce = randomBytes(32).toString(\"base64url\")\n\n try {\n child = fork(this.dependencies.supervisorPath ?? defaultSupervisorPath(), [], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n })\n if (child.pid === undefined) throw new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor did not receive a PID\")\n await this.waitForMessage(child, \"ready\", 2_000)\n await this.addOwnedProcess({\n id: processId,\n runId: input.runId,\n commandSummary: [path.basename(input.executable), ...input.args.map((value) => path.basename(value))]\n .join(\" \")\n .slice(0, 8_192),\n supervisorPid: child.pid,\n ownerNonceHash: createHash(\"sha256\").update(ownerNonce).digest(\"hex\"),\n status: \"starting\",\n startedAt: clock.now().toISOString(),\n })\n\n const consume = (stream: ProcessStream, chunk: Buffer) => {\n for (const record of decoder.push(stream, chunk)) {\n writes = writes\n .then(() => this.persistRecord(record, input, run.label))\n .then((kind) => {\n if (kind === \"probe\") probeEvents += 1\n else if (kind === \"stdout\") stdoutEvents += 1\n else if (kind === \"stderr\") stderrEvents += 1\n })\n }\n }\n child.stdout?.on(\"data\", (chunk: Buffer) => consume(\"stdout\", chunk))\n child.stderr?.on(\"data\", (chunk: Buffer) => consume(\"stderr\", chunk))\n\n const resultPromise = new Promise<ReturnType<typeof parseChildMessage>>((resolve, reject) => {\n child?.on(\"message\", (value: unknown) => {\n try {\n const message = parseChildMessage(value)\n if (message.type === \"started\") startedUpdate = this.markStarted(processId, message.targetPid)\n if (message.type === \"failure\") reject(new DebugModeError(\"PROCESS_START_FAILED\", message.message))\n if (message.type === \"result\") resolve(message)\n } catch {\n reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor returned an invalid message\"))\n }\n })\n child?.once(\"error\", () => reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor failed to start\")))\n child?.once(\"exit\", (code) => {\n if (code !== 0) reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor exited unexpectedly\"))\n })\n })\n\n child.send({\n type: \"start\",\n executable: input.executable,\n args: input.args,\n cwd: input.cwd,\n env: input.env,\n timeoutMs: input.timeoutMs,\n ownerNonce,\n })\n\n const abort = () => {\n if (child?.connected) child.send({ type: \"terminate\", reason: \"abort\" })\n }\n input.signal?.addEventListener(\"abort\", abort, { once: true })\n if (input.signal?.aborted === true) abort()\n let result: ReturnType<typeof parseChildMessage>\n try {\n result = await resultPromise\n } finally {\n input.signal?.removeEventListener(\"abort\", abort)\n }\n if (result.type !== \"result\") throw new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor returned no result\")\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n for (const record of decoder.flush(stream)) {\n writes = writes\n .then(() => this.persistRecord(record, input, run.label))\n .then((kind) => {\n if (kind === \"probe\") probeEvents += 1\n else if (kind === \"stdout\") stdoutEvents += 1\n else if (kind === \"stderr\") stderrEvents += 1\n })\n }\n }\n await writes\n await startedUpdate\n await this.markCompleted(processId, result)\n return {\n processId,\n runId: input.runId,\n exitCode: result.exitCode,\n signal: result.signal,\n timedOut: result.timedOut,\n durationMs: clock.monotonicMs() - startedAt,\n stdoutEvents,\n stderrEvents,\n probeEvents,\n }\n } finally {\n if (child?.connected) child.disconnect()\n release()\n }\n }\n\n private async persistRecord(\n record: DecodedProcessRecord,\n input: ProcessCaptureInput,\n runLabel: \"pre-fix\" | \"post-fix\",\n ): Promise<\"stdout\" | \"stderr\" | \"probe\" | \"ignored\"> {\n if (record.kind === \"truncated\") {\n const result = await this.dependencies.evidence.append({\n schemaVersion: EVENT_SCHEMA_VERSION,\n eventId: generatedId(\"event_\"),\n timestamp: new Date().toISOString(),\n sessionId: this.dependencies.session.publicId,\n runId: input.runId,\n runLabel,\n hypothesisId: \"hyp_process\",\n probeId: \"probe_process\",\n kind: `process.${record.stream}`,\n message: \"[TRUNCATED OUTPUT LINE]\",\n data: { maximumBytes: record.maximumBytes },\n source: { file: \"process\", line: 1 },\n })\n return result.status === \"accepted\" ? record.stream : \"ignored\"\n }\n if (record.kind === \"output\") {\n if (record.text.length === 0) return \"ignored\"\n const result = await this.dependencies.evidence.append({\n schemaVersion: EVENT_SCHEMA_VERSION,\n eventId: generatedId(\"event_\"),\n timestamp: new Date().toISOString(),\n sessionId: this.dependencies.session.publicId,\n runId: input.runId,\n runLabel,\n hypothesisId: \"hyp_process\",\n probeId: \"probe_process\",\n kind: `process.${record.stream}`,\n message: record.text,\n data: null,\n source: { file: \"process\", line: 1 },\n })\n return result.status === \"accepted\" ? record.stream : \"ignored\"\n }\n\n const parsed = EventInputSchema.safeParse(record.value)\n if (!parsed.success) return \"ignored\"\n const validated =\n this.dependencies.probes === undefined ? parsed.data : await this.dependencies.probes.validateEvent(parsed.data)\n const result = await this.dependencies.evidence.append({\n ...validated,\n eventId: generatedId(\"event_\"),\n kind: \"probe\",\n })\n return result.status === \"accepted\" ? \"probe\" : \"ignored\"\n }\n\n private async addOwnedProcess(owned: OwnedProcess): Promise<void> {\n await this.updateManifest((manifest) => ({ ...manifest, processes: [...manifest.processes, owned] }))\n }\n\n private async markStarted(id: string, targetPid: number): Promise<void> {\n await this.updateManifest((manifest) => ({\n ...manifest,\n processes: manifest.processes.map((entry) =>\n entry.id === id ? { ...entry, targetPid, status: \"running\" as const } : entry,\n ),\n }))\n }\n\n private async markCompleted(\n id: string,\n result: Extract<ReturnType<typeof parseChildMessage>, { type: \"result\" }>,\n ): Promise<void> {\n await this.updateManifest((manifest) => ({\n ...manifest,\n processes: manifest.processes.map((entry) =>\n entry.id === id\n ? {\n ...entry,\n status: result.timedOut ? (\"timed_out\" as const) : (\"exited\" as const),\n completedAt: new Date().toISOString(),\n exitCode: result.exitCode,\n signal: result.signal,\n }\n : entry,\n ),\n }))\n }\n\n private async updateManifest(mutate: (manifest: CleanupManifest) => CleanupManifest): Promise<void> {\n await this.dependencies.session.manifestStore.modify(mutate)\n }\n\n private waitForMessage(child: ChildProcess, type: string, timeoutMs: number): Promise<void> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n cleanup()\n reject(new DebugModeError(\"PROCESS_START_FAILED\", `Supervisor did not become ${type}`))\n }, timeoutMs)\n const message = (value: unknown) => {\n try {\n if (parseChildMessage(value).type === type) {\n cleanup()\n resolve()\n }\n } catch {\n cleanup()\n reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor returned an invalid message\"))\n }\n }\n const exit = () => {\n cleanup()\n reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor exited before becoming ready\"))\n }\n const cleanup = () => {\n clearTimeout(timeout)\n child.off(\"message\", message)\n child.off(\"exit\", exit)\n }\n child.on(\"message\", message)\n child.once(\"exit\", exit)\n })\n }\n}\n","import { StringDecoder } from \"node:string_decoder\"\nimport { PROCESS_EVENT_PREFIX } from \"../core/constants.js\"\n\nexport type ProcessStream = \"stdout\" | \"stderr\"\nexport type DecodedProcessRecord =\n | { kind: \"output\"; stream: ProcessStream; text: string; rejectedProbe?: boolean }\n | { kind: \"probe-candidate\"; stream: ProcessStream; value: unknown }\n | { kind: \"truncated\"; stream: ProcessStream; maximumBytes: number }\n\ntype StreamState = { decoder: StringDecoder; pending: string; discarding: boolean }\n\nexport class ProcessLineDecoder {\n private readonly streams: Record<ProcessStream, StreamState> = {\n stdout: { decoder: new StringDecoder(\"utf8\"), pending: \"\", discarding: false },\n stderr: { decoder: new StringDecoder(\"utf8\"), pending: \"\", discarding: false },\n }\n\n constructor(private readonly options: { maxLineBytes: number }) {}\n\n push(stream: ProcessStream, chunk: Buffer): DecodedProcessRecord[] {\n return this.consume(stream, this.streams[stream].decoder.write(chunk))\n }\n\n flush(stream: ProcessStream): DecodedProcessRecord[] {\n const state = this.streams[stream]\n const records = this.consume(stream, state.decoder.end())\n if (!state.discarding && state.pending.length > 0) {\n records.push(this.decodeLine(stream, state.pending.replace(/\\r$/u, \"\")))\n }\n state.pending = \"\"\n state.discarding = false\n return records\n }\n\n private consume(stream: ProcessStream, text: string): DecodedProcessRecord[] {\n const state = this.streams[stream]\n const records: DecodedProcessRecord[] = []\n let remainder = text\n if (state.discarding) {\n const newline = remainder.indexOf(\"\\n\")\n if (newline < 0) return records\n state.discarding = false\n remainder = remainder.slice(newline + 1)\n }\n state.pending += remainder\n\n while (true) {\n const newline = state.pending.indexOf(\"\\n\")\n if (newline < 0) break\n const line = state.pending.slice(0, newline).replace(/\\r$/u, \"\")\n state.pending = state.pending.slice(newline + 1)\n if (Buffer.byteLength(line) > this.options.maxLineBytes) {\n records.push({ kind: \"truncated\", stream, maximumBytes: this.options.maxLineBytes })\n } else {\n records.push(this.decodeLine(stream, line))\n }\n }\n\n if (Buffer.byteLength(state.pending) > this.options.maxLineBytes) {\n state.pending = \"\"\n state.discarding = true\n records.push({ kind: \"truncated\", stream, maximumBytes: this.options.maxLineBytes })\n }\n return records\n }\n\n private decodeLine(stream: ProcessStream, text: string): DecodedProcessRecord {\n if (!text.startsWith(PROCESS_EVENT_PREFIX)) return { kind: \"output\", stream, text }\n try {\n return { kind: \"probe-candidate\", stream, value: JSON.parse(text.slice(PROCESS_EVENT_PREFIX.length)) }\n } catch {\n return { kind: \"output\", stream, text, rejectedProbe: true }\n }\n }\n}\n","import { z } from \"zod\"\n\nconst MAX_MESSAGE_BYTES = 64 * 1024\nconst BoundedString = z.string().max(8_192)\n\nconst StartMessageSchema = z\n .object({\n type: z.literal(\"start\"),\n executable: BoundedString.min(1),\n args: z.array(BoundedString).max(256),\n cwd: BoundedString.min(1),\n env: z\n .record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), BoundedString)\n .refine((value) => Object.keys(value).length <= 256),\n timeoutMs: z.number().int().min(1).max(300_000),\n ownerNonce: z\n .string()\n .min(32)\n .max(128)\n .regex(/^[A-Za-z0-9_-]+$/),\n })\n .strict()\n\nconst TerminateMessageSchema = z.object({ type: z.literal(\"terminate\"), reason: BoundedString }).strict()\n\nexport const ParentMessageSchema = z.discriminatedUnion(\"type\", [StartMessageSchema, TerminateMessageSchema])\n\nexport const ChildMessageSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"ready\") }).strict(),\n z.object({ type: z.literal(\"started\"), targetPid: z.number().int().positive() }).strict(),\n z\n .object({\n type: z.literal(\"result\"),\n targetPid: z.number().int().positive(),\n exitCode: z.number().int().nullable(),\n signal: z.string().max(64).nullable(),\n timedOut: z.boolean(),\n termination: z\n .object({\n graceful: z.boolean(),\n forced: z.boolean(),\n remaining: z.boolean(),\n durationMs: z.number().nonnegative(),\n errors: z.array(z.string().max(256)).max(20),\n })\n .strict()\n .optional(),\n })\n .strict(),\n z.object({ type: z.literal(\"failure\"), code: z.string().max(128), message: z.string().max(512) }).strict(),\n])\n\nexport type ParentMessage = z.infer<typeof ParentMessageSchema>\nexport type ChildMessage = z.infer<typeof ChildMessageSchema>\n\nfunction assertSize(value: unknown): void {\n let serialized: string\n try {\n serialized = JSON.stringify(value)\n } catch {\n throw new Error(\"IPC message is not serializable\")\n }\n if (Buffer.byteLength(serialized) > MAX_MESSAGE_BYTES) throw new Error(\"IPC message exceeds 64 KiB\")\n}\n\nexport function parseParentMessage(value: unknown): ParentMessage {\n assertSize(value)\n return ParentMessageSchema.parse(value)\n}\n\nexport function parseChildMessage(value: unknown): ChildMessage {\n assertSize(value)\n return ChildMessageSchema.parse(value)\n}\n","import { randomBytes } from \"node:crypto\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { RunLabelSchema } from \"../core/schemas.js\"\nimport type { CleanupManifest, ManifestRun } from \"../session/types.js\"\n\nexport interface RunPersistence {\n read(): Promise<CleanupManifest>\n update(expectedRevision: number, mutate: (value: CleanupManifest) => CleanupManifest): Promise<CleanupManifest>\n}\n\nexport type LeaseFactory = (kind: \"process\" | \"waiting\") => Promise<() => void> | (() => void)\n\nfunction createId(prefix: string): string {\n return `${prefix}${randomBytes(16).toString(\"base64url\")}`\n}\n\nexport class RunService {\n private readonly waitingReleases = new Map<string, () => void>()\n\n constructor(\n private readonly persistence: RunPersistence,\n private readonly clock: Clock = systemClock,\n private readonly acquireLease?: LeaseFactory,\n ) {}\n\n async start(input: {\n label: \"pre-fix\" | \"post-fix\"\n reproduction: string\n waitingForUser: boolean\n }): Promise<ManifestRun> {\n const label = RunLabelSchema.parse(input.label)\n const current = await this.persistence.read()\n if (current.runs.length >= 20) throw new DebugModeError(\"RUN_LIMIT\", \"The run limit has been reached\")\n const now = this.clock.now().toISOString()\n const run: ManifestRun = {\n id: createId(\"run_\"),\n label,\n reproduction: input.reproduction.slice(0, 8_192),\n status: input.waitingForUser ? \"waiting\" : \"running\",\n createdAt: now,\n }\n await this.persistence.update(current.revision, (manifest) => ({\n ...manifest,\n waitingForReproduction: input.waitingForUser || manifest.waitingForReproduction,\n runs: [...manifest.runs, run],\n }))\n if (input.waitingForUser && this.acquireLease !== undefined) {\n this.waitingReleases.set(run.id, await this.acquireLease(\"waiting\"))\n }\n return run\n }\n\n async require(runId: string): Promise<ManifestRun> {\n const manifest = await this.persistence.read()\n const run = manifest.runs.find((candidate) => candidate.id === runId)\n if (run === undefined) throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n return run\n }\n\n async complete(runId: string, status: \"completed\" | \"failed\" | \"timed_out\" | \"cancelled\"): Promise<ManifestRun> {\n const current = await this.persistence.read()\n const index = current.runs.findIndex((candidate) => candidate.id === runId)\n if (index < 0) throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n const existing = current.runs[index]\n if (existing === undefined) throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n const updated: ManifestRun = { ...existing, status, completedAt: this.clock.now().toISOString() }\n await this.persistence.update(current.revision, (manifest) => ({\n ...manifest,\n waitingForReproduction: false,\n runs: manifest.runs.map((candidate) => (candidate.id === runId ? updated : candidate)),\n }))\n this.waitingReleases.get(runId)?.()\n this.waitingReleases.delete(runId)\n return updated\n }\n}\n","import type { Dirent } from \"node:fs\"\nimport { lstat, readdir, realpath } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { CleanupService } from \"../cleanup/service.js\"\nimport type { FinalReportInput } from \"../cleanup/types.js\"\nimport { InvestigationStore } from \"../investigation/store.js\"\nimport { ManifestStore } from \"./manifest-store.js\"\nimport { isContained } from \"./paths.js\"\nimport type { DebugSession } from \"./registry.js\"\nimport { SecretStore } from \"./secret-store.js\"\nimport type { CleanupManifest } from \"./types.js\"\n\nexport type OrphanRecoveryOptions = Readonly<{\n tempBase: string\n now?: Date\n activeSessionDirs?: Set<string>\n cleanup?: (session: DebugSession, manifest: CleanupManifest) => Promise<void>\n}>\n\nasync function assertContainedReference(target: string, roots: string[]): Promise<void> {\n const absolute = path.resolve(target)\n if (!roots.some((root) => absolute === root || isContained(root, absolute))) {\n throw new Error(\"Manifest path escapes its owned roots\")\n }\n try {\n const canonical = await realpath(absolute)\n if (!roots.some((root) => canonical === root || isContained(root, canonical))) {\n throw new Error(\"Manifest path resolves outside its owned roots\")\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n}\n\nexport async function recoverOrphans(options: OrphanRecoveryOptions): Promise<{\n cleaned: string[]\n ignored: string[]\n errors: Array<{ directory: string; reason: string }>\n}> {\n const cleaned: string[] = []\n const ignored: string[] = []\n const errors: Array<{ directory: string; reason: string }> = []\n let entries: Dirent<string>[]\n try {\n entries = await readdir(options.tempBase, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { cleaned, ignored, errors }\n throw error\n }\n const now = (options.now ?? new Date()).getTime()\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"session-\")) {\n ignored.push(entry.name)\n continue\n }\n const sessionDir = path.join(options.tempBase, entry.name)\n try {\n if ((await lstat(sessionDir)).isSymbolicLink()) {\n ignored.push(entry.name)\n continue\n }\n const canonicalSessionDir = await realpath(sessionDir)\n if (options.activeSessionDirs?.has(canonicalSessionDir) === true) {\n ignored.push(entry.name)\n continue\n }\n const manifestStore = new ManifestStore(path.join(sessionDir, \"manifest.json\"))\n const manifest = await manifestStore.read()\n const canonicalProjectRoot = await realpath(manifest.projectRoot)\n if (\n (await realpath(manifest.sessionDir)) !== canonicalSessionDir ||\n new Date(manifest.expiresAt).getTime() >= now\n ) {\n ignored.push(entry.name)\n continue\n }\n for (const probe of manifest.probes) {\n await assertContainedReference(probe.sourceFile, [canonicalProjectRoot])\n }\n for (const permission of manifest.permissionChanges) {\n await assertContainedReference(permission.manifestPath, [canonicalProjectRoot])\n }\n for (const owned of manifest.ownedFiles) {\n await assertContainedReference(owned.path, [canonicalProjectRoot, canonicalSessionDir])\n }\n const paths = Object.freeze({\n baseDir: options.tempBase,\n sessionDir: manifest.sessionDir,\n projectRoot: canonicalProjectRoot,\n manifestFile: path.join(manifest.sessionDir, \"manifest.json\"),\n secretFile: path.join(manifest.sessionDir, \"secret.bin\"),\n stateFile: path.join(manifest.sessionDir, \"investigation-state.json\"),\n evidenceFile: path.join(manifest.sessionDir, \"evidence.ndjson\"),\n })\n const secretStore = new SecretStore(paths.secretFile)\n const secret = await secretStore.read().catch(() => \"\")\n const session: DebugSession = {\n publicId: manifest.sessionId,\n trustedHash: manifest.trustedSessionHash,\n projectRoot: canonicalProjectRoot,\n directory: canonicalProjectRoot,\n paths,\n manifestStore,\n investigationStore: new InvestigationStore(paths.stateFile),\n secretStore,\n secret,\n }\n if (options.cleanup !== undefined) await options.cleanup(session, manifest)\n else {\n const report: FinalReportInput = {\n outcome: \"abandoned\",\n rootCause: \"Investigation ended after its orphaned session expired\",\n decidingEvidence: [],\n hypotheses: [],\n fix: \"No recovery-time fix was applied\",\n changedFiles: [],\n verification: [\"Verified package-owned cleanup during startup recovery\"],\n }\n await new CleanupService(session).run({ reason: \"orphan-recovery\", finalReport: report })\n }\n cleaned.push(manifest.sessionId)\n } catch (error) {\n errors.push({\n directory: entry.name,\n reason: error instanceof Error ? error.name.slice(0, 128) : \"recovery-failed\",\n })\n }\n }\n return { cleaned, ignored, errors }\n}\n","import { readFile, stat } from \"node:fs/promises\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { LIMITS, STATE_SCHEMA_VERSION } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { atomicWriteJson } from \"../session/atomic-json.js\"\nimport { type InvestigationState, InvestigationStateSchema } from \"./schema.js\"\n\nexport type StateRecoveryResult =\n | { ok: true; state: InvestigationState; warnings: string[] }\n | { ok: false; error: { code: \"STATE_MISSING\" | \"STATE_INVALID\" | \"STATE_VERSION_UNSUPPORTED\"; message: string } }\n\nexport function initialInvestigationState(now: string): InvestigationState {\n return InvestigationStateSchema.parse({\n schemaVersion: STATE_SCHEMA_VERSION,\n revision: 0,\n updatedAt: now,\n problemSummary: \"\",\n expectedBehavior: \"\",\n actualBehavior: \"\",\n runtimeContext: { kind: \"other\", target: \"\" },\n reproduction: { method: \"\", requiresUser: false, confirmed: null },\n successCriteria: [],\n phase: \"intake\",\n loopIteration: 0,\n singleCauseEvidenceRef: null,\n hypotheses: [],\n completedChecks: [],\n runs: [],\n probeRefs: [],\n decidingEvidenceIds: [],\n developerConfirmations: [],\n decisions: [],\n nextAction: \"\",\n instrumentedFiles: [],\n fixedFiles: [],\n cleanup: { status: \"not_started\", completedResources: [] },\n })\n}\n\nexport class InvestigationStore {\n private tail: Promise<void> = Promise.resolve()\n\n constructor(\n private readonly filename: string,\n private readonly clock: Clock = systemClock,\n ) {}\n\n async create(state: InvestigationState): Promise<number> {\n const parsed = this.validate(state)\n try {\n await stat(this.filename)\n throw new DebugModeError(\"STATE_INVALID\", \"Investigation checkpoint already exists\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n return this.write(parsed)\n }\n\n async read(): Promise<InvestigationState> {\n const recovery = await this.readRecovery()\n if (!recovery.ok) throw new DebugModeError(recovery.error.code, recovery.error.message)\n return recovery.state\n }\n\n async readRecovery(): Promise<StateRecoveryResult> {\n let raw: string\n try {\n const info = await stat(this.filename)\n if (info.size > LIMITS.checkpointBytes) {\n return { ok: false, error: { code: \"STATE_INVALID\", message: \"Checkpoint exceeds its byte limit\" } }\n }\n raw = await readFile(this.filename, \"utf8\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { ok: false, error: { code: \"STATE_MISSING\", message: \"Investigation checkpoint is missing\" } }\n }\n return { ok: false, error: { code: \"STATE_INVALID\", message: \"Investigation checkpoint could not be read\" } }\n }\n\n try {\n const value: unknown = JSON.parse(raw)\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"schemaVersion\" in value &&\n (value as { schemaVersion?: unknown }).schemaVersion !== STATE_SCHEMA_VERSION\n ) {\n return {\n ok: false,\n error: { code: \"STATE_VERSION_UNSUPPORTED\", message: \"Investigation checkpoint version is unsupported\" },\n }\n }\n return { ok: true, state: InvestigationStateSchema.parse(value), warnings: [] }\n } catch {\n return { ok: false, error: { code: \"STATE_INVALID\", message: \"Investigation checkpoint is invalid\" } }\n }\n }\n\n async checkpoint(\n expectedRevision: number,\n state: InvestigationState,\n ): Promise<{ state: InvestigationState; bytes: number }> {\n return this.exclusive(async () => {\n const current = await this.read()\n if (current.revision !== expectedRevision) {\n throw new DebugModeError(\"STALE_REVISION\", `Expected revision ${expectedRevision}; found ${current.revision}`)\n }\n const candidate = this.validate({\n ...(state as unknown as Record<string, unknown>),\n revision: expectedRevision + 1,\n updatedAt: this.clock.now().toISOString(),\n })\n const bytes = await this.write(candidate)\n return { state: candidate, bytes }\n })\n }\n\n private validate(value: unknown): InvestigationState {\n const result = InvestigationStateSchema.safeParse(value)\n if (!result.success) throw new DebugModeError(\"STATE_INVALID\", \"Investigation checkpoint failed schema validation\")\n const bytes = Buffer.byteLength(`${JSON.stringify(result.data)}\\n`)\n if (bytes > LIMITS.checkpointBytes)\n throw new DebugModeError(\"STATE_TOO_LARGE\", \"Investigation checkpoint is too large\")\n return result.data\n }\n\n private async write(state: InvestigationState): Promise<number> {\n try {\n return await atomicWriteJson(this.filename, state, LIMITS.checkpointBytes)\n } catch (error) {\n if (error instanceof RangeError)\n throw new DebugModeError(\"STATE_TOO_LARGE\", \"Investigation checkpoint is too large\")\n throw error\n }\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n const previous = this.tail\n let release!: () => void\n this.tail = new Promise<void>((resolve) => {\n release = resolve\n })\n await previous\n try {\n return await operation()\n } finally {\n release()\n }\n }\n}\n","import { randomBytes } from \"node:crypto\"\nimport { open, rename, rm } from \"node:fs/promises\"\nimport path from \"node:path\"\n\nexport async function atomicWriteJson(filename: string, value: unknown, maximumBytes: number): Promise<number> {\n const serialized = `${JSON.stringify(value)}\\n`\n const bytes = Buffer.byteLength(serialized)\n if (bytes > maximumBytes) throw new RangeError(`Serialized JSON exceeds ${maximumBytes} bytes`)\n\n const temporary = path.join(\n path.dirname(filename),\n `${path.basename(filename)}.next-${randomBytes(8).toString(\"hex\")}`,\n )\n let handle: Awaited<ReturnType<typeof open>> | undefined\n try {\n handle = await open(temporary, \"wx\", 0o600)\n await handle.writeFile(serialized, \"utf8\")\n await handle.sync()\n await handle.close()\n handle = undefined\n await rename(temporary, filename)\n return bytes\n } catch (error) {\n await handle?.close().catch(() => undefined)\n await rm(temporary, { force: true }).catch(() => undefined)\n throw error\n }\n}\n","import { readFile, realpath, stat } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { LIMITS, MANIFEST_SCHEMA_VERSION, PACKAGE_ID } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { atomicWriteJson } from \"./atomic-json.js\"\nimport { isContained } from \"./paths.js\"\nimport { type CleanupManifest, ManifestSchema } from \"./types.js\"\n\nconst MANIFEST_MAX_BYTES = 1024 * 1024\n\nexport function createInitialManifest(input: {\n sessionId: string\n trustedSessionHash: string\n projectRoot: string\n sessionDir: string\n now: string\n keepArtifacts?: boolean\n retentionDestination?: string\n}): CleanupManifest {\n const expiresAt = new Date(new Date(input.now).getTime() + LIMITS.idleMs).toISOString()\n const candidate = {\n package: PACKAGE_ID,\n schemaVersion: MANIFEST_SCHEMA_VERSION,\n revision: 0,\n sessionId: input.sessionId,\n trustedSessionHash: input.trustedSessionHash,\n projectRoot: input.projectRoot,\n sessionDir: input.sessionDir,\n status: \"active\",\n createdAt: input.now,\n lastActivityAt: input.now,\n expiresAt,\n waitingForReproduction: false,\n keepArtifacts: input.keepArtifacts ?? false,\n collector: null,\n runs: [],\n processes: [],\n probes: [],\n ownedFiles: [],\n permissionChanges: [],\n counters: { accepted: 0, rejected: 0, sampled: 0, truncated: 0, dropped: 0, requests: 0 },\n cleanup: { status: \"not_started\", completedResources: [] },\n ...(input.retentionDestination === undefined ? {} : { retentionDestination: input.retentionDestination }),\n }\n return ManifestSchema.parse(candidate)\n}\n\nexport class ManifestStore {\n private tail: Promise<void> = Promise.resolve()\n\n constructor(private readonly filename: string) {}\n\n async create(value: CleanupManifest): Promise<CleanupManifest> {\n return this.exclusive(async () => {\n const parsed = ManifestSchema.parse(value)\n await this.verifyPaths(parsed)\n try {\n await stat(this.filename)\n throw new DebugModeError(\"SESSION_EXISTS\", \"Session manifest already exists\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n await atomicWriteJson(this.filename, parsed, MANIFEST_MAX_BYTES)\n return parsed\n })\n }\n\n async read(): Promise<CleanupManifest> {\n const info = await stat(this.filename)\n if (info.size > MANIFEST_MAX_BYTES) throw new Error(\"Manifest exceeds its byte limit\")\n const parsed = ManifestSchema.parse(JSON.parse(await readFile(this.filename, \"utf8\")))\n await this.verifyPaths(parsed)\n return parsed\n }\n\n async update(\n expectedRevision: number,\n mutate: (value: CleanupManifest) => CleanupManifest,\n ): Promise<CleanupManifest> {\n return this.exclusive(async () => {\n const current = await this.read()\n if (current.revision !== expectedRevision) {\n throw new DebugModeError(\"STALE_REVISION\", `Expected revision ${expectedRevision}; found ${current.revision}`)\n }\n return this.writeNext(current, mutate)\n })\n }\n\n async modify(mutate: (value: CleanupManifest) => CleanupManifest): Promise<CleanupManifest> {\n return this.exclusive(async () => this.writeNext(await this.read(), mutate))\n }\n\n private async writeNext(\n current: CleanupManifest,\n mutate: (value: CleanupManifest) => CleanupManifest,\n ): Promise<CleanupManifest> {\n const next = ManifestSchema.parse({ ...mutate(structuredClone(current)), revision: current.revision + 1 })\n await this.verifyPaths(next)\n await atomicWriteJson(this.filename, next, MANIFEST_MAX_BYTES)\n return next\n }\n\n private async verifyPaths(value: CleanupManifest): Promise<void> {\n const actualSessionDir = await realpath(path.dirname(this.filename))\n const declaredSessionDir = await realpath(value.sessionDir)\n if (actualSessionDir !== declaredSessionDir)\n throw new Error(\"Manifest session directory does not match its location\")\n const packageBase = await realpath(path.dirname(actualSessionDir))\n if (!isContained(packageBase, actualSessionDir)) throw new Error(\"Manifest is outside the package temporary base\")\n if ((await realpath(value.projectRoot)) !== value.projectRoot) {\n throw new Error(\"Manifest project root is not canonical\")\n }\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n const previous = this.tail\n let release!: () => void\n this.tail = new Promise<void>((resolve) => {\n release = resolve\n })\n await previous\n try {\n return await operation()\n } finally {\n release()\n }\n }\n}\n","import { randomBytes } from \"node:crypto\"\nimport { readFile, unlink, writeFile } from \"node:fs/promises\"\n\nconst TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/\n\nexport class SecretStore {\n constructor(private readonly filename: string) {}\n\n async create(): Promise<string> {\n const value = randomBytes(32).toString(\"base64url\")\n await writeFile(this.filename, value, { flag: \"wx\", mode: 0o600 })\n return value\n }\n\n async read(): Promise<string> {\n const value = await readFile(this.filename, \"utf8\")\n if (!TOKEN_PATTERN.test(value) || Buffer.from(value, \"base64url\").byteLength !== 32) {\n throw new Error(\"Stored collector credential is invalid\")\n }\n return value\n }\n\n async remove(): Promise<\"success\" | \"already-clean\"> {\n let length: number\n try {\n length = (await readFile(this.filename)).byteLength\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return \"already-clean\"\n throw error\n }\n\n try {\n await writeFile(this.filename, randomBytes(length), { flag: \"r+\" })\n } catch {\n // Deletion is still attempted if best-effort overwrite is unavailable.\n }\n try {\n await unlink(this.filename)\n return \"success\"\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return \"already-clean\"\n throw error\n }\n }\n}\n","import { createHash, randomBytes } from \"node:crypto\"\nimport type { Dirent } from \"node:fs\"\nimport { lstat, readdir, realpath, rm } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { LIMITS } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { InvestigationStore, initialInvestigationState } from \"../investigation/store.js\"\nimport { createInitialManifest, ManifestStore } from \"./manifest-store.js\"\nimport { createSessionPaths, isContained, type SessionPaths } from \"./paths.js\"\nimport { SecretStore } from \"./secret-store.js\"\nimport type { CleanupManifest } from \"./types.js\"\n\nexport function trustedSessionHash(openCodeSessionId: string): string {\n return createHash(\"sha256\").update(\"opencode-debug-mode:v1:\", \"utf8\").update(openCodeSessionId, \"utf8\").digest(\"hex\")\n}\n\nexport type ProjectContext = Readonly<{ directory: string; worktree: string }>\n\nexport type DebugSession = Readonly<{\n publicId: string\n trustedHash: string\n projectRoot: string\n directory: string\n paths: SessionPaths\n manifestStore: ManifestStore\n investigationStore: InvestigationStore\n secretStore: SecretStore\n secret: string\n}>\n\ntype MutableSession = DebugSession & { leases: Map<\"process\" | \"waiting\", number> }\n\nexport type RegistryCleanup = (session: DebugSession, reason: \"idle-expired\") => Promise<void>\n\nexport class SessionRegistry {\n private readonly sessions = new Map<string, MutableSession>()\n private readonly timer: NodeJS.Timeout\n private closed = false\n\n constructor(\n private readonly tempBase: string,\n private readonly clock: Clock = systemClock,\n private readonly cleanup?: RegistryCleanup,\n ) {\n this.timer = setInterval(() => void this.sweep(), 30_000)\n this.timer.unref()\n }\n\n async start(\n trustedId: string,\n context: ProjectContext,\n options: { keepArtifacts?: boolean; retentionDestination?: string } = {},\n ): Promise<DebugSession> {\n this.assertOpen()\n if (Number(process.versions.node.split(\".\")[0]) < 20) {\n throw new DebugModeError(\"NODE_UNSUPPORTED\", \"Node.js 20 or newer is required\")\n }\n if (options.keepArtifacts === true && options.retentionDestination === undefined) {\n throw new DebugModeError(\"DESTINATION_REQUIRED\", \"An explicit retention destination is required\")\n }\n const hash = trustedSessionHash(trustedId)\n if (this.sessions.has(hash) || (await this.findPersisted(hash)) !== undefined) {\n throw new DebugModeError(\"SESSION_EXISTS\", \"A debug session already exists for this OpenCode session\")\n }\n\n const projectRoot = await realpath(context.worktree)\n const directory = await realpath(context.directory)\n if (directory !== projectRoot && !isContained(projectRoot, directory)) {\n throw new DebugModeError(\"STORAGE_UNAVAILABLE\", \"The active directory is outside the worktree\")\n }\n\n let paths: SessionPaths | undefined\n try {\n paths = await createSessionPaths(this.tempBase, projectRoot)\n const secretStore = new SecretStore(paths.secretFile)\n const secret = await secretStore.create()\n const publicId = `session_${randomBytes(16).toString(\"base64url\")}`\n const manifestStore = new ManifestStore(paths.manifestFile)\n const investigationStore = new InvestigationStore(paths.stateFile, this.clock)\n const now = this.clock.now().toISOString()\n await manifestStore.create(\n createInitialManifest({\n sessionId: publicId,\n trustedSessionHash: hash,\n projectRoot,\n sessionDir: paths.sessionDir,\n now,\n keepArtifacts: options.keepArtifacts ?? false,\n ...(options.retentionDestination === undefined\n ? {}\n : { retentionDestination: path.resolve(options.retentionDestination) }),\n }),\n )\n await investigationStore.create(initialInvestigationState(now))\n const session: MutableSession = {\n publicId,\n trustedHash: hash,\n projectRoot,\n directory,\n paths,\n manifestStore,\n investigationStore,\n secretStore,\n secret,\n leases: new Map(),\n }\n this.sessions.set(hash, session)\n return session\n } catch (error) {\n if (paths !== undefined) await rm(paths.sessionDir, { recursive: true, force: true }).catch(() => undefined)\n if (error instanceof DebugModeError) throw error\n throw new DebugModeError(\"STORAGE_UNAVAILABLE\", \"The debug session could not be initialized\")\n }\n }\n\n async requireOwned(trustedId: string): Promise<DebugSession> {\n this.assertOpen()\n const hash = trustedSessionHash(trustedId)\n const inMemory = this.sessions.get(hash)\n if (inMemory !== undefined) return inMemory\n const persisted = await this.findPersisted(hash)\n if (persisted === undefined) throw new DebugModeError(\"NO_ACTIVE_SESSION\", \"No active debug session exists\")\n this.sessions.set(hash, persisted)\n return persisted\n }\n\n async hasTrusted(trustedId: string): Promise<boolean> {\n try {\n await this.requireOwned(trustedId)\n return true\n } catch (error) {\n if (error instanceof DebugModeError && error.code === \"NO_ACTIVE_SESSION\") return false\n throw error\n }\n }\n\n async touch(trustedId: string): Promise<void> {\n const session = (await this.requireOwned(trustedId)) as MutableSession\n await this.touchSession(session)\n }\n\n async touchSession(sessionValue: DebugSession): Promise<void> {\n const session = this.sessions.get(sessionValue.trustedHash)\n if (session === undefined || session.publicId !== sessionValue.publicId) {\n throw new DebugModeError(\"SESSION_OWNERSHIP_MISMATCH\", \"Session is not owned by this registry\")\n }\n const now = this.clock.now()\n await session.manifestStore.modify((manifest) => ({\n ...manifest,\n lastActivityAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + LIMITS.idleMs).toISOString(),\n }))\n }\n\n async acquireLease(trustedId: string, kind: \"process\" | \"waiting\"): Promise<() => void> {\n const session = (await this.requireOwned(trustedId)) as MutableSession\n return this.acquireLeaseForSession(session, kind)\n }\n\n acquireLeaseForSession(sessionValue: DebugSession, kind: \"process\" | \"waiting\"): () => void {\n const session = this.sessions.get(sessionValue.trustedHash)\n if (session === undefined || session.publicId !== sessionValue.publicId) {\n throw new DebugModeError(\"SESSION_OWNERSHIP_MISMATCH\", \"Session is not owned by this registry\")\n }\n session.leases.set(kind, (session.leases.get(kind) ?? 0) + 1)\n let released = false\n return () => {\n if (released) return\n released = true\n const next = Math.max(0, (session.leases.get(kind) ?? 1) - 1)\n if (next === 0) session.leases.delete(kind)\n else session.leases.set(kind, next)\n }\n }\n\n async sweep(): Promise<void> {\n if (this.closed) return\n const now = this.clock.now().getTime()\n for (const [hash, session] of this.sessions) {\n const manifest = await session.manifestStore.read().catch(() => undefined)\n if (\n manifest === undefined ||\n manifest.waitingForReproduction ||\n session.leases.size > 0 ||\n new Date(manifest.lastActivityAt).getTime() + LIMITS.idleMs > now\n ) {\n continue\n }\n if (this.cleanup !== undefined) await this.cleanup(session, \"idle-expired\")\n this.sessions.delete(hash)\n }\n }\n\n listActive(): DebugSession[] {\n return [...this.sessions.values()]\n }\n\n forgetTrusted(trustedId: string): void {\n this.sessions.delete(trustedSessionHash(trustedId))\n }\n\n async closeAll(): Promise<void> {\n if (this.closed) return\n this.closed = true\n clearInterval(this.timer)\n this.sessions.clear()\n }\n\n private async findPersisted(hash: string): Promise<MutableSession | undefined> {\n let entries: Dirent<string>[]\n try {\n entries = await readdir(this.tempBase, { withFileTypes: true, encoding: \"utf8\" })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined\n throw error\n }\n const matches: MutableSession[] = []\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"session-\")) continue\n const sessionDir = path.join(this.tempBase, entry.name)\n if ((await lstat(sessionDir)).isSymbolicLink()) continue\n try {\n const manifestStore = new ManifestStore(path.join(sessionDir, \"manifest.json\"))\n const manifest = await manifestStore.read()\n if (manifest.trustedSessionHash !== hash || manifest.status !== \"active\") continue\n if (!manifest.waitingForReproduction && new Date(manifest.expiresAt).getTime() < this.clock.now().getTime())\n continue\n const paths = this.pathsFromManifest(manifest)\n const secretStore = new SecretStore(paths.secretFile)\n const secret = await secretStore.read()\n const investigationStore = new InvestigationStore(paths.stateFile, this.clock)\n const recovery = await investigationStore.readRecovery()\n if (!recovery.ok) throw new DebugModeError(recovery.error.code, recovery.error.message)\n matches.push({\n publicId: manifest.sessionId,\n trustedHash: hash,\n projectRoot: manifest.projectRoot,\n directory: manifest.projectRoot,\n paths,\n manifestStore,\n investigationStore,\n secretStore,\n secret,\n leases: new Map(),\n })\n } catch {}\n }\n if (matches.length > 1) {\n throw new DebugModeError(\"SESSION_OWNERSHIP_MISMATCH\", \"Multiple session manifests match this trusted session\")\n }\n return matches[0]\n }\n\n private pathsFromManifest(manifest: CleanupManifest): SessionPaths {\n return Object.freeze({\n baseDir: this.tempBase,\n sessionDir: manifest.sessionDir,\n projectRoot: manifest.projectRoot,\n manifestFile: path.join(manifest.sessionDir, \"manifest.json\"),\n secretFile: path.join(manifest.sessionDir, \"secret.bin\"),\n stateFile: path.join(manifest.sessionDir, \"investigation-state.json\"),\n evidenceFile: path.join(manifest.sessionDir, \"evidence.ndjson\"),\n })\n }\n\n private assertOpen(): void {\n if (this.closed) throw new DebugModeError(\"NO_ACTIVE_SESSION\", \"The session registry is closed\")\n }\n}\n","import path from \"node:path\"\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { CleanupService } from \"../cleanup/service.js\"\nimport type { FinalReportInput } from \"../cleanup/types.js\"\nimport { isContained } from \"../session/paths.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\nconst reportSchema = schema\n .object({\n outcome: schema.enum([\"completed\", \"unresolved\", \"abandoned\", \"escalated\"]),\n rootCause: schema.string().max(8_192),\n decidingEvidence: schema.array(schema.string().max(8_192)).max(100),\n hypotheses: schema\n .array(\n schema\n .object({\n id: schema.string().max(64),\n status: schema.enum([\"open\", \"confirmed\", \"eliminated\"]),\n statement: schema.string().max(8_192),\n })\n .strict(),\n )\n .max(4),\n fix: schema.string().max(8_192),\n changedFiles: schema.array(schema.string().max(8_192)).max(200),\n verification: schema.array(schema.string().max(8_192)).max(100),\n })\n .strict()\n\nexport function createCleanupTool(\n registry: SessionRegistry,\n cleanupFor: (session: DebugSession) => CleanupService,\n): ToolDefinition {\n return tool({\n description: \"Tear down every owned debug resource and optionally retain a sanitized report\",\n args: {\n reason: schema.enum([\"completed\", \"unresolved\", \"abandoned\", \"escalated\", \"cancelled\"]),\n finalReport: reportSchema,\n cleanCheck: schema\n .object({\n executable: schema.string().min(1).max(8_192),\n args: schema.array(schema.string().max(8_192)).max(256),\n cwd: schema.string().min(1).max(8_192),\n timeoutMs: schema.number().int().min(1).max(300_000),\n })\n .strict()\n .optional(),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await cleanupFor(session).run({\n reason: args.reason,\n finalReport: args.finalReport as FinalReportInput,\n ...(args.cleanCheck === undefined ? {} : { cleanCheck: args.cleanCheck }),\n })\n const sanitize = (location: string | undefined) => {\n if (location === undefined) return undefined\n const absolute = path.resolve(location)\n return absolute === session.projectRoot || isContained(session.projectRoot, absolute)\n ? path.relative(session.projectRoot, absolute) || \".\"\n : undefined\n }\n const resources = {\n ...result.resources,\n probes: result.resources.probes.map((value) => ({ ...value, location: sanitize(value.location) })),\n permissions: result.resources.permissions.map((value) => ({ ...value, location: sanitize(value.location) })),\n files: result.resources.files.map((value) => ({ ...value, location: sanitize(value.location) })),\n }\n return jsonSuccess({\n ...result,\n resources,\n remainingArtifacts: result.remainingArtifacts.map(sanitize).filter(Boolean),\n })\n } catch (error) {\n return jsonFailure(error, \"Cleanup failed\")\n }\n },\n })\n}\n","import type { DebugErrorCode, SafeErrorDetail } from \"./errors.js\"\n\nexport type ToolWarning = Readonly<{ code: string; message: string }>\n\nexport type ToolResultEnvelope<T> =\n | { ok: true; data: T; warnings: ToolWarning[] }\n | {\n ok: false\n error: {\n code: DebugErrorCode\n message: string\n retryable: boolean\n action?: string\n details?: Record<string, SafeErrorDetail>\n }\n }\n\nexport function success<T>(data: T, warnings: ToolWarning[] = []): ToolResultEnvelope<T> {\n return { ok: true, data, warnings }\n}\n\nexport function failure(\n code: DebugErrorCode,\n message: string,\n retryable: boolean,\n options: { action?: string; details?: Record<string, SafeErrorDetail> } = {},\n): ToolResultEnvelope<never> {\n const error: Extract<ToolResultEnvelope<never>, { ok: false }>[\"error\"] = {\n code,\n message: message.slice(0, 8_192),\n retryable,\n }\n if (options.action !== undefined) error.action = options.action.slice(0, 8_192)\n if (options.details !== undefined) error.details = options.details\n return { ok: false, error }\n}\n","import { DebugModeError } from \"../core/errors.js\"\nimport { failure, success, type ToolResultEnvelope } from \"../core/result.js\"\n\nexport function jsonSuccess<T>(value: T): string {\n return JSON.stringify(success(value))\n}\n\nexport function jsonFailure(error: unknown, fallback = \"Tool operation failed\"): string {\n if (error instanceof DebugModeError) {\n return JSON.stringify(\n failure(error.code, error.message, error.retryable, {\n ...(error.action === undefined ? {} : { action: error.action }),\n ...(error.details === undefined ? {} : { details: error.details }),\n }),\n )\n }\n return JSON.stringify(failure(\"INTERNAL_ERROR\", fallback, false))\n}\n\nexport function serializeEnvelope<T>(value: ToolResultEnvelope<T>): string {\n return JSON.stringify(value)\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport interface PublicCollectorService {\n start(input: {\n runtime: \"web\" | \"extension-background\"\n transportTargetPath?: string\n extensionManifestPath?: string\n }): Promise<{\n collectorId: string\n host: \"127.0.0.1\" | \"::1\"\n port: number\n status: string\n helperImport?: string\n helperPath?: string\n }>\n}\n\nexport function createCollectorStartTool(\n registry: SessionRegistry,\n collectorFor: (session: DebugSession) => PublicCollectorService,\n): ToolDefinition {\n return tool({\n description: \"Start the authenticated loopback evidence collector\",\n args: {\n runtime: schema.enum([\"web\", \"extension-background\"]),\n transportTargetPath: schema.string().min(1).max(8_192).optional(),\n extensionManifestPath: schema.string().min(1).max(8_192).optional(),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await collectorFor(session).start({\n runtime: args.runtime,\n ...(args.transportTargetPath === undefined ? {} : { transportTargetPath: args.transportTargetPath }),\n ...(args.extensionManifestPath === undefined ? {} : { extensionManifestPath: args.extensionManifestPath }),\n })\n await registry.touch(context.sessionID)\n return jsonSuccess(result)\n } catch (error) {\n return jsonFailure(error, \"Collector startup failed\")\n }\n },\n })\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { EvidenceStore } from \"../evidence/store.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport function createEvidenceReadTool(\n registry: SessionRegistry,\n evidenceFor: (session: DebugSession) => EvidenceStore,\n): ToolDefinition {\n return tool({\n description: \"Read a bounded filtered page of sanitized local evidence\",\n args: {\n runId: schema.string().optional(),\n hypothesisId: schema.string().optional(),\n probeId: schema.string().optional(),\n from: schema.string().optional(),\n to: schema.string().optional(),\n keyword: schema.string().max(8_192).optional(),\n cursor: schema.string().regex(/^\\d+$/).optional(),\n limit: schema.number().int().min(1).max(100).default(100),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await evidenceFor(session).read({\n sessionId: session.publicId,\n limit: args.limit,\n ...(args.runId === undefined ? {} : { runId: args.runId }),\n ...(args.hypothesisId === undefined ? {} : { hypothesisId: args.hypothesisId }),\n ...(args.probeId === undefined ? {} : { probeId: args.probeId }),\n ...(args.from === undefined ? {} : { from: args.from }),\n ...(args.to === undefined ? {} : { to: args.to }),\n ...(args.keyword === undefined ? {} : { keyword: args.keyword }),\n ...(args.cursor === undefined ? {} : { cursor: args.cursor }),\n })\n await registry.touch(context.sessionID)\n return jsonSuccess(result)\n } catch (error) {\n return jsonFailure(error, \"Evidence is unavailable\")\n }\n },\n })\n}\n","import path from \"node:path\"\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { ProbeRegistry } from \"../probes/registry.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport function createProbePrepareTool(\n registry: SessionRegistry,\n probesFor: (session: DebugSession) => ProbeRegistry,\n): ToolDefinition {\n return tool({\n description: \"Prepare one safe owned JavaScript or TypeScript probe\",\n args: {\n runId: schema.string().regex(/^[A-Za-z0-9_-]+$/),\n hypothesisId: schema.string().regex(/^[A-Za-z0-9_-]+$/),\n sourceFile: schema.string().min(1).max(8_192),\n sourceLine: schema.number().int().positive(),\n sourceColumn: schema.number().int().positive().optional(),\n message: schema.string().min(1).max(8_192),\n captures: schema\n .array(\n schema.object({ label: schema.string().min(1).max(128), path: schema.string().min(1).max(512) }).strict(),\n )\n .max(20),\n transport: schema.enum([\"process\", \"http-web\", \"extension-background\", \"extension-content\"]),\n sampling: schema.union([\n schema.object({ mode: schema.literal(\"every\"), n: schema.number().int().min(1).max(10_000) }).strict(),\n schema\n .object({ mode: schema.literal(\"aggregate\"), windowMs: schema.number().int().min(100).max(60_000) })\n .strict(),\n ]),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const { sourceColumn, ...required } = args\n const probe = await probesFor(session).plan({\n ...required,\n ...(sourceColumn === undefined ? {} : { sourceColumn }),\n })\n await registry.touch(context.sessionID)\n return jsonSuccess({\n probeId: probe.id,\n markerBlock: probe.markerBlock,\n source: path.relative(session.projectRoot, probe.sourceFile),\n line: probe.sourceLine,\n })\n } catch (error) {\n return jsonFailure(error, \"Probe preparation failed\")\n }\n },\n })\n}\n\nexport function createProbeRegisterTool(\n registry: SessionRegistry,\n probesFor: (session: DebugSession) => ProbeRegistry,\n): ToolDefinition {\n return tool({\n description: \"Verify and register an exact owned probe marker\",\n args: { probeId: schema.string().regex(/^[A-Za-z0-9_-]+$/) },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const probe = await probesFor(session).register(args.probeId)\n await registry.touch(context.sessionID)\n return jsonSuccess({ probeId: probe.id, status: probe.status, validationStatus: probe.validationStatus })\n } catch (error) {\n return jsonFailure(error, \"Probe registration failed\")\n }\n },\n })\n}\n","import path from \"node:path\"\nimport { type ToolContext, type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { failure, success } from \"../core/result.js\"\nimport type { ProbeRegistry } from \"../probes/registry.js\"\nimport type { ProcessCaptureResult, ProcessService } from \"../process/service.js\"\nimport type { RunService } from \"../run/service.js\"\nimport { isContained } from \"../session/paths.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\n\nconst schema = tool.schema\n\nconst ApprovalClassSchema = schema.enum([\n \"local-deterministic\",\n \"credentials\",\n \"device\",\n \"external-state\",\n \"materially-different\",\n])\n\nconst ProcessArgs = {\n approvalClass: ApprovalClassSchema,\n purpose: schema.enum([\"instrumentation-check\", \"reproduction\", \"verification\"]),\n probeIds: schema.array(schema.string().regex(/^[A-Za-z0-9_-]+$/)).max(100),\n executable: schema.string().min(1).max(8_192),\n args: schema.array(schema.string().max(8_192)).max(256),\n cwd: schema.string().min(1).max(8_192),\n env: schema\n .record(schema.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), schema.string().max(8_192))\n .refine((value) => Object.keys(value).length <= 256),\n runId: schema.string().regex(/^[A-Za-z0-9_-]+$/),\n timeoutMs: schema.number().int().min(1).max(300_000),\n}\n\nexport interface RunToolDependencies {\n registry: Pick<SessionRegistry, \"requireOwned\">\n processFor(session: DebugSession): Pick<ProcessService, \"capture\">\n probesFor(session: DebugSession): Pick<ProbeRegistry, \"validate\" | \"requireValidatedForRun\">\n}\n\nasync function requestApproval(\n context: ToolContext,\n permission: string,\n executable: string,\n args: string[],\n): Promise<void> {\n try {\n await context.ask({\n permission,\n patterns: [[path.basename(executable), ...args.map((value) => path.basename(value))].join(\" \").slice(0, 512)],\n always: [],\n metadata: { executable: path.basename(executable), argumentCount: args.length },\n })\n } catch {\n throw new DebugModeError(\"COMMAND_REQUIRES_APPROVAL\", \"The requested process command was not approved\")\n }\n}\n\nfunction serializeResult(result: ProcessCaptureResult): string {\n return JSON.stringify(success(result))\n}\n\nexport function createProcessCaptureTool(dependencies: RunToolDependencies): ToolDefinition {\n return tool({\n description: \"Run one supervised command and capture bounded runtime evidence\",\n args: ProcessArgs,\n execute: async (args, context) => {\n try {\n const session = await dependencies.registry.requireOwned(context.sessionID)\n if (args.approvalClass !== \"local-deterministic\") {\n await requestApproval(context, \"debug_process_external\", args.executable, args.args)\n }\n const resolvedCwd = path.resolve(args.cwd)\n const worktree = path.resolve(context.worktree)\n if (resolvedCwd !== worktree && !isContained(worktree, resolvedCwd)) {\n await requestApproval(context, \"external_directory\", args.executable, args.args)\n }\n const probes = dependencies.probesFor(session)\n if (args.purpose === \"reproduction\") await probes.requireValidatedForRun(args.runId)\n const result = await dependencies.processFor(session).capture({\n runId: args.runId,\n executable: args.executable,\n args: args.args,\n cwd: resolvedCwd,\n env: args.env,\n timeoutMs: args.timeoutMs,\n probeIds: args.probeIds,\n purpose: args.purpose,\n signal: context.abort,\n })\n if (args.purpose === \"instrumentation-check\" && result.exitCode === 0) await probes.validate(args.probeIds)\n return serializeResult(result)\n } catch (error) {\n if (error instanceof DebugModeError) {\n return JSON.stringify(\n failure(error.code, error.message, error.retryable, {\n ...(error.action === undefined ? {} : { action: error.action }),\n ...(error.details === undefined ? {} : { details: error.details }),\n }),\n )\n }\n return JSON.stringify(failure(\"INTERNAL_ERROR\", \"Process capture failed\", false))\n }\n },\n })\n}\n\nexport function createRunStartTool(\n registry: SessionRegistry,\n runFor: (session: DebugSession) => RunService,\n): ToolDefinition {\n return tool({\n description: \"Start a correlated pre-fix or post-fix reproduction run\",\n args: {\n label: schema.enum([\"pre-fix\", \"post-fix\"]),\n reproduction: schema.string().min(1).max(8_192),\n waitingForUser: schema.boolean().default(false),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const run = await runFor(session).start(args)\n await registry.touch(context.sessionID)\n return JSON.stringify(success({ runId: run.id, status: run.status, label: run.label }))\n } catch (error) {\n if (error instanceof DebugModeError) return JSON.stringify(failure(error.code, error.message, error.retryable))\n return JSON.stringify(failure(\"INTERNAL_ERROR\", \"Run could not be started\", false))\n }\n },\n })\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport { LIMITS } from \"../core/constants.js\"\nimport type { SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport function createSessionStartTool(registry: SessionRegistry): ToolDefinition {\n return tool({\n description: \"Start an isolated runtime-debugging session\",\n args: {\n keepArtifacts: schema.boolean().default(false),\n retentionDestination: schema.string().min(1).max(8_192).optional(),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.start(\n context.sessionID,\n { directory: context.directory, worktree: context.worktree },\n {\n keepArtifacts: args.keepArtifacts,\n ...(args.retentionDestination === undefined ? {} : { retentionDestination: args.retentionDestination }),\n },\n )\n return jsonSuccess({\n sessionId: session.publicId,\n status: \"active\",\n limits: LIMITS,\n capabilities: { process: true, web: true, extension: true, languages: [\"javascript\", \"typescript\"] },\n })\n } catch (error) {\n return jsonFailure(error, \"Debug session could not be started\")\n }\n },\n })\n}\n\nexport function createSessionStatusTool(registry: SessionRegistry): ToolDefinition {\n return tool({\n description: \"Read the public status of the active debug session\",\n args: {},\n execute: async (_args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const manifest = await session.manifestStore.read()\n const state = await session.investigationStore.readRecovery()\n return jsonSuccess({\n sessionId: session.publicId,\n status: manifest.status,\n phase: state.ok ? state.state.phase : \"recovery-required\",\n revision: state.ok ? state.state.revision : manifest.revision,\n collector:\n manifest.collector === null\n ? null\n : { status: manifest.collector.status, host: manifest.collector.host, port: manifest.collector.port },\n processCount: manifest.processes.length,\n probeCount: manifest.probes.length,\n counters: manifest.counters,\n limits: LIMITS,\n })\n } catch (error) {\n return jsonFailure(error, \"Debug session status is unavailable\")\n }\n },\n })\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { InvestigationState } from \"../investigation/schema.js\"\nimport type { SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport function createStateReadTool(registry: SessionRegistry): ToolDefinition {\n return tool({\n description: \"Read and reconcile the durable investigation checkpoint\",\n args: {},\n execute: async (_args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await session.investigationStore.readRecovery()\n if (!result.ok) throw Object.assign(new Error(result.error.message), { code: result.error.code })\n return jsonSuccess({ state: result.state, recoveryWarnings: result.warnings })\n } catch (error) {\n if (typeof error === \"object\" && error !== null && \"code\" in error) {\n const value = error as { code: string; message: string }\n const { DebugModeError } = await import(\"../core/errors.js\")\n return jsonFailure(new DebugModeError(value.code as never, value.message), \"Checkpoint is unavailable\")\n }\n return jsonFailure(error, \"Checkpoint is unavailable\")\n }\n },\n })\n}\n\nexport function createStateCheckpointTool(registry: SessionRegistry): ToolDefinition {\n return tool({\n description: \"Atomically replace the durable investigation checkpoint\",\n args: { expectedRevision: schema.number().int().nonnegative(), state: schema.unknown() },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await session.investigationStore.checkpoint(\n args.expectedRevision,\n args.state as InvestigationState,\n )\n await registry.touch(context.sessionID)\n return jsonSuccess({ revision: result.state.revision, bytes: result.bytes })\n } catch (error) {\n return jsonFailure(error, \"Checkpoint update failed\")\n }\n },\n })\n}\n","import type { ToolDefinition } from \"@opencode-ai/plugin\"\nimport type { CleanupService } from \"../cleanup/service.js\"\nimport type { EvidenceStore } from \"../evidence/store.js\"\nimport type { ProbeRegistry } from \"../probes/registry.js\"\nimport type { RunService } from \"../run/service.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { createCleanupTool } from \"./cleanup-tool.js\"\nimport { createCollectorStartTool, type PublicCollectorService } from \"./collector-tools.js\"\nimport { createEvidenceReadTool } from \"./evidence-tools.js\"\nimport { createProbePrepareTool, createProbeRegisterTool } from \"./probe-tools.js\"\nimport { createProcessCaptureTool, createRunStartTool, type RunToolDependencies } from \"./run-tools.js\"\nimport { createSessionStartTool, createSessionStatusTool } from \"./session-tools.js\"\nimport { createStateCheckpointTool, createStateReadTool } from \"./state-tools.js\"\n\nexport interface DebugToolDependencies extends RunToolDependencies {\n registry: SessionRegistry\n runFor(session: DebugSession): RunService\n collectorFor(session: DebugSession): PublicCollectorService\n probesFor(session: DebugSession): ProbeRegistry\n evidenceFor(session: DebugSession): EvidenceStore\n cleanupFor(session: DebugSession): CleanupService\n}\n\nexport type DebugTools = {\n debug_session_start: ToolDefinition\n debug_session_status: ToolDefinition\n debug_state_read: ToolDefinition\n debug_state_checkpoint: ToolDefinition\n debug_run_start: ToolDefinition\n debug_process_capture: ToolDefinition\n debug_collector_start: ToolDefinition\n debug_probe_prepare: ToolDefinition\n debug_probe_register: ToolDefinition\n debug_evidence_read: ToolDefinition\n debug_cleanup: ToolDefinition\n}\n\nexport function createDebugTools(dependencies: DebugToolDependencies): DebugTools {\n return {\n debug_session_start: createSessionStartTool(dependencies.registry),\n debug_session_status: createSessionStatusTool(dependencies.registry),\n debug_state_read: createStateReadTool(dependencies.registry),\n debug_state_checkpoint: createStateCheckpointTool(dependencies.registry),\n debug_run_start: createRunStartTool(dependencies.registry, dependencies.runFor),\n debug_process_capture: createProcessCaptureTool(dependencies),\n debug_collector_start: createCollectorStartTool(dependencies.registry, dependencies.collectorFor),\n debug_probe_prepare: createProbePrepareTool(dependencies.registry, dependencies.probesFor),\n debug_probe_register: createProbeRegisterTool(dependencies.registry, dependencies.probesFor),\n debug_evidence_read: createEvidenceReadTool(dependencies.registry, dependencies.evidenceFor),\n debug_cleanup: createCleanupTool(dependencies.registry, dependencies.cleanupFor),\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,cAAc;AACvB,OAAOC,YAAU;;;ACFjB,SAAS,SAAAC,cAAa;AACtB,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,YAAAC,WAAU,MAAAC,WAAU;AAC7B,SAAS,eAAAC,oBAAmB;;;ACH5B,SAAS,UAAU,iBAAiB;AACpC,SAAS,YAAY,QAAyB,aAAa;AAO3D,IAAM,iBAAiB;AACvB,IAAM,aAAa,EAAE,SAAS,GAAG,cAAc,MAAM,KAAK,KAAK;AAE/D,SAAS,aAAa,MAAuC;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,QACtF;AAAA,MACF;AAAA,MACA,mCAAmC,OAAO,EAAE,UAAU,GAAG,WAAW;AAClE,YAAI,MAAM,SAAS,WAAW,SAAS,GAAG;AACxC,iBAAO,QAAQ;AAAA,YACb;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,MACA,SAAS,YAAY;AACnB,mBAAW,WAAW,SAAS,WAAW,GAAG;AAC3C,gBAAM,WAAW,OAAO,EAAE,QAAQ,IAAI;AAAA,YACpC,QAAQ;AAAA,YACR,aAAa,eAAe,aAAa,8BAA8B;AAAA,UACzE,CAAC;AAAA,QACH;AACA,cAAM,SAAS,SAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,kBAA0B,sBAAsB;","names":["readFile","path","spawn","createHash","readFile","rm","performance","error","matches","index","readFile","writeFile","error","error","createHash","mkdir","readFile","realpath","writeFile","path","value","z","z","z","z","error","z","createHash","writeFile","realpath","path","mkdir","readFile","error","performance","result","rm","error","readFile","createHash","spawn","randomBytes","z","createHash","z","error","randomBytes","randomBytes","error","randomBytes","performance","appendFile","z","z","z","createReadStream","createReadStream","error","z","appendFile","error","createHash","mkdir","realpath","writeFile","path","realpath","path","mkdir","writeFile","sha256","createHash","createHash","randomBytes","readFile","realpath","path","randomBytes","sha256","createHash","run","path","realpath","readFile","occurrences","createHash","randomBytes","path","z","randomBytes","path","createHash","result","randomBytes","randomBytes","lstat","readdir","realpath","path","readFile","stat","randomBytes","rename","rm","path","error","stat","error","readFile","readFile","realpath","stat","path","stat","error","readFile","realpath","path","randomBytes","readFile","writeFile","error","path","realpath","error","readdir","lstat","createHash","randomBytes","lstat","readdir","realpath","rm","path","createHash","realpath","randomBytes","path","error","rm","readdir","matches","lstat","path","error","error","path","error","tool","schema","tool","error","tool","schema","tool","error","path","tool","schema","tool","path","error","path","tool","schema","tool","path","error","tool","schema","tool","error","tool","schema","tool","error","DebugModeError","readFile","path","error"]}
1
+ {"version":3,"sources":["../src/plugin.ts","../src/cleanup/service.ts","../src/probes/extension-permissions.ts","../src/probes/remove.ts","../src/process/tree.ts","../src/core/constants.ts","../src/cleanup/export.ts","../src/evidence/sanitize.ts","../src/evidence/types.ts","../src/core/schemas.ts","../src/investigation/schema.ts","../src/session/paths.ts","../src/cleanup/types.ts","../src/collector/ingest.ts","../src/collector/body.ts","../src/collector/auth.ts","../src/collector/router.ts","../src/collector/server.ts","../src/core/clock.ts","../src/evidence/store.ts","../src/session/types.ts","../src/evidence/read.ts","../src/probes/helper.ts","../src/probes/registry.ts","../src/probes/types.ts","../src/probes/template.ts","../src/process/service.ts","../src/process/line-decoder.ts","../src/process/protocol.ts","../src/run/service.ts","../src/session/orphan-recovery.ts","../src/investigation/store.ts","../src/session/atomic-json.ts","../src/session/manifest-store.ts","../src/session/secret-store.ts","../src/session/registry.ts","../src/tools/cleanup-tool.ts","../src/core/result.ts","../src/tools/common.ts","../src/tools/collector-tools.ts","../src/tools/evidence-tools.ts","../src/tools/probe-tools.ts","../src/tools/run-tools.ts","../src/tools/session-tools.ts","../src/tools/state-tools.ts","../src/tools/index.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\nimport type { Config, Plugin } from \"@opencode-ai/plugin\"\nimport { CleanupService } from \"./cleanup/service.js\"\nimport type { FinalReportInput } from \"./cleanup/types.js\"\nimport { createIngestHandler } from \"./collector/ingest.js\"\nimport { createCollectorRouter } from \"./collector/router.js\"\nimport { CollectorServer } from \"./collector/server.js\"\nimport type { Clock } from \"./core/clock.js\"\nimport { systemClock } from \"./core/clock.js\"\nimport { TEMP_BASE_NAME } from \"./core/constants.js\"\nimport { DebugModeError } from \"./core/errors.js\"\nimport { EvidenceStore } from \"./evidence/store.js\"\nimport { addLoopbackPermission, removeLoopbackPermission } from \"./probes/extension-permissions.js\"\nimport { TransportHelper } from \"./probes/helper.js\"\nimport { ProbeRegistry } from \"./probes/registry.js\"\nimport { ProcessService } from \"./process/service.js\"\nimport { RunService } from \"./run/service.js\"\nimport { recoverOrphans } from \"./session/orphan-recovery.js\"\nimport { isContained } from \"./session/paths.js\"\nimport { type DebugSession, SessionRegistry } from \"./session/registry.js\"\nimport { createDebugTools } from \"./tools/index.js\"\n\ntype SessionServices = {\n evidence: EvidenceStore\n runs: RunService\n probes: ProbeRegistry\n process: ProcessService\n collectorServer?: CollectorServer\n collector: {\n start(input: {\n runtime: \"web\" | \"extension-background\"\n transportTargetPath?: string\n extensionManifestPath?: string\n }): Promise<{\n collectorId: string\n host: \"127.0.0.1\" | \"::1\"\n port: number\n status: string\n helperImport?: string\n helperPath?: string\n }>\n }\n cleanup: CleanupService\n}\n\nasync function updateManifest(session: DebugSession, mutate: Parameters<DebugSession[\"manifestStore\"][\"modify\"]>[0]) {\n return session.manifestStore.modify(mutate)\n}\n\nfunction terminalReport(outcome: \"abandoned\" | \"escalated\", reason: string): FinalReportInput {\n return {\n outcome,\n rootCause: reason,\n decidingEvidence: [],\n hypotheses: [],\n fix: \"No additional fix was applied during lifecycle cleanup\",\n changedFiles: [],\n verification: [\"Package-owned resources were cleaned by the lifecycle hook\"],\n }\n}\n\nexport type DebugModePluginOptions = Readonly<{\n clock?: Clock\n tempBase?: string\n}>\n\nexport function createDebugModePlugin(options: DebugModePluginOptions = {}): Plugin {\n return async (input) => {\n const prompt = await readFile(new URL(\"../assets/debug-agent.md\", import.meta.url), \"utf8\")\n const tempBase = options.tempBase ?? path.join(tmpdir(), TEMP_BASE_NAME)\n const clock = options.clock ?? systemClock\n const recovery = await recoverOrphans({ tempBase, now: clock.now() }).catch((error) => ({\n cleaned: [],\n ignored: [],\n errors: [{ directory: \"<temp-base>\", reason: error instanceof Error ? error.name : \"recovery-failed\" }],\n }))\n if (recovery.errors.length > 0) {\n await input.client.app.log({\n body: {\n service: \"opencode-debug-mode\",\n level: \"warn\",\n message: `Orphan recovery reported ${recovery.errors.length} failure(s)`,\n },\n })\n }\n const services = new Map<string, SessionServices>()\n let registry: SessionRegistry\n\n const forSession = (session: DebugSession): SessionServices => {\n const existing = services.get(session.publicId)\n if (existing !== undefined) return existing\n const evidence = new EvidenceStore(\n session.paths.evidenceFile,\n async (counters) => {\n await updateManifest(session, (manifest) => ({ ...manifest, counters })).catch(() => undefined)\n },\n clock,\n async () => (await session.manifestStore.read()).counters,\n )\n const runs = new RunService(session.manifestStore, clock, (kind) =>\n registry.acquireLeaseForSession(session, kind),\n )\n const probes = new ProbeRegistry(session.manifestStore, session.projectRoot, async (id) => {\n const state = await session.investigationStore.read()\n return state.hypotheses.some((hypothesis) => hypothesis.id === id)\n })\n const sampleCounts = new Map<string, number>()\n const processService = new ProcessService({\n session,\n runs,\n evidence,\n probes,\n acquireLease: async () => registry.acquireLeaseForSession(session, \"process\"),\n })\n let collectorServer: CollectorServer | undefined\n const collector = {\n start: async (request: {\n runtime: \"web\" | \"extension-background\"\n transportTargetPath?: string\n extensionManifestPath?: string\n }) => {\n const manifest = await session.manifestStore.read()\n if (manifest.collector !== null) throw new DebugModeError(\"COLLECTOR_EXISTS\", \"A collector is already active\")\n const ingest = createIngestHandler({\n evidence,\n validateEvent: (event) => probes.validateEvent(event),\n sample: async (event) => {\n const probe = (await session.manifestStore.read()).probes.find(\n (candidate) => candidate.id === event.probeId,\n )\n if (probe?.sampling.mode !== \"every\" || probe.sampling.n === 1) return false\n const count = (sampleCounts.get(probe.id) ?? 0) + 1\n sampleCounts.set(probe.id, count)\n return count % probe.sampling.n !== 0\n },\n })\n collectorServer = new CollectorServer(\n createCollectorRouter({\n token: session.secret,\n ingest,\n onAuthenticated: () => registry.touchSession(session),\n }),\n async () => {\n await service.cleanup.run({\n reason: \"collector-failure\",\n finalReport: terminalReport(\"escalated\", \"Collector failed\"),\n })\n },\n )\n const handle = await collectorServer.start()\n let permissionChange: Awaited<ReturnType<typeof addLoopbackPermission>> | undefined\n if (request.extensionManifestPath !== undefined) {\n if (request.runtime !== \"extension-background\") {\n await collectorServer.close()\n throw new DebugModeError(\n \"PERMISSION_MISMATCH\",\n \"Extension permissions require extension-background runtime\",\n )\n }\n const manifestPath = path.resolve(session.projectRoot, request.extensionManifestPath)\n if (!isContained(session.projectRoot, manifestPath)) {\n await collectorServer.close()\n throw new DebugModeError(\"PERMISSION_MISMATCH\", \"Extension manifest must be inside the project\")\n }\n const host = handle.host === \"::1\" ? \"[::1]\" : handle.host\n permissionChange = await addLoopbackPermission(manifestPath, `http://${host}:${handle.port}/*`)\n }\n try {\n await updateManifest(session, (value) => ({\n ...value,\n collector: {\n id: handle.id,\n host: handle.host,\n port: handle.port,\n status: \"ready\",\n startedAt: clock.now().toISOString(),\n },\n permissionChanges:\n permissionChange === undefined\n ? value.permissionChanges\n : [...value.permissionChanges, permissionChange],\n }))\n } catch (error) {\n if (permissionChange !== undefined) {\n await removeLoopbackPermission(permissionChange.manifestPath, permissionChange).catch(() => undefined)\n }\n await collectorServer.close()\n throw error\n }\n let helper: Awaited<ReturnType<TransportHelper[\"create\"]>> | undefined\n if (request.transportTargetPath !== undefined) {\n const transportHelper = new TransportHelper(session.projectRoot, async (owned) => {\n await updateManifest(session, (value) => ({\n ...value,\n ownedFiles: [...value.ownedFiles, { ...owned, kind: \"transport-helper\" }],\n }))\n })\n helper = await transportHelper.create({\n targetPath: request.transportTargetPath,\n host: handle.host,\n port: handle.port,\n token: session.secret,\n runtime: request.runtime,\n })\n }\n return {\n collectorId: handle.id,\n host: handle.host,\n port: handle.port,\n status: handle.status,\n ...(helper === undefined ? {} : { helperImport: helper.requiredImport, helperPath: helper.relativePath }),\n }\n },\n }\n const cleanup = new CleanupService(session, {\n collector: { close: async () => collectorServer?.close() },\n })\n const service: SessionServices = {\n evidence,\n runs,\n probes,\n process: processService,\n collector,\n cleanup,\n ...(collectorServer === undefined ? {} : { collectorServer }),\n }\n services.set(session.publicId, service)\n return service\n }\n\n registry = new SessionRegistry(tempBase, clock, async (session) => {\n const result = await forSession(session).cleanup.run({\n reason: \"idle-expired\",\n finalReport: terminalReport(\"abandoned\", \"Debug session expired after inactivity\"),\n })\n services.delete(session.publicId)\n if (result.status === \"partial\") {\n await input.client.app.log({\n body: {\n service: \"opencode-debug-mode\",\n level: \"warn\",\n message: \"Idle session cleanup completed with partial failures\",\n },\n })\n }\n })\n\n const tools = createDebugTools({\n registry,\n runFor: (session) => forSession(session).runs,\n processFor: (session) => forSession(session).process,\n collectorFor: (session) => forSession(session).collector,\n probesFor: (session) => forSession(session).probes,\n evidenceFor: (session) => forSession(session).evidence,\n cleanupFor: (session) => forSession(session).cleanup,\n })\n\n const logCollision = (name: string) => {\n void input.client.app.log({\n body: { service: \"opencode-debug-mode\", level: \"warn\", message: `Replacing conflicting ${name} configuration` },\n })\n }\n\n return {\n config: async (config: Config) => {\n if (config.agent?.debug !== undefined) logCollision(\"agent.debug\")\n if (config.command?.debug !== undefined) logCollision(\"command.debug\")\n config.agent ??= {}\n config.command ??= {}\n // OpenCode accepts arbitrary permission names, while its generated 1.x Config type lists only legacy keys.\n const permission: Record<string, \"allow\" | \"ask\" | \"deny\"> = { question: \"allow\" }\n config.agent.debug = {\n mode: \"primary\",\n description: \"Hypothesis-driven runtime debugging\",\n prompt,\n permission,\n }\n config.command.debug = {\n description: \"Start hypothesis-driven runtime debugging\",\n agent: \"debug\",\n template: \"$ARGUMENTS\",\n }\n },\n tool: tools,\n event: async ({ event }) => {\n if (event.type !== \"session.deleted\") return\n const trustedId = event.properties.info.id\n try {\n const session = await registry.requireOwned(trustedId)\n await forSession(session).cleanup.run({\n reason: \"session-deleted\",\n finalReport: terminalReport(\"abandoned\", \"OpenCode session was deleted\"),\n })\n registry.forgetTrusted(trustedId)\n } catch (error) {\n if (!(error instanceof DebugModeError && error.code === \"NO_ACTIVE_SESSION\")) throw error\n }\n },\n \"experimental.session.compacting\": async ({ sessionID }, output) => {\n if (await registry.hasTrusted(sessionID)) {\n output.context.push(\n \"An opencode-debug-mode investigation is active. Before any next action, call debug_state_read and reconcile its revision, phase, completed checks, evidence references, and nextAction. Do not repeat a conclusive check unless the checkpoint records invalidating evidence.\",\n )\n }\n },\n dispose: async () => {\n for (const session of registry.listActive()) {\n await forSession(session).cleanup.run({\n reason: \"plugin-dispose\",\n finalReport: terminalReport(\"abandoned\", \"OpenCode plugin was disposed\"),\n })\n }\n await registry.closeAll()\n },\n }\n }\n}\n\nexport const DebugModePlugin: Plugin = createDebugModePlugin()\n","import { spawn } from \"node:child_process\"\nimport { createHash } from \"node:crypto\"\nimport { readFile, rm } from \"node:fs/promises\"\nimport { performance } from \"node:perf_hooks\"\nimport type { z } from \"zod\"\nimport type { CollectorServer } from \"../collector/server.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { removeLoopbackPermission } from \"../probes/extension-permissions.js\"\nimport { removeOwnedProbe } from \"../probes/remove.js\"\nimport { terminateTree } from \"../process/tree.js\"\nimport type { DebugSession } from \"../session/registry.js\"\nimport type { OwnedFileManifestSchema, ProcessManifestSchema } from \"../session/types.js\"\nimport { finalizeRetainedBundle, type StagedBundle, stageRetainedBundle } from \"./export.js\"\nimport { type CleanupResult, type FinalReportInput, FinalReportInputSchema } from \"./types.js\"\n\ntype OwnedFile = z.infer<typeof OwnedFileManifestSchema>\ntype OwnedProcess = z.infer<typeof ProcessManifestSchema>\ntype ResourceResult = CleanupResult[\"resources\"][\"collector\"]\n\nexport class CleanupService {\n private running: Promise<CleanupResult> | undefined\n private completed: CleanupResult | undefined\n\n constructor(\n private readonly session: DebugSession,\n private readonly dependencies: {\n collector?: Pick<CollectorServer, \"close\">\n terminateProcess?: (process: OwnedProcess) => Promise<ResourceResult>\n removeSecret?: () => Promise<\"success\" | \"already-clean\">\n securityValues?: string[]\n } = {},\n ) {}\n\n async run(input: {\n reason: string\n finalReport: FinalReportInput\n cleanCheck?: { executable: string; args: string[]; cwd: string; timeoutMs: number }\n }): Promise<CleanupResult> {\n if (this.completed !== undefined) return this.completed\n this.running ??= this.execute(input)\n this.completed = await this.running\n return this.completed\n }\n\n private async execute(input: {\n reason: string\n finalReport: FinalReportInput\n cleanCheck?: { executable: string; args: string[]; cwd: string; timeoutMs: number }\n }): Promise<CleanupResult> {\n const started = performance.now()\n const finalReport = FinalReportInputSchema.parse(input.finalReport)\n const manifest = await this.session.manifestStore\n .modify((value) => ({\n ...value,\n status: \"cleaning\",\n cleanup: { status: \"running\", completedResources: [] },\n }))\n .catch(() => this.session.manifestStore.read())\n const state = await this.session.investigationStore.read().catch(() => undefined)\n if (state !== undefined) {\n await this.session.investigationStore\n .checkpoint(state.revision, {\n ...state,\n phase: \"cleaning\",\n cleanup: { status: \"running\", completedResources: state.cleanup.completedResources },\n })\n .catch(() => undefined)\n }\n\n let collector: ResourceResult = { status: \"skipped\", reason: \"not-running\" }\n if (manifest.collector !== null) {\n if (this.dependencies.collector === undefined)\n collector = { status: \"failed\", reason: \"collector-runtime-unavailable\" }\n else {\n try {\n await this.dependencies.collector.close()\n collector = { status: \"success\" }\n } catch {\n collector = { status: \"failed\", reason: \"collector-close-failed\" }\n }\n }\n }\n\n const processes: ResourceResult[] = []\n for (const owned of manifest.processes) {\n try {\n if (this.dependencies.terminateProcess !== undefined)\n processes.push(await this.dependencies.terminateProcess(owned))\n else if (owned.targetPid !== undefined) {\n const result = await terminateTree(owned.targetPid)\n processes.push(result.remaining ? { status: \"failed\", reason: \"process-remains\" } : { status: \"success\" })\n } else processes.push({ status: \"already-clean\" })\n } catch {\n processes.push({ status: \"failed\", reason: \"process-termination-failed\" })\n }\n }\n\n const probes: ResourceResult[] = []\n for (const probe of manifest.probes) {\n const result = await removeOwnedProbe(probe)\n probes.push({\n status: result.status === \"already-clean\" ? \"already-clean\" : result.status,\n ...(result.reason === undefined ? {} : { reason: result.reason }),\n location: probe.sourceFile,\n })\n }\n\n const permissions: ResourceResult[] = []\n for (const change of manifest.permissionChanges) {\n const result = await removeLoopbackPermission(change.manifestPath, change)\n permissions.push({\n status: result.status,\n ...(result.reason === undefined ? {} : { reason: result.reason }),\n location: change.manifestPath,\n })\n }\n\n const files: ResourceResult[] = []\n for (const owned of manifest.ownedFiles) files.push(await this.removeOwnedFile(owned))\n\n const cleanCheck = input.cleanCheck === undefined ? undefined : await this.runCleanCheck(input.cleanCheck)\n let staged: StagedBundle | undefined\n if (manifest.keepArtifacts && manifest.retentionDestination !== undefined) {\n try {\n staged = await stageRetainedBundle({\n keepArtifacts: true,\n destination: manifest.retentionDestination,\n sessionDir: manifest.sessionDir,\n evidenceFile: this.session.paths.evidenceFile,\n stateFile: this.session.paths.stateFile,\n token: this.session.secret,\n securityValues: this.dependencies.securityValues ?? [],\n finalReport,\n })\n } catch {\n files.push({ status: \"failed\", reason: \"retention-export-failed\" })\n }\n }\n\n let secret: ResourceResult\n try {\n const status = await (this.dependencies.removeSecret?.() ?? this.session.secretStore.remove())\n secret = { status }\n } catch {\n secret = { status: \"failed\", reason: \"secret-removal-failed\" }\n }\n\n let sessionDirectory: ResourceResult\n try {\n await rm(this.session.paths.sessionDir, { recursive: true, force: true })\n sessionDirectory = { status: \"success\" }\n } catch {\n sessionDirectory = { status: \"failed\", reason: \"session-directory-removal-failed\" }\n }\n\n const resources = { collector, processes, probes, permissions, files, secret, sessionDirectory }\n const failures = [collector, ...processes, ...probes, ...permissions, ...files, secret, sessionDirectory].filter(\n (result) => result.status === \"failed\",\n )\n const remainingArtifacts = failures.flatMap((result) => (result.location === undefined ? [] : [result.location]))\n const result: CleanupResult = {\n status: failures.length === 0 ? \"complete\" : \"partial\",\n reason: input.reason.slice(0, 256),\n resources,\n remainingArtifacts,\n durationMs: performance.now() - started,\n ...(cleanCheck === undefined ? {} : { cleanCheck }),\n }\n if (staged !== undefined) {\n try {\n const retained = await finalizeRetainedBundle(staged, result)\n result.retainedArtifactLocation = retained.path\n } catch (error) {\n result.status = \"partial\"\n result.resources.files.push({\n status: \"failed\",\n reason:\n error instanceof DebugModeError\n ? `retention-finalize-failed:${error.code}:${error.message}`.slice(0, 8_192)\n : \"retention-finalize-failed\",\n })\n }\n }\n return result\n }\n\n private async removeOwnedFile(owned: OwnedFile): Promise<ResourceResult> {\n try {\n const content = await readFile(owned.path)\n if (createHash(\"sha256\").update(content).digest(\"hex\") !== owned.sha256 || content.byteLength !== owned.bytes) {\n return { status: \"failed\", reason: \"owned-file-hash-mismatch\", location: owned.path }\n }\n await rm(owned.path)\n return { status: \"success\", location: owned.path }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { status: \"already-clean\", location: owned.path }\n return { status: \"failed\", reason: \"owned-file-removal-failed\", location: owned.path }\n }\n }\n\n private runCleanCheck(input: { executable: string; args: string[]; cwd: string; timeoutMs: number }) {\n const started = performance.now()\n return new Promise<NonNullable<CleanupResult[\"cleanCheck\"]>>((resolve) => {\n const child = spawn(input.executable, input.args, {\n cwd: input.cwd,\n shell: false,\n stdio: \"ignore\",\n windowsHide: true,\n })\n let timedOut = false\n const timeout = setTimeout(() => {\n timedOut = true\n child.kill(\"SIGKILL\")\n }, input.timeoutMs)\n child.once(\"exit\", (exitCode) => {\n clearTimeout(timeout)\n resolve({\n command: [input.executable, ...input.args].join(\" \").slice(0, 8_192),\n exitCode,\n timedOut,\n durationMs: performance.now() - started,\n })\n })\n child.once(\"error\", () => {\n clearTimeout(timeout)\n resolve({\n command: input.executable.slice(0, 8_192),\n exitCode: null,\n timedOut,\n durationMs: performance.now() - started,\n })\n })\n })\n }\n}\n","import { readFile, writeFile } from \"node:fs/promises\"\nimport { applyEdits, modify, type ParseError, parse } from \"jsonc-parser\"\nimport type { z } from \"zod\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport type { PermissionChangeSchema } from \"../session/types.js\"\n\nexport type PermissionChange = z.infer<typeof PermissionChangeSchema>\n\nconst LOOPBACK_MATCH = /^http:\\/\\/(?:127\\.0\\.0\\.1:\\d{1,5}|\\[::1\\]:\\d{1,5})\\/\\*$/u\nconst formatting = { tabSize: 2, insertSpaces: true, eol: \"\\n\" }\n\nfunction readManifest(text: string): Record<string, unknown> {\n const errors: ParseError[] = []\n const value = parse(text, errors, { allowTrailingComma: true, disallowComments: false }) as unknown\n if (errors.length > 0 || typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new DebugModeError(\"PERMISSION_MISMATCH\", \"Extension manifest is invalid\")\n }\n return value as Record<string, unknown>\n}\n\nfunction permissionProperty(manifest: Record<string, unknown>): \"permissions\" | \"host_permissions\" {\n if (manifest.manifest_version === 2) return \"permissions\"\n if (manifest.manifest_version === 3) return \"host_permissions\"\n throw new DebugModeError(\"PERMISSION_MISMATCH\", \"Extension manifest version must be 2 or 3\")\n}\n\nexport async function addLoopbackPermission(manifestPath: string, matchPattern: string): Promise<PermissionChange> {\n if (!LOOPBACK_MATCH.test(matchPattern)) {\n throw new DebugModeError(\"PERMISSION_MISMATCH\", \"Only an exact active loopback match pattern is allowed\")\n }\n const text = await readFile(manifestPath, \"utf8\")\n const manifest = readManifest(text)\n const property = permissionProperty(manifest)\n const current = manifest[property]\n if (current !== undefined && (!Array.isArray(current) || current.some((entry) => typeof entry !== \"string\"))) {\n throw new DebugModeError(\"PERMISSION_MISMATCH\", `Extension ${property} must be a string array`)\n }\n const permissions = (current ?? []) as string[]\n if (permissions.includes(matchPattern)) {\n return { manifestPath, property, matchPattern, addedBySession: false }\n }\n const edits = Array.isArray(current)\n ? modify(text, [property, permissions.length], matchPattern, {\n formattingOptions: formatting,\n isArrayInsertion: true,\n })\n : modify(text, [property], [matchPattern], { formattingOptions: formatting })\n await writeFile(manifestPath, applyEdits(text, edits), \"utf8\")\n return { manifestPath, property, matchPattern, addedBySession: true }\n}\n\nexport async function removeLoopbackPermission(\n manifestPath: string,\n change: PermissionChange,\n): Promise<{ status: \"success\" | \"already-clean\" | \"failed\"; reason?: string }> {\n if (!change.addedBySession) return { status: \"already-clean\" }\n let text: string\n try {\n text = await readFile(manifestPath, \"utf8\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { status: \"already-clean\" }\n return { status: \"failed\", reason: \"manifest-read-failed\" }\n }\n let manifest: Record<string, unknown>\n try {\n manifest = readManifest(text)\n } catch {\n return { status: \"failed\", reason: \"manifest-invalid\" }\n }\n if (permissionProperty(manifest) !== change.property) return { status: \"failed\", reason: \"manifest-version-changed\" }\n const current = manifest[change.property]\n if (current === undefined) return { status: \"already-clean\" }\n if (!Array.isArray(current) || current.some((entry) => typeof entry !== \"string\")) {\n return { status: \"failed\", reason: \"permission-structure-changed\" }\n }\n const matches = current.flatMap((entry, index) => (entry === change.matchPattern ? [index] : []))\n if (matches.length === 0) return { status: \"already-clean\" }\n if (matches.length !== 1) return { status: \"failed\", reason: \"permission-ambiguous\" }\n const index = matches[0]\n if (index === undefined) return { status: \"already-clean\" }\n const edits = modify(text, [change.property, index], undefined, { formattingOptions: formatting })\n await writeFile(manifestPath, applyEdits(text, edits), \"utf8\")\n return { status: \"success\" }\n}\n","import { createHash } from \"node:crypto\"\nimport { readFile, writeFile } from \"node:fs/promises\"\nimport type { ManifestProbe } from \"../session/types.js\"\n\nexport type ProbeRemovalResult =\n | { status: \"success\"; file: string; reason?: never }\n | { status: \"already-clean\"; file: string; reason?: never }\n | { status: \"failed\"; file: string; reason: string; line?: number }\n\nfunction occurrences(value: string, needle: string): number {\n if (needle.length === 0) return 0\n return value.split(needle).length - 1\n}\n\nfunction lineAt(value: string, index: number): number {\n return value.slice(0, index).split(/\\r?\\n/u).length\n}\n\nexport async function removeOwnedProbe(probe: ManifestProbe): Promise<ProbeRemovalResult> {\n for (let attempt = 0; attempt < 2; attempt += 1) {\n let source: string\n try {\n source = await readFile(probe.sourceFile, \"utf8\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { status: \"already-clean\", file: probe.sourceFile }\n return { status: \"failed\", file: probe.sourceFile, reason: \"source-read-failed\" }\n }\n const starts = occurrences(source, probe.markerStart)\n const ends = occurrences(source, probe.markerEnd)\n if (starts === 0 && ends === 0) return { status: \"already-clean\", file: probe.sourceFile }\n const startIndex = source.indexOf(probe.markerStart)\n if (starts !== 1 || ends !== 1 || startIndex < 0) {\n return {\n status: \"failed\",\n file: probe.sourceFile,\n reason: \"marker-ambiguous\",\n ...(startIndex < 0 ? {} : { line: lineAt(source, startIndex) }),\n }\n }\n if (probe.expectedBlock === undefined || probe.expectedHash === undefined) {\n return {\n status: \"failed\",\n file: probe.sourceFile,\n reason: \"marker-ownership-incomplete\",\n line: lineAt(source, startIndex),\n }\n }\n if (\n occurrences(source, probe.expectedBlock) !== 1 ||\n createHash(\"sha256\").update(probe.expectedBlock).digest(\"hex\") !== probe.expectedHash\n ) {\n return {\n status: \"failed\",\n file: probe.sourceFile,\n reason: \"marker-content-mismatch\",\n line: lineAt(source, startIndex),\n }\n }\n const current = await readFile(probe.sourceFile, \"utf8\")\n if (current !== source) continue\n const blockIndex = source.indexOf(probe.expectedBlock)\n const next = source.slice(0, blockIndex) + source.slice(blockIndex + probe.expectedBlock.length)\n await writeFile(probe.sourceFile, next, \"utf8\")\n return { status: \"success\", file: probe.sourceFile }\n }\n return { status: \"failed\", file: probe.sourceFile, reason: \"concurrent-source-change\" }\n}\n","import { spawn } from \"node:child_process\"\nimport { performance } from \"node:perf_hooks\"\nimport { LIMITS } from \"../core/constants.js\"\n\nexport type Execute = (executable: string, args: string[]) => Promise<{ exitCode: number | null }>\n\nexport type TerminationResult = Readonly<{\n graceful: boolean\n forced: boolean\n remaining: boolean\n durationMs: number\n errors: string[]\n}>\n\nconst defaultExecute: Execute = (executable, args) =>\n new Promise((resolve, reject) => {\n const child = spawn(executable, args, { shell: false, windowsHide: true, stdio: \"ignore\" })\n child.once(\"error\", reject)\n child.once(\"exit\", (exitCode) => resolve({ exitCode }))\n })\n\nfunction isAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== \"ESRCH\"\n }\n}\n\nasync function waitForExit(pid: number, milliseconds: number): Promise<boolean> {\n const deadline = performance.now() + milliseconds\n while (performance.now() < deadline) {\n if (!isAlive(pid)) return true\n await new Promise<void>((resolve) => setTimeout(resolve, 20))\n }\n return !isAlive(pid)\n}\n\nfunction safeError(error: unknown): string {\n const code = (error as NodeJS.ErrnoException).code\n return typeof code === \"string\" ? code.slice(0, 64) : \"termination-failed\"\n}\n\nexport async function terminateTree(\n targetPid: number,\n options: {\n platform?: NodeJS.Platform\n execute?: Execute\n gracefulMs?: number\n forceMs?: number\n } = {},\n): Promise<TerminationResult> {\n const started = performance.now()\n const errors: string[] = []\n let graceful = false\n let forced = false\n const platform = options.platform ?? process.platform\n const gracefulMs = options.gracefulMs ?? LIMITS.gracefulKillMs\n const forceMs = options.forceMs ?? LIMITS.forcedKillMs\n\n if (!Number.isInteger(targetPid) || targetPid <= 0) {\n return {\n graceful: false,\n forced: false,\n remaining: false,\n durationMs: performance.now() - started,\n errors: [\"invalid-pid\"],\n }\n }\n\n if (platform === \"win32\") {\n const execute = options.execute ?? defaultExecute\n try {\n const result = await execute(\"taskkill\", [\"/PID\", String(targetPid), \"/T\"])\n graceful = result.exitCode === 0\n } catch (error) {\n errors.push(safeError(error))\n }\n await waitForExit(targetPid, gracefulMs)\n try {\n const result = await execute(\"taskkill\", [\"/PID\", String(targetPid), \"/T\", \"/F\"])\n forced = result.exitCode === 0\n } catch (error) {\n errors.push(safeError(error))\n }\n await waitForExit(targetPid, forceMs)\n } else {\n try {\n process.kill(-targetPid, \"SIGTERM\")\n graceful = true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ESRCH\") {\n return { graceful: false, forced: false, remaining: false, durationMs: performance.now() - started, errors }\n }\n errors.push(safeError(error))\n }\n if (!(await waitForExit(targetPid, gracefulMs))) {\n try {\n process.kill(-targetPid, \"SIGKILL\")\n forced = true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ESRCH\") errors.push(safeError(error))\n }\n await waitForExit(targetPid, forceMs)\n }\n }\n\n return {\n graceful,\n forced,\n remaining: isAlive(targetPid),\n durationMs: performance.now() - started,\n errors,\n }\n}\n","export const PACKAGE_ID = \"opencode-debug-mode\" as const\nexport const MANIFEST_SCHEMA_VERSION = 1 as const\nexport const STATE_SCHEMA_VERSION = 1 as const\nexport const EVENT_SCHEMA_VERSION = 1 as const\nexport const TEMP_BASE_NAME = \"opencode-debug-mode-v1\" as const\nexport const PROCESS_EVENT_PREFIX = \"__OPENCODE_DEBUG_EVENT_V1__\" as const\n\nexport const LIMITS = Object.freeze({\n requestBytes: 64 * 1024,\n scalarBytes: 8 * 1024,\n events: 25_000,\n evidenceBytes: 25 * 1024 * 1024,\n checkpointBytes: 256 * 1024,\n eventsPerBatch: 100,\n idleMs: 30 * 60 * 1000,\n collectorReadyMs: 2_000,\n cleanupMs: 5_000,\n gracefulKillMs: 750,\n forcedKillMs: 1_500,\n noSignalIterations: 3,\n})\n","import { createHash, randomBytes } from \"node:crypto\"\nimport { createReadStream } from \"node:fs\"\nimport { appendFile, mkdir, readdir, readFile, realpath, rename, rm, writeFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { createInterface } from \"node:readline\"\nimport { PACKAGE_ID } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { sanitizeEvidenceData } from \"../evidence/sanitize.js\"\nimport { EvidenceEventSchema } from \"../evidence/types.js\"\nimport { InvestigationStateSchema } from \"../investigation/schema.js\"\nimport { isContained } from \"../session/paths.js\"\nimport { type CleanupResult, CleanupResultSchema, type FinalReportInput, FinalReportInputSchema } from \"./types.js\"\n\nexport type RetainedBundleInput = Readonly<{\n keepArtifacts: boolean\n destination?: string\n sessionDir: string\n evidenceFile: string\n stateFile: string\n token: string\n securityValues?: string[]\n finalReport: FinalReportInput\n}>\n\nexport type StagedBundle = Readonly<{\n partialPath: string\n finalPath: string\n token: string\n securityValues: string[]\n report: FinalReportInput\n eventCount: number\n}>\n\nfunction sha256(value: Buffer | string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\")\n}\n\nfunction redactKnownSecrets(value: unknown, secrets: string[]): unknown {\n if (typeof value === \"string\") {\n return secrets.reduce((text, secret) => (secret.length === 0 ? text : text.replaceAll(secret, \"[REDACTED]\")), value)\n }\n if (Array.isArray(value)) return value.map((entry) => redactKnownSecrets(entry, secrets))\n if (typeof value === \"object\" && value !== null) {\n return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, redactKnownSecrets(entry, secrets)]))\n }\n return value\n}\n\nasync function sanitizedEvidence(source: string, destination: string): Promise<number> {\n let count = 0\n await writeFile(destination, \"\", { mode: 0o600 })\n const lines = createInterface({ input: createReadStream(source), crlfDelay: Number.POSITIVE_INFINITY })\n for await (const line of lines) {\n if (line.length === 0) continue\n const event = EvidenceEventSchema.parse(JSON.parse(line))\n const sanitized = sanitizeEvidenceData(event.data)\n await appendFile(\n destination,\n `${JSON.stringify({\n ...event,\n data: sanitized.value,\n sanitization: {\n flags: [...new Set([...event.sanitization.flags, ...sanitized.flags])].sort(),\n droppedKeys: event.sanitization.droppedKeys + sanitized.droppedKeys,\n storedBytes: sanitized.storedBytes,\n ...(sanitized.originalBytes === undefined ? {} : { originalBytes: sanitized.originalBytes }),\n },\n })}\\n`,\n { mode: 0o600 },\n )\n count += 1\n }\n return count\n}\n\nfunction renderReport(report: FinalReportInput, cleanup: CleanupResult, retainedPath: string): string {\n const hypotheses = report.hypotheses.map((value) => `- ${value.id}: ${value.status} — ${value.statement}`).join(\"\\n\")\n return `# Debug investigation report\n\nOutcome: ${report.outcome}\n\n## Root cause\n\n${report.rootCause}\n\n## Deciding evidence\n\n${report.decidingEvidence.map((value) => `- ${value}`).join(\"\\n\")}\n\n## Hypotheses\n\n${hypotheses}\n\n## Fix\n\n${report.fix}\n\nChanged files: ${report.changedFiles.join(\", \")}\n\n## Verification\n\n${report.verification.map((value) => `- ${value}`).join(\"\\n\")}\n\n## Cleanup\n\nStatus: ${cleanup.status}\n\nRetained artifact: ${retainedPath}\n`\n}\n\nexport async function stageRetainedBundle(input: RetainedBundleInput): Promise<StagedBundle> {\n if (!input.keepArtifacts || input.destination === undefined) {\n throw new DebugModeError(\"DESTINATION_REQUIRED\", \"Explicit retention is not enabled\")\n }\n let partialPath: string | undefined\n try {\n const destination = await realpath(input.destination)\n const sessionDir = await realpath(input.sessionDir)\n if (destination === sessionDir || isContained(sessionDir, destination)) {\n throw new DebugModeError(\"EXPORT_FAILED\", \"Retention destination cannot be inside the ephemeral session\")\n }\n const suffix = randomBytes(8).toString(\"hex\")\n partialPath = path.join(destination, `.partial-${PACKAGE_ID}-${suffix}`)\n const finalPath = path.join(\n destination,\n `${PACKAGE_ID}-${new Date().toISOString().replace(/[:.]/gu, \"-\")}-${suffix}`,\n )\n await mkdir(partialPath, { mode: 0o700 })\n const state = InvestigationStateSchema.parse(JSON.parse(await readFile(input.stateFile, \"utf8\")))\n const sanitizedState = InvestigationStateSchema.parse(\n sanitizeEvidenceData(redactKnownSecrets(state, [input.token, ...(input.securityValues ?? [])])).value,\n )\n await writeFile(\n path.join(partialPath, \"investigation-state.json\"),\n `${JSON.stringify(sanitizedState, null, 2)}\\n`,\n {\n mode: 0o600,\n },\n )\n const eventCount = await sanitizedEvidence(input.evidenceFile, path.join(partialPath, \"evidence.ndjson\"))\n return {\n partialPath,\n finalPath,\n token: input.token,\n securityValues: input.securityValues ?? [],\n report: FinalReportInputSchema.parse(input.finalReport),\n eventCount,\n }\n } catch (error) {\n if (partialPath !== undefined) await rm(partialPath, { recursive: true, force: true }).catch(() => undefined)\n if (error instanceof DebugModeError) throw error\n throw new DebugModeError(\"EXPORT_FAILED\", \"Retained bundle could not be staged\")\n }\n}\n\nexport async function finalizeRetainedBundle(\n staged: StagedBundle,\n cleanupInput: CleanupResult,\n): Promise<{ path: string }> {\n try {\n const cleanup = CleanupResultSchema.parse(cleanupInput)\n const report = renderReport(staged.report, cleanup, staged.finalPath)\n await writeFile(path.join(staged.partialPath, \"report.md\"), report, { mode: 0o600 })\n const publicFiles = [\"evidence.ndjson\", \"investigation-state.json\", \"report.md\"]\n const files: Record<string, { bytes: number; sha256: string }> = {}\n for (const name of publicFiles) {\n const value = await readFile(path.join(staged.partialPath, name))\n files[name] = { bytes: value.byteLength, sha256: sha256(value) }\n }\n const manifest = {\n package: PACKAGE_ID,\n schemaVersion: 1,\n createdAt: new Date().toISOString(),\n eventCount: staged.eventCount,\n files,\n }\n await writeFile(path.join(staged.partialPath, \"bundle-manifest.json\"), `${JSON.stringify(manifest, null, 2)}\\n`, {\n mode: 0o600,\n })\n for (const name of await readdir(staged.partialPath)) {\n const text = await readFile(path.join(staged.partialPath, name), \"utf8\")\n if ([staged.token, ...staged.securityValues].some((secret) => secret.length > 0 && text.includes(secret))) {\n throw new DebugModeError(\"EXPORT_FAILED\", \"Retained bundle failed its secret scan\")\n }\n }\n await rename(staged.partialPath, staged.finalPath)\n return { path: staged.finalPath }\n } catch (error) {\n await rm(staged.partialPath, { recursive: true, force: true }).catch(() => undefined)\n if (error instanceof DebugModeError) throw error\n throw new DebugModeError(\"EXPORT_FAILED\", \"Retained bundle could not be finalized\")\n }\n}\n","import { LIMITS } from \"../core/constants.js\"\nimport type { JsonValue, SanitizationFlag } from \"./types.js\"\n\nconst MAX_DEPTH = 6\nconst MAX_KEYS = 50\nconst MAX_ARRAY = 100\nconst SECRET_KEYS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"password\",\n \"passwd\",\n \"secret\",\n \"token\",\n \"access-token\",\n \"refresh-token\",\n \"api-key\",\n \"apikey\",\n \"private-key\",\n \"client-secret\",\n])\n\nexport type SanitizeResult = Readonly<{\n value: JsonValue\n flags: SanitizationFlag[]\n droppedKeys: number\n originalBytes?: number\n storedBytes: number\n}>\n\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[_\\s]+/g, \"-\")\n}\n\nfunction truncateUtf8(value: string, maximumBytes: number): string {\n if (Buffer.byteLength(value) <= maximumBytes) return value\n return Buffer.from(value)\n .subarray(0, maximumBytes)\n .toString(\"utf8\")\n .replace(/\\uFFFD$/u, \"\")\n}\n\nfunction estimateOriginalBytes(value: unknown): number | undefined {\n try {\n const serialized = JSON.stringify(value)\n return serialized === undefined ? undefined : Buffer.byteLength(serialized)\n } catch {\n return undefined\n }\n}\n\nexport function sanitizeEvidenceData(input: unknown): SanitizeResult {\n const flags = new Set<SanitizationFlag>()\n const seen = new WeakSet<object>()\n let droppedKeys = 0\n\n const visit = (value: unknown, depth: number): JsonValue => {\n if (depth > MAX_DEPTH) {\n flags.add(\"truncated\")\n return \"[TRUNCATED: depth]\"\n }\n if (value === null) return null\n if (typeof value === \"string\") {\n const truncated = truncateUtf8(value, LIMITS.scalarBytes)\n if (truncated !== value) flags.add(\"truncated\")\n return truncated\n }\n if (typeof value === \"boolean\") return value\n if (typeof value === \"number\") {\n if (Number.isFinite(value)) return value\n flags.add(\"unsupported\")\n return `[${String(value)}]`\n }\n if (typeof value === \"bigint\") {\n flags.add(\"unsupported\")\n return `[BigInt ${truncateUtf8(value.toString(), 128)}]`\n }\n if (typeof value === \"undefined\") {\n flags.add(\"unsupported\")\n return \"[undefined]\"\n }\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n flags.add(\"unsupported\")\n return `[${typeof value}]`\n }\n\n if (Buffer.isBuffer(value) || ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {\n flags.add(\"binary\")\n const length = Buffer.isBuffer(value)\n ? value.byteLength\n : value instanceof ArrayBuffer\n ? value.byteLength\n : value.byteLength\n return `[Binary ${length} bytes]`\n }\n if (value instanceof Date) return Number.isNaN(value.getTime()) ? \"[Invalid Date]\" : value.toISOString()\n if (value instanceof RegExp) {\n flags.add(\"unsupported\")\n return truncateUtf8(value.toString(), 256)\n }\n if (value instanceof Error) {\n flags.add(\"unsupported\")\n return { name: truncateUtf8(value.name, 128), message: truncateUtf8(value.message, LIMITS.scalarBytes) }\n }\n if (seen.has(value)) {\n flags.add(\"cycle\")\n return \"[CYCLE]\"\n }\n seen.add(value)\n\n if (Array.isArray(value)) {\n if (value.length > MAX_ARRAY) {\n flags.add(\"truncated\")\n droppedKeys += value.length - MAX_ARRAY\n }\n return value.slice(0, MAX_ARRAY).map((entry) => visit(entry, depth + 1))\n }\n\n const record = value as Record<string, unknown>\n try {\n if (typeof record.nodeType === \"number\" && typeof record.nodeName === \"string\") {\n flags.add(\"unsupported\")\n return `[DOM ${truncateUtf8(record.nodeName, 128)}]`\n }\n } catch {\n flags.add(\"unsupported\")\n }\n\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n flags.add(\"unsupported\")\n return `[Unsupported ${truncateUtf8(value.constructor?.name ?? \"object\", 128)}]`\n }\n\n let keys: string[]\n try {\n keys = Object.keys(record).sort()\n } catch {\n flags.add(\"unsupported\")\n return \"[Unreadable object]\"\n }\n if (keys.length > MAX_KEYS) {\n flags.add(\"truncated\")\n droppedKeys += keys.length - MAX_KEYS\n keys = keys.slice(0, MAX_KEYS)\n }\n\n const result: Record<string, JsonValue> = {}\n for (const key of keys) {\n if (SECRET_KEYS.has(normalizeKey(key))) {\n result[key] = \"[REDACTED]\"\n flags.add(\"redacted\")\n continue\n }\n try {\n result[key] = visit(record[key], depth + 1)\n } catch {\n result[key] = \"[Unreadable property]\"\n flags.add(\"unsupported\")\n }\n }\n return result\n }\n\n const value = visit(input, 0)\n const storedBytes = Buffer.byteLength(JSON.stringify(value))\n const originalBytes = estimateOriginalBytes(input)\n return {\n value,\n flags: [...flags].sort(),\n droppedKeys,\n ...(originalBytes === undefined ? {} : { originalBytes }),\n storedBytes,\n }\n}\n","import { z } from \"zod\"\nimport { EVENT_SCHEMA_VERSION, LIMITS } from \"../core/constants.js\"\nimport { IsoTimestampSchema, OpaqueIdSchema, RunLabelSchema } from \"../core/schemas.js\"\n\nexport type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }\n\nexport const SourceLocationSchema = z\n .object({\n file: z.string().min(1).max(LIMITS.scalarBytes),\n line: z.number().int().positive(),\n column: z.number().int().positive().optional(),\n })\n .strict()\n\nexport const EventInputSchema = z\n .object({\n schemaVersion: z.literal(EVENT_SCHEMA_VERSION),\n sessionId: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n runLabel: RunLabelSchema,\n hypothesisId: OpaqueIdSchema,\n probeId: OpaqueIdSchema,\n timestamp: IsoTimestampSchema,\n message: z.string().min(1).max(LIMITS.scalarBytes),\n source: SourceLocationSchema,\n data: z.unknown().optional(),\n })\n .strict()\n\nexport const SanitizationFlagSchema = z.enum([\"redacted\", \"truncated\", \"cycle\", \"binary\", \"unsupported\"])\n\nexport const EvidenceEventSchema = z\n .object({\n schemaVersion: z.literal(EVENT_SCHEMA_VERSION),\n eventId: OpaqueIdSchema,\n receivedAt: IsoTimestampSchema,\n timestamp: IsoTimestampSchema,\n sessionId: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n runLabel: RunLabelSchema,\n hypothesisId: OpaqueIdSchema,\n probeId: OpaqueIdSchema,\n kind: z.string().min(1).max(128),\n message: z.string().min(1).max(LIMITS.scalarBytes),\n data: z.unknown(),\n source: SourceLocationSchema,\n sanitization: z\n .object({\n flags: z.array(SanitizationFlagSchema),\n droppedKeys: z.number().int().nonnegative(),\n originalBytes: z.number().int().nonnegative().optional(),\n storedBytes: z.number().int().nonnegative(),\n })\n .strict(),\n })\n .strict()\n\nexport type EventInput = z.infer<typeof EventInputSchema>\nexport type EvidenceEvent = z.infer<typeof EvidenceEventSchema>\nexport type SanitizationFlag = z.infer<typeof SanitizationFlagSchema>\n\nexport type EvidenceFilter = Readonly<{\n sessionId?: string\n runId?: string\n hypothesisId?: string\n probeId?: string\n from?: string\n to?: string\n keyword?: string\n cursor?: string\n limit?: number\n}>\n","import { z } from \"zod\"\n\nexport const OpaqueIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(/^[A-Za-z0-9_-]+$/)\nexport const IsoTimestampSchema = z.string().datetime({ offset: true })\nexport const HexSha256Schema = z.string().regex(/^[a-f0-9]{64}$/)\nexport const RunLabelSchema = z.enum([\"pre-fix\", \"post-fix\"])\n\nexport type OpaqueId = z.infer<typeof OpaqueIdSchema>\n","import { z } from \"zod\"\nimport { LIMITS, STATE_SCHEMA_VERSION } from \"../core/constants.js\"\nimport { IsoTimestampSchema, OpaqueIdSchema, RunLabelSchema } from \"../core/schemas.js\"\n\nconst Text = z.string().max(LIMITS.scalarBytes)\nconst TextList = (maximum: number) => z.array(Text).max(maximum)\nconst EvidenceIds = z.array(OpaqueIdSchema).max(500)\n\nexport const HypothesisSchema = z\n .object({\n id: OpaqueIdSchema,\n rank: z.number().int().min(1).max(4),\n statement: Text,\n confirmationSignals: TextList(20),\n eliminationSignals: TextList(20),\n status: z.enum([\"open\", \"confirmed\", \"eliminated\"]),\n evidenceRefs: EvidenceIds,\n invalidatedBy: Text.optional(),\n })\n .strict()\n\nexport const CompletedCheckSchema = z\n .object({\n id: OpaqueIdSchema,\n summary: Text,\n interpretation: Text,\n conclusive: z.boolean(),\n evidenceRefs: EvidenceIds,\n completedAt: IsoTimestampSchema,\n invalidatedBy: Text.optional(),\n })\n .strict()\n\nexport const RunReferenceSchema = z\n .object({\n id: OpaqueIdSchema,\n label: RunLabelSchema,\n status: z.enum([\"planned\", \"running\", \"waiting\", \"completed\", \"failed\", \"timed_out\", \"cancelled\"]),\n evidenceRefs: EvidenceIds,\n })\n .strict()\n\nexport const ProbeReferenceSchema = z\n .object({\n id: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n hypothesisId: OpaqueIdSchema,\n sourceFile: Text,\n status: z.enum([\"planned\", \"registered\", \"validated\", \"active\", \"removed\", \"ambiguous\"]),\n })\n .strict()\n\nexport const DeveloperConfirmationSchema = z\n .object({ id: OpaqueIdSchema, statement: Text, confirmedAt: IsoTimestampSchema })\n .strict()\n\nexport const DecisionSchema = z\n .object({ id: OpaqueIdSchema, summary: Text, evidenceRefs: EvidenceIds, decidedAt: IsoTimestampSchema })\n .strict()\n\nexport const InvestigationStateSchema = z\n .object({\n schemaVersion: z.literal(STATE_SCHEMA_VERSION),\n revision: z.number().int().nonnegative(),\n updatedAt: IsoTimestampSchema,\n problemSummary: Text,\n expectedBehavior: Text,\n actualBehavior: Text,\n runtimeContext: z.object({ kind: z.enum([\"cli\", \"web\", \"extension\", \"other\"]), target: Text }).strict(),\n reproduction: z.object({ method: Text, requiresUser: z.boolean(), confirmed: z.boolean().nullable() }).strict(),\n successCriteria: TextList(50),\n phase: z.enum([\n \"intake\",\n \"hypotheses\",\n \"baseline\",\n \"instrumenting\",\n \"waiting_for_reproduction\",\n \"analyzing\",\n \"fixing\",\n \"verifying\",\n \"cleaning\",\n \"completed\",\n \"abandoned\",\n \"escalated\",\n ]),\n loopIteration: z.number().int().min(0).max(3),\n singleCauseEvidenceRef: OpaqueIdSchema.nullable(),\n hypotheses: z.array(HypothesisSchema).max(4),\n completedChecks: z.array(CompletedCheckSchema).max(100),\n runs: z.array(RunReferenceSchema).max(20),\n probeRefs: z.array(ProbeReferenceSchema).max(100),\n decidingEvidenceIds: EvidenceIds,\n developerConfirmations: z.array(DeveloperConfirmationSchema).max(100),\n decisions: z.array(DecisionSchema).max(100),\n nextAction: Text,\n instrumentedFiles: TextList(200),\n fixedFiles: TextList(200),\n cleanup: z\n .object({\n status: z.enum([\"not_started\", \"running\", \"complete\", \"partial\"]),\n completedResources: TextList(1_000),\n })\n .strict(),\n })\n .strict()\n\nexport type InvestigationState = z.infer<typeof InvestigationStateSchema>\n","import { lstat, mkdir, mkdtemp, realpath } from \"node:fs/promises\"\nimport path from \"node:path\"\n\nexport type SessionPaths = Readonly<{\n baseDir: string\n sessionDir: string\n projectRoot: string\n manifestFile: string\n secretFile: string\n stateFile: string\n evidenceFile: string\n}>\n\nexport function isContained(parent: string, child: string): boolean {\n const relative = path.relative(parent, child)\n return relative !== \"\" && !relative.startsWith(`..${path.sep}`) && relative !== \"..\" && !path.isAbsolute(relative)\n}\n\nexport async function createSessionPaths(tempBase: string, projectRoot: string): Promise<SessionPaths> {\n const absoluteBase = path.resolve(tempBase)\n try {\n const existing = await lstat(absoluteBase)\n if (existing.isSymbolicLink()) throw new Error(\"Temporary base must not be a symbolic link\")\n if (!existing.isDirectory()) throw new Error(\"Temporary base must be a directory\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n await mkdir(absoluteBase, { recursive: true, mode: 0o700 })\n }\n\n await realpath(absoluteBase)\n const canonicalProject = await realpath(projectRoot)\n const sessionDir = await mkdtemp(path.join(absoluteBase, \"session-\"))\n if (!isContained(absoluteBase, sessionDir)) throw new Error(\"Created session directory escaped the temporary base\")\n\n return Object.freeze({\n baseDir: absoluteBase,\n sessionDir,\n projectRoot: canonicalProject,\n manifestFile: path.join(sessionDir, \"manifest.json\"),\n secretFile: path.join(sessionDir, \"secret.bin\"),\n stateFile: path.join(sessionDir, \"investigation-state.json\"),\n evidenceFile: path.join(sessionDir, \"evidence.ndjson\"),\n })\n}\n","import { z } from \"zod\"\n\nexport const ResourceCleanupResultSchema = z\n .object({\n status: z.enum([\"success\", \"already-clean\", \"skipped\", \"failed\"]),\n reason: z.string().max(8_192).optional(),\n location: z.string().max(8_192).optional(),\n })\n .strict()\n\nexport const CleanupResultSchema = z\n .object({\n status: z.enum([\"complete\", \"partial\"]),\n reason: z.string().max(256),\n resources: z\n .object({\n collector: ResourceCleanupResultSchema,\n processes: z.array(ResourceCleanupResultSchema),\n probes: z.array(ResourceCleanupResultSchema),\n permissions: z.array(ResourceCleanupResultSchema),\n files: z.array(ResourceCleanupResultSchema),\n secret: ResourceCleanupResultSchema,\n sessionDirectory: ResourceCleanupResultSchema,\n })\n .strict(),\n remainingArtifacts: z.array(z.string().max(8_192)),\n durationMs: z.number().nonnegative(),\n cleanCheck: z\n .object({\n command: z.string().max(8_192),\n exitCode: z.number().int().nullable(),\n timedOut: z.boolean(),\n durationMs: z.number().nonnegative(),\n })\n .strict()\n .optional(),\n retainedArtifactLocation: z.string().max(8_192).optional(),\n })\n .strict()\n\nexport const FinalReportInputSchema = z\n .object({\n outcome: z.enum([\"completed\", \"unresolved\", \"abandoned\", \"escalated\"]),\n rootCause: z.string().max(8_192),\n decidingEvidence: z.array(z.string().max(8_192)).max(100),\n hypotheses: z\n .array(\n z\n .object({\n id: z.string().max(64),\n status: z.enum([\"open\", \"confirmed\", \"eliminated\"]),\n statement: z.string().max(8_192),\n })\n .strict(),\n )\n .max(4),\n fix: z.string().max(8_192),\n changedFiles: z.array(z.string().max(8_192)).max(200),\n verification: z.array(z.string().max(8_192)).max(100),\n })\n .strict()\n\nexport const FinalReportSchema = FinalReportInputSchema.extend({\n cleanup: CleanupResultSchema,\n retainedArtifactLocation: z.string().max(8_192).optional(),\n}).strict()\n\nexport type CleanupResult = z.infer<typeof CleanupResultSchema>\nexport type FinalReportInput = z.infer<typeof FinalReportInputSchema>\nexport type FinalReport = z.infer<typeof FinalReportSchema>\n","import { randomBytes } from \"node:crypto\"\nimport type { IncomingMessage, ServerResponse } from \"node:http\"\nimport { z } from \"zod\"\nimport { LIMITS } from \"../core/constants.js\"\nimport type { EvidenceStore } from \"../evidence/store.js\"\nimport { type EventInput, EventInputSchema } from \"../evidence/types.js\"\nimport { CollectorBodyError, readBoundedJsonBody } from \"./body.js\"\nimport { writeCollectorJson } from \"./router.js\"\n\nconst EventBatchSchema = z.object({ events: z.array(EventInputSchema).min(1).max(LIMITS.eventsPerBatch) }).strict()\n\nfunction errorBody(code: string, message: string, retryable = false) {\n return { ok: false, error: { code, message, retryable } }\n}\n\nexport function createIngestHandler(options: {\n evidence: EvidenceStore\n validateEvent: (event: EventInput) => Promise<EventInput>\n sample?: (event: EventInput) => boolean | Promise<boolean>\n}) {\n return async (request: IncomingMessage, response: ServerResponse, origin?: string): Promise<void> => {\n await options.evidence.countRequest()\n let body: unknown\n try {\n body = await readBoundedJsonBody(request)\n } catch (error) {\n if (error instanceof CollectorBodyError) {\n await options.evidence.recordRejected()\n writeCollectorJson(response, error.status, errorBody(error.code, error.message), origin)\n return\n }\n throw error\n }\n const parsed = EventBatchSchema.safeParse(body)\n if (!parsed.success) {\n await options.evidence.recordRejected()\n writeCollectorJson(response, 400, errorBody(\"INVALID_REQUEST\", \"Invalid event batch\"), origin)\n return\n }\n\n const validated: EventInput[] = []\n try {\n for (const event of parsed.data.events) validated.push(await options.validateEvent(event))\n } catch {\n await options.evidence.recordRejected(parsed.data.events.length)\n writeCollectorJson(response, 400, errorBody(\"INVALID_REQUEST\", \"Event ownership is invalid\"), origin)\n return\n }\n\n let accepted = 0\n let sampled = 0\n let dropped = 0\n for (const event of validated) {\n const result = await options.evidence.append(\n {\n ...event,\n eventId: `event_${randomBytes(16).toString(\"base64url\")}`,\n kind: \"probe\",\n },\n { sampled: (await options.sample?.(event)) ?? false },\n )\n if (result.status === \"accepted\") accepted += 1\n else if (result.status === \"sampled\") sampled += 1\n else if (result.status === \"dropped\") dropped += 1\n }\n writeCollectorJson(response, 202, { ok: true, accepted, sampled, dropped }, origin)\n }\n}\n","import type { IncomingMessage } from \"node:http\"\nimport { LIMITS } from \"../core/constants.js\"\n\nexport class CollectorBodyError extends Error {\n constructor(\n readonly status: 400 | 413 | 415,\n readonly code: \"INVALID_REQUEST\" | \"LIMIT_EXCEEDED\" | \"UNSUPPORTED_MEDIA_TYPE\",\n ) {\n super(code)\n }\n}\n\nexport async function readBoundedJsonBody(request: IncomingMessage): Promise<unknown> {\n const contentType = request.headers[\"content-type\"]?.split(\";\", 1)[0]?.trim().toLowerCase()\n if (contentType !== \"application/json\") throw new CollectorBodyError(415, \"UNSUPPORTED_MEDIA_TYPE\")\n const declared = request.headers[\"content-length\"]\n if (declared !== undefined) {\n if (!/^\\d+$/u.test(declared)) throw new CollectorBodyError(400, \"INVALID_REQUEST\")\n if (Number(declared) > LIMITS.requestBytes) {\n request.resume()\n throw new CollectorBodyError(413, \"LIMIT_EXCEEDED\")\n }\n }\n\n const chunks: Buffer[] = []\n let bytes = 0\n for await (const chunk of request) {\n const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n bytes += buffer.byteLength\n if (bytes > LIMITS.requestBytes) {\n request.resume()\n throw new CollectorBodyError(413, \"LIMIT_EXCEEDED\")\n }\n chunks.push(buffer)\n }\n try {\n return JSON.parse(Buffer.concat(chunks, bytes).toString(\"utf8\"))\n } catch {\n throw new CollectorBodyError(400, \"INVALID_REQUEST\")\n }\n}\n","import { createHash, timingSafeEqual } from \"node:crypto\"\nimport type { SecretStore } from \"../session/secret-store.js\"\n\nconst TOKEN = /^[A-Za-z0-9_-]{43}$/\n\nfunction decode(value: string): Buffer | undefined {\n if (!TOKEN.test(value)) return undefined\n const decoded = Buffer.from(value, \"base64url\")\n if (decoded.byteLength !== 32 || decoded.toString(\"base64url\") !== value) return undefined\n return decoded\n}\n\nexport function authenticateBearer(header: string | undefined, expectedToken: string): boolean {\n if (header === undefined || !header.startsWith(\"Bearer \") || header.indexOf(\" \", 7) !== -1) return false\n const provided = decode(header.slice(7))\n const expected = decode(expectedToken)\n if (provided === undefined || expected === undefined) return false\n const providedDigest = createHash(\"sha256\").update(provided).digest()\n const expectedDigest = createHash(\"sha256\").update(expected).digest()\n return timingSafeEqual(providedDigest, expectedDigest)\n}\n\nexport async function createCollectorCredential(store: SecretStore): Promise<string> {\n return store.create()\n}\n","import type { IncomingMessage, ServerResponse } from \"node:http\"\nimport { authenticateBearer } from \"./auth.js\"\n\nexport type IngestHandler = (request: IncomingMessage, response: ServerResponse, origin?: string) => Promise<void>\n\nconst ERROR_MESSAGES = {\n INVALID_REQUEST: \"Invalid request\",\n UNAUTHORIZED: \"Unauthorized\",\n NOT_FOUND: \"Not found\",\n METHOD_NOT_ALLOWED: \"Method not allowed\",\n COLLECTOR_DRAINING: \"Collector is draining\",\n} as const\n\nfunction baseHeaders(): Record<string, string> {\n return {\n \"Cache-Control\": \"no-store\",\n \"X-Content-Type-Options\": \"nosniff\",\n \"Content-Type\": \"application/json; charset=utf-8\",\n }\n}\n\nfunction json(response: ServerResponse, status: number, value: unknown, headers: Record<string, string> = {}): void {\n response.writeHead(status, { ...baseHeaders(), ...headers })\n response.end(JSON.stringify(value))\n}\n\nfunction error(\n response: ServerResponse,\n status: number,\n code: keyof typeof ERROR_MESSAGES,\n retryable = false,\n headers: Record<string, string> = {},\n): void {\n json(response, status, { ok: false, error: { code, message: ERROR_MESSAGES[code], retryable } }, headers)\n}\n\nfunction validOrigin(value: string): boolean {\n if (value.length > 2_048 || /[\\s\\r\\n]/u.test(value)) return false\n return /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\/[^/]+$/u.test(value)\n}\n\nfunction preflight(request: IncomingMessage, response: ServerResponse): void {\n const origin = request.headers.origin\n const requestedMethod = request.headers[\"access-control-request-method\"]\n const rawHeaders = request.headers[\"access-control-request-headers\"] ?? \"\"\n if (\n origin === undefined ||\n !validOrigin(origin) ||\n requestedMethod !== \"POST\" ||\n typeof rawHeaders !== \"string\" ||\n rawHeaders.length > 256\n ) {\n error(response, 400, \"INVALID_REQUEST\")\n return\n }\n const requestedHeaders = rawHeaders\n .split(\",\")\n .map((value) => value.trim().toLowerCase())\n .filter(Boolean)\n if (requestedHeaders.some((value) => value !== \"authorization\" && value !== \"content-type\")) {\n error(response, 400, \"INVALID_REQUEST\")\n return\n }\n response.writeHead(204, {\n ...baseHeaders(),\n \"Access-Control-Allow-Origin\": origin,\n \"Access-Control-Allow-Methods\": \"POST\",\n \"Access-Control-Allow-Headers\": \"Authorization, Content-Type\",\n \"Access-Control-Max-Age\": \"600\",\n Vary: \"Origin\",\n })\n response.end()\n}\n\nexport function createCollectorRouter(options: {\n token: string\n ingest?: IngestHandler\n onAuthenticated?: () => void | Promise<void>\n}) {\n return async (\n request: IncomingMessage,\n response: ServerResponse,\n status: () => \"ready\" | \"draining\",\n ): Promise<void> => {\n const rawUrl = request.url ?? \"\"\n let url: URL\n try {\n url = new URL(rawUrl, \"http://loopback.invalid\")\n } catch {\n error(response, 404, \"NOT_FOUND\")\n return\n }\n if (url.search !== \"\") {\n error(response, 404, \"NOT_FOUND\")\n return\n }\n const pathname = url.pathname\n if (request.method === \"OPTIONS\") {\n if (pathname === \"/v1/events\") preflight(request, response)\n else error(response, 404, \"NOT_FOUND\")\n return\n }\n\n const authorization = Array.isArray(request.headers.authorization) ? undefined : request.headers.authorization\n if (!authenticateBearer(authorization, options.token)) {\n error(response, 401, \"UNAUTHORIZED\")\n return\n }\n await options.onAuthenticated?.()\n\n if (pathname === \"/v1/health\") {\n if (request.method !== \"GET\") {\n error(response, 405, \"METHOD_NOT_ALLOWED\", false, { Allow: \"GET\" })\n return\n }\n json(response, 200, { ok: true, status: status() })\n return\n }\n if (pathname === \"/v1/events\") {\n if (request.method !== \"POST\") {\n error(response, 405, \"METHOD_NOT_ALLOWED\", false, { Allow: \"OPTIONS, POST\" })\n return\n }\n if (status() === \"draining\") {\n error(response, 429, \"COLLECTOR_DRAINING\", true)\n return\n }\n if (options.ingest === undefined) {\n error(response, 400, \"INVALID_REQUEST\")\n return\n }\n const origin = request.headers.origin\n await options.ingest(request, response, typeof origin === \"string\" && validOrigin(origin) ? origin : undefined)\n return\n }\n error(response, 404, \"NOT_FOUND\")\n }\n}\n\nexport function writeCollectorJson(response: ServerResponse, status: number, value: unknown, origin?: string): void {\n json(response, status, value, origin === undefined ? {} : { \"Access-Control-Allow-Origin\": origin, Vary: \"Origin\" })\n}\n","import { randomBytes } from \"node:crypto\"\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\"\nimport type { Socket } from \"node:net\"\nimport { LIMITS } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\n\nexport type CollectorStatus = \"stopped\" | \"starting\" | \"ready\" | \"draining\" | \"failed\"\nexport type CollectorRequestHandler = (\n request: IncomingMessage,\n response: ServerResponse,\n status: () => \"ready\" | \"draining\",\n) => void | Promise<void>\n\nexport type CollectorHandle = Readonly<{\n id: string\n host: \"127.0.0.1\" | \"::1\"\n port: number\n status: \"ready\"\n close(): Promise<void>\n}>\n\nexport class CollectorServer {\n private server: Server | undefined\n private readonly sockets = new Set<Socket>()\n private state: CollectorStatus = \"stopped\"\n private handle: CollectorHandle | undefined\n private failureReported = false\n\n constructor(\n private readonly handler: CollectorRequestHandler = (_request, response) => {\n response.writeHead(404, { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" })\n response.end('{\"ok\":false,\"error\":{\"code\":\"NOT_FOUND\",\"message\":\"Not found\",\"retryable\":false}}')\n },\n private readonly onFailure?: (reason: string) => void | Promise<void>,\n ) {}\n\n async start(): Promise<CollectorHandle> {\n if (this.handle !== undefined && this.state === \"ready\") return this.handle\n if (this.state !== \"stopped\") throw new DebugModeError(\"COLLECTOR_EXISTS\", \"A collector already exists\")\n this.state = \"starting\"\n try {\n this.handle = await this.bind(\"127.0.0.1\")\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code\n if (code !== \"EAFNOSUPPORT\" && code !== \"EADDRNOTAVAIL\") {\n this.state = \"failed\"\n throw new DebugModeError(\"LOOPBACK_BIND_FAILED\", \"The IPv4 loopback collector could not bind\")\n }\n try {\n this.handle = await this.bind(\"::1\")\n } catch {\n this.state = \"failed\"\n throw new DebugModeError(\"LOOPBACK_BIND_FAILED\", \"Neither loopback address could bind\")\n }\n }\n this.state = \"ready\"\n return this.handle\n }\n\n get status(): CollectorStatus {\n return this.state\n }\n\n async close(): Promise<void> {\n if (this.state === \"stopped\") return\n this.state = \"draining\"\n const server = this.server\n if (server === undefined) {\n this.state = \"stopped\"\n return\n }\n await Promise.race([\n new Promise<void>((resolve) => server.close(() => resolve())),\n new Promise<void>((resolve) =>\n setTimeout(() => {\n for (const socket of this.sockets) socket.destroy()\n server.closeAllConnections?.()\n resolve()\n }, 1_000),\n ),\n ])\n for (const socket of this.sockets) socket.destroy()\n this.sockets.clear()\n this.server = undefined\n this.handle = undefined\n this.state = \"stopped\"\n }\n\n private bind(host: \"127.0.0.1\" | \"::1\"): Promise<CollectorHandle> {\n return new Promise((resolve, reject) => {\n const server = createServer(\n {\n requestTimeout: 5_000,\n headersTimeout: 5_000,\n keepAliveTimeout: 1_000,\n maxHeaderSize: 16_384,\n connectionsCheckingInterval: 1_000,\n },\n (request, response) => {\n void Promise.resolve(\n this.handler(request, response, () => (this.state === \"draining\" ? \"draining\" : \"ready\")),\n ).catch(() => {\n if (!response.headersSent) response.writeHead(500, { \"Content-Type\": \"application/json\" })\n response.end('{\"ok\":false,\"error\":{\"code\":\"INTERNAL_ERROR\",\"message\":\"Request failed\",\"retryable\":false}}')\n })\n },\n )\n server.maxHeadersCount = 32\n this.server = server\n server.on(\"connection\", (socket) => {\n this.sockets.add(socket)\n socket.once(\"close\", () => this.sockets.delete(socket))\n })\n const startupTimeout = setTimeout(() => {\n cleanupStartup()\n server.close()\n const error = new Error(\"Collector startup timed out\") as NodeJS.ErrnoException\n error.code = \"ETIMEDOUT\"\n reject(error)\n }, LIMITS.collectorReadyMs)\n const startupError = (error: Error) => {\n cleanupStartup()\n server.close()\n reject(error)\n }\n const listening = () => {\n cleanupStartup()\n const address = server.address()\n if (address === null || typeof address === \"string\") {\n reject(new Error(\"Collector returned no TCP address\"))\n return\n }\n const handle: CollectorHandle = Object.freeze({\n id: `collector_${randomBytes(16).toString(\"base64url\")}`,\n host,\n port: address.port,\n status: \"ready\" as const,\n close: () => this.close(),\n })\n server.on(\"error\", () => void this.reportFailure(\"listener-error\"))\n server.on(\"close\", () => {\n if (this.state === \"ready\") void this.reportFailure(\"unexpected-close\")\n })\n resolve(handle)\n }\n const cleanupStartup = () => {\n clearTimeout(startupTimeout)\n server.off(\"error\", startupError)\n server.off(\"listening\", listening)\n }\n server.once(\"error\", startupError)\n server.once(\"listening\", listening)\n server.listen({ host, port: 0, exclusive: true })\n })\n }\n\n private async reportFailure(reason: string): Promise<void> {\n if (this.failureReported) return\n this.failureReported = true\n this.state = \"failed\"\n await this.onFailure?.(reason)\n }\n}\n","import { performance } from \"node:perf_hooks\"\n\nexport interface Clock {\n now(): Date\n monotonicMs(): number\n}\n\nexport const systemClock: Clock = Object.freeze({\n now: () => new Date(),\n monotonicMs: () => performance.now(),\n})\n","import { appendFile, stat } from \"node:fs/promises\"\nimport { z } from \"zod\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { EVENT_SCHEMA_VERSION, LIMITS } from \"../core/constants.js\"\nimport { type EvidenceCounters, EvidenceCountersSchema } from \"../session/types.js\"\nimport { readEvidence } from \"./read.js\"\nimport { sanitizeEvidenceData } from \"./sanitize.js\"\nimport { type EvidenceEvent, EvidenceEventSchema, type EvidenceFilter } from \"./types.js\"\n\nconst AppendEventSchema = EvidenceEventSchema.omit({ receivedAt: true, sanitization: true, data: true }).extend({\n schemaVersion: z.literal(EVENT_SCHEMA_VERSION),\n data: z.unknown().optional(),\n})\n\nexport type EvidenceAppendInput = z.infer<typeof AppendEventSchema>\nexport type CounterUpdate = (counters: EvidenceCounters) => void | Promise<void>\n\nexport class EvidenceStore {\n private tail: Promise<void> = Promise.resolve()\n private currentBytes = 0\n private initialized = false\n private readonly counters: EvidenceCounters = {\n accepted: 0,\n rejected: 0,\n sampled: 0,\n truncated: 0,\n dropped: 0,\n requests: 0,\n }\n\n constructor(\n private readonly filename: string,\n private readonly onCounters?: CounterUpdate,\n private readonly clock: Clock = systemClock,\n private readonly loadCounters?: () => Promise<EvidenceCounters>,\n ) {}\n\n async append(\n input: EvidenceAppendInput,\n options: { sampled?: boolean } = {},\n ): Promise<{ status: \"accepted\" | \"sampled\" | \"dropped\" | \"rejected\"; event?: EvidenceEvent }> {\n return this.exclusive(async () => {\n await this.initialize()\n if (options.sampled === true) {\n await this.increment(\"sampled\")\n return { status: \"sampled\" }\n }\n\n const parsed = AppendEventSchema.safeParse(input)\n if (!parsed.success) {\n await this.increment(\"rejected\")\n return { status: \"rejected\" }\n }\n if (this.counters.accepted >= LIMITS.events) {\n await this.increment(\"dropped\")\n return { status: \"dropped\" }\n }\n\n const sanitized = sanitizeEvidenceData(parsed.data.data)\n const event = EvidenceEventSchema.parse({\n ...parsed.data,\n data: sanitized.value,\n receivedAt: this.clock.now().toISOString(),\n sanitization: {\n flags: sanitized.flags,\n droppedKeys: sanitized.droppedKeys,\n storedBytes: sanitized.storedBytes,\n ...(sanitized.originalBytes === undefined ? {} : { originalBytes: sanitized.originalBytes }),\n },\n })\n const line = `${JSON.stringify(event)}\\n`\n const bytes = Buffer.byteLength(line)\n if (this.currentBytes + bytes > LIMITS.evidenceBytes) {\n await this.increment(\"dropped\")\n return { status: \"dropped\" }\n }\n\n try {\n await appendFile(this.filename, line, { encoding: \"utf8\", mode: 0o600 })\n } catch (error) {\n await this.increment(\"rejected\")\n throw error\n }\n this.currentBytes += bytes\n await this.increment(\"accepted\")\n if (sanitized.flags.includes(\"truncated\")) await this.increment(\"truncated\")\n return { status: \"accepted\", event }\n })\n }\n\n async read(filter: EvidenceFilter = {}) {\n await this.initialize()\n const page = await readEvidence(this.filename, filter)\n return { ...page, counters: EvidenceCountersSchema.parse(this.counters) }\n }\n\n snapshotCounters(): EvidenceCounters {\n return EvidenceCountersSchema.parse(this.counters)\n }\n\n async countRequest(): Promise<void> {\n await this.exclusive(async () => {\n await this.initialize()\n await this.increment(\"requests\")\n })\n }\n\n async recordRejected(count = 1): Promise<void> {\n await this.exclusive(async () => {\n await this.initialize()\n for (let index = 0; index < count; index += 1) await this.increment(\"rejected\")\n })\n }\n\n private async initialize(): Promise<void> {\n if (this.initialized) return\n if (this.loadCounters !== undefined) {\n Object.assign(this.counters, EvidenceCountersSchema.parse(await this.loadCounters()))\n }\n try {\n this.currentBytes = (await stat(this.filename)).size\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n this.initialized = true\n }\n\n private async increment(field: keyof EvidenceCounters): Promise<void> {\n this.counters[field] += 1\n await this.onCounters?.(EvidenceCountersSchema.parse(this.counters))\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n const previous = this.tail\n let release!: () => void\n this.tail = new Promise<void>((resolve) => {\n release = resolve\n })\n await previous\n try {\n return await operation()\n } finally {\n release()\n }\n }\n}\n","import { z } from \"zod\"\nimport { LIMITS, MANIFEST_SCHEMA_VERSION, PACKAGE_ID } from \"../core/constants.js\"\nimport { HexSha256Schema, IsoTimestampSchema, OpaqueIdSchema, RunLabelSchema } from \"../core/schemas.js\"\n\nexport const EvidenceCountersSchema = z\n .object({\n accepted: z.number().int().nonnegative(),\n rejected: z.number().int().nonnegative(),\n sampled: z.number().int().nonnegative(),\n truncated: z.number().int().nonnegative(),\n dropped: z.number().int().nonnegative(),\n requests: z.number().int().nonnegative(),\n })\n .strict()\n\nexport const CollectorManifestSchema = z\n .object({\n id: OpaqueIdSchema,\n host: z.enum([\"127.0.0.1\", \"::1\"]),\n port: z.number().int().min(1).max(65_535),\n status: z.enum([\"starting\", \"ready\", \"draining\", \"stopped\", \"failed\"]),\n startedAt: IsoTimestampSchema,\n stoppedAt: IsoTimestampSchema.optional(),\n })\n .strict()\n\nexport const RunManifestSchema = z\n .object({\n id: OpaqueIdSchema,\n label: RunLabelSchema,\n reproduction: z.string().max(LIMITS.scalarBytes),\n status: z.enum([\"planned\", \"running\", \"waiting\", \"completed\", \"failed\", \"timed_out\", \"cancelled\"]),\n createdAt: IsoTimestampSchema,\n completedAt: IsoTimestampSchema.optional(),\n })\n .strict()\n\nexport const ProcessManifestSchema = z\n .object({\n id: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n commandSummary: z.string().max(LIMITS.scalarBytes),\n supervisorPid: z.number().int().positive().optional(),\n targetPid: z.number().int().positive().optional(),\n ownerNonceHash: HexSha256Schema,\n status: z.enum([\"starting\", \"running\", \"exited\", \"timed_out\", \"cancelled\", \"terminated\", \"failed\"]),\n startedAt: IsoTimestampSchema,\n completedAt: IsoTimestampSchema.optional(),\n exitCode: z.number().int().nullable().optional(),\n signal: z.string().max(64).nullable().optional(),\n })\n .strict()\n\nexport const ProbeManifestSchema = z\n .object({\n id: OpaqueIdSchema,\n runId: OpaqueIdSchema,\n hypothesisId: OpaqueIdSchema,\n sourceFile: z.string().min(1),\n sourceLine: z.number().int().positive(),\n sourceColumn: z.number().int().positive().optional(),\n message: z.string().min(1).max(LIMITS.scalarBytes),\n transport: z.enum([\"process\", \"http-web\", \"extension-background\", \"extension-content\"]),\n captures: z\n .array(z.object({ label: z.string().min(1).max(128), path: z.string().min(1).max(512) }).strict())\n .max(20),\n sampling: z.discriminatedUnion(\"mode\", [\n z.object({ mode: z.literal(\"every\"), n: z.number().int().min(1).max(10_000) }).strict(),\n z.object({ mode: z.literal(\"aggregate\"), windowMs: z.number().int().min(100).max(60_000) }).strict(),\n ]),\n status: z.enum([\"planned\", \"registered\", \"validated\", \"active\", \"removed\", \"ambiguous\"]),\n validationStatus: z.enum([\"pending\", \"validated\", \"failed\"]),\n markerStart: z.string().min(1),\n markerEnd: z.string().min(1),\n expectedBlock: z.string().optional(),\n expectedHash: HexSha256Schema.optional(),\n })\n .strict()\n\nexport const OwnedFileManifestSchema = z\n .object({\n path: z.string().min(1),\n sha256: HexSha256Schema,\n bytes: z.number().int().nonnegative(),\n kind: z.enum([\"transport-helper\", \"temporary\"]),\n })\n .strict()\n\nexport const PermissionChangeSchema = z\n .object({\n manifestPath: z.string().min(1),\n property: z.enum([\"permissions\", \"host_permissions\"]),\n matchPattern: z.string().min(1),\n addedBySession: z.boolean(),\n })\n .strict()\n\nexport const CleanupProgressSchema = z\n .object({\n status: z.enum([\"not_started\", \"running\", \"complete\", \"partial\"]),\n completedResources: z.array(z.string().max(256)).max(10_000),\n })\n .strict()\n\nexport const ManifestSchema = z\n .object({\n package: z.literal(PACKAGE_ID),\n schemaVersion: z.literal(MANIFEST_SCHEMA_VERSION),\n revision: z.number().int().nonnegative(),\n sessionId: OpaqueIdSchema,\n trustedSessionHash: HexSha256Schema,\n projectRoot: z.string().min(1),\n sessionDir: z.string().min(1),\n status: z.enum([\"active\", \"cleaning\", \"cleaned\", \"partial\"]),\n createdAt: IsoTimestampSchema,\n lastActivityAt: IsoTimestampSchema,\n expiresAt: IsoTimestampSchema,\n waitingForReproduction: z.boolean(),\n keepArtifacts: z.boolean(),\n retentionDestination: z.string().min(1).optional(),\n collector: CollectorManifestSchema.nullable(),\n runs: z.array(RunManifestSchema),\n processes: z.array(ProcessManifestSchema),\n probes: z.array(ProbeManifestSchema),\n ownedFiles: z.array(OwnedFileManifestSchema),\n permissionChanges: z.array(PermissionChangeSchema),\n counters: EvidenceCountersSchema,\n cleanup: CleanupProgressSchema,\n })\n .strict()\n\nexport type CleanupManifest = z.infer<typeof ManifestSchema>\nexport type ManifestProbe = z.infer<typeof ProbeManifestSchema>\nexport type ManifestRun = z.infer<typeof RunManifestSchema>\nexport type EvidenceCounters = z.infer<typeof EvidenceCountersSchema>\n","import { createReadStream } from \"node:fs\"\nimport { type EvidenceEvent, EvidenceEventSchema, type EvidenceFilter } from \"./types.js\"\n\nexport type EvidencePage = Readonly<{\n events: EvidenceEvent[]\n nextCursor: string | null\n trailingPartialLine: boolean\n invalidLines: number\n}>\n\nfunction matches(event: EvidenceEvent, filter: EvidenceFilter): boolean {\n if (filter.sessionId !== undefined && event.sessionId !== filter.sessionId) return false\n if (filter.runId !== undefined && event.runId !== filter.runId) return false\n if (filter.hypothesisId !== undefined && event.hypothesisId !== filter.hypothesisId) return false\n if (filter.probeId !== undefined && event.probeId !== filter.probeId) return false\n if (filter.from !== undefined && event.timestamp < filter.from) return false\n if (filter.to !== undefined && event.timestamp > filter.to) return false\n if (filter.keyword !== undefined && !JSON.stringify(event).toLowerCase().includes(filter.keyword.toLowerCase()))\n return false\n return true\n}\n\nexport async function readEvidence(filename: string, filter: EvidenceFilter = {}): Promise<EvidencePage> {\n const limit = Math.min(Math.max(filter.limit ?? 100, 1), 100)\n const start = filter.cursor === undefined ? 0 : Number(filter.cursor)\n if (!Number.isSafeInteger(start) || start < 0) throw new Error(\"Evidence cursor is invalid\")\n\n const events: EvidenceEvent[] = []\n let invalidLines = 0\n let trailingPartialLine = false\n let buffer = Buffer.alloc(0)\n let offset = start\n let nextCursor: string | null = null\n const stream = createReadStream(filename, { start })\n\n try {\n for await (const chunk of stream) {\n buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)])\n while (true) {\n const newline = buffer.indexOf(0x0a)\n if (newline < 0) break\n const line = buffer.subarray(0, newline)\n buffer = buffer.subarray(newline + 1)\n offset += newline + 1\n if (line.byteLength === 0) continue\n try {\n const event = EvidenceEventSchema.parse(JSON.parse(line.toString(\"utf8\")))\n if (matches(event, filter)) {\n events.push(event)\n if (events.length >= limit) {\n nextCursor = String(offset)\n stream.destroy()\n return { events, nextCursor, trailingPartialLine: false, invalidLines }\n }\n }\n } catch {\n invalidLines += 1\n }\n }\n }\n trailingPartialLine = buffer.byteLength > 0\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n } finally {\n stream.destroy()\n }\n return { events, nextCursor, trailingPartialLine, invalidLines }\n}\n","import { createHash } from \"node:crypto\"\nimport { mkdir, realpath, writeFile } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { isContained } from \"../session/paths.js\"\n\nexport type TransportHelperResult = Readonly<{\n relativePath: string\n requiredImport: string\n sha256: string\n bytes: number\n}>\n\nfunction helperSource(options: { endpoint: string; token: string; extensionBackground: boolean }): string {\n const listener = options.extensionBackground\n ? `\nconst runtime = globalThis.browser?.runtime ?? globalThis.chrome?.runtime\nruntime?.onMessage?.addListener((message) => {\n if (message?.type === \"opencode-debug-event\") __opencodeDebugEmit(message.event)\n})\n`\n : \"\"\n return `const endpoint = ${JSON.stringify(options.endpoint)}\nconst authorization = ${JSON.stringify(`Bearer ${options.token}`)}\nconst queue = []\nlet sending = false\nlet dropped = 0\n\nfunction bound(value, depth = 0) {\n if (depth > 6) return \"[TRUNCATED]\"\n if (typeof value === \"string\") return value.slice(0, 8192)\n if (Array.isArray(value)) return value.slice(0, 100).map((item) => bound(item, depth + 1))\n if (value && typeof value === \"object\") {\n return Object.fromEntries(Object.keys(value).sort().slice(0, 50).map((key) => [key, bound(value[key], depth + 1)]))\n }\n return value\n}\n\nexport function __opencodeDebugEmit(event) {\n if (queue.length >= 100) { dropped += 1; return }\n queue.push(bound(event))\n void flush()\n}\n\nasync function flush() {\n if (sending) return\n sending = true\n try {\n while (queue.length > 0) {\n const events = queue.splice(0, 100)\n if (dropped > 0) { events.push({ ...events[0], message: \"dropped events\", data: { dropped } }); dropped = 0 }\n const response = await fetch(endpoint, {\n method: \"POST\",\n credentials: \"omit\",\n headers: { Authorization: authorization, \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ events }),\n })\n if (!response.ok) break\n }\n } catch {\n // Runtime evidence transport is best effort and never affects target behavior.\n } finally {\n sending = false\n }\n}\n${listener}`\n}\n\nexport class TransportHelper {\n constructor(\n private readonly projectRoot: string,\n private readonly recordOwnedFile?: (value: { path: string; sha256: string; bytes: number }) => void | Promise<void>,\n ) {}\n\n async create(options: {\n targetPath: string\n host: \"127.0.0.1\" | \"::1\"\n port: number\n token: string\n runtime: \"web\" | \"extension-background\"\n }): Promise<TransportHelperResult> {\n const canonicalRoot = await realpath(this.projectRoot)\n const absoluteTarget = path.resolve(canonicalRoot, options.targetPath)\n if (!isContained(canonicalRoot, absoluteTarget)) {\n throw new DebugModeError(\"HELPER_PATH_UNSAFE\", \"Transport helper must remain inside the project\")\n }\n const parent = path.dirname(absoluteTarget)\n await mkdir(parent, { recursive: true })\n if ((await realpath(parent)) !== parent) {\n throw new DebugModeError(\"HELPER_PATH_UNSAFE\", \"Transport helper parent is not canonical\")\n }\n const endpointHost = options.host === \"::1\" ? \"[::1]\" : options.host\n const source = helperSource({\n endpoint: `http://${endpointHost}:${options.port}/v1/events`,\n token: options.token,\n extensionBackground: options.runtime === \"extension-background\",\n })\n await writeFile(absoluteTarget, source, { flag: \"wx\", mode: 0o600 })\n const bytes = Buffer.byteLength(source)\n const sha256 = createHash(\"sha256\").update(source).digest(\"hex\")\n await this.recordOwnedFile?.({ path: absoluteTarget, sha256, bytes })\n const relativePath = `./${path.relative(canonicalRoot, absoluteTarget).split(path.sep).join(\"/\")}`\n return {\n relativePath,\n requiredImport: `import { __opencodeDebugEmit } from ${JSON.stringify(relativePath)}`,\n sha256,\n bytes,\n }\n }\n}\n","import { createHash, randomBytes } from \"node:crypto\"\nimport { readFile, realpath } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport type { EventInput } from \"../evidence/types.js\"\nimport type { ManifestStore } from \"../session/manifest-store.js\"\nimport { isContained } from \"../session/paths.js\"\nimport type { CleanupManifest, ManifestProbe } from \"../session/types.js\"\nimport { createProbeTemplate } from \"./template.js\"\nimport { type ProbePlanInput, SAFE_CAPTURE } from \"./types.js\"\n\nconst SUPPORTED_EXTENSIONS = new Set([\".js\", \".jsx\", \".ts\", \".tsx\", \".mjs\", \".cjs\"])\n\nfunction probeId(): string {\n return `probe_${randomBytes(16).toString(\"base64url\")}`\n}\n\nfunction sha256(value: string): string {\n return createHash(\"sha256\").update(value).digest(\"hex\")\n}\n\nfunction markerLines(sessionId: string, input: ProbePlanInput, id: string) {\n const ownership = `opencode-debug-mode session=${sessionId} run=${input.runId} hypothesis=${input.hypothesisId} probe=${id}`\n return { start: `/* DEBUG-START ${ownership} */`, end: `/* DEBUG-END ${ownership} */` }\n}\n\nexport class ProbeRegistry {\n constructor(\n private readonly store: ManifestStore,\n private readonly projectRoot: string,\n private readonly hasHypothesis: (id: string) => Promise<boolean>,\n ) {}\n\n async plan(input: ProbePlanInput): Promise<ManifestProbe & { markerBlock: string }> {\n const manifest = await this.store.read()\n if (!manifest.runs.some((run) => run.id === input.runId))\n throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n if (!(await this.hasHypothesis(input.hypothesisId))) {\n throw new DebugModeError(\"STATE_INVALID\", \"Hypothesis was not found in the checkpoint\")\n }\n if (!Number.isInteger(input.sourceLine) || input.sourceLine < 1) {\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Source line must be one-based\")\n }\n if (input.message.length < 1 || Buffer.byteLength(input.message) > 8_192) {\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Probe message is invalid\")\n }\n if (input.captures.length > 20 || input.captures.some((capture) => !SAFE_CAPTURE.test(capture.path))) {\n throw new DebugModeError(\"UNSAFE_CAPTURE\", \"Probe capture path is unsafe\")\n }\n\n const absoluteSource = path.resolve(this.projectRoot, input.sourceFile)\n if (!isContained(this.projectRoot, absoluteSource)) {\n throw new DebugModeError(\"HELPER_PATH_UNSAFE\", \"Probe source is outside the project\")\n }\n if (!SUPPORTED_EXTENSIONS.has(path.extname(absoluteSource).toLowerCase())) {\n throw new DebugModeError(\"UNSUPPORTED_LANGUAGE\", \"Only JavaScript and TypeScript probes are supported\")\n }\n const canonicalSource = await realpath(absoluteSource)\n if (!isContained(this.projectRoot, canonicalSource)) {\n throw new DebugModeError(\"HELPER_PATH_UNSAFE\", \"Probe source resolves outside the project\")\n }\n\n const id = probeId()\n const markers = markerLines(manifest.sessionId, input, id)\n const run = manifest.runs.find((candidate) => candidate.id === input.runId)\n if (run === undefined) throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n const markerBlock =\n input.markerBlock ??\n createProbeTemplate({\n sessionId: manifest.sessionId,\n runId: input.runId,\n runLabel: run.label,\n hypothesisId: input.hypothesisId,\n probeId: id,\n sourceFile: path.relative(this.projectRoot, canonicalSource),\n sourceLine: input.sourceLine,\n message: input.message,\n captures: input.captures,\n transport: input.transport,\n sampling: input.sampling,\n }).markerBlock\n const probe: ManifestProbe = {\n id,\n runId: input.runId,\n hypothesisId: input.hypothesisId,\n sourceFile: canonicalSource,\n sourceLine: input.sourceLine,\n ...(input.sourceColumn === undefined ? {} : { sourceColumn: input.sourceColumn }),\n message: input.message,\n transport: input.transport,\n captures: input.captures,\n sampling: input.sampling,\n status: \"planned\",\n validationStatus: \"pending\",\n markerStart: markers.start,\n markerEnd: markers.end,\n expectedBlock: markerBlock,\n }\n await this.update(manifest, (value) => ({ ...value, probes: [...value.probes, probe] }))\n return { ...probe, markerBlock }\n }\n\n async register(id: string): Promise<ManifestProbe> {\n const manifest = await this.store.read()\n const probe = manifest.probes.find((candidate) => candidate.id === id)\n if (probe === undefined) throw new DebugModeError(\"MARKER_MISSING\", \"Probe was not planned\")\n if (probe.expectedBlock === undefined)\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Probe marker content is unavailable\")\n const source = await readFile(probe.sourceFile, \"utf8\")\n const occurrences = source.split(probe.expectedBlock).length - 1\n if (occurrences === 0) throw new DebugModeError(\"MARKER_MISSING\", \"Owned probe marker is missing\")\n if (occurrences !== 1) throw new DebugModeError(\"MARKER_MISMATCH\", \"Owned probe marker is not unique\")\n const updated: ManifestProbe = {\n ...probe,\n expectedHash: sha256(probe.expectedBlock),\n status: \"registered\",\n validationStatus: \"pending\",\n }\n await this.update(manifest, (value) => ({\n ...value,\n probes: value.probes.map((candidate) => (candidate.id === id ? updated : candidate)),\n }))\n return updated\n }\n\n async validate(probeIds: string[]): Promise<void> {\n const manifest = await this.store.read()\n if (probeIds.some((id) => !manifest.probes.some((probe) => probe.id === id && probe.status === \"registered\"))) {\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Only registered probes can be validated\")\n }\n await this.update(manifest, (value) => ({\n ...value,\n probes: value.probes.map((probe) =>\n probeIds.includes(probe.id)\n ? { ...probe, status: \"validated\" as const, validationStatus: \"validated\" as const }\n : probe,\n ),\n }))\n }\n\n async requireValidatedForRun(runId: string): Promise<void> {\n const manifest = await this.store.read()\n if (manifest.probes.some((probe) => probe.runId === runId && probe.validationStatus !== \"validated\")) {\n throw new DebugModeError(\"PROBE_NOT_VALIDATED\", \"Every active probe must pass an instrumentation check\")\n }\n }\n\n async validateEvent(input: EventInput): Promise<EventInput> {\n const manifest = await this.store.read()\n const probe = manifest.probes.find((candidate) => candidate.id === input.probeId)\n const run = manifest.runs.find((candidate) => candidate.id === input.runId)\n if (\n probe === undefined ||\n run === undefined ||\n input.sessionId !== manifest.sessionId ||\n probe.runId !== input.runId ||\n probe.hypothesisId !== input.hypothesisId ||\n run.label !== input.runLabel\n ) {\n throw new DebugModeError(\"MARKER_MISMATCH\", \"Runtime event ownership does not match the registered probe\")\n }\n return {\n ...input,\n source: {\n file: path.relative(this.projectRoot, probe.sourceFile),\n line: probe.sourceLine,\n ...(probe.sourceColumn === undefined ? {} : { column: probe.sourceColumn }),\n },\n }\n }\n\n private async update(\n _manifest: CleanupManifest,\n mutate: (value: CleanupManifest) => CleanupManifest,\n ): Promise<CleanupManifest> {\n return this.store.modify(mutate)\n }\n}\n","export const SAFE_CAPTURE = /^[A-Za-z_$][\\w$]*(?:(?:\\.|\\?\\.)[A-Za-z_$][\\w$]*)*$/\n\nexport type ProbeTransport = \"process\" | \"http-web\" | \"extension-background\" | \"extension-content\"\nexport type ProbeSampling = { mode: \"every\"; n: number } | { mode: \"aggregate\"; windowMs: number }\n\nexport type ProbePlanInput = Readonly<{\n runId: string\n hypothesisId: string\n sourceFile: string\n sourceLine: number\n sourceColumn?: number\n message: string\n captures: Array<{ label: string; path: string }>\n transport: ProbeTransport\n sampling: ProbeSampling\n markerBlock?: string\n}>\n","import { PROCESS_EVENT_PREFIX } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { type ProbeSampling, type ProbeTransport, SAFE_CAPTURE } from \"./types.js\"\n\nexport type ProbeTemplateInput = Readonly<{\n sessionId: string\n runId: string\n runLabel: \"pre-fix\" | \"post-fix\"\n hypothesisId: string\n probeId: string\n sourceFile: string\n sourceLine: number\n message: string\n captures: Array<{ label: string; path: string }>\n transport: ProbeTransport\n sampling: ProbeSampling\n contentAdapter?: \"chrome.runtime.sendMessage\" | \"browser.runtime.sendMessage\" | \"wrapper.sendMessage\"\n}>\n\nexport function createProbeTemplate(input: ProbeTemplateInput): { markerBlock: string } {\n if (input.captures.some((capture) => !SAFE_CAPTURE.test(capture.path))) {\n throw new DebugModeError(\"UNSAFE_CAPTURE\", \"Probe capture path is unsafe\")\n }\n const ownership = `opencode-debug-mode session=${input.sessionId} run=${input.runId} hypothesis=${input.hypothesisId} probe=${input.probeId}`\n const data = input.captures.map((capture) => `${JSON.stringify(capture.label)}: ${capture.path}`).join(\", \")\n const event = `{\n schemaVersion: 1,\n sessionId: ${JSON.stringify(input.sessionId)},\n runId: ${JSON.stringify(input.runId)},\n runLabel: ${JSON.stringify(input.runLabel)},\n hypothesisId: ${JSON.stringify(input.hypothesisId)},\n probeId: ${JSON.stringify(input.probeId)},\n timestamp: new Date().toISOString(),\n message: ${JSON.stringify(input.message)},\n source: { file: ${JSON.stringify(input.sourceFile)}, line: ${input.sourceLine} },\n data: { ${data} },\n}`\n let emission: string\n if (input.transport === \"process\") {\n emission = `void ((event) => process.stderr.write(${JSON.stringify(PROCESS_EVENT_PREFIX)} + JSON.stringify(event) + \"\\\\n\"))(${event})`\n } else if (input.transport === \"extension-content\") {\n const adapter = input.contentAdapter ?? \"chrome.runtime.sendMessage\"\n emission = `void ${adapter}({ type: \"opencode-debug-event\", event: ${event} })`\n } else {\n emission = `void __opencodeDebugEmit(${event})`\n }\n return {\n markerBlock: `/* DEBUG-START ${ownership} */\\n${emission}\\n/* DEBUG-END ${ownership} */`,\n }\n}\n","import { type ChildProcess, fork } from \"node:child_process\"\nimport { createHash, randomBytes } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport type { z } from \"zod\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { EVENT_SCHEMA_VERSION } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport type { EvidenceStore } from \"../evidence/store.js\"\nimport { EventInputSchema } from \"../evidence/types.js\"\nimport type { ProbeRegistry } from \"../probes/registry.js\"\nimport type { RunService } from \"../run/service.js\"\nimport type { DebugSession } from \"../session/registry.js\"\nimport type { CleanupManifest, ProcessManifestSchema } from \"../session/types.js\"\nimport { type DecodedProcessRecord, ProcessLineDecoder, type ProcessStream } from \"./line-decoder.js\"\nimport { parseChildMessage } from \"./protocol.js\"\n\ntype OwnedProcess = z.infer<typeof ProcessManifestSchema>\n\nexport type ProcessCaptureInput = Readonly<{\n runId: string\n executable: string\n args: string[]\n cwd: string\n env: Record<string, string>\n timeoutMs: number\n probeIds?: string[]\n purpose?: \"instrumentation-check\" | \"reproduction\" | \"verification\"\n signal?: AbortSignal\n}>\n\nexport type ProcessCaptureResult = Readonly<{\n processId: string\n runId: string\n exitCode: number | null\n signal: string | null\n timedOut: boolean\n durationMs: number\n stdoutEvents: number\n stderrEvents: number\n probeEvents: number\n}>\n\nfunction generatedId(prefix: string): string {\n return `${prefix}${randomBytes(16).toString(\"base64url\")}`\n}\n\nfunction defaultSupervisorPath(): string {\n const directory = path.dirname(fileURLToPath(import.meta.url))\n const bundled = path.join(directory, \"process-supervisor.js\")\n if (existsSync(bundled)) return bundled\n return path.resolve(directory, \"../../dist/process-supervisor.js\")\n}\n\nexport class ProcessService {\n constructor(\n private readonly dependencies: {\n session: DebugSession\n runs: RunService\n evidence: EvidenceStore\n acquireLease: () => Promise<() => void>\n probes?: ProbeRegistry\n supervisorPath?: string\n clock?: Clock\n },\n ) {}\n\n async capture(input: ProcessCaptureInput): Promise<ProcessCaptureResult> {\n const run = await this.dependencies.runs.require(input.runId)\n const release = await this.dependencies.acquireLease()\n const clock = this.dependencies.clock ?? systemClock\n const startedAt = clock.monotonicMs()\n const decoder = new ProcessLineDecoder({ maxLineBytes: 8_192 })\n let stdoutEvents = 0\n let stderrEvents = 0\n let probeEvents = 0\n let writes: Promise<void> = Promise.resolve()\n let startedUpdate: Promise<void> = Promise.resolve()\n let child: ChildProcess | undefined\n const processId = generatedId(\"process_\")\n const ownerNonce = randomBytes(32).toString(\"base64url\")\n\n try {\n child = fork(this.dependencies.supervisorPath ?? defaultSupervisorPath(), [], {\n stdio: [\"ignore\", \"pipe\", \"pipe\", \"ipc\"],\n })\n if (child.pid === undefined) throw new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor did not receive a PID\")\n await this.waitForMessage(child, \"ready\", 2_000)\n await this.addOwnedProcess({\n id: processId,\n runId: input.runId,\n commandSummary: [path.basename(input.executable), ...input.args.map((value) => path.basename(value))]\n .join(\" \")\n .slice(0, 8_192),\n supervisorPid: child.pid,\n ownerNonceHash: createHash(\"sha256\").update(ownerNonce).digest(\"hex\"),\n status: \"starting\",\n startedAt: clock.now().toISOString(),\n })\n\n const consume = (stream: ProcessStream, chunk: Buffer) => {\n for (const record of decoder.push(stream, chunk)) {\n writes = writes\n .then(() => this.persistRecord(record, input, run.label))\n .then((kind) => {\n if (kind === \"probe\") probeEvents += 1\n else if (kind === \"stdout\") stdoutEvents += 1\n else if (kind === \"stderr\") stderrEvents += 1\n })\n }\n }\n child.stdout?.on(\"data\", (chunk: Buffer) => consume(\"stdout\", chunk))\n child.stderr?.on(\"data\", (chunk: Buffer) => consume(\"stderr\", chunk))\n\n const resultPromise = new Promise<ReturnType<typeof parseChildMessage>>((resolve, reject) => {\n child?.on(\"message\", (value: unknown) => {\n try {\n const message = parseChildMessage(value)\n if (message.type === \"started\") startedUpdate = this.markStarted(processId, message.targetPid)\n if (message.type === \"failure\") reject(new DebugModeError(\"PROCESS_START_FAILED\", message.message))\n if (message.type === \"result\") resolve(message)\n } catch {\n reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor returned an invalid message\"))\n }\n })\n child?.once(\"error\", () => reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor failed to start\")))\n child?.once(\"exit\", (code) => {\n if (code !== 0) reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor exited unexpectedly\"))\n })\n })\n\n child.send({\n type: \"start\",\n executable: input.executable,\n args: input.args,\n cwd: input.cwd,\n env: input.env,\n timeoutMs: input.timeoutMs,\n ownerNonce,\n })\n\n const abort = () => {\n if (child?.connected) child.send({ type: \"terminate\", reason: \"abort\" })\n }\n input.signal?.addEventListener(\"abort\", abort, { once: true })\n if (input.signal?.aborted === true) abort()\n let result: ReturnType<typeof parseChildMessage>\n try {\n result = await resultPromise\n } finally {\n input.signal?.removeEventListener(\"abort\", abort)\n }\n if (result.type !== \"result\") throw new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor returned no result\")\n for (const stream of [\"stdout\", \"stderr\"] as const) {\n for (const record of decoder.flush(stream)) {\n writes = writes\n .then(() => this.persistRecord(record, input, run.label))\n .then((kind) => {\n if (kind === \"probe\") probeEvents += 1\n else if (kind === \"stdout\") stdoutEvents += 1\n else if (kind === \"stderr\") stderrEvents += 1\n })\n }\n }\n await writes\n await startedUpdate\n await this.markCompleted(processId, result)\n return {\n processId,\n runId: input.runId,\n exitCode: result.exitCode,\n signal: result.signal,\n timedOut: result.timedOut,\n durationMs: clock.monotonicMs() - startedAt,\n stdoutEvents,\n stderrEvents,\n probeEvents,\n }\n } finally {\n if (child?.connected) child.disconnect()\n release()\n }\n }\n\n private async persistRecord(\n record: DecodedProcessRecord,\n input: ProcessCaptureInput,\n runLabel: \"pre-fix\" | \"post-fix\",\n ): Promise<\"stdout\" | \"stderr\" | \"probe\" | \"ignored\"> {\n if (record.kind === \"truncated\") {\n const result = await this.dependencies.evidence.append({\n schemaVersion: EVENT_SCHEMA_VERSION,\n eventId: generatedId(\"event_\"),\n timestamp: new Date().toISOString(),\n sessionId: this.dependencies.session.publicId,\n runId: input.runId,\n runLabel,\n hypothesisId: \"hyp_process\",\n probeId: \"probe_process\",\n kind: `process.${record.stream}`,\n message: \"[TRUNCATED OUTPUT LINE]\",\n data: { maximumBytes: record.maximumBytes },\n source: { file: \"process\", line: 1 },\n })\n return result.status === \"accepted\" ? record.stream : \"ignored\"\n }\n if (record.kind === \"output\") {\n if (record.text.length === 0) return \"ignored\"\n const result = await this.dependencies.evidence.append({\n schemaVersion: EVENT_SCHEMA_VERSION,\n eventId: generatedId(\"event_\"),\n timestamp: new Date().toISOString(),\n sessionId: this.dependencies.session.publicId,\n runId: input.runId,\n runLabel,\n hypothesisId: \"hyp_process\",\n probeId: \"probe_process\",\n kind: `process.${record.stream}`,\n message: record.text,\n data: null,\n source: { file: \"process\", line: 1 },\n })\n return result.status === \"accepted\" ? record.stream : \"ignored\"\n }\n\n const parsed = EventInputSchema.safeParse(record.value)\n if (!parsed.success) return \"ignored\"\n const validated =\n this.dependencies.probes === undefined ? parsed.data : await this.dependencies.probes.validateEvent(parsed.data)\n const result = await this.dependencies.evidence.append({\n ...validated,\n eventId: generatedId(\"event_\"),\n kind: \"probe\",\n })\n return result.status === \"accepted\" ? \"probe\" : \"ignored\"\n }\n\n private async addOwnedProcess(owned: OwnedProcess): Promise<void> {\n await this.updateManifest((manifest) => ({ ...manifest, processes: [...manifest.processes, owned] }))\n }\n\n private async markStarted(id: string, targetPid: number): Promise<void> {\n await this.updateManifest((manifest) => ({\n ...manifest,\n processes: manifest.processes.map((entry) =>\n entry.id === id ? { ...entry, targetPid, status: \"running\" as const } : entry,\n ),\n }))\n }\n\n private async markCompleted(\n id: string,\n result: Extract<ReturnType<typeof parseChildMessage>, { type: \"result\" }>,\n ): Promise<void> {\n await this.updateManifest((manifest) => ({\n ...manifest,\n processes: manifest.processes.map((entry) =>\n entry.id === id\n ? {\n ...entry,\n status: result.timedOut ? (\"timed_out\" as const) : (\"exited\" as const),\n completedAt: new Date().toISOString(),\n exitCode: result.exitCode,\n signal: result.signal,\n }\n : entry,\n ),\n }))\n }\n\n private async updateManifest(mutate: (manifest: CleanupManifest) => CleanupManifest): Promise<void> {\n await this.dependencies.session.manifestStore.modify(mutate)\n }\n\n private waitForMessage(child: ChildProcess, type: string, timeoutMs: number): Promise<void> {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout(() => {\n cleanup()\n reject(new DebugModeError(\"PROCESS_START_FAILED\", `Supervisor did not become ${type}`))\n }, timeoutMs)\n const message = (value: unknown) => {\n try {\n if (parseChildMessage(value).type === type) {\n cleanup()\n resolve()\n }\n } catch {\n cleanup()\n reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor returned an invalid message\"))\n }\n }\n const exit = () => {\n cleanup()\n reject(new DebugModeError(\"PROCESS_START_FAILED\", \"Supervisor exited before becoming ready\"))\n }\n const cleanup = () => {\n clearTimeout(timeout)\n child.off(\"message\", message)\n child.off(\"exit\", exit)\n }\n child.on(\"message\", message)\n child.once(\"exit\", exit)\n })\n }\n}\n","import { StringDecoder } from \"node:string_decoder\"\nimport { PROCESS_EVENT_PREFIX } from \"../core/constants.js\"\n\nexport type ProcessStream = \"stdout\" | \"stderr\"\nexport type DecodedProcessRecord =\n | { kind: \"output\"; stream: ProcessStream; text: string; rejectedProbe?: boolean }\n | { kind: \"probe-candidate\"; stream: ProcessStream; value: unknown }\n | { kind: \"truncated\"; stream: ProcessStream; maximumBytes: number }\n\ntype StreamState = { decoder: StringDecoder; pending: string; discarding: boolean }\n\nexport class ProcessLineDecoder {\n private readonly streams: Record<ProcessStream, StreamState> = {\n stdout: { decoder: new StringDecoder(\"utf8\"), pending: \"\", discarding: false },\n stderr: { decoder: new StringDecoder(\"utf8\"), pending: \"\", discarding: false },\n }\n\n constructor(private readonly options: { maxLineBytes: number }) {}\n\n push(stream: ProcessStream, chunk: Buffer): DecodedProcessRecord[] {\n return this.consume(stream, this.streams[stream].decoder.write(chunk))\n }\n\n flush(stream: ProcessStream): DecodedProcessRecord[] {\n const state = this.streams[stream]\n const records = this.consume(stream, state.decoder.end())\n if (!state.discarding && state.pending.length > 0) {\n records.push(this.decodeLine(stream, state.pending.replace(/\\r$/u, \"\")))\n }\n state.pending = \"\"\n state.discarding = false\n return records\n }\n\n private consume(stream: ProcessStream, text: string): DecodedProcessRecord[] {\n const state = this.streams[stream]\n const records: DecodedProcessRecord[] = []\n let remainder = text\n if (state.discarding) {\n const newline = remainder.indexOf(\"\\n\")\n if (newline < 0) return records\n state.discarding = false\n remainder = remainder.slice(newline + 1)\n }\n state.pending += remainder\n\n while (true) {\n const newline = state.pending.indexOf(\"\\n\")\n if (newline < 0) break\n const line = state.pending.slice(0, newline).replace(/\\r$/u, \"\")\n state.pending = state.pending.slice(newline + 1)\n if (Buffer.byteLength(line) > this.options.maxLineBytes) {\n records.push({ kind: \"truncated\", stream, maximumBytes: this.options.maxLineBytes })\n } else {\n records.push(this.decodeLine(stream, line))\n }\n }\n\n if (Buffer.byteLength(state.pending) > this.options.maxLineBytes) {\n state.pending = \"\"\n state.discarding = true\n records.push({ kind: \"truncated\", stream, maximumBytes: this.options.maxLineBytes })\n }\n return records\n }\n\n private decodeLine(stream: ProcessStream, text: string): DecodedProcessRecord {\n if (!text.startsWith(PROCESS_EVENT_PREFIX)) return { kind: \"output\", stream, text }\n try {\n return { kind: \"probe-candidate\", stream, value: JSON.parse(text.slice(PROCESS_EVENT_PREFIX.length)) }\n } catch {\n return { kind: \"output\", stream, text, rejectedProbe: true }\n }\n }\n}\n","import { z } from \"zod\"\n\nconst MAX_MESSAGE_BYTES = 64 * 1024\nconst BoundedString = z.string().max(8_192)\n\nconst StartMessageSchema = z\n .object({\n type: z.literal(\"start\"),\n executable: BoundedString.min(1),\n args: z.array(BoundedString).max(256),\n cwd: BoundedString.min(1),\n env: z\n .record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), BoundedString)\n .refine((value) => Object.keys(value).length <= 256),\n timeoutMs: z.number().int().min(1).max(300_000),\n ownerNonce: z\n .string()\n .min(32)\n .max(128)\n .regex(/^[A-Za-z0-9_-]+$/),\n })\n .strict()\n\nconst TerminateMessageSchema = z.object({ type: z.literal(\"terminate\"), reason: BoundedString }).strict()\n\nexport const ParentMessageSchema = z.discriminatedUnion(\"type\", [StartMessageSchema, TerminateMessageSchema])\n\nexport const ChildMessageSchema = z.discriminatedUnion(\"type\", [\n z.object({ type: z.literal(\"ready\") }).strict(),\n z.object({ type: z.literal(\"started\"), targetPid: z.number().int().positive() }).strict(),\n z\n .object({\n type: z.literal(\"result\"),\n targetPid: z.number().int().positive(),\n exitCode: z.number().int().nullable(),\n signal: z.string().max(64).nullable(),\n timedOut: z.boolean(),\n termination: z\n .object({\n graceful: z.boolean(),\n forced: z.boolean(),\n remaining: z.boolean(),\n durationMs: z.number().nonnegative(),\n errors: z.array(z.string().max(256)).max(20),\n })\n .strict()\n .optional(),\n })\n .strict(),\n z.object({ type: z.literal(\"failure\"), code: z.string().max(128), message: z.string().max(512) }).strict(),\n])\n\nexport type ParentMessage = z.infer<typeof ParentMessageSchema>\nexport type ChildMessage = z.infer<typeof ChildMessageSchema>\n\nfunction assertSize(value: unknown): void {\n let serialized: string\n try {\n serialized = JSON.stringify(value)\n } catch {\n throw new Error(\"IPC message is not serializable\")\n }\n if (Buffer.byteLength(serialized) > MAX_MESSAGE_BYTES) throw new Error(\"IPC message exceeds 64 KiB\")\n}\n\nexport function parseParentMessage(value: unknown): ParentMessage {\n assertSize(value)\n return ParentMessageSchema.parse(value)\n}\n\nexport function parseChildMessage(value: unknown): ChildMessage {\n assertSize(value)\n return ChildMessageSchema.parse(value)\n}\n","import { randomBytes } from \"node:crypto\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { RunLabelSchema } from \"../core/schemas.js\"\nimport type { CleanupManifest, ManifestRun } from \"../session/types.js\"\n\nexport interface RunPersistence {\n read(): Promise<CleanupManifest>\n update(expectedRevision: number, mutate: (value: CleanupManifest) => CleanupManifest): Promise<CleanupManifest>\n}\n\nexport type LeaseFactory = (kind: \"process\" | \"waiting\") => Promise<() => void> | (() => void)\n\nfunction createId(prefix: string): string {\n return `${prefix}${randomBytes(16).toString(\"base64url\")}`\n}\n\nexport class RunService {\n private readonly waitingReleases = new Map<string, () => void>()\n\n constructor(\n private readonly persistence: RunPersistence,\n private readonly clock: Clock = systemClock,\n private readonly acquireLease?: LeaseFactory,\n ) {}\n\n async start(input: {\n label: \"pre-fix\" | \"post-fix\"\n reproduction: string\n waitingForUser: boolean\n }): Promise<ManifestRun> {\n const label = RunLabelSchema.parse(input.label)\n const current = await this.persistence.read()\n if (current.runs.length >= 20) throw new DebugModeError(\"RUN_LIMIT\", \"The run limit has been reached\")\n const now = this.clock.now().toISOString()\n const run: ManifestRun = {\n id: createId(\"run_\"),\n label,\n reproduction: input.reproduction.slice(0, 8_192),\n status: input.waitingForUser ? \"waiting\" : \"running\",\n createdAt: now,\n }\n await this.persistence.update(current.revision, (manifest) => ({\n ...manifest,\n waitingForReproduction: input.waitingForUser || manifest.waitingForReproduction,\n runs: [...manifest.runs, run],\n }))\n if (input.waitingForUser && this.acquireLease !== undefined) {\n this.waitingReleases.set(run.id, await this.acquireLease(\"waiting\"))\n }\n return run\n }\n\n async require(runId: string): Promise<ManifestRun> {\n const manifest = await this.persistence.read()\n const run = manifest.runs.find((candidate) => candidate.id === runId)\n if (run === undefined) throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n return run\n }\n\n async complete(runId: string, status: \"completed\" | \"failed\" | \"timed_out\" | \"cancelled\"): Promise<ManifestRun> {\n const current = await this.persistence.read()\n const index = current.runs.findIndex((candidate) => candidate.id === runId)\n if (index < 0) throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n const existing = current.runs[index]\n if (existing === undefined) throw new DebugModeError(\"RUN_NOT_FOUND\", \"Run was not found\")\n const updated: ManifestRun = { ...existing, status, completedAt: this.clock.now().toISOString() }\n await this.persistence.update(current.revision, (manifest) => ({\n ...manifest,\n waitingForReproduction: false,\n runs: manifest.runs.map((candidate) => (candidate.id === runId ? updated : candidate)),\n }))\n this.waitingReleases.get(runId)?.()\n this.waitingReleases.delete(runId)\n return updated\n }\n}\n","import type { Dirent } from \"node:fs\"\nimport { lstat, readdir, realpath } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { CleanupService } from \"../cleanup/service.js\"\nimport type { FinalReportInput } from \"../cleanup/types.js\"\nimport { InvestigationStore } from \"../investigation/store.js\"\nimport { ManifestStore } from \"./manifest-store.js\"\nimport { isContained } from \"./paths.js\"\nimport type { DebugSession } from \"./registry.js\"\nimport { SecretStore } from \"./secret-store.js\"\nimport type { CleanupManifest } from \"./types.js\"\n\nexport type OrphanRecoveryOptions = Readonly<{\n tempBase: string\n now?: Date\n activeSessionDirs?: Set<string>\n cleanup?: (session: DebugSession, manifest: CleanupManifest) => Promise<void>\n}>\n\nasync function assertContainedReference(target: string, roots: string[]): Promise<void> {\n const absolute = path.resolve(target)\n if (!roots.some((root) => absolute === root || isContained(root, absolute))) {\n throw new Error(\"Manifest path escapes its owned roots\")\n }\n try {\n const canonical = await realpath(absolute)\n if (!roots.some((root) => canonical === root || isContained(root, canonical))) {\n throw new Error(\"Manifest path resolves outside its owned roots\")\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n}\n\nexport async function recoverOrphans(options: OrphanRecoveryOptions): Promise<{\n cleaned: string[]\n ignored: string[]\n errors: Array<{ directory: string; reason: string }>\n}> {\n const cleaned: string[] = []\n const ignored: string[] = []\n const errors: Array<{ directory: string; reason: string }> = []\n let entries: Dirent<string>[]\n try {\n entries = await readdir(options.tempBase, { withFileTypes: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return { cleaned, ignored, errors }\n throw error\n }\n const now = (options.now ?? new Date()).getTime()\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"session-\")) {\n ignored.push(entry.name)\n continue\n }\n const sessionDir = path.join(options.tempBase, entry.name)\n try {\n if ((await lstat(sessionDir)).isSymbolicLink()) {\n ignored.push(entry.name)\n continue\n }\n const canonicalSessionDir = await realpath(sessionDir)\n if (options.activeSessionDirs?.has(canonicalSessionDir) === true) {\n ignored.push(entry.name)\n continue\n }\n const manifestStore = new ManifestStore(path.join(sessionDir, \"manifest.json\"))\n const manifest = await manifestStore.read()\n const canonicalProjectRoot = await realpath(manifest.projectRoot)\n if (\n (await realpath(manifest.sessionDir)) !== canonicalSessionDir ||\n new Date(manifest.expiresAt).getTime() >= now\n ) {\n ignored.push(entry.name)\n continue\n }\n for (const probe of manifest.probes) {\n await assertContainedReference(probe.sourceFile, [canonicalProjectRoot])\n }\n for (const permission of manifest.permissionChanges) {\n await assertContainedReference(permission.manifestPath, [canonicalProjectRoot])\n }\n for (const owned of manifest.ownedFiles) {\n await assertContainedReference(owned.path, [canonicalProjectRoot, canonicalSessionDir])\n }\n const paths = Object.freeze({\n baseDir: options.tempBase,\n sessionDir: manifest.sessionDir,\n projectRoot: canonicalProjectRoot,\n manifestFile: path.join(manifest.sessionDir, \"manifest.json\"),\n secretFile: path.join(manifest.sessionDir, \"secret.bin\"),\n stateFile: path.join(manifest.sessionDir, \"investigation-state.json\"),\n evidenceFile: path.join(manifest.sessionDir, \"evidence.ndjson\"),\n })\n const secretStore = new SecretStore(paths.secretFile)\n const secret = await secretStore.read().catch(() => \"\")\n const session: DebugSession = {\n publicId: manifest.sessionId,\n trustedHash: manifest.trustedSessionHash,\n projectRoot: canonicalProjectRoot,\n directory: canonicalProjectRoot,\n paths,\n manifestStore,\n investigationStore: new InvestigationStore(paths.stateFile),\n secretStore,\n secret,\n }\n if (options.cleanup !== undefined) await options.cleanup(session, manifest)\n else {\n const report: FinalReportInput = {\n outcome: \"abandoned\",\n rootCause: \"Investigation ended after its orphaned session expired\",\n decidingEvidence: [],\n hypotheses: [],\n fix: \"No recovery-time fix was applied\",\n changedFiles: [],\n verification: [\"Verified package-owned cleanup during startup recovery\"],\n }\n await new CleanupService(session).run({ reason: \"orphan-recovery\", finalReport: report })\n }\n cleaned.push(manifest.sessionId)\n } catch (error) {\n errors.push({\n directory: entry.name,\n reason: error instanceof Error ? error.name.slice(0, 128) : \"recovery-failed\",\n })\n }\n }\n return { cleaned, ignored, errors }\n}\n","import { readFile, stat } from \"node:fs/promises\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { LIMITS, STATE_SCHEMA_VERSION } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { atomicWriteJson } from \"../session/atomic-json.js\"\nimport { type InvestigationState, InvestigationStateSchema } from \"./schema.js\"\n\nexport type StateRecoveryResult =\n | { ok: true; state: InvestigationState; warnings: string[] }\n | { ok: false; error: { code: \"STATE_MISSING\" | \"STATE_INVALID\" | \"STATE_VERSION_UNSUPPORTED\"; message: string } }\n\nexport function initialInvestigationState(now: string): InvestigationState {\n return InvestigationStateSchema.parse({\n schemaVersion: STATE_SCHEMA_VERSION,\n revision: 0,\n updatedAt: now,\n problemSummary: \"\",\n expectedBehavior: \"\",\n actualBehavior: \"\",\n runtimeContext: { kind: \"other\", target: \"\" },\n reproduction: { method: \"\", requiresUser: false, confirmed: null },\n successCriteria: [],\n phase: \"intake\",\n loopIteration: 0,\n singleCauseEvidenceRef: null,\n hypotheses: [],\n completedChecks: [],\n runs: [],\n probeRefs: [],\n decidingEvidenceIds: [],\n developerConfirmations: [],\n decisions: [],\n nextAction: \"\",\n instrumentedFiles: [],\n fixedFiles: [],\n cleanup: { status: \"not_started\", completedResources: [] },\n })\n}\n\nexport class InvestigationStore {\n private tail: Promise<void> = Promise.resolve()\n\n constructor(\n private readonly filename: string,\n private readonly clock: Clock = systemClock,\n ) {}\n\n async create(state: InvestigationState): Promise<number> {\n const parsed = this.validate(state)\n try {\n await stat(this.filename)\n throw new DebugModeError(\"STATE_INVALID\", \"Investigation checkpoint already exists\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n return this.write(parsed)\n }\n\n async read(): Promise<InvestigationState> {\n const recovery = await this.readRecovery()\n if (!recovery.ok) throw new DebugModeError(recovery.error.code, recovery.error.message)\n return recovery.state\n }\n\n async readRecovery(): Promise<StateRecoveryResult> {\n let raw: string\n try {\n const info = await stat(this.filename)\n if (info.size > LIMITS.checkpointBytes) {\n return { ok: false, error: { code: \"STATE_INVALID\", message: \"Checkpoint exceeds its byte limit\" } }\n }\n raw = await readFile(this.filename, \"utf8\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { ok: false, error: { code: \"STATE_MISSING\", message: \"Investigation checkpoint is missing\" } }\n }\n return { ok: false, error: { code: \"STATE_INVALID\", message: \"Investigation checkpoint could not be read\" } }\n }\n\n try {\n const value: unknown = JSON.parse(raw)\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"schemaVersion\" in value &&\n (value as { schemaVersion?: unknown }).schemaVersion !== STATE_SCHEMA_VERSION\n ) {\n return {\n ok: false,\n error: { code: \"STATE_VERSION_UNSUPPORTED\", message: \"Investigation checkpoint version is unsupported\" },\n }\n }\n return { ok: true, state: InvestigationStateSchema.parse(value), warnings: [] }\n } catch {\n return { ok: false, error: { code: \"STATE_INVALID\", message: \"Investigation checkpoint is invalid\" } }\n }\n }\n\n async checkpoint(\n expectedRevision: number,\n state: InvestigationState,\n ): Promise<{ state: InvestigationState; bytes: number }> {\n return this.exclusive(async () => {\n const current = await this.read()\n if (current.revision !== expectedRevision) {\n throw new DebugModeError(\"STALE_REVISION\", `Expected revision ${expectedRevision}; found ${current.revision}`)\n }\n const candidate = this.validate({\n ...(state as unknown as Record<string, unknown>),\n revision: expectedRevision + 1,\n updatedAt: this.clock.now().toISOString(),\n })\n const bytes = await this.write(candidate)\n return { state: candidate, bytes }\n })\n }\n\n private validate(value: unknown): InvestigationState {\n const result = InvestigationStateSchema.safeParse(value)\n if (!result.success) throw new DebugModeError(\"STATE_INVALID\", \"Investigation checkpoint failed schema validation\")\n const bytes = Buffer.byteLength(`${JSON.stringify(result.data)}\\n`)\n if (bytes > LIMITS.checkpointBytes)\n throw new DebugModeError(\"STATE_TOO_LARGE\", \"Investigation checkpoint is too large\")\n return result.data\n }\n\n private async write(state: InvestigationState): Promise<number> {\n try {\n return await atomicWriteJson(this.filename, state, LIMITS.checkpointBytes)\n } catch (error) {\n if (error instanceof RangeError)\n throw new DebugModeError(\"STATE_TOO_LARGE\", \"Investigation checkpoint is too large\")\n throw error\n }\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n const previous = this.tail\n let release!: () => void\n this.tail = new Promise<void>((resolve) => {\n release = resolve\n })\n await previous\n try {\n return await operation()\n } finally {\n release()\n }\n }\n}\n","import { randomBytes } from \"node:crypto\"\nimport { open, rename, rm } from \"node:fs/promises\"\nimport path from \"node:path\"\n\nexport async function atomicWriteJson(filename: string, value: unknown, maximumBytes: number): Promise<number> {\n const serialized = `${JSON.stringify(value)}\\n`\n const bytes = Buffer.byteLength(serialized)\n if (bytes > maximumBytes) throw new RangeError(`Serialized JSON exceeds ${maximumBytes} bytes`)\n\n const temporary = path.join(\n path.dirname(filename),\n `${path.basename(filename)}.next-${randomBytes(8).toString(\"hex\")}`,\n )\n let handle: Awaited<ReturnType<typeof open>> | undefined\n try {\n handle = await open(temporary, \"wx\", 0o600)\n await handle.writeFile(serialized, \"utf8\")\n await handle.sync()\n await handle.close()\n handle = undefined\n await rename(temporary, filename)\n return bytes\n } catch (error) {\n await handle?.close().catch(() => undefined)\n await rm(temporary, { force: true }).catch(() => undefined)\n throw error\n }\n}\n","import { readFile, realpath, stat } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport { LIMITS, MANIFEST_SCHEMA_VERSION, PACKAGE_ID } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { atomicWriteJson } from \"./atomic-json.js\"\nimport { isContained } from \"./paths.js\"\nimport { type CleanupManifest, ManifestSchema } from \"./types.js\"\n\nconst MANIFEST_MAX_BYTES = 1024 * 1024\n\nexport function createInitialManifest(input: {\n sessionId: string\n trustedSessionHash: string\n projectRoot: string\n sessionDir: string\n now: string\n keepArtifacts?: boolean\n retentionDestination?: string\n}): CleanupManifest {\n const expiresAt = new Date(new Date(input.now).getTime() + LIMITS.idleMs).toISOString()\n const candidate = {\n package: PACKAGE_ID,\n schemaVersion: MANIFEST_SCHEMA_VERSION,\n revision: 0,\n sessionId: input.sessionId,\n trustedSessionHash: input.trustedSessionHash,\n projectRoot: input.projectRoot,\n sessionDir: input.sessionDir,\n status: \"active\",\n createdAt: input.now,\n lastActivityAt: input.now,\n expiresAt,\n waitingForReproduction: false,\n keepArtifacts: input.keepArtifacts ?? false,\n collector: null,\n runs: [],\n processes: [],\n probes: [],\n ownedFiles: [],\n permissionChanges: [],\n counters: { accepted: 0, rejected: 0, sampled: 0, truncated: 0, dropped: 0, requests: 0 },\n cleanup: { status: \"not_started\", completedResources: [] },\n ...(input.retentionDestination === undefined ? {} : { retentionDestination: input.retentionDestination }),\n }\n return ManifestSchema.parse(candidate)\n}\n\nexport class ManifestStore {\n private tail: Promise<void> = Promise.resolve()\n\n constructor(private readonly filename: string) {}\n\n async create(value: CleanupManifest): Promise<CleanupManifest> {\n return this.exclusive(async () => {\n const parsed = ManifestSchema.parse(value)\n await this.verifyPaths(parsed)\n try {\n await stat(this.filename)\n throw new DebugModeError(\"SESSION_EXISTS\", \"Session manifest already exists\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n await atomicWriteJson(this.filename, parsed, MANIFEST_MAX_BYTES)\n return parsed\n })\n }\n\n async read(): Promise<CleanupManifest> {\n const info = await stat(this.filename)\n if (info.size > MANIFEST_MAX_BYTES) throw new Error(\"Manifest exceeds its byte limit\")\n const parsed = ManifestSchema.parse(JSON.parse(await readFile(this.filename, \"utf8\")))\n await this.verifyPaths(parsed)\n return parsed\n }\n\n async update(\n expectedRevision: number,\n mutate: (value: CleanupManifest) => CleanupManifest,\n ): Promise<CleanupManifest> {\n return this.exclusive(async () => {\n const current = await this.read()\n if (current.revision !== expectedRevision) {\n throw new DebugModeError(\"STALE_REVISION\", `Expected revision ${expectedRevision}; found ${current.revision}`)\n }\n return this.writeNext(current, mutate)\n })\n }\n\n async modify(mutate: (value: CleanupManifest) => CleanupManifest): Promise<CleanupManifest> {\n return this.exclusive(async () => this.writeNext(await this.read(), mutate))\n }\n\n private async writeNext(\n current: CleanupManifest,\n mutate: (value: CleanupManifest) => CleanupManifest,\n ): Promise<CleanupManifest> {\n const next = ManifestSchema.parse({ ...mutate(structuredClone(current)), revision: current.revision + 1 })\n await this.verifyPaths(next)\n await atomicWriteJson(this.filename, next, MANIFEST_MAX_BYTES)\n return next\n }\n\n private async verifyPaths(value: CleanupManifest): Promise<void> {\n const actualSessionDir = await realpath(path.dirname(this.filename))\n const declaredSessionDir = await realpath(value.sessionDir)\n if (actualSessionDir !== declaredSessionDir)\n throw new Error(\"Manifest session directory does not match its location\")\n const packageBase = await realpath(path.dirname(actualSessionDir))\n if (!isContained(packageBase, actualSessionDir)) throw new Error(\"Manifest is outside the package temporary base\")\n if ((await realpath(value.projectRoot)) !== value.projectRoot) {\n throw new Error(\"Manifest project root is not canonical\")\n }\n }\n\n private async exclusive<T>(operation: () => Promise<T>): Promise<T> {\n const previous = this.tail\n let release!: () => void\n this.tail = new Promise<void>((resolve) => {\n release = resolve\n })\n await previous\n try {\n return await operation()\n } finally {\n release()\n }\n }\n}\n","import { randomBytes } from \"node:crypto\"\nimport { readFile, unlink, writeFile } from \"node:fs/promises\"\n\nconst TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/\n\nexport class SecretStore {\n constructor(private readonly filename: string) {}\n\n async create(): Promise<string> {\n const value = randomBytes(32).toString(\"base64url\")\n await writeFile(this.filename, value, { flag: \"wx\", mode: 0o600 })\n return value\n }\n\n async read(): Promise<string> {\n const value = await readFile(this.filename, \"utf8\")\n if (!TOKEN_PATTERN.test(value) || Buffer.from(value, \"base64url\").byteLength !== 32) {\n throw new Error(\"Stored collector credential is invalid\")\n }\n return value\n }\n\n async remove(): Promise<\"success\" | \"already-clean\"> {\n let length: number\n try {\n length = (await readFile(this.filename)).byteLength\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return \"already-clean\"\n throw error\n }\n\n try {\n await writeFile(this.filename, randomBytes(length), { flag: \"r+\" })\n } catch {\n // Deletion is still attempted if best-effort overwrite is unavailable.\n }\n try {\n await unlink(this.filename)\n return \"success\"\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return \"already-clean\"\n throw error\n }\n }\n}\n","import { createHash, randomBytes } from \"node:crypto\"\nimport type { Dirent } from \"node:fs\"\nimport { lstat, readdir, realpath, rm } from \"node:fs/promises\"\nimport path from \"node:path\"\nimport type { Clock } from \"../core/clock.js\"\nimport { systemClock } from \"../core/clock.js\"\nimport { LIMITS } from \"../core/constants.js\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { InvestigationStore, initialInvestigationState } from \"../investigation/store.js\"\nimport { createInitialManifest, ManifestStore } from \"./manifest-store.js\"\nimport { createSessionPaths, isContained, type SessionPaths } from \"./paths.js\"\nimport { SecretStore } from \"./secret-store.js\"\nimport type { CleanupManifest } from \"./types.js\"\n\nexport function trustedSessionHash(openCodeSessionId: string): string {\n return createHash(\"sha256\").update(\"opencode-debug-mode:v1:\", \"utf8\").update(openCodeSessionId, \"utf8\").digest(\"hex\")\n}\n\nexport type ProjectContext = Readonly<{ directory: string; worktree: string }>\n\nexport type DebugSession = Readonly<{\n publicId: string\n trustedHash: string\n projectRoot: string\n directory: string\n paths: SessionPaths\n manifestStore: ManifestStore\n investigationStore: InvestigationStore\n secretStore: SecretStore\n secret: string\n}>\n\ntype MutableSession = DebugSession & { leases: Map<\"process\" | \"waiting\", number> }\n\nexport type RegistryCleanup = (session: DebugSession, reason: \"idle-expired\") => Promise<void>\n\nexport class SessionRegistry {\n private readonly sessions = new Map<string, MutableSession>()\n private readonly timer: NodeJS.Timeout\n private closed = false\n\n constructor(\n private readonly tempBase: string,\n private readonly clock: Clock = systemClock,\n private readonly cleanup?: RegistryCleanup,\n ) {\n this.timer = setInterval(() => void this.sweep(), 30_000)\n this.timer.unref()\n }\n\n async start(\n trustedId: string,\n context: ProjectContext,\n options: { keepArtifacts?: boolean; retentionDestination?: string } = {},\n ): Promise<DebugSession> {\n this.assertOpen()\n if (Number(process.versions.node.split(\".\")[0]) < 20) {\n throw new DebugModeError(\"NODE_UNSUPPORTED\", \"Node.js 20 or newer is required\")\n }\n if (options.keepArtifacts === true && options.retentionDestination === undefined) {\n throw new DebugModeError(\"DESTINATION_REQUIRED\", \"An explicit retention destination is required\")\n }\n const hash = trustedSessionHash(trustedId)\n if (this.sessions.has(hash) || (await this.findPersisted(hash)) !== undefined) {\n throw new DebugModeError(\"SESSION_EXISTS\", \"A debug session already exists for this OpenCode session\")\n }\n\n const projectRoot = await realpath(context.worktree)\n const directory = await realpath(context.directory)\n if (directory !== projectRoot && !isContained(projectRoot, directory)) {\n throw new DebugModeError(\"STORAGE_UNAVAILABLE\", \"The active directory is outside the worktree\")\n }\n\n let paths: SessionPaths | undefined\n try {\n paths = await createSessionPaths(this.tempBase, projectRoot)\n const secretStore = new SecretStore(paths.secretFile)\n const secret = await secretStore.create()\n const publicId = `session_${randomBytes(16).toString(\"base64url\")}`\n const manifestStore = new ManifestStore(paths.manifestFile)\n const investigationStore = new InvestigationStore(paths.stateFile, this.clock)\n const now = this.clock.now().toISOString()\n await manifestStore.create(\n createInitialManifest({\n sessionId: publicId,\n trustedSessionHash: hash,\n projectRoot,\n sessionDir: paths.sessionDir,\n now,\n keepArtifacts: options.keepArtifacts ?? false,\n ...(options.retentionDestination === undefined\n ? {}\n : { retentionDestination: path.resolve(options.retentionDestination) }),\n }),\n )\n await investigationStore.create(initialInvestigationState(now))\n const session: MutableSession = {\n publicId,\n trustedHash: hash,\n projectRoot,\n directory,\n paths,\n manifestStore,\n investigationStore,\n secretStore,\n secret,\n leases: new Map(),\n }\n this.sessions.set(hash, session)\n return session\n } catch (error) {\n if (paths !== undefined) await rm(paths.sessionDir, { recursive: true, force: true }).catch(() => undefined)\n if (error instanceof DebugModeError) throw error\n throw new DebugModeError(\"STORAGE_UNAVAILABLE\", \"The debug session could not be initialized\")\n }\n }\n\n async requireOwned(trustedId: string): Promise<DebugSession> {\n this.assertOpen()\n const hash = trustedSessionHash(trustedId)\n const inMemory = this.sessions.get(hash)\n if (inMemory !== undefined) return inMemory\n const persisted = await this.findPersisted(hash)\n if (persisted === undefined) throw new DebugModeError(\"NO_ACTIVE_SESSION\", \"No active debug session exists\")\n this.sessions.set(hash, persisted)\n return persisted\n }\n\n async hasTrusted(trustedId: string): Promise<boolean> {\n try {\n await this.requireOwned(trustedId)\n return true\n } catch (error) {\n if (error instanceof DebugModeError && error.code === \"NO_ACTIVE_SESSION\") return false\n throw error\n }\n }\n\n async touch(trustedId: string): Promise<void> {\n const session = (await this.requireOwned(trustedId)) as MutableSession\n await this.touchSession(session)\n }\n\n async touchSession(sessionValue: DebugSession): Promise<void> {\n const session = this.sessions.get(sessionValue.trustedHash)\n if (session === undefined || session.publicId !== sessionValue.publicId) {\n throw new DebugModeError(\"SESSION_OWNERSHIP_MISMATCH\", \"Session is not owned by this registry\")\n }\n const now = this.clock.now()\n await session.manifestStore.modify((manifest) => ({\n ...manifest,\n lastActivityAt: now.toISOString(),\n expiresAt: new Date(now.getTime() + LIMITS.idleMs).toISOString(),\n }))\n }\n\n async acquireLease(trustedId: string, kind: \"process\" | \"waiting\"): Promise<() => void> {\n const session = (await this.requireOwned(trustedId)) as MutableSession\n return this.acquireLeaseForSession(session, kind)\n }\n\n acquireLeaseForSession(sessionValue: DebugSession, kind: \"process\" | \"waiting\"): () => void {\n const session = this.sessions.get(sessionValue.trustedHash)\n if (session === undefined || session.publicId !== sessionValue.publicId) {\n throw new DebugModeError(\"SESSION_OWNERSHIP_MISMATCH\", \"Session is not owned by this registry\")\n }\n session.leases.set(kind, (session.leases.get(kind) ?? 0) + 1)\n let released = false\n return () => {\n if (released) return\n released = true\n const next = Math.max(0, (session.leases.get(kind) ?? 1) - 1)\n if (next === 0) session.leases.delete(kind)\n else session.leases.set(kind, next)\n }\n }\n\n async sweep(): Promise<void> {\n if (this.closed) return\n const now = this.clock.now().getTime()\n for (const [hash, session] of this.sessions) {\n const manifest = await session.manifestStore.read().catch(() => undefined)\n if (\n manifest === undefined ||\n manifest.waitingForReproduction ||\n session.leases.size > 0 ||\n new Date(manifest.lastActivityAt).getTime() + LIMITS.idleMs > now\n ) {\n continue\n }\n if (this.cleanup !== undefined) await this.cleanup(session, \"idle-expired\")\n this.sessions.delete(hash)\n }\n }\n\n listActive(): DebugSession[] {\n return [...this.sessions.values()]\n }\n\n forgetTrusted(trustedId: string): void {\n this.sessions.delete(trustedSessionHash(trustedId))\n }\n\n async closeAll(): Promise<void> {\n if (this.closed) return\n this.closed = true\n clearInterval(this.timer)\n this.sessions.clear()\n }\n\n private async findPersisted(hash: string): Promise<MutableSession | undefined> {\n let entries: Dirent<string>[]\n try {\n entries = await readdir(this.tempBase, { withFileTypes: true, encoding: \"utf8\" })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return undefined\n throw error\n }\n const matches: MutableSession[] = []\n for (const entry of entries) {\n if (!entry.isDirectory() || !entry.name.startsWith(\"session-\")) continue\n const sessionDir = path.join(this.tempBase, entry.name)\n if ((await lstat(sessionDir)).isSymbolicLink()) continue\n try {\n const manifestStore = new ManifestStore(path.join(sessionDir, \"manifest.json\"))\n const manifest = await manifestStore.read()\n if (manifest.trustedSessionHash !== hash || manifest.status !== \"active\") continue\n if (!manifest.waitingForReproduction && new Date(manifest.expiresAt).getTime() < this.clock.now().getTime())\n continue\n const paths = this.pathsFromManifest(manifest)\n const secretStore = new SecretStore(paths.secretFile)\n const secret = await secretStore.read()\n const investigationStore = new InvestigationStore(paths.stateFile, this.clock)\n const recovery = await investigationStore.readRecovery()\n if (!recovery.ok) throw new DebugModeError(recovery.error.code, recovery.error.message)\n matches.push({\n publicId: manifest.sessionId,\n trustedHash: hash,\n projectRoot: manifest.projectRoot,\n directory: manifest.projectRoot,\n paths,\n manifestStore,\n investigationStore,\n secretStore,\n secret,\n leases: new Map(),\n })\n } catch {}\n }\n if (matches.length > 1) {\n throw new DebugModeError(\"SESSION_OWNERSHIP_MISMATCH\", \"Multiple session manifests match this trusted session\")\n }\n return matches[0]\n }\n\n private pathsFromManifest(manifest: CleanupManifest): SessionPaths {\n return Object.freeze({\n baseDir: this.tempBase,\n sessionDir: manifest.sessionDir,\n projectRoot: manifest.projectRoot,\n manifestFile: path.join(manifest.sessionDir, \"manifest.json\"),\n secretFile: path.join(manifest.sessionDir, \"secret.bin\"),\n stateFile: path.join(manifest.sessionDir, \"investigation-state.json\"),\n evidenceFile: path.join(manifest.sessionDir, \"evidence.ndjson\"),\n })\n }\n\n private assertOpen(): void {\n if (this.closed) throw new DebugModeError(\"NO_ACTIVE_SESSION\", \"The session registry is closed\")\n }\n}\n","import path from \"node:path\"\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { CleanupService } from \"../cleanup/service.js\"\nimport type { FinalReportInput } from \"../cleanup/types.js\"\nimport { isContained } from \"../session/paths.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\nconst reportSchema = schema\n .object({\n outcome: schema.enum([\"completed\", \"unresolved\", \"abandoned\", \"escalated\"]),\n rootCause: schema.string().max(8_192),\n decidingEvidence: schema.array(schema.string().max(8_192)).max(100),\n hypotheses: schema\n .array(\n schema\n .object({\n id: schema.string().max(64),\n status: schema.enum([\"open\", \"confirmed\", \"eliminated\"]),\n statement: schema.string().max(8_192),\n })\n .strict(),\n )\n .max(4),\n fix: schema.string().max(8_192),\n changedFiles: schema.array(schema.string().max(8_192)).max(200),\n verification: schema.array(schema.string().max(8_192)).max(100),\n })\n .strict()\n\nexport function createCleanupTool(\n registry: SessionRegistry,\n cleanupFor: (session: DebugSession) => CleanupService,\n): ToolDefinition {\n return tool({\n description: \"Tear down every owned debug resource and optionally retain a sanitized report\",\n args: {\n reason: schema.enum([\"completed\", \"unresolved\", \"abandoned\", \"escalated\", \"cancelled\"]),\n finalReport: reportSchema,\n cleanCheck: schema\n .object({\n executable: schema.string().min(1).max(8_192),\n args: schema.array(schema.string().max(8_192)).max(256),\n cwd: schema.string().min(1).max(8_192),\n timeoutMs: schema.number().int().min(1).max(300_000),\n })\n .strict()\n .optional(),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await cleanupFor(session).run({\n reason: args.reason,\n finalReport: args.finalReport as FinalReportInput,\n ...(args.cleanCheck === undefined ? {} : { cleanCheck: args.cleanCheck }),\n })\n const sanitize = (location: string | undefined) => {\n if (location === undefined) return undefined\n const absolute = path.resolve(location)\n return absolute === session.projectRoot || isContained(session.projectRoot, absolute)\n ? path.relative(session.projectRoot, absolute) || \".\"\n : undefined\n }\n const resources = {\n ...result.resources,\n probes: result.resources.probes.map((value) => ({ ...value, location: sanitize(value.location) })),\n permissions: result.resources.permissions.map((value) => ({ ...value, location: sanitize(value.location) })),\n files: result.resources.files.map((value) => ({ ...value, location: sanitize(value.location) })),\n }\n return jsonSuccess({\n ...result,\n resources,\n remainingArtifacts: result.remainingArtifacts.map(sanitize).filter(Boolean),\n })\n } catch (error) {\n return jsonFailure(error, \"Cleanup failed\")\n }\n },\n })\n}\n","import type { DebugErrorCode, SafeErrorDetail } from \"./errors.js\"\n\nexport type ToolWarning = Readonly<{ code: string; message: string }>\n\nexport type ToolResultEnvelope<T> =\n | { ok: true; data: T; warnings: ToolWarning[] }\n | {\n ok: false\n error: {\n code: DebugErrorCode\n message: string\n retryable: boolean\n action?: string\n details?: Record<string, SafeErrorDetail>\n }\n }\n\nexport function success<T>(data: T, warnings: ToolWarning[] = []): ToolResultEnvelope<T> {\n return { ok: true, data, warnings }\n}\n\nexport function failure(\n code: DebugErrorCode,\n message: string,\n retryable: boolean,\n options: { action?: string; details?: Record<string, SafeErrorDetail> } = {},\n): ToolResultEnvelope<never> {\n const error: Extract<ToolResultEnvelope<never>, { ok: false }>[\"error\"] = {\n code,\n message: message.slice(0, 8_192),\n retryable,\n }\n if (options.action !== undefined) error.action = options.action.slice(0, 8_192)\n if (options.details !== undefined) error.details = options.details\n return { ok: false, error }\n}\n","import { DebugModeError } from \"../core/errors.js\"\nimport { failure, success, type ToolResultEnvelope } from \"../core/result.js\"\n\nexport function jsonSuccess<T>(value: T): string {\n return JSON.stringify(success(value))\n}\n\nexport function jsonFailure(error: unknown, fallback = \"Tool operation failed\"): string {\n if (error instanceof DebugModeError) {\n return JSON.stringify(\n failure(error.code, error.message, error.retryable, {\n ...(error.action === undefined ? {} : { action: error.action }),\n ...(error.details === undefined ? {} : { details: error.details }),\n }),\n )\n }\n return JSON.stringify(failure(\"INTERNAL_ERROR\", fallback, false))\n}\n\nexport function serializeEnvelope<T>(value: ToolResultEnvelope<T>): string {\n return JSON.stringify(value)\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport interface PublicCollectorService {\n start(input: {\n runtime: \"web\" | \"extension-background\"\n transportTargetPath?: string\n extensionManifestPath?: string\n }): Promise<{\n collectorId: string\n host: \"127.0.0.1\" | \"::1\"\n port: number\n status: string\n helperImport?: string\n helperPath?: string\n }>\n}\n\nexport function createCollectorStartTool(\n registry: SessionRegistry,\n collectorFor: (session: DebugSession) => PublicCollectorService,\n): ToolDefinition {\n return tool({\n description: \"Start the authenticated loopback evidence collector\",\n args: {\n runtime: schema.enum([\"web\", \"extension-background\"]),\n transportTargetPath: schema.string().min(1).max(8_192).optional(),\n extensionManifestPath: schema.string().min(1).max(8_192).optional(),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await collectorFor(session).start({\n runtime: args.runtime,\n ...(args.transportTargetPath === undefined ? {} : { transportTargetPath: args.transportTargetPath }),\n ...(args.extensionManifestPath === undefined ? {} : { extensionManifestPath: args.extensionManifestPath }),\n })\n await registry.touch(context.sessionID)\n return jsonSuccess(result)\n } catch (error) {\n return jsonFailure(error, \"Collector startup failed\")\n }\n },\n })\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { EvidenceStore } from \"../evidence/store.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport function createEvidenceReadTool(\n registry: SessionRegistry,\n evidenceFor: (session: DebugSession) => EvidenceStore,\n): ToolDefinition {\n return tool({\n description: \"Read a bounded filtered page of sanitized local evidence\",\n args: {\n runId: schema.string().optional(),\n hypothesisId: schema.string().optional(),\n probeId: schema.string().optional(),\n from: schema.string().optional(),\n to: schema.string().optional(),\n keyword: schema.string().max(8_192).optional(),\n cursor: schema.string().regex(/^\\d+$/).optional(),\n limit: schema.number().int().min(1).max(100).default(100),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await evidenceFor(session).read({\n sessionId: session.publicId,\n limit: args.limit,\n ...(args.runId === undefined ? {} : { runId: args.runId }),\n ...(args.hypothesisId === undefined ? {} : { hypothesisId: args.hypothesisId }),\n ...(args.probeId === undefined ? {} : { probeId: args.probeId }),\n ...(args.from === undefined ? {} : { from: args.from }),\n ...(args.to === undefined ? {} : { to: args.to }),\n ...(args.keyword === undefined ? {} : { keyword: args.keyword }),\n ...(args.cursor === undefined ? {} : { cursor: args.cursor }),\n })\n await registry.touch(context.sessionID)\n return jsonSuccess(result)\n } catch (error) {\n return jsonFailure(error, \"Evidence is unavailable\")\n }\n },\n })\n}\n","import path from \"node:path\"\nimport { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { ProbeRegistry } from \"../probes/registry.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport function createProbePrepareTool(\n registry: SessionRegistry,\n probesFor: (session: DebugSession) => ProbeRegistry,\n): ToolDefinition {\n return tool({\n description: \"Prepare one safe owned JavaScript or TypeScript probe\",\n args: {\n runId: schema.string().regex(/^[A-Za-z0-9_-]+$/),\n hypothesisId: schema.string().regex(/^[A-Za-z0-9_-]+$/),\n sourceFile: schema.string().min(1).max(8_192),\n sourceLine: schema.number().int().positive(),\n sourceColumn: schema.number().int().positive().optional(),\n message: schema.string().min(1).max(8_192),\n captures: schema\n .array(\n schema.object({ label: schema.string().min(1).max(128), path: schema.string().min(1).max(512) }).strict(),\n )\n .max(20),\n transport: schema.enum([\"process\", \"http-web\", \"extension-background\", \"extension-content\"]),\n sampling: schema.union([\n schema.object({ mode: schema.literal(\"every\"), n: schema.number().int().min(1).max(10_000) }).strict(),\n schema\n .object({ mode: schema.literal(\"aggregate\"), windowMs: schema.number().int().min(100).max(60_000) })\n .strict(),\n ]),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const { sourceColumn, ...required } = args\n const probe = await probesFor(session).plan({\n ...required,\n ...(sourceColumn === undefined ? {} : { sourceColumn }),\n })\n await registry.touch(context.sessionID)\n return jsonSuccess({\n probeId: probe.id,\n markerBlock: probe.markerBlock,\n source: path.relative(session.projectRoot, probe.sourceFile),\n line: probe.sourceLine,\n })\n } catch (error) {\n return jsonFailure(error, \"Probe preparation failed\")\n }\n },\n })\n}\n\nexport function createProbeRegisterTool(\n registry: SessionRegistry,\n probesFor: (session: DebugSession) => ProbeRegistry,\n): ToolDefinition {\n return tool({\n description: \"Verify and register an exact owned probe marker\",\n args: { probeId: schema.string().regex(/^[A-Za-z0-9_-]+$/) },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const probe = await probesFor(session).register(args.probeId)\n await registry.touch(context.sessionID)\n return jsonSuccess({ probeId: probe.id, status: probe.status, validationStatus: probe.validationStatus })\n } catch (error) {\n return jsonFailure(error, \"Probe registration failed\")\n }\n },\n })\n}\n","import path from \"node:path\"\nimport { type ToolContext, type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport { DebugModeError } from \"../core/errors.js\"\nimport { failure, success } from \"../core/result.js\"\nimport type { ProbeRegistry } from \"../probes/registry.js\"\nimport type { ProcessCaptureResult, ProcessService } from \"../process/service.js\"\nimport type { RunService } from \"../run/service.js\"\nimport { isContained } from \"../session/paths.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\n\nconst schema = tool.schema\n\nconst ApprovalClassSchema = schema.enum([\n \"local-deterministic\",\n \"credentials\",\n \"device\",\n \"external-state\",\n \"materially-different\",\n])\n\nconst ProcessArgs = {\n approvalClass: ApprovalClassSchema,\n purpose: schema.enum([\"instrumentation-check\", \"reproduction\", \"verification\"]),\n probeIds: schema.array(schema.string().regex(/^[A-Za-z0-9_-]+$/)).max(100),\n executable: schema.string().min(1).max(8_192),\n args: schema.array(schema.string().max(8_192)).max(256),\n cwd: schema.string().min(1).max(8_192),\n env: schema\n .record(schema.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/), schema.string().max(8_192))\n .refine((value) => Object.keys(value).length <= 256),\n runId: schema.string().regex(/^[A-Za-z0-9_-]+$/),\n timeoutMs: schema.number().int().min(1).max(300_000),\n}\n\nexport interface RunToolDependencies {\n registry: Pick<SessionRegistry, \"requireOwned\">\n processFor(session: DebugSession): Pick<ProcessService, \"capture\">\n probesFor(session: DebugSession): Pick<ProbeRegistry, \"validate\" | \"requireValidatedForRun\">\n}\n\nasync function requestApproval(\n context: ToolContext,\n permission: string,\n executable: string,\n args: string[],\n): Promise<void> {\n try {\n await context.ask({\n permission,\n patterns: [[path.basename(executable), ...args.map((value) => path.basename(value))].join(\" \").slice(0, 512)],\n always: [],\n metadata: { executable: path.basename(executable), argumentCount: args.length },\n })\n } catch {\n throw new DebugModeError(\"COMMAND_REQUIRES_APPROVAL\", \"The requested process command was not approved\")\n }\n}\n\nfunction serializeResult(result: ProcessCaptureResult): string {\n return JSON.stringify(success(result))\n}\n\nexport function createProcessCaptureTool(dependencies: RunToolDependencies): ToolDefinition {\n return tool({\n description: \"Run one supervised command and capture bounded runtime evidence\",\n args: ProcessArgs,\n execute: async (args, context) => {\n try {\n const session = await dependencies.registry.requireOwned(context.sessionID)\n if (args.approvalClass !== \"local-deterministic\") {\n await requestApproval(context, \"debug_process_external\", args.executable, args.args)\n }\n const resolvedCwd = path.resolve(args.cwd)\n const worktree = path.resolve(context.worktree)\n if (resolvedCwd !== worktree && !isContained(worktree, resolvedCwd)) {\n await requestApproval(context, \"external_directory\", args.executable, args.args)\n }\n const probes = dependencies.probesFor(session)\n if (args.purpose === \"reproduction\") await probes.requireValidatedForRun(args.runId)\n const result = await dependencies.processFor(session).capture({\n runId: args.runId,\n executable: args.executable,\n args: args.args,\n cwd: resolvedCwd,\n env: args.env,\n timeoutMs: args.timeoutMs,\n probeIds: args.probeIds,\n purpose: args.purpose,\n signal: context.abort,\n })\n if (args.purpose === \"instrumentation-check\" && result.exitCode === 0) await probes.validate(args.probeIds)\n return serializeResult(result)\n } catch (error) {\n if (error instanceof DebugModeError) {\n return JSON.stringify(\n failure(error.code, error.message, error.retryable, {\n ...(error.action === undefined ? {} : { action: error.action }),\n ...(error.details === undefined ? {} : { details: error.details }),\n }),\n )\n }\n return JSON.stringify(failure(\"INTERNAL_ERROR\", \"Process capture failed\", false))\n }\n },\n })\n}\n\nexport function createRunStartTool(\n registry: SessionRegistry,\n runFor: (session: DebugSession) => RunService,\n): ToolDefinition {\n return tool({\n description: \"Start a correlated pre-fix or post-fix reproduction run\",\n args: {\n label: schema.enum([\"pre-fix\", \"post-fix\"]),\n reproduction: schema.string().min(1).max(8_192),\n waitingForUser: schema.boolean().default(false),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const run = await runFor(session).start(args)\n await registry.touch(context.sessionID)\n return JSON.stringify(success({ runId: run.id, status: run.status, label: run.label }))\n } catch (error) {\n if (error instanceof DebugModeError) return JSON.stringify(failure(error.code, error.message, error.retryable))\n return JSON.stringify(failure(\"INTERNAL_ERROR\", \"Run could not be started\", false))\n }\n },\n })\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport { LIMITS } from \"../core/constants.js\"\nimport type { SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport function createSessionStartTool(registry: SessionRegistry): ToolDefinition {\n return tool({\n description: \"Start an isolated runtime-debugging session\",\n args: {\n keepArtifacts: schema.boolean().default(false),\n retentionDestination: schema.string().min(1).max(8_192).optional(),\n },\n execute: async (args, context) => {\n try {\n const session = await registry.start(\n context.sessionID,\n { directory: context.directory, worktree: context.worktree },\n {\n keepArtifacts: args.keepArtifacts,\n ...(args.retentionDestination === undefined ? {} : { retentionDestination: args.retentionDestination }),\n },\n )\n return jsonSuccess({\n sessionId: session.publicId,\n status: \"active\",\n limits: LIMITS,\n capabilities: { process: true, web: true, extension: true, languages: [\"javascript\", \"typescript\"] },\n })\n } catch (error) {\n return jsonFailure(error, \"Debug session could not be started\")\n }\n },\n })\n}\n\nexport function createSessionStatusTool(registry: SessionRegistry): ToolDefinition {\n return tool({\n description: \"Read the public status of the active debug session\",\n args: {},\n execute: async (_args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const manifest = await session.manifestStore.read()\n const state = await session.investigationStore.readRecovery()\n return jsonSuccess({\n sessionId: session.publicId,\n status: manifest.status,\n phase: state.ok ? state.state.phase : \"recovery-required\",\n revision: state.ok ? state.state.revision : manifest.revision,\n collector:\n manifest.collector === null\n ? null\n : { status: manifest.collector.status, host: manifest.collector.host, port: manifest.collector.port },\n processCount: manifest.processes.length,\n probeCount: manifest.probes.length,\n counters: manifest.counters,\n limits: LIMITS,\n })\n } catch (error) {\n return jsonFailure(error, \"Debug session status is unavailable\")\n }\n },\n })\n}\n","import { type ToolDefinition, tool } from \"@opencode-ai/plugin\"\nimport type { InvestigationState } from \"../investigation/schema.js\"\nimport type { SessionRegistry } from \"../session/registry.js\"\nimport { jsonFailure, jsonSuccess } from \"./common.js\"\n\nconst schema = tool.schema\n\nexport function createStateReadTool(registry: SessionRegistry): ToolDefinition {\n return tool({\n description: \"Read and reconcile the durable investigation checkpoint\",\n args: {},\n execute: async (_args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await session.investigationStore.readRecovery()\n if (!result.ok) throw Object.assign(new Error(result.error.message), { code: result.error.code })\n return jsonSuccess({ state: result.state, recoveryWarnings: result.warnings })\n } catch (error) {\n if (typeof error === \"object\" && error !== null && \"code\" in error) {\n const value = error as { code: string; message: string }\n const { DebugModeError } = await import(\"../core/errors.js\")\n return jsonFailure(new DebugModeError(value.code as never, value.message), \"Checkpoint is unavailable\")\n }\n return jsonFailure(error, \"Checkpoint is unavailable\")\n }\n },\n })\n}\n\nexport function createStateCheckpointTool(registry: SessionRegistry): ToolDefinition {\n return tool({\n description: \"Atomically replace the durable investigation checkpoint\",\n args: { expectedRevision: schema.number().int().nonnegative(), state: schema.unknown() },\n execute: async (args, context) => {\n try {\n const session = await registry.requireOwned(context.sessionID)\n const result = await session.investigationStore.checkpoint(\n args.expectedRevision,\n args.state as InvestigationState,\n )\n await registry.touch(context.sessionID)\n return jsonSuccess({ revision: result.state.revision, bytes: result.bytes })\n } catch (error) {\n return jsonFailure(error, \"Checkpoint update failed\")\n }\n },\n })\n}\n","import type { ToolDefinition } from \"@opencode-ai/plugin\"\nimport type { CleanupService } from \"../cleanup/service.js\"\nimport type { EvidenceStore } from \"../evidence/store.js\"\nimport type { ProbeRegistry } from \"../probes/registry.js\"\nimport type { RunService } from \"../run/service.js\"\nimport type { DebugSession, SessionRegistry } from \"../session/registry.js\"\nimport { createCleanupTool } from \"./cleanup-tool.js\"\nimport { createCollectorStartTool, type PublicCollectorService } from \"./collector-tools.js\"\nimport { createEvidenceReadTool } from \"./evidence-tools.js\"\nimport { createProbePrepareTool, createProbeRegisterTool } from \"./probe-tools.js\"\nimport { createProcessCaptureTool, createRunStartTool, type RunToolDependencies } from \"./run-tools.js\"\nimport { createSessionStartTool, createSessionStatusTool } from \"./session-tools.js\"\nimport { createStateCheckpointTool, createStateReadTool } from \"./state-tools.js\"\n\nexport interface DebugToolDependencies extends RunToolDependencies {\n registry: SessionRegistry\n runFor(session: DebugSession): RunService\n collectorFor(session: DebugSession): PublicCollectorService\n probesFor(session: DebugSession): ProbeRegistry\n evidenceFor(session: DebugSession): EvidenceStore\n cleanupFor(session: DebugSession): CleanupService\n}\n\nexport type DebugTools = {\n debug_session_start: ToolDefinition\n debug_session_status: ToolDefinition\n debug_state_read: ToolDefinition\n debug_state_checkpoint: ToolDefinition\n debug_run_start: ToolDefinition\n debug_process_capture: ToolDefinition\n debug_collector_start: ToolDefinition\n debug_probe_prepare: ToolDefinition\n debug_probe_register: ToolDefinition\n debug_evidence_read: ToolDefinition\n debug_cleanup: ToolDefinition\n}\n\nexport function createDebugTools(dependencies: DebugToolDependencies): DebugTools {\n return {\n debug_session_start: createSessionStartTool(dependencies.registry),\n debug_session_status: createSessionStatusTool(dependencies.registry),\n debug_state_read: createStateReadTool(dependencies.registry),\n debug_state_checkpoint: createStateCheckpointTool(dependencies.registry),\n debug_run_start: createRunStartTool(dependencies.registry, dependencies.runFor),\n debug_process_capture: createProcessCaptureTool(dependencies),\n debug_collector_start: createCollectorStartTool(dependencies.registry, dependencies.collectorFor),\n debug_probe_prepare: createProbePrepareTool(dependencies.registry, dependencies.probesFor),\n debug_probe_register: createProbeRegisterTool(dependencies.registry, dependencies.probesFor),\n debug_evidence_read: createEvidenceReadTool(dependencies.registry, dependencies.evidenceFor),\n debug_cleanup: createCleanupTool(dependencies.registry, dependencies.cleanupFor),\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,cAAc;AACvB,OAAOC,YAAU;;;ACFjB,SAAS,SAAAC,cAAa;AACtB,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,YAAAC,WAAU,MAAAC,WAAU;AAC7B,SAAS,eAAAC,oBAAmB;;;ACH5B,SAAS,UAAU,iBAAiB;AACpC,SAAS,YAAY,QAAyB,aAAa;AAO3D,IAAM,iBAAiB;AACvB,IAAM,aAAa,EAAE,SAAS,GAAG,cAAc,MAAM,KAAK,KAAK;AAE/D,SAAS,aAAa,MAAuC;AAC3D,QAAM,SAAuB,CAAC;AAC9B,QAAM,QAAQ,MAAM,MAAM,QAAQ,EAAE,oBAAoB,MAAM,k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OAAO,EAAE,UAAU,GAAG,WAAW;AAClE,YAAI,MAAM,SAAS,WAAW,SAAS,GAAG;AACxC,iBAAO,QAAQ;AAAA,YACb;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,MACA,SAAS,YAAY;AACnB,mBAAW,WAAW,SAAS,WAAW,GAAG;AAC3C,gBAAM,WAAW,OAAO,EAAE,QAAQ,IAAI;AAAA,YACpC,QAAQ;AAAA,YACR,aAAa,eAAe,aAAa,8BAA8B;AAAA,UACzE,CAAC;AAAA,QACH;AACA,cAAM,SAAS,SAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF;AACF;AAEO,IAAM,kBAA0B,sBAAsB;","names":["readFile","path","spawn","createHash","readFile","rm","performance","error","matches","index","readFile","writeFile","error","error","createHash","mkdir","readFile","realpath","writeFile","path","value","z","z","z","z","error","z","createHash","writeFile","realpath","path","mkdir","readFile","error","performance","result","rm","error","readFile","createHash","spawn","randomBytes","z","createHash","z","error","randomBytes","randomBytes","error","randomBytes","performance","appendFile","z","z","z","createReadStream","createReadStream","error","z","appendFile","error","createHash","mkdir","realpath","writeFile","path","realpath","path","mkdir","writeFile","sha256","createHash","createHash","randomBytes","readFile","realpath","path","randomBytes","sha256","createHash","run","path","realpath","readFile","occurrences","createHash","randomBytes","path","z","randomBytes","path","createHash","result","randomBytes","randomBytes","lstat","readdir","realpath","path","readFile","stat","randomBytes","rename","rm","path","error","stat","error","readFile","readFile","realpath","stat","path","stat","error","readFile","realpath","path","randomBytes","readFile","writeFile","error","path","realpath","error","readdir","lstat","createHash","randomBytes","lstat","readdir","realpath","rm","path","createHash","realpath","randomBytes","path","error","rm","readdir","matches","lstat","path","error","error","path","error","tool","schema","tool","error","tool","schema","tool","error","path","tool","schema","tool","path","error","path","tool","schema","tool","path","error","tool","schema","tool","error","tool","schema","tool","error","DebugModeError","readFile","path","error"]}