debuganything 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.claude-plugin/plugin.json +15 -0
  2. package/DISCLAIMER.md +101 -0
  3. package/GEMINI.md +97 -0
  4. package/LICENSE +21 -0
  5. package/README.md +283 -2
  6. package/assets/README.md +9 -0
  7. package/assets/debuganything-logo.png +0 -0
  8. package/assets/debuganything-mark-512.png +0 -0
  9. package/dist/chunk-32IDKAZK.js +9 -0
  10. package/dist/chunk-32IDKAZK.js.map +1 -0
  11. package/dist/chunk-5BXTDASF.js +135 -0
  12. package/dist/chunk-5BXTDASF.js.map +1 -0
  13. package/dist/chunk-5RAKTYW5.js +292 -0
  14. package/dist/chunk-5RAKTYW5.js.map +1 -0
  15. package/dist/chunk-7MMXFUUN.js +79 -0
  16. package/dist/chunk-7MMXFUUN.js.map +1 -0
  17. package/dist/chunk-D742WJPT.js +436 -0
  18. package/dist/chunk-D742WJPT.js.map +1 -0
  19. package/dist/chunk-EMR42ZJQ.js +102 -0
  20. package/dist/chunk-EMR42ZJQ.js.map +1 -0
  21. package/dist/chunk-MLDOO673.js +1416 -0
  22. package/dist/chunk-MLDOO673.js.map +1 -0
  23. package/dist/chunk-NFL22T3H.js +309 -0
  24. package/dist/chunk-NFL22T3H.js.map +1 -0
  25. package/dist/chunk-STFC7C5C.js +245 -0
  26. package/dist/chunk-STFC7C5C.js.map +1 -0
  27. package/dist/chunk-VGYXHXTY.js +1015 -0
  28. package/dist/chunk-VGYXHXTY.js.map +1 -0
  29. package/dist/chunk-YY6M5RIJ.js +215 -0
  30. package/dist/chunk-YY6M5RIJ.js.map +1 -0
  31. package/dist/cli.js +254 -0
  32. package/dist/cli.js.map +1 -0
  33. package/dist/docker-ORXYMES4.js +23 -0
  34. package/dist/docker-ORXYMES4.js.map +1 -0
  35. package/dist/hook-QYLLBUNK.js +14 -0
  36. package/dist/hook-QYLLBUNK.js.map +1 -0
  37. package/dist/import-CT55AEEE.js +268 -0
  38. package/dist/import-CT55AEEE.js.map +1 -0
  39. package/dist/investigate-2GFD6EWB.js +102 -0
  40. package/dist/investigate-2GFD6EWB.js.map +1 -0
  41. package/dist/lsof-GBLZJBJR.js +22 -0
  42. package/dist/lsof-GBLZJBJR.js.map +1 -0
  43. package/dist/psmem-UB3VCMG3.js +20 -0
  44. package/dist/psmem-UB3VCMG3.js.map +1 -0
  45. package/dist/report_html-2ENM7HLC.js +99 -0
  46. package/dist/report_html-2ENM7HLC.js.map +1 -0
  47. package/dist/server.js +190 -0
  48. package/dist/server.js.map +1 -0
  49. package/dist/setup-NTPRUTMT.js +265 -0
  50. package/dist/setup-NTPRUTMT.js.map +1 -0
  51. package/dist/target-WJE4WFYA.js +36 -0
  52. package/dist/target-WJE4WFYA.js.map +1 -0
  53. package/gemini-extension.json +9 -0
  54. package/hooks/debuganything-hook.mjs +36 -0
  55. package/hooks/hooks.json +10 -0
  56. package/package.json +85 -3
  57. package/server.json +30 -0
  58. package/skills/debug-anything/SKILL.md +102 -0
  59. package/skills/inspect-product/SKILL.md +138 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/pyspy.ts","../src/stacks.ts","../src/adapters/strace.ts","../src/adapters/gdb.ts","../src/adapters/lldb.ts","../src/adapters/perf.ts","../src/adapters/tcpdump.ts","../src/adapters/sample_macos.ts","../src/adapters/fs_usage.ts","../src/adapters/jvm.ts"],"sourcesContent":["/**\n * py-spy adapter: profile_cpu (record → folded stacks → flamegraph), dump_stacks\n * (thread stacks + lock-wait detection), snapshot_memory contribution (dump --locals).\n */\nimport { readFileSync } from \"node:fs\";\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport type { ToolResult } from \"../contracts.js\";\nimport { ResultBuilder } from \"../evidence.js\";\nimport { runCapped, clampDuration, looksLikePermissionError, rootRequiredLimitation, LIMITS } from \"../safety.js\";\nimport { aggregateFrames, hottestStacks, parseFolded, renderFlamegraph, IDLE_FRAME } from \"../stacks.js\";\nimport { platform } from \"../session.js\";\n\n// ---------------------------------------------------------------------------\n// Parsing `py-spy dump`\n// ---------------------------------------------------------------------------\n\nexport interface PyThread {\n id: string;\n state: string; // active | idle\n name: string;\n frames: Array<{ func: string; file: string; line: number; locals?: Record<string, string> }>;\n os_tid?: string;\n}\n\nexport interface PyDump {\n pid?: number;\n command?: string;\n python?: string;\n threads: PyThread[];\n}\n\n/** Parse `py-spy dump [--locals]` text. Pure. */\nexport function parsePySpyDump(raw: string): PyDump {\n const out: PyDump = { threads: [] };\n let cur: PyThread | null = null;\n let localsTarget: Record<string, string> | null = null;\n for (const line of raw.split(\"\\n\")) {\n let m = /^Process (\\d+): (.*)$/.exec(line);\n if (m) {\n out.pid = Number(m[1]);\n out.command = m[2]!.trim();\n continue;\n }\n m = /^Python v([\\d.]+)/.exec(line);\n if (m) {\n out.python = m[1];\n continue;\n }\n m = /^Thread (0x[0-9A-Fa-f]+|\\d+) \\((\\w+)\\)(?:: \"(.*)\")?(?:.*?\\(os thread (\\S+)\\))?/.exec(line);\n if (m) {\n cur = { id: m[1]!, state: m[2]!, name: m[3] ?? \"\", frames: [], os_tid: m[4] };\n out.threads.push(cur);\n localsTarget = null;\n continue;\n }\n if (!cur) continue;\n m = /^\\s{4}(\\S.*?) \\((.+?):(\\d+)\\)\\s*$/.exec(line);\n if (m) {\n cur.frames.push({ func: m[1]!, file: m[2]!, line: Number(m[3]) });\n localsTarget = null;\n continue;\n }\n if (/^\\s{8}(Arguments|Locals):/.test(line)) {\n const f = cur.frames[cur.frames.length - 1];\n if (f) {\n f.locals ??= {};\n localsTarget = f.locals;\n }\n continue;\n }\n m = /^\\s{12}(\\w+): (.*)$/.exec(line);\n if (m && localsTarget) localsTarget[m[1]!] = m[2]!.slice(0, 200);\n }\n return out;\n}\n\nconst STDLIB_FILE = /(^|\\/)(threading|queue|socket|selectors|ssl|asyncio\\/[a-z_]+|concurrent\\/futures\\/[a-z_]+|subprocess|time|multiprocessing\\/[a-z_]+)\\.py$/;\n\nexport type WaitKind = \"lock\" | \"join\" | \"sleep\" | \"io\" | \"native\" | \"idle_loop\";\n\nexport interface LockWait {\n thread: string;\n state: string;\n kind: WaitKind;\n /** Where (top frame) the thread is blocked. */\n waiting_in: string;\n /** First application frame (outside the stdlib) — where in the app it waits. */\n at: string;\n /** Source text of the blocking line when readable on this host. */\n source?: string;\n lock_repr?: string;\n}\n\n/** Read one source line (1-based) if the file is readable locally; capped. Not pure, but safe. */\nexport function sourceLine(file: string, line: number, reader: (f: string) => string | undefined = defaultReader): string | undefined {\n if (!file || !/\\.py$/.test(file) || line < 1) return undefined;\n const text = reader(file);\n if (!text) return undefined;\n return text.split(\"\\n\")[line - 1]?.trim().slice(0, 160);\n}\n\nconst srcCache = new Map<string, string | undefined>();\nfunction defaultReader(f: string): string | undefined {\n if (srcCache.has(f)) return srcCache.get(f);\n let v: string | undefined;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n v = readFileSync(f, \"utf8\");\n } catch {\n v = undefined;\n }\n srcCache.set(f, v);\n return v;\n}\n\nconst LOCK_SRC = /\\bwith\\b[^:]*(lock|mutex|sem|cond|rlock|lk\\b)|\\.acquire\\(|\\.__enter__\\(|lock\\(|Lock\\(\\)\\.acquire/i;\nconst JOIN_SRC = /\\.join\\(|\\.result\\(|\\.wait\\(|\\.get\\(|wait_for|as_completed|\\.gather\\(/;\nconst SLEEP_SRC = /\\bsleep\\(/;\nconst IO_SRC = /\\.(recv|recv_into|recvfrom|read|readline|readinto|accept|connect|send|sendall|write)\\(|requests\\.|urlopen|httpx\\.|\\.execute\\(|\\.fetch(one|all|many)\\(|\\.commit\\(|select\\.select|\\.poll\\(/;\n\n/**\n * Classify what each thread is blocked in. py-spy shows a thread blocked in a\n * C-level call (lock acquire, sleep, socket read) with the *Python caller* as the\n * top frame, so we look at the top frame's function, file and — when readable —\n * its source line. Pure given a reader.\n */\nexport function findLockWaits(dump: PyDump, reader?: (f: string) => string | undefined, cwd?: string): LockWait[] {\n const out: LockWait[] = [];\n const resolve = (f: string) => (cwd && !f.startsWith(\"/\") ? `${cwd.replace(/\\/$/, \"\")}/${f}` : f);\n for (const t of dump.threads) {\n const top = t.frames[0];\n if (!top) continue;\n const user = t.frames.find((f) => !STDLIB_FILE.test(f.file) && !/<frozen|importlib|site-packages\\/(werkzeug|flask|gunicorn|uvicorn|django)/.test(f.file)) ?? top;\n const base = {\n thread: t.name || t.id,\n state: t.state,\n waiting_in: `${top.func} (${top.file.split(\"/\").pop()}:${top.line})`,\n at: `${user.func} (${user.file.split(\"/\").pop()}:${user.line})`,\n lock_repr: Object.entries(top.locals ?? {}).find(([k]) => /lock|cond|mutex|sem/i.test(k))?.[1],\n };\n const inStdlib = STDLIB_FILE.test(top.file);\n let kind: WaitKind | undefined;\n if (inStdlib) {\n if (/_wait_for_tstate_lock|^join$/.test(top.func)) kind = \"join\";\n else if (/acquire|__enter__|^wait$|_acquire_restore|^get$|^put$/.test(top.func) && /threading|queue/.test(top.file)) kind = /^(get|put)$/.test(top.func) ? \"join\" : \"lock\";\n else if (/sleep/.test(top.func)) kind = \"sleep\";\n else if (/select|poll|recv|read|accept|connect|send|^wait$/.test(top.func)) kind = \"io\";\n else if (/asyncio|run_forever|_run_once|serve_forever/.test(top.file + top.func)) kind = \"idle_loop\";\n }\n if (!kind && t.state !== \"active\") {\n // Blocked in a C call from user code: read the line to see what it does.\n const src = sourceLine(resolve(top.file), top.line, reader);\n if (src) {\n if (LOCK_SRC.test(src)) kind = \"lock\";\n else if (SLEEP_SRC.test(src)) kind = \"sleep\";\n else if (JOIN_SRC.test(src)) kind = \"join\";\n else if (IO_SRC.test(src)) kind = \"io\";\n else kind = \"native\";\n out.push({ ...base, kind, source: src });\n continue;\n }\n if (!inStdlib) kind = \"native\";\n }\n if (kind) out.push({ ...base, kind });\n }\n return out;\n}\n\n/** Working directory of a pid (to resolve relative source paths py-spy reports). */\nexport async function targetCwd(pid: number): Promise<string | undefined> {\n if (platform() === \"linux\") {\n try {\n const { readlink } = await import(\"node:fs/promises\");\n return await readlink(`/proc/${pid}/cwd`);\n } catch {\n return undefined;\n }\n }\n const r = await runCapped(\"lsof\", [\"-a\", \"-p\", String(pid), \"-d\", \"cwd\", \"-Fn\"], { timeoutMs: 5000 });\n return r.stdout.split(\"\\n\").find((l) => l.startsWith(\"n\"))?.slice(1);\n}\n\n/** Group lock waits by lock repr (when --locals gave us one). Pure. */\nexport function sameLockGroups(waits: LockWait[]): Array<{ lock: string; threads: string[] }> {\n const by = new Map<string, string[]>();\n for (const w of waits) {\n if (!w.lock_repr || w.kind !== \"lock\") continue;\n const k = w.lock_repr.replace(/\\s+/g, \" \");\n by.set(k, [...(by.get(k) ?? []), w.thread]);\n }\n return [...by].filter(([, t]) => t.length > 1).map(([lock, threads]) => ({ lock, threads }));\n}\n\n// ---------------------------------------------------------------------------\n// Tools\n// ---------------------------------------------------------------------------\n\nfunction needsSudoNote(b: ResultBuilder, stderr: string, cmd: string): boolean {\n if (looksLikePermissionError(stderr) || /Operation not permitted|ptrace|task_for_pid|Permission denied/i.test(stderr)) {\n b.limitation(rootRequiredLimitation(\"py-spy\", cmd));\n if (platform() === \"darwin\") b.limitation(\"macOS: py-spy needs sudo (or the target must be a child of this process). SIP blocks task_for_pid otherwise.\");\n if (platform() === \"linux\") b.limitation(\"Linux: set kernel.yama.ptrace_scope=0 or run with CAP_SYS_PTRACE; inside Docker add --cap-add SYS_PTRACE\");\n return true;\n }\n return false;\n}\n\n/** Shared by dump_stacks, snapshot_memory and `debuganything import`: parsed dump → evidence + findings. */\nexport async function summarizePySpyDump(b: ResultBuilder, dump: PyDump, art: string, pid?: number): Promise<void> {\n const active = dump.threads.filter((t) => t.state === \"active\");\n const summaryEv = b.evidenceOf(\n \"stack_summary\",\n `${dump.threads.length} thread(s): ${active.length} active, ${dump.threads.length - active.length} idle; python ${dump.python ?? \"?\"}`,\n dump.threads.map((t) => ({ thread: t.name || t.id, state: t.state, top: t.frames[0] ? `${t.frames[0].func} (${t.frames[0].file.split(\"/\").pop()}:${t.frames[0].line})` : \"?\" , depth: t.frames.length })),\n { artifact: art },\n );\n for (const t of dump.threads.slice(0, 12)) {\n b.evidenceOf(\n \"stack\",\n `${t.name || t.id} [${t.state}]: ${t.frames\n .slice(0, 4)\n .map((f) => `${f.func}@${f.file.split(\"/\").pop()}:${f.line}`)\n .join(\" ← \")}`,\n { thread: t.name || t.id, state: t.state, frames: t.frames.slice(0, 15).map((f) => ({ func: f.func, file: f.file, line: f.line, ...(f.locals ? { locals: f.locals } : {}) })) },\n { artifact: art },\n );\n }\n const cwd = pid ? await targetCwd(pid) : undefined;\n const waits = findLockWaits(dump, undefined, cwd);\n const locks = waits.filter((w) => w.kind === \"lock\");\n const joins = waits.filter((w) => w.kind === \"join\");\n const io = waits.filter((w) => w.kind === \"io\");\n const sleeps = waits.filter((w) => w.kind === \"sleep\");\n const natives = waits.filter((w) => w.kind === \"native\");\n const loops = waits.filter((w) => w.kind === \"idle_loop\");\n const fmt = (w: LockWait) => `${w.thread} at ${w.at}${w.source ? ` [${w.source}]` : \"\"}`;\n if (waits.length) {\n const waitEv = b.evidenceOf(\n \"lock_wait\",\n `${waits.length} blocked thread(s): ${locks.length} on locks, ${joins.length} joining/waiting, ${io.length} in I/O, ${sleeps.length} sleeping, ${natives.length} in other native calls, ${loops.length} idle event loops`,\n waits.map((w) => ({ thread: w.thread, kind: w.kind, at: w.at, waiting_in: w.waiting_in, source: w.source, lock_repr: w.lock_repr })),\n { artifact: art },\n );\n const groups = sameLockGroups(waits);\n if (groups.length) b.finding(\"high\", `${groups[0]!.threads.length} threads wait on the same lock ${groups[0]!.lock}: ${groups[0]!.threads.join(\", \")}`, [waitEv], \"observed\");\n if (locks.length >= 2 && active.length === 0) {\n b.finding(\n \"high\",\n `likely deadlock: ${locks.length} thread(s) blocked acquiring locks and no thread is running — ${locks.slice(0, 6).map(fmt).join(\"; \")}`,\n [waitEv, summaryEv],\n \"inferred\",\n `${joins.length ? `${joins.length} thread(s) are joined on them (${joins.slice(0, 3).map((w) => w.thread).join(\", \")}). ` : \"\"}Re-run dump_stacks: identical positions confirm a deadlock. Handoff: attach a step debugger (e.g. mcp-debugger) at ${locks[0]!.at} to inspect lock owners.`,\n );\n } else if (locks.length) {\n b.finding(\"warn\", `${locks.length} thread(s) blocked acquiring a lock: ${locks.slice(0, 6).map(fmt).join(\"; \")}`, [waitEv], \"observed\");\n }\n if (joins.length >= 3 && !locks.length) b.finding(\"warn\", `${joins.length} thread(s) waiting on other threads/queues: ${joins.slice(0, 4).map(fmt).join(\"; \")}`, [waitEv], \"observed\");\n if (io.length) b.finding(io.length >= 3 ? \"warn\" : \"info\", `${io.length} thread(s) blocked in I/O: ${io.slice(0, 4).map(fmt).join(\"; \")}`, [waitEv], \"observed\", \"inspect_sockets shows which remote they talk to.\");\n if (sleeps.length) b.finding(\"info\", `${sleeps.length} thread(s) in sleep(): ${sleeps.slice(0, 3).map(fmt).join(\"; \")}`, [waitEv], \"observed\");\n if (natives.length) b.finding(\"info\", `${natives.length} thread(s) blocked in native calls from user code: ${natives.slice(0, 3).map(fmt).join(\"; \")}`, [waitEv], \"observed\");\n }\n if (b.findingCount === 0 && active.length === 0) b.finding(\"info\", \"all threads idle — the process is not stuck in Python code; if the caller hangs, look at the network path (inspect_sockets)\", [summaryEv], \"inferred\");\n if (active.length) {\n const t = active[0]!;\n const f = t.frames[0];\n if (f) b.finding(\"info\", `active thread ${t.name || t.id} is executing ${f.func} (${f.file.split(\"/\").pop()}:${f.line})`, [summaryEv]);\n }\n}\n\nasync function dumpStacks(ctx: AdapterContext, withLocals: boolean, tool = \"dump_stacks\"): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(tool, session, target);\n if (!target.pid) return b.fail(\"no pid\").build();\n const args = [\"dump\", \"--pid\", String(target.pid), \"--nonblocking\"];\n if (withLocals) args.push(\"--locals\");\n const cmd = `py-spy ${args.join(\" \")}`;\n const r = await runCapped(\"py-spy\", args, { timeoutMs: 30_000 });\n const raw = r.stdout + (r.stderr ? `\\n--- stderr ---\\n${r.stderr}` : \"\");\n const art = await b.writeArtifact(\"pyspy-dump.txt\", raw, \"raw_text\", cmd);\n if (r.exitCode !== 0) {\n if (!needsSudoNote(b, r.stderr, cmd)) b.limitation(`py-spy exited ${r.exitCode}: ${r.stderr.trim().slice(0, 300)}`);\n b.next(`import_artifact (pyspy_dump, after running the sudo command above)`, \"inspect_sockets\", \"inspect_files\", \"snapshot_memory\");\n return b.fail(\"py-spy dump failed\").build();\n }\n await summarizePySpyDump(b, parsePySpyDump(r.stdout), art, target.pid);\n b.limitation(\"instant snapshot (nonblocking); take two dumps to distinguish a hang from a slow step\");\n b.next(\"inspect_sockets\", \"trace_syscalls\", \"profile_cpu\");\n return b.build();\n}\n\nasync function profileCpu(ctx: AdapterContext, args: { duration_s?: number }): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"profile_cpu\", session, target);\n if (!target.pid) return b.fail(\"no pid\").build();\n const duration = clampDuration(args.duration_s, 15);\n const rawPath = b.artifactPath(\"pyspy-folded.txt\");\n const cmdArgs = [\"record\", \"--pid\", String(target.pid), \"--duration\", String(duration), \"--format\", \"raw\", \"--output\", rawPath, \"--nonblocking\", \"--subprocesses\"];\n const r = await runCapped(\"py-spy\", cmdArgs, { timeoutMs: duration * 1000 + LIMITS.DURATION_SLACK_MS + 5000 });\n if (r.exitCode !== 0) {\n await b.writeArtifact(\"pyspy-stderr.txt\", r.stderr, \"raw_text\");\n if (!needsSudoNote(b, r.stderr, `py-spy ${cmdArgs.join(\" \")}`)) b.limitation(`py-spy exited ${r.exitCode}: ${r.stderr.trim().slice(0, 300)}`);\n b.next(\"import_artifact (folded, after running the sudo command above)\", \"inspect_sockets\", \"snapshot_memory\");\n return b.fail(\"py-spy record failed\").build();\n }\n const { readFile } = await import(\"node:fs/promises\");\n const folded = await readFile(rawPath, \"utf8\").catch(() => \"\");\n await b.addArtifact(rawPath, \"folded_stacks\", { description: `py-spy record ${duration}s, folded stacks` });\n return summarizeProfile(b, folded, duration, \"py-spy\", 100);\n}\n\n/**\n * Shared by py-spy/perf/sample: folded stacks → evidence + findings + svg.\n * `sampleHz` is the profiler's rate so we can turn work samples into \"% of wall time\"\n * (perf only samples on-CPU time, so its idle share is ~0 by construction).\n */\nexport async function summarizeProfile(b: ResultBuilder, folded: string, duration: number, profiler: string, sampleHz?: number): Promise<ToolResult> {\n const stacks = parseFolded(folded);\n if (!stacks.length) {\n b.limitation(`${profiler} produced no samples in ${duration}s (process idle, or sampling blocked)`);\n const ev = b.evidenceOf(\"metric\", \"0 samples\", { name: \"samples\", value: 0 });\n b.finding(\"info\", `no CPU samples in ${duration}s — the process is idle or sleeping, not CPU-bound`, [ev], \"inferred\");\n b.next(\"dump_stacks\", \"trace_syscalls\", \"inspect_sockets\");\n return b.build();\n }\n const { frames, totalSamples } = aggregateFrames(stacks, 15);\n // Idle/wait leaves vs work leaves. Multi-threaded targets have many permanently idle threads, so we\n // rank hot frames among WORK samples, not all samples.\n const workStacks = stacks.filter((s) => !IDLE_FRAME.test(s.frames[s.frames.length - 1]!));\n const workSamples = workStacks.reduce((n, s) => n + s.count, 0);\n const idlePct = Math.round((100 * (totalSamples - workSamples)) / totalSamples);\n const { frames: workFrames } = aggregateFrames(workStacks, 15);\n const hot = hottestStacks(workStacks.length ? workStacks : stacks, 5);\n const svg = renderFlamegraph(stacks, { title: `${profiler} ${duration}s pid ${b.target.pid}` });\n const svgPath = await b.writeArtifact(\"flamegraph.svg\", svg, \"flamegraph_svg\", \"flame graph (all threads, idle included)\");\n // Busy share of wall time: for a single-threaded runtime this is \"how busy was the main thread\".\n const busyWall = sampleHz ? Math.min(100, Math.round((100 * workSamples) / (sampleHz * duration))) : undefined;\n const framesEv = b.evidenceOf(\n \"frame_hot\",\n workFrames.length\n ? `top self among ${workSamples} work samples: ${workFrames\n .slice(0, 5)\n .map((f) => `${shortFrame(f.frame)} ${f.self_pct}%`)\n .join(\", \")}`\n : `no work frames; all ${totalSamples} samples idle`,\n (workFrames.length ? workFrames : frames).map((f) => ({ frame: f.frame, self: f.self, total: f.total, self_pct: f.self_pct, total_pct: f.total_pct })),\n { artifact: svgPath },\n );\n const stacksEv = b.evidenceOf(\"stack\", `hottest work stack (${hot[0]?.pct}% of work): ${hot[0]?.stack.slice(-4).map(shortFrame).join(\" ← \")}`, hot, { artifact: svgPath });\n const metricEv = b.evidenceOf(\n \"metric\",\n `${totalSamples} samples over ${duration}s: ${workSamples} work, ${idlePct}% idle/wait${busyWall !== undefined ? `; ≈${busyWall}% of wall time CPU-busy (${sampleHz} Hz)` : \"\"}`,\n { name: \"samples\", value: totalSamples, work_samples: workSamples, idle_pct: idlePct, busy_wall_pct: busyWall, duration_s: duration, sample_hz: sampleHz },\n );\n\n const topWork = workFrames[0];\n if (topWork && topWork.self_pct >= 20) {\n b.finding(busyWall === undefined || busyWall >= 25 ? \"high\" : \"warn\", `${shortFrame(topWork.frame)} accounts for ${topWork.self_pct}% of CPU work (${topWork.total_pct}% inclusive)${busyWall !== undefined ? `; the process was CPU-busy ≈${busyWall}% of the time` : \"\"}`, [framesEv, stacksEv, metricEv], \"observed\", `Hot path: ${hot[0]?.stack.slice(-6).map(shortFrame).join(\" ← \")}. Handoff: attach a step debugger (e.g. mcp-debugger) at ${topWork.frame}.`);\n } else if (topWork && topWork.self_pct >= 8) {\n b.finding(\"warn\", `${shortFrame(topWork.frame)} is the top CPU frame at ${topWork.self_pct}% of work`, [framesEv, stacksEv], \"observed\");\n }\n if (busyWall !== undefined && busyWall < 15) {\n b.finding(\"info\", `process CPU-busy only ≈${busyWall}% of wall time — mostly waiting, not CPU-bound`, [metricEv], \"inferred\", \"Look at trace_syscalls (what is it waiting on?) and inspect_sockets (whom?).\");\n } else if (busyWall === undefined && idlePct >= 90 && !topWork) {\n b.finding(\"info\", `~${idlePct}% of samples are in idle/wait frames — the process is mostly waiting, not CPU-bound`, [metricEv], \"inferred\");\n }\n if (b.findingCount === 0) b.finding(\"info\", `CPU spread thin: top work frame ${shortFrame((workFrames[0] ?? frames[0])!.frame)} at ${(workFrames[0] ?? frames[0])!.self_pct}%`, [framesEv]);\n b.limitation(`sampled ${duration}s only (${profiler}${sampleHz ? ` @ ${sampleHz} Hz` : \"\"}); idle frames across all threads are excluded from the hot-frame ranking`);\n b.next(\"trace_syscalls\", \"dump_stacks\", \"inspect_sockets\");\n if (topWork && topWork.self_pct >= 20 && (profiler === \"perf\" || profiler === \"sample\")) {\n const dso = /\\(([^)]+)\\)\\s*$/.exec(topWork.frame)?.[1];\n b.next(`static analysis: decompile ${shortFrame(topWork.frame).replace(/\\s*\\(.*$/, \"\")}${dso ? ` in ${dso}` : \"\"} to see what the hot code does`);\n }\n return b.build();\n}\n\nfunction shortFrame(f: string): string {\n // \"func (path/to/file.py:12)\" → \"func (file.py:12)\"; \"lib.so`sym\" → keep; perf \"sym+0x1 (dso)\" → \"sym (dso)\"\n return f.replace(/\\(([^)]*\\/)?([^/)]+)\\)/, \"($2)\").replace(/\\+0x[0-9a-f]+/, \"\").slice(0, 80);\n}\n\nexport const pyspyAdapter: Adapter = {\n name: \"py-spy\",\n tools: [\"profile_cpu\", \"dump_stacks\", \"snapshot_memory\"],\n platforms: [\"linux\", \"darwin\"],\n requires: [\"py-spy\"],\n runtimes: [\"python\"],\n install: { linux: \"pip install py-spy (or: cargo install py-spy)\", darwin: \"pip install py-spy (or: brew install py-spy)\" },\n priority: 20,\n check(base, env) {\n if (env.platform === \"darwin\" && !env.isRoot) base.notes.push(\"macOS: attaching to processes you did not spawn requires sudo\");\n if (env.platform === \"linux\" && env.ptraceScope !== null && env.ptraceScope >= 1 && !env.isRoot) base.notes.push(`ptrace_scope=${env.ptraceScope}: can only attach to child processes without root`);\n return base;\n },\n async run(tool, args, ctx) {\n if (tool === \"dump_stacks\") return dumpStacks(ctx, false);\n if (tool === \"profile_cpu\") return profileCpu(ctx, args as { duration_s?: number });\n if (tool === \"snapshot_memory\") {\n // py-spy contributes a stack+locals dump; psmem adapter adds RSS series. Dispatcher takes the first ok result,\n // so we merge both here.\n const { snapshotMemoryGeneric } = await import(\"./psmem.js\");\n const base = await snapshotMemoryGeneric(ctx, args as { window_s?: number });\n const dump = await dumpStacks(ctx, true, \"snapshot_memory\");\n return mergeResults(base, dump, [\"instant stack+locals via py-spy; Python has no retained-size heap view without tracemalloc — enable tracemalloc in the app for allocation-site attribution\"]);\n }\n throw new Error(`py-spy adapter cannot run ${tool}`);\n },\n};\n\n/** Merge evidence/findings/artifacts of `extra` into `base`, re-numbering ids. Pure. */\nexport function mergeResults(base: ToolResult, extra: ToolResult, limitations: string[] = []): ToolResult {\n const offsetE = base.evidence.length;\n const offsetF = base.findings.length;\n const idMap = new Map<string, string>();\n const evidence = [...base.evidence];\n for (const e of extra.evidence) {\n const id = `e${evidence.length + 1}`;\n idMap.set(e.id, id);\n evidence.push({ ...e, id });\n }\n const findings = [...base.findings];\n for (const f of extra.findings) {\n findings.push({ ...f, id: `f${findings.length + 1}`, evidence_ids: f.evidence_ids.map((x) => idMap.get(x) ?? x) });\n }\n void offsetE;\n void offsetF;\n return {\n ...base,\n ok: base.ok || extra.ok,\n findings,\n evidence,\n limitations: [...new Set([...base.limitations, ...extra.limitations, ...limitations])],\n suggested_next: [...new Set([...base.suggested_next, ...extra.suggested_next])],\n artifacts: [...base.artifacts, ...extra.artifacts],\n duration_ms: base.duration_ms + extra.duration_ms,\n error: base.ok || extra.ok ? undefined : base.error ?? extra.error,\n };\n}\n","/**\n * Folded-stack utilities shared by profilers (py-spy, perf, sample):\n * parse \"a;b;c N\" lines, aggregate self/total per frame, find hottest stacks,\n * and render a flamegraph SVG with a small inline implementation (no Perl).\n */\n\nexport interface FoldedStack {\n frames: string[]; // root → leaf\n count: number;\n}\n\n/** Parse folded/collapsed stacks (\"root;child;leaf 12\"). Pure. */\nexport function parseFolded(raw: string): FoldedStack[] {\n const out: FoldedStack[] = [];\n for (const line of raw.split(\"\\n\")) {\n const t = line.trimEnd();\n if (!t) continue;\n const sp = t.lastIndexOf(\" \");\n if (sp < 0) continue;\n const count = Number(t.slice(sp + 1));\n if (!Number.isFinite(count)) continue;\n const frames = t.slice(0, sp).split(\";\").filter(Boolean);\n if (frames.length) out.push({ frames, count });\n }\n return out;\n}\n\nexport interface FrameStat {\n frame: string;\n self: number;\n total: number;\n self_pct: number;\n total_pct: number;\n}\n\n/** Aggregate self and inclusive sample counts per frame. Pure. */\nexport function aggregateFrames(stacks: FoldedStack[], limit = 15): { frames: FrameStat[]; totalSamples: number } {\n const self = new Map<string, number>();\n const total = new Map<string, number>();\n let totalSamples = 0;\n for (const s of stacks) {\n totalSamples += s.count;\n const leaf = s.frames[s.frames.length - 1]!;\n self.set(leaf, (self.get(leaf) ?? 0) + s.count);\n for (const f of new Set(s.frames)) total.set(f, (total.get(f) ?? 0) + s.count);\n }\n const frames = [...total.keys()]\n .map((frame) => ({\n frame,\n self: self.get(frame) ?? 0,\n total: total.get(frame) ?? 0,\n self_pct: totalSamples ? Math.round((1000 * (self.get(frame) ?? 0)) / totalSamples) / 10 : 0,\n total_pct: totalSamples ? Math.round((1000 * (total.get(frame) ?? 0)) / totalSamples) / 10 : 0,\n }))\n .sort((a, b) => b.self - a.self || b.total - a.total)\n .slice(0, limit);\n return { frames, totalSamples };\n}\n\n/** Hottest full stacks by count. Pure. */\nexport function hottestStacks(stacks: FoldedStack[], limit = 5, maxDepth = 12): Array<{ count: number; pct: number; stack: string[] }> {\n const total = stacks.reduce((s, x) => s + x.count, 0);\n return [...stacks]\n .sort((a, b) => b.count - a.count)\n .slice(0, limit)\n .map((s) => ({ count: s.count, pct: total ? Math.round((1000 * s.count) / total) / 10 : 0, stack: s.frames.length > maxDepth ? [...s.frames.slice(0, 3), `… ${s.frames.length - maxDepth + 3} frames …`, ...s.frames.slice(-(maxDepth - 4))] : s.frames }));\n}\n\n/** Frames that look like idle/wait rather than CPU work. */\nexport const IDLE_FRAME = /\\b(semaphore_wait_trap|__psynch_mutexwait|__ulock_wait|__workq_kernreturn|__sigsuspend|__wait4|epoll_wait|epoll_pwait|kevent|poll|select|futex|nanosleep|clock_nanosleep|pthread_cond_wait|pthread_cond_timedwait|__psynch_cvwait|mach_msg|mach_msg2_trap|__semwait_signal|__select|__workq_kernreturn|uv__io_poll|uv_run|sleep|time\\.sleep|wait|_wait_for_tstate_lock|<idle>|swapper)\\b/i;\n\n// ---------------------------------------------------------------------------\n// Flamegraph SVG\n// ---------------------------------------------------------------------------\n\ninterface Node {\n name: string;\n value: number;\n children: Map<string, Node>;\n}\n\nfunction buildTree(stacks: FoldedStack[]): Node {\n const root: Node = { name: \"all\", value: 0, children: new Map() };\n for (const s of stacks) {\n root.value += s.count;\n let cur = root;\n for (const f of s.frames) {\n let n = cur.children.get(f);\n if (!n) {\n n = { name: f, value: 0, children: new Map() };\n cur.children.set(f, n);\n }\n n.value += s.count;\n cur = n;\n }\n }\n return root;\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\");\n}\n\nfunction colorFor(name: string): string {\n // Deterministic warm palette keyed by name hash, like flamegraph.pl's \"hot\".\n let h = 0;\n for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0;\n const r = 205 + (h % 50);\n const g = 60 + ((h >> 8) % 120);\n const b = (h >> 16) % 60;\n return `rgb(${r},${g},${b})`;\n}\n\n/** Render folded stacks as a self-contained flamegraph SVG. Pure. */\nexport function renderFlamegraph(stacks: FoldedStack[], opts: { title?: string; width?: number; minWidthPx?: number } = {}): string {\n const width = opts.width ?? 1200;\n const rowH = 16;\n const minW = opts.minWidthPx ?? 0.5;\n const root = buildTree(stacks);\n const total = root.value || 1;\n let maxDepth = 0;\n const rects: string[] = [];\n const walk = (n: Node, x: number, depth: number) => {\n const w = (n.value / total) * width;\n if (w < minW) return;\n maxDepth = Math.max(maxDepth, depth);\n const label = w > 40 ? n.name.slice(0, Math.floor(w / 7)) : \"\";\n rects.push(\n `<g class=\"f\"><title>${esc(n.name)} (${n.value} samples, ${((100 * n.value) / total).toFixed(2)}%)</title><rect x=\"${x.toFixed(2)}\" y=\"${depth}\" width=\"${w.toFixed(2)}\" height=\"${rowH - 1}\" fill=\"${colorFor(n.name)}\" rx=\"1\"/>${label ? `<text x=\"${(x + 2).toFixed(2)}\" y=\"${depth + 11.5}\">${esc(label)}</text>` : \"\"}</g>`,\n );\n let cx = x;\n const kids = [...n.children.values()].sort((a, b) => b.value - a.value);\n for (const k of kids) {\n walk(k, cx, depth + 1);\n cx += (k.value / total) * width;\n }\n };\n walk(root, 0, 0);\n const height = (maxDepth + 1) * rowH + 40;\n // y positions are depth indexes; flip so root is at the bottom.\n const body = rects.map((r) => r.replace(/ y=\"(\\d+)\"/, (_m, d) => ` y=\"${height - 24 - (Number(d) + 1) * rowH}\"`).replace(/<text x=\"([\\d.]+)\" y=\"(\\d+)\\.5\"/, (_m, x, d) => `<text x=\"${x}\" y=\"${height - 24 - (Number(d) + 1) * rowH + 11.5}\"`)).join(\"\\n\");\n return `<?xml version=\"1.0\" standalone=\"no\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\" viewBox=\"0 0 ${width} ${height}\" font-family=\"Verdana, sans-serif\" font-size=\"11\">\n<style>.f rect:hover{stroke:#000;stroke-width:1}.f text{pointer-events:none;fill:#000}</style>\n<rect width=\"100%\" height=\"100%\" fill=\"#f8f8f8\"/>\n<text x=\"${width / 2}\" y=\"18\" text-anchor=\"middle\" font-size=\"15\">${esc(opts.title ?? \"Flame Graph\")} — ${total} samples</text>\n${body}\n<text x=\"8\" y=\"${height - 6}\" fill=\"#666\">Generated by DEA (Debug Anything). Hover for counts; width = share of samples.</text>\n</svg>\n`;\n}\n","/**\n * strace adapter (Linux): trace_syscalls.\n * strace -f -T -tt -e trace=<set> -p PID -o <file>\n * Returns top syscalls by total time and count, slowest individual calls,\n * error counts, and blocked waits. Raw log → artifact.\n */\nimport { readFile } from \"node:fs/promises\";\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport type { SyscallCategory, ToolResult } from \"../contracts.js\";\nimport { ResultBuilder } from \"../evidence.js\";\nimport { runCapped, clampDuration, looksLikePermissionError, rootRequiredLimitation, LIMITS } from \"../safety.js\";\n\nexport const CATEGORY_SETS: Record<SyscallCategory, string> = {\n network: \"%network\",\n file: \"%file,%desc\",\n process: \"%process\",\n signal: \"%signal\",\n memory: \"%memory\",\n all: \"all\",\n};\n\nexport interface SyscallRecord {\n pid?: number;\n time?: string; // wall clock from -tt\n name: string;\n args: string;\n result: string; // \"0\", \"-1 ENOENT (No such file or directory)\", \"?\"\n errno?: string;\n duration_s?: number; // from -T\n unfinished?: boolean;\n resumed?: boolean;\n line: number; // 1-based line in the raw log\n}\n\nconst LINE_RE = /^(?:\\[pid\\s+(\\d+)\\]\\s+|(\\d+)\\s+)?(?:(\\d{2}:\\d{2}:\\d{2}\\.\\d+)\\s+)?(\\w+)\\((.*?)\\)\\s+=\\s+(.+?)(?:\\s+<([\\d.]+)>)?$/;\nconst UNFINISHED_RE = /^(?:\\[pid\\s+(\\d+)\\]\\s+|(\\d+)\\s+)?(?:(\\d{2}:\\d{2}:\\d{2}\\.\\d+)\\s+)?(\\w+)\\((.*)<unfinished \\.\\.\\.>$/;\nconst RESUMED_RE = /^(?:\\[pid\\s+(\\d+)\\]\\s+|(\\d+)\\s+)?(?:(\\d{2}:\\d{2}:\\d{2}\\.\\d+)\\s+)?<\\.\\.\\. (\\w+) resumed>\\s*(.*?)\\)?\\s+=\\s+(.+?)(?:\\s+<([\\d.]+)>)?$/;\n\n/** Parse an strace log produced with -f -T -tt. Pure. */\nexport function parseStrace(raw: string): SyscallRecord[] {\n const out: SyscallRecord[] = [];\n const lines = raw.split(\"\\n\");\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!.trimEnd();\n if (!line || line.startsWith(\"strace:\") || /\\+\\+\\+ (exited|killed)|--- SIG/.test(line)) continue;\n let m = LINE_RE.exec(line);\n if (m) {\n const result = m[6]!;\n const errno = /^-1 ([A-Z]+)/.exec(result)?.[1];\n out.push({ pid: m[1] ? Number(m[1]) : m[2] ? Number(m[2]) : undefined, time: m[3], name: m[4]!, args: m[5]!, result, errno, duration_s: m[7] ? Number(m[7]) : undefined, line: i + 1 });\n continue;\n }\n m = UNFINISHED_RE.exec(line);\n if (m) {\n out.push({ pid: m[1] ? Number(m[1]) : m[2] ? Number(m[2]) : undefined, time: m[3], name: m[4]!, args: m[5]!, result: \"?\", unfinished: true, line: i + 1 });\n continue;\n }\n m = RESUMED_RE.exec(line);\n if (m) {\n const result = m[6]!;\n const errno = /^-1 ([A-Z]+)/.exec(result)?.[1];\n // Attach to the matching unfinished record for the same pid, if any.\n const pid = m[1] ? Number(m[1]) : m[2] ? Number(m[2]) : undefined;\n const open = [...out].reverse().find((r) => r.unfinished && r.name === m![4] && r.pid === pid && r.result === \"?\");\n if (open) {\n open.result = result;\n open.errno = errno;\n open.duration_s = m[7] ? Number(m[7]) : undefined;\n open.args += m[5] ?? \"\";\n open.resumed = true;\n } else out.push({ pid, time: m[3], name: m[4]!, args: m[5] ?? \"\", result, errno, duration_s: m[7] ? Number(m[7]) : undefined, resumed: true, line: i + 1 });\n }\n }\n return out;\n}\n\nexport interface SyscallStat {\n syscall: string;\n count: number;\n total_ms: number;\n avg_ms: number;\n max_ms: number;\n errors: number;\n}\n\nconst WAIT_SYSCALLS = new Set([\"futex\", \"epoll_wait\", \"epoll_pwait\", \"epoll_pwait2\", \"poll\", \"ppoll\", \"select\", \"pselect6\", \"nanosleep\", \"clock_nanosleep\", \"wait4\", \"waitid\", \"read\", \"recvfrom\", \"recvmsg\", \"recv\", \"accept\", \"accept4\", \"connect\", \"flock\", \"fcntl\", \"io_uring_enter\", \"rt_sigtimedwait\", \"pause\", \"sched_yield\"]);\n\n/** Aggregate per-syscall stats. Pure. */\nexport function aggregateSyscalls(records: SyscallRecord[]): { stats: SyscallStat[]; errors: Array<{ errno: string; syscall: string; count: number; example?: string }>; slowest: SyscallRecord[]; totalMs: number; waitMs: number } {\n const by = new Map<string, SyscallStat>();\n const errBy = new Map<string, { errno: string; syscall: string; count: number; example?: string }>();\n let totalMs = 0;\n let waitMs = 0;\n for (const r of records) {\n const s = by.get(r.name) ?? { syscall: r.name, count: 0, total_ms: 0, avg_ms: 0, max_ms: 0, errors: 0 };\n s.count++;\n const ms = (r.duration_s ?? 0) * 1000;\n s.total_ms += ms;\n s.max_ms = Math.max(s.max_ms, ms);\n if (r.errno) {\n s.errors++;\n const k = `${r.errno}:${r.name}`;\n const e = errBy.get(k) ?? { errno: r.errno, syscall: r.name, count: 0, example: r.args.slice(0, 120) };\n e.count++;\n errBy.set(k, e);\n }\n by.set(r.name, s);\n totalMs += ms;\n if (WAIT_SYSCALLS.has(r.name)) waitMs += ms;\n }\n const stats = [...by.values()].map((s) => ({ ...s, total_ms: round(s.total_ms), avg_ms: round(s.count ? s.total_ms / s.count : 0), max_ms: round(s.max_ms) })).sort((a, b) => b.total_ms - a.total_ms);\n const errors = [...errBy.values()].sort((a, b) => b.count - a.count);\n const slowest = [...records].filter((r) => r.duration_s !== undefined).sort((a, b) => b.duration_s! - a.duration_s!).slice(0, 10);\n return { stats, errors, slowest, totalMs: round(totalMs), waitMs: round(waitMs) };\n}\n\nfunction round(n: number): number {\n return Math.round(n * 1000) / 1000;\n}\n\n/** Extract a human-ish target from syscall args: path for open/stat, fd + addr for connect, fd for read/write. Pure. */\nexport function describeArgs(r: SyscallRecord): string {\n const path = /\"([^\"]{1,120})\"/.exec(r.args)?.[1];\n const addr = /sin_addr=inet_addr\\(\"([^\"]+)\"\\)|sin6_addr=inet_pton\\([^,]+,\\s*\"([^\"]+)\"|sun_path=\"([^\"]+)\"/.exec(r.args);\n const port = /sin6?_port=htons\\((\\d+)\\)/.exec(r.args)?.[1];\n const parts: string[] = [];\n if (path && !addr) parts.push(path);\n if (addr) parts.push(`${addr[1] ?? addr[2] ?? addr[3]}${port ? `:${port}` : \"\"}`);\n if (!parts.length) parts.push(r.args.slice(0, 60));\n return parts.join(\" \");\n}\n\n/** Shared by strace, fs_usage and `debuganything import`: records → evidence + findings. */\nexport function summarizeSyscallRecords(b: ResultBuilder, records: SyscallRecord[], duration: number, artifactPath: string): void {\n const agg = aggregateSyscalls(records);\n const topEv = b.evidenceOf(\n \"syscall_stat\",\n `${records.length} syscalls, ${agg.totalMs} ms inside the kernel over ${duration}s; top by time: ${agg.stats\n .slice(0, 5)\n .map((s) => `${s.syscall} ${s.total_ms}ms×${s.count}`)\n .join(\", \")}`,\n agg.stats.slice(0, 20),\n { artifact: artifactPath },\n );\n const slow = agg.slowest.slice(0, 8).map((rec) => ({ syscall: rec.name, ms: round((rec.duration_s ?? 0) * 1000), pid: rec.pid, at: rec.time, target: describeArgs(rec), result: rec.result.slice(0, 60), line: rec.line }));\n const slowEv = b.evidenceOf(\"syscall_slow\", slow.length ? `slowest: ${slow.slice(0, 3).map((s) => `${s.syscall}(${s.target}) ${s.ms}ms`).join(\"; \")}` : \"no timed syscalls\", slow, { artifact: artifactPath, lines: slow[0] ? [slow[0].line, slow[0].line] : undefined });\n const errEv = b.evidenceOf(\"syscall_error\", agg.errors.length ? `errors: ${agg.errors.slice(0, 5).map((e) => `${e.syscall}→${e.errno}×${e.count}`).join(\", \")}` : \"no failing syscalls\", agg.errors.slice(0, 15), { artifact: artifactPath });\n const waitPct = agg.totalMs ? Math.round((100 * agg.waitMs) / agg.totalMs) : 0;\n const waitEv = b.evidenceOf(\"metric\", `${waitPct}% of kernel time in blocking waits (futex/poll/epoll/read/recv/nanosleep)`, { name: \"wait_pct\", value: waitPct, wait_ms: agg.waitMs, total_ms: agg.totalMs });\n\n // Findings\n const top = agg.stats[0];\n if (top && agg.totalMs > 0 && top.total_ms / agg.totalMs > 0.5) {\n const isWait = WAIT_SYSCALLS.has(top.syscall);\n b.finding(isWait ? \"info\" : \"warn\", `${top.syscall} dominates: ${top.total_ms} ms over ${top.count} calls (${Math.round((100 * top.total_ms) / agg.totalMs)}% of kernel time)${isWait ? \" — blocking wait, the process is waiting on something\" : \"\"}`, [topEv, slowEv], \"observed\");\n }\n const nanosleep = agg.stats.find((s) => /nanosleep/.test(s.syscall));\n if (nanosleep && nanosleep.total_ms > duration * 100) b.finding(\"warn\", `${nanosleep.total_ms} ms in ${nanosleep.syscall} (${nanosleep.count} calls) — deliberate sleeps/timers on the request path`, [topEv], \"inferred\");\n const fileChurn = agg.stats.filter((s) => /^(openat|open|stat|newfstatat|statx|lstat|access|readlink)$/.test(s.syscall)).reduce((n, s) => n + s.count, 0);\n if (fileChurn > duration * 200) b.finding(\"warn\", `${fileChurn} path lookups (open/stat) in ${duration}s — filesystem churn (missing cache? module resolution per request?)`, [topEv], \"inferred\");\n const reads = agg.stats.find((s) => s.syscall === \"read\");\n if (reads && reads.count > duration * 300) b.finding(\"warn\", `${reads.count} read() calls in ${duration}s (avg ${reads.avg_ms} ms) — many small reads; sync I/O in a loop?`, [topEv], \"inferred\");\n for (const e of agg.errors.slice(0, 4)) {\n const sev = /ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EMFILE|ENOSPC|ENOMEM/.test(e.errno) ? \"high\" : e.count > 50 ? \"warn\" : \"info\";\n const hint = e.errno === \"EAGAIN\" ? \" (non-blocking I/O would-block; normal for event loops unless excessive)\" : e.errno === \"ENOENT\" ? ` (missing file; e.g. ${e.example?.split(\",\")[0]})` : e.errno === \"ECONNREFUSED\" ? \" — a downstream service is not accepting connections\" : \"\";\n b.finding(sev, `${e.count}× ${e.syscall} failed with ${e.errno}${hint}`, [errEv], \"observed\");\n }\n if (slow[0] && slow[0].ms > 500) b.finding(\"warn\", `slowest single call: ${slow[0].syscall}(${slow[0].target}) took ${slow[0].ms} ms`, [slowEv], \"observed\");\n if (b.findingCount === 0) b.finding(\"info\", `${records.length} syscalls in ${duration}s, nothing dominant; top ${top?.syscall ?? \"?\"}`, [topEv, waitEv]);\n}\n\nasync function traceSyscalls(ctx: AdapterContext, args: { duration_s?: number; categories?: SyscallCategory[] }): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"trace_syscalls\", session, target);\n if (!target.pid) return b.fail(\"no pid\").build();\n const duration = clampDuration(args.duration_s, 10);\n const cats = args.categories?.length ? args.categories : ([\"all\"] as SyscallCategory[]);\n const set = cats.includes(\"all\") ? \"all\" : [...new Set(cats.map((c) => CATEGORY_SETS[c]))].join(\",\");\n const out = b.artifactPath(\"strace.log\");\n const straceArgs = [\"-f\", \"-T\", \"-tt\", \"-qq\", \"-s\", \"64\", \"-e\", `trace=${set}`, \"-p\", String(target.pid), \"-o\", out];\n // strace has no --duration; we rely on the time cap (SIGTERM → strace detaches cleanly).\n const r = await runCapped(\"strace\", straceArgs, { timeoutMs: duration * 1000, captureInMemory: true });\n const raw = await readFile(out, \"utf8\").catch(() => \"\");\n const art = await b.addArtifact(out, \"raw_text\", { description: `strace ${straceArgs.join(\" \")} for ${duration}s`, truncated: r.outputCapped });\n if (!raw.trim()) {\n const cmd = `strace ${straceArgs.join(\" \")}`;\n if (looksLikePermissionError(r.stderr)) {\n b.limitation(rootRequiredLimitation(\"trace_syscalls\", cmd));\n b.limitation(\"Linux: kernel.yama.ptrace_scope ≥ 1 blocks attaching to non-child processes; sudo sysctl kernel.yama.ptrace_scope=0 for this boot, or run Debug Anything as root / with CAP_SYS_PTRACE\");\n b.next(\"import_artifact (strace, after running the sudo command above)\", \"inspect_sockets\", \"inspect_files\", \"snapshot_memory\");\n return b.fail(\"strace could not attach (permission denied)\").build();\n }\n if (r.stderr.trim()) b.limitation(`strace: ${r.stderr.trim().slice(0, 300)}`);\n const ev = b.evidenceOf(\"syscall_stat\", `0 syscalls in ${duration}s`, { name: \"syscalls\", count: 0 });\n b.finding(\"info\", `no syscalls in ${duration}s — the process made no kernel calls (spinning in user space, or fully idle in a wait that started before the trace)`, [ev], \"inferred\");\n b.next(\"dump_stacks\", \"profile_cpu\");\n return b.build();\n }\n summarizeSyscallRecords(b, parseStrace(raw), duration, art.path);\n b.limitation(`traced ${duration}s only (${set}); strace adds overhead to every syscall — latencies are inflated`);\n if (r.outputCapped) b.limitation(`raw log hit the ${LIMITS.MAX_RAW_BYTES / 1024 / 1024} MB cap and was cut short`);\n b.next(\"profile_cpu\", \"inspect_sockets\", \"inspect_files\");\n return b.build();\n}\n\nexport const straceAdapter: Adapter = {\n name: \"strace\",\n tools: [\"trace_syscalls\"],\n platforms: [\"linux\"],\n requires: [\"strace\"],\n install: { linux: \"sudo apt install strace | sudo dnf install strace | apk add strace\" },\n priority: 10,\n check(base, env) {\n if (env.ptraceScope !== null && env.ptraceScope >= 1 && !env.isRoot) base.notes.push(`ptrace_scope=${env.ptraceScope}: can only trace child processes without root`);\n return base;\n },\n async run(tool, args, ctx) {\n if (tool !== \"trace_syscalls\") throw new Error(`strace adapter cannot run ${tool}`);\n return traceSyscalls(ctx, args as { duration_s?: number; categories?: SyscallCategory[] });\n },\n};\n","/**\n * gdb adapter (Linux): dump_stacks for native/Node/Go/Java targets.\n * gdb -p PID -batch -ex \"thread apply all bt\" -ex detach\n */\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport type { ToolResult } from \"../contracts.js\";\nimport { ResultBuilder } from \"../evidence.js\";\nimport { runCapped, looksLikePermissionError, rootRequiredLimitation } from \"../safety.js\";\n\nexport interface NativeThread {\n index: number;\n tid?: number;\n name?: string;\n frames: Array<{ n: number; func: string; loc?: string; addr?: string }>;\n}\n\n/** Parse `thread apply all bt` output (gdb). Pure. */\nexport function parseGdbBacktrace(raw: string): NativeThread[] {\n const threads: NativeThread[] = [];\n let cur: NativeThread | null = null;\n for (const line of raw.split(\"\\n\")) {\n let m = /^Thread (\\d+) \\(Thread 0x[0-9a-f]+ \\(LWP (\\d+)\\)(?: \"([^\"]*)\")?\\):?/.exec(line) ?? /^Thread (\\d+) \\((?:process )?(\\d+)(?: \"([^\"]*)\")?\\):?/.exec(line);\n if (m) {\n cur = { index: Number(m[1]), tid: Number(m[2]), name: m[3], frames: [] };\n threads.push(cur);\n continue;\n }\n m = /^#(\\d+)\\s+(?:(0x[0-9a-f]+) in )?(\\S+?)\\s*\\((?:[^)]*)\\)(?: at (\\S+))?(?: from (\\S+))?/.exec(line);\n if (m && cur) {\n cur.frames.push({ n: Number(m[1]), func: m[3]!, loc: m[4] ?? m[5], addr: m[2] });\n continue;\n }\n // Continuation lines of long frames are ignored.\n }\n return threads;\n}\n\n/** Mutex-style acquisition: contention, potentially a deadlock. */\nconst LOCK_FUNCS = /^(__GI_)?(pthread_mutex_lock|__lll_lock_wait|__lll_lock_wait_private|pthread_rwlock_(rd|wr)lock|uv_mutex_lock|__lll_lock|_?_pthread_mutex_firstfit_lock_slow|__psynch_mutexwait|__ulock_wait)$|absl::Mutex::Lock|std::mutex::lock|SpinLock|ObjectMonitor::enter|futex_wait_queue|__futex_abstimed_wait_(common|cancelable)/;\n/** Condition / semaphore / event waits: idle worker threads, not contention. */\nconst IDLE_FUNCS = /pthread_cond_wait|pthread_cond_timedwait|__psynch_cvwait|uv_cond_wait|sem_wait|uv_sem_wait|semaphore_wait_trap|Monitor::wait|epoll_wait|epoll_pwait|^(__GI_)?p?poll$|^select$|^pselect6$|kevent|io_uring_enter|uv__io_poll|^pause$|sigwait|sigtimedwait|^wait4$|^waitid$|mach_msg|__workq_kernreturn|_dispatch_(worker|event_loop)|GCDAsync|^swapper$|__semwait_signal/;\n/** Blocking I/O or sleeps: waiting on a peer or a timer. */\nconst IO_FUNCS = /^(__GI_)?(read|recv|recvfrom|recvmsg|accept|accept4|connect|nanosleep|clock_nanosleep|__clock_nanosleep|__select|__recvfrom|__read_nocancel|__connect|__accept)$|__libc_read|__libc_recv|SSL_read|usleep|^sleep$/;\n\nexport interface NativeLockWait {\n thread: string;\n waiting_in: string;\n at: string;\n kind: \"lock\" | \"io\" | \"idle\";\n}\n\n/** Classify threads by what they are blocked in. Pure. */\nexport function classifyNativeThreads(threads: NativeThread[]): { lock: NativeLockWait[]; io: NativeLockWait[]; idle: NativeLockWait[]; running: NativeThread[] } {\n const lock: NativeLockWait[] = [];\n const io: NativeLockWait[] = [];\n const idle: NativeLockWait[] = [];\n const running: NativeThread[] = [];\n const isSys = (f: string) => LOCK_FUNCS.test(f) || IDLE_FUNCS.test(f) || IO_FUNCS.test(f) || /^(__|_IO_|std::|uv_|uv__|start_thread|thread_start|_pthread_start|clone|clone3|\\?\\?|_dispatch|libsystem)/.test(f);\n for (const t of threads) {\n const top = t.frames.slice(0, 4);\n const lockF = top.find((f) => LOCK_FUNCS.test(f.func));\n const idleF = top.find((f) => IDLE_FUNCS.test(f.func));\n const ioF = top.find((f) => IO_FUNCS.test(f.func));\n const user = t.frames.find((f) => !isSys(f.func));\n const at = user ? `${user.func}${user.loc ? ` (${user.loc.split(\"/\").pop()})` : \"\"}` : (t.frames.find((f) => !LOCK_FUNCS.test(f.func) && !IDLE_FUNCS.test(f.func) && !IO_FUNCS.test(f.func))?.func ?? \"?\");\n const label = `${t.name ? `${t.name} ` : \"\"}#${t.index}${t.tid ? ` (tid ${t.tid})` : \"\"}`;\n if (lockF) lock.push({ thread: label, waiting_in: lockF.func, at, kind: \"lock\" });\n else if (idleF) idle.push({ thread: label, waiting_in: idleF.func, at, kind: \"idle\" });\n else if (ioF) io.push({ thread: label, waiting_in: ioF.func, at, kind: \"io\" });\n else running.push(t);\n }\n return { lock, io, idle, running };\n}\n\nexport async function summarizeNativeStacks(b: ResultBuilder, threads: NativeThread[], artifact: string, debugger_: string): Promise<ToolResult> {\n if (!threads.length) {\n b.limitation(`${debugger_} produced no thread backtraces (no symbols? target exited?)`);\n return b.fail(`${debugger_}: no stacks parsed`).build();\n }\n const { lock, io, idle, running } = classifyNativeThreads(threads);\n const summaryEv = b.evidenceOf(\n \"stack_summary\",\n `${threads.length} thread(s): ${running.length} running/other, ${lock.length} in locks, ${io.length} in blocking I/O, ${idle.length} idle (cond/event waits)`,\n threads.map((t) => ({ thread: `${t.name ?? \"\"}#${t.index}`, tid: t.tid, top: t.frames[0]?.func ?? \"?\", depth: t.frames.length })),\n { artifact },\n );\n for (const t of threads.slice(0, 12)) {\n b.evidenceOf(\"stack\", `${t.name ? `${t.name} ` : \"\"}#${t.index}: ${t.frames.slice(0, 5).map((f) => f.func).join(\" ← \")}`, { thread: `${t.name ?? \"\"}#${t.index}`, frames: t.frames.slice(0, 20).map((f) => `${f.func}${f.loc ? ` (${f.loc.split(\"/\").pop()})` : \"\"}`) }, { artifact });\n }\n const noSymbols = threads.flatMap((t) => t.frames).filter((f) => f.func === \"??\").length;\n if (noSymbols > 0) b.limitation(`${noSymbols} frame(s) have no symbols (stripped binaries); install debug symbols for better names`);\n if (lock.length) {\n const lockEv = b.evidenceOf(\"lock_wait\", `${lock.length} thread(s) blocked on locks: ${lock.map((l) => `${l.thread} in ${l.waiting_in} at ${l.at}`).join(\"; \")}`, lock, { artifact });\n if (lock.length >= 2 && running.length === 0) b.finding(\"high\", `likely deadlock: ${lock.length} threads blocked in lock acquisition and none running (${lock.map((l) => `${l.thread}@${l.at}`).join(\", \")})`, [lockEv, summaryEv], \"inferred\", \"Take a second dump_stacks; identical positions confirm it. Handoff: step debugger at the lock sites.\");\n else b.finding(\"warn\", `${lock.length} thread(s) waiting on locks: ${lock.map((l) => `${l.thread} at ${l.at}`).join(\"; \")}`, [lockEv], \"observed\");\n }\n if (io.length) {\n const ioEv = b.evidenceOf(\"lock_wait\", `${io.length} thread(s) in blocking I/O/sleep: ${io.slice(0, 5).map((l) => `${l.thread} in ${l.waiting_in} at ${l.at}`).join(\"; \")}`, io, { artifact });\n const mainBlocked = io.find((l) => /#1\\b/.test(l.thread));\n if (mainBlocked) b.finding(\"warn\", `main thread is blocked in ${mainBlocked.waiting_in} at ${mainBlocked.at} — waiting on a peer, a file or a timer`, [ioEv], \"observed\", \"inspect_sockets shows which remote; trace_syscalls shows how long each wait takes.\");\n else b.finding(\"info\", `${io.length} thread(s) blocked in I/O: ${io.slice(0, 3).map((l) => `${l.thread} in ${l.waiting_in}`).join(\"; \")}`, [ioEv]);\n }\n if (idle.length) {\n const idleEv = b.evidenceOf(\"stack_summary\", `${idle.length} idle thread(s) in ${[...new Set(idle.map((i) => i.waiting_in))].join(\", \")}`, idle.slice(0, 20), { artifact });\n if (!lock.length && !io.length && running.length === 0) b.finding(\"info\", `all ${threads.length} threads are idle in event/condition waits (${[...new Set(idle.map((i) => i.waiting_in))].slice(0, 4).join(\", \")}) — not stuck in user code; if callers hang, the work is pending elsewhere (inspect_sockets, trace_syscalls)`, [idleEv, summaryEv], \"inferred\");\n }\n if (running.length) {\n const t = running[0]!;\n b.finding(\"info\", `thread ${t.name ?? \"\"}#${t.index} is executing ${t.frames[0]?.func ?? \"?\"}${t.frames[1] ? ` ← ${t.frames[1].func}` : \"\"}`, [summaryEv]);\n }\n b.limitation(\"instant snapshot; the target was paused for the duration of the dump (typically <1 s)\");\n b.next(\"inspect_sockets\", \"trace_syscalls\", \"profile_cpu\");\n const interesting = lock[0]?.at ?? io.find((l) => /#1\\b/.test(l.thread))?.at;\n if (interesting && interesting !== \"?\") b.next(`static analysis: decompile ${interesting.replace(/\\s*\\(.*$/, \"\")} to see what it locks/reads`);\n return b.build();\n}\n\nasync function dumpStacks(ctx: AdapterContext): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"dump_stacks\", session, target);\n if (!target.pid) return b.fail(\"no pid\").build();\n const args = [\"-p\", String(target.pid), \"-batch\", \"-q\", \"-nx\", \"-ex\", \"set pagination off\", \"-ex\", \"thread apply all bt 25\", \"-ex\", \"detach\", \"-ex\", \"quit\"];\n const r = await runCapped(\"gdb\", args, { timeoutMs: 45_000 });\n const raw = r.stdout + (r.stderr ? `\\n--- stderr ---\\n${r.stderr}` : \"\");\n const art = await b.writeArtifact(\"gdb-bt.txt\", raw, \"raw_text\", `gdb ${args.join(\" \")}`);\n if (looksLikePermissionError(r.stderr) || /ptrace: Operation not permitted/.test(raw)) {\n b.limitation(rootRequiredLimitation(\"dump_stacks\", `gdb ${args.join(\" \")}`));\n b.limitation(\"Linux: kernel.yama.ptrace_scope ≥ 1 blocks attaching to non-child processes\");\n b.next(\"import_artifact (gdb, after running the sudo command above)\", \"inspect_sockets\", \"inspect_files\", \"snapshot_memory\");\n return b.fail(\"gdb could not attach (permission denied)\").build();\n }\n const threads = parseGdbBacktrace(r.stdout);\n if (target.runtime === \"node\") b.limitation(\"native stacks only; JS frames show as v8 internals. For JS-level stacks use Node's inspector (--inspect) or `node --cpu-prof`.\");\n return summarizeNativeStacks(b, threads, art, \"gdb\");\n}\n\nexport const gdbAdapter: Adapter = {\n name: \"gdb\",\n tools: [\"dump_stacks\"],\n platforms: [\"linux\"],\n requires: [\"gdb\"],\n runtimes: [\"native\", \"node\", \"go\", \"java\", \"unknown\"],\n install: { linux: \"sudo apt install gdb | sudo dnf install gdb\" },\n priority: 5,\n check(base, env) {\n if (env.ptraceScope !== null && env.ptraceScope >= 1 && !env.isRoot) base.notes.push(`ptrace_scope=${env.ptraceScope}: can only attach to child processes without root`);\n return base;\n },\n async run(tool, _args, ctx) {\n if (tool !== \"dump_stacks\") throw new Error(`gdb adapter cannot run ${tool}`);\n return dumpStacks(ctx);\n },\n};\n","/**\n * lldb adapter (macOS): dump_stacks for native/Node targets.\n * lldb -p PID --batch -o \"thread backtrace all\" -o detach\n */\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport type { ToolResult } from \"../contracts.js\";\nimport { ResultBuilder } from \"../evidence.js\";\nimport { runCapped, looksLikePermissionError, rootRequiredLimitation } from \"../safety.js\";\nimport { summarizeNativeStacks, type NativeThread } from \"./gdb.js\";\n\n/** Parse `thread backtrace all` output (lldb). Pure. */\nexport function parseLldbBacktrace(raw: string): NativeThread[] {\n const threads: NativeThread[] = [];\n let cur: NativeThread | null = null;\n for (const line of raw.split(\"\\n\")) {\n let m = /^\\*?\\s*thread #(\\d+)(?:, name = '([^']*)')?(?:, queue = '([^']*)')?/.exec(line);\n if (m) {\n const idx = Number(m[1]);\n const existing = threads.find((t) => t.index === idx);\n if (existing) {\n cur = existing;\n cur.frames = [];\n continue;\n }\n cur = { index: idx, name: m[2] ?? m[3], frames: [] };\n threads.push(cur);\n continue;\n }\n // frame #0: 0x00007ff8 libsystem_kernel.dylib`__psynch_cvwait + 10\n // frame #3: 0x0000000100003f2c app`main(argc=1, argv=...) at main.c:12:5\n m = /^\\s*(?:\\*\\s*)?frame #(\\d+): (0x[0-9a-f]+) ([^`]+)`(.+?)(?: \\+ \\d+)?(?: at (\\S+))?$/.exec(line);\n if (m && cur) {\n const func = m[4]!.replace(/\\(.*$/, \"\").trim();\n cur.frames.push({ n: Number(m[1]), func, loc: m[5] ?? m[3], addr: m[2] });\n }\n }\n return threads;\n}\n\nasync function dumpStacks(ctx: AdapterContext): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"dump_stacks\", session, target);\n if (!target.pid) return b.fail(\"no pid\").build();\n const args = [\"-p\", String(target.pid), \"--batch\", \"-o\", \"thread backtrace all\", \"-o\", \"detach\", \"-o\", \"quit\"];\n const r = await runCapped(\"lldb\", args, { timeoutMs: 45_000 });\n const raw = r.stdout + (r.stderr ? `\\n--- stderr ---\\n${r.stderr}` : \"\");\n const art = await b.writeArtifact(\"lldb-bt.txt\", raw, \"raw_text\", `lldb ${args.join(\" \")}`);\n if (looksLikePermissionError(raw) || /attach failed|not permitted|Permission denied|does not exist|unable to attach/i.test(raw)) {\n b.limitation(rootRequiredLimitation(\"dump_stacks\", `lldb ${args.join(\" \")}`));\n b.limitation(\"macOS: attaching to a process you did not spawn needs sudo, or the target must opt in (com.apple.security.get-task-allow). Hardened/SIP-protected binaries cannot be attached at all.\");\n b.next(\"import_artifact (lldb, after running the sudo command above)\", \"inspect_sockets\", \"snapshot_memory\", \"profile_cpu (sample, own processes)\");\n return b.fail(\"lldb could not attach (permission denied)\").build();\n }\n const threads = parseLldbBacktrace(r.stdout);\n if (target.runtime === \"node\") b.limitation(\"native stacks only; JS frames appear as v8 internals. For JS-level stacks use the inspector (--inspect).\");\n return summarizeNativeStacks(b, threads, art, \"lldb\");\n}\n\nexport const lldbAdapter: Adapter = {\n name: \"lldb\",\n tools: [\"dump_stacks\"],\n platforms: [\"darwin\"],\n requires: [\"lldb\"],\n runtimes: [\"native\", \"node\", \"go\", \"java\", \"unknown\"],\n install: { darwin: \"xcode-select --install\" },\n priority: 5,\n check(base, env) {\n if (!env.isRoot) base.notes.push(\"macOS: attaching needs sudo unless the target is your own debuggable child\");\n return base;\n },\n async run(tool, _args, ctx) {\n if (tool !== \"dump_stacks\") throw new Error(`lldb adapter cannot run ${tool}`);\n return dumpStacks(ctx);\n },\n};\n","/**\n * perf adapter (Linux): profile_cpu for native / Node / Go / Java targets.\n * perf record -F 99 -g -p PID -o <file> -- sleep N\n * perf script -i <file> → folded stacks (our own folder, no Perl) → flamegraph.svg\n * Node: symbols need `--perf-basic-prof` on the target; we say so.\n */\nimport { readFile } from \"node:fs/promises\";\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport type { ToolResult } from \"../contracts.js\";\nimport { ResultBuilder } from \"../evidence.js\";\nimport { runCapped, clampDuration, looksLikePermissionError, rootRequiredLimitation, LIMITS } from \"../safety.js\";\nimport { summarizeProfile } from \"./pyspy.js\";\n\n/**\n * Fold `perf script` output into \"frame;frame;frame count\" lines. Pure.\n * perf script prints one sample header line followed by indented stack lines\n * (leaf first) and a blank line:\n * node 1234 5678.123456: 250000 cpu-clock:\n * 7f0a2b1c0a3e epoll_wait+0x4e (/usr/lib/libc.so.6)\n * 5a3c1b uv__io_poll+0x1ab (/usr/bin/node)\n */\nexport function perfScriptToFolded(raw: string, opts: { includeComm?: boolean } = {}): string {\n const counts = new Map<string, number>();\n let comm: string | null = null;\n let frames: string[] = [];\n const flush = () => {\n if (comm !== null && frames.length) {\n const stack = [...(opts.includeComm ? [comm] : []), ...frames.reverse()];\n const key = stack.join(\";\");\n counts.set(key, (counts.get(key) ?? 0) + 1);\n }\n comm = null;\n frames = [];\n };\n for (const line of raw.split(\"\\n\")) {\n if (!line.trim()) {\n flush();\n continue;\n }\n if (!/^\\s/.test(line)) {\n // header: comm pid [cpu] time: period event:\n flush();\n const m = /^(\\S+)\\s+\\d+/.exec(line);\n comm = m ? m[1]! : \"?\";\n continue;\n }\n const m = /^\\s+[0-9a-f]+\\s+(.+?)(?:\\+0x[0-9a-f]+)?\\s+\\((.*)\\)\\s*$/.exec(line);\n if (m && comm !== null) {\n let sym = m[1]!;\n const dso = m[2]!;\n if (sym === \"[unknown]\") sym = `[unknown] (${dso.split(\"/\").pop()})`;\n frames.push(sym.replace(/;/g, \",\"));\n }\n }\n flush();\n return [...counts].map(([k, v]) => `${k} ${v}`).join(\"\\n\") + (counts.size ? \"\\n\" : \"\");\n}\n\nasync function profileCpu(ctx: AdapterContext, args: { duration_s?: number }): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"profile_cpu\", session, target);\n if (!target.pid) return b.fail(\"no pid\").build();\n const duration = clampDuration(args.duration_s, 15);\n const dataPath = b.artifactPath(\"perf.data\");\n const recArgs = [\"record\", \"-F\", \"99\", \"-g\", \"--call-graph\", \"fp\", \"-p\", String(target.pid), \"-o\", dataPath, \"--\", \"sleep\", String(duration)];\n const rec = await runCapped(\"perf\", recArgs, { timeoutMs: duration * 1000 + LIMITS.DURATION_SLACK_MS + 10_000 });\n if (rec.exitCode !== 0 || looksLikePermissionError(rec.stderr) || /perf_event_open|Permission|not permitted/i.test(rec.stderr)) {\n await b.writeArtifact(\"perf-stderr.txt\", rec.stderr, \"raw_text\");\n if (looksLikePermissionError(rec.stderr) || /paranoid|perf_event_open/i.test(rec.stderr)) {\n b.limitation(rootRequiredLimitation(\"profile_cpu\", `perf ${recArgs.join(\" \")}`));\n b.limitation(\"Linux: lower kernel.perf_event_paranoid to 1 (sudo sysctl kernel.perf_event_paranoid=1) or grant CAP_PERFMON; inside Docker add --cap-add PERFMON --cap-add SYS_ADMIN\");\n b.next(\"import_artifact (perf_script, after running the sudo command above)\", \"dump_stacks\", \"trace_syscalls\", \"snapshot_memory\");\n return b.fail(\"perf record needs permissions\").build();\n }\n b.limitation(`perf record exited ${rec.exitCode}: ${rec.stderr.trim().slice(0, 300)}`);\n return b.fail(\"perf record failed\").build();\n }\n const scriptPath = b.artifactPath(\"perf-script.txt\");\n const scr = await runCapped(\"perf\", [\"script\", \"-i\", dataPath, \"-F\", \"comm,pid,time,event,ip,sym,dso\"], { timeoutMs: 60_000, stdoutFile: scriptPath });\n const raw = await readFile(scriptPath, \"utf8\").catch(() => \"\");\n await b.addArtifact(dataPath, \"raw_text\", { description: \"perf.data (binary)\" });\n await b.addArtifact(scriptPath, \"raw_text\", { description: \"perf script output\", truncated: scr.outputCapped });\n const folded = perfScriptToFolded(raw);\n await b.writeArtifact(\"perf-folded.txt\", folded, \"folded_stacks\", \"folded stacks\");\n const unknown = (folded.match(/\\[unknown\\]/g) ?? []).length;\n if (unknown > 0) b.limitation(`${unknown} stack frames have no symbols${target.runtime === \"node\" ? \" — start Node with --perf-basic-prof (or --perf-prof) so JIT frames get names\" : target.runtime === \"java\" ? \" — use perf-map-agent or async-profiler for JIT frames\" : \"; install debug symbols or build with frame pointers\"}`);\n b.limitation(\"perf samples at 99 Hz with frame-pointer unwinding; frames may be missing in code built without frame pointers (use --call-graph dwarf manually for those)\");\n return summarizeProfile(b, folded, duration, \"perf\", 99);\n}\n\nexport const perfAdapter: Adapter = {\n name: \"perf\",\n tools: [\"profile_cpu\"],\n platforms: [\"linux\"],\n requires: [\"perf\"],\n runtimes: [\"native\", \"node\", \"go\", \"java\", \"unknown\"],\n install: { linux: \"sudo apt install linux-perf (Debian/Ubuntu: linux-tools-$(uname -r)) | sudo dnf install perf\" },\n priority: 5,\n check(base, env) {\n if (env.perfParanoid !== null && env.perfParanoid > 1 && !env.isRoot) base.notes.push(`perf_event_paranoid=${env.perfParanoid}: cannot profile other processes without root`);\n return base;\n },\n async run(tool, args, ctx) {\n if (tool !== \"profile_cpu\") throw new Error(`perf adapter cannot run ${tool}`);\n return profileCpu(ctx, args as { duration_s?: number });\n },\n};\n","/**\n * tcpdump adapter: capture_traffic, scoped to the target's ports (derived from\n * lsof at run time) — never an unbounded capture. Requires consent: true.\n * tcpdump -i any -nn -tt -q -U -w <pcap> -G N -W 1 '<filter>'\n * then `tcpdump -nn -tt -r <pcap>` is parsed for the summary.\n */\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport type { ToolResult } from \"../contracts.js\";\nimport { ResultBuilder, humanBytes } from \"../evidence.js\";\nimport { runCapped, clampDuration, looksLikePermissionError, rootRequiredLimitation, LIMITS, assertSafeBpfFragment, isRoot } from \"../safety.js\";\nimport { platform } from \"../session.js\";\nimport { targetPids } from \"../target.js\";\nimport { parseLsofFields } from \"./lsof.js\";\n\nexport interface PacketLine {\n ts: number;\n proto: \"IP\" | \"IP6\" | \"ARP\" | \"other\";\n src: string;\n sport?: number;\n dst: string;\n dport?: number;\n flags?: string;\n length?: number;\n kind: \"tcp\" | \"udp\" | \"dns\" | \"other\";\n dnsQuery?: string;\n tlsSni?: string;\n retransmit?: boolean;\n /** \"In\"/\"Out\" when captured with -i any (Linux SLL2). */\n dir?: string;\n /** TCP sequence range text, e.g. \"1:101\" or \"1\". */\n seq?: string;\n}\n\nfunction splitHostPort(s: string): { host: string; port?: number } {\n const m = /^(.*)\\.(\\d+)$/.exec(s);\n if (!m) return { host: s };\n return { host: m[1]!, port: Number(m[2]) };\n}\n\n/** Parse `tcpdump -nn -tt -r file` text lines (tcp/udp/dns). Pure. */\nexport function parseTcpdump(raw: string): PacketLine[] {\n const out: PacketLine[] = [];\n for (const line of raw.split(\"\\n\")) {\n const m = /^(\\d+\\.\\d+) (?:[\\w.-]+\\s+(In|Out|B|M|P)\\s+)?(IP6?|ARP) (.*)$/.exec(line.trim());\n if (!m) continue;\n const ts = Number(m[1]);\n const dir = m[2];\n const proto = m[3] as PacketLine[\"proto\"];\n const rest = m[4]!;\n const flow = /^(\\S+) > (\\S+): (.*)$/.exec(rest);\n if (!flow) continue;\n const s = splitHostPort(flow[1]!);\n const d = splitHostPort(flow[2]!.replace(/:$/, \"\"));\n const body = flow[3]!;\n const pkt: PacketLine = { ts, proto, src: s.host, sport: s.port, dst: d.host, dport: d.port, kind: \"other\", dir };\n if (/^Flags \\[/.test(body)) {\n pkt.kind = \"tcp\";\n pkt.flags = /^Flags \\[([^\\]]*)\\]/.exec(body)?.[1];\n pkt.seq = /\\bseq (\\d+(?::\\d+)?)/.exec(body)?.[1];\n const len = /length (\\d+)/.exec(body);\n if (len) pkt.length = Number(len[1]);\n // TLS ClientHello SNI is only visible with -X/-A; tcpdump -v prints \"(SNI=...)\" on some builds.\n const sni = /SNI=([A-Za-z0-9.-]+)/.exec(body);\n if (sni) pkt.tlsSni = sni[1];\n } else if (/^\\d+\\+?\\$? [A-Z]+\\??/.test(body) || /^\\d+ [A-Z]+\\? /.test(body) || (/\\b(A|AAAA|CNAME|MX|TXT|SRV)\\?/.test(body) && (d.port === 53 || s.port === 53))) {\n pkt.kind = \"dns\";\n const q = /\\b(?:A|AAAA|CNAME|MX|TXT|SRV|PTR)\\? ([^\\s,]+)/.exec(body);\n if (q) pkt.dnsQuery = q[1]!.replace(/\\.$/, \"\");\n } else if (/^UDP, length (\\d+)/.test(body)) {\n pkt.kind = \"udp\";\n pkt.length = Number(/length (\\d+)/.exec(body)![1]);\n }\n out.push(pkt);\n }\n return out;\n}\n\nexport interface TrafficSummary {\n packets: number;\n bytes: number;\n byRemote: Array<{ remote: string; packets: number; bytes: number; rst: number; syn: number; fin: number; retransmits: number }>;\n rst: number;\n syn_no_synack: number;\n retransmits: number;\n dns: Array<{ name: string; count: number }>;\n sni: Array<{ name: string; count: number }>;\n duration_s: number;\n}\n\n/** Summarize packets relative to a set of local ports. Pure. */\nexport function summarizeTraffic(pkts: PacketLine[], localPorts: Set<number>): TrafficSummary {\n const remotes = new Map<string, TrafficSummary[\"byRemote\"][number]>();\n const dns = new Map<string, number>();\n const sni = new Map<string, number>();\n let rst = 0;\n let retransmits = 0;\n let bytes = 0;\n // With `-i any` on Linux, loopback traffic is seen twice (In + Out). Collapse exact duplicates within 2 ms.\n const deduped: PacketLine[] = [];\n const lastSeen = new Map<string, number>();\n for (const p of pkts) {\n const key = `${p.src}:${p.sport}>${p.dst}:${p.dport}|${p.flags ?? \"\"}|${p.seq ?? \"\"}|${p.length ?? \"\"}|${p.kind}`;\n const prev = lastSeen.get(key);\n lastSeen.set(key, p.ts);\n if (prev !== undefined && p.ts - prev < 0.002 && p.dir !== undefined) continue;\n deduped.push(p);\n }\n const seenSeq = new Map<string, number>(); // flow|seq → first ts, for retransmit detection\n const syns = new Map<string, number>();\n const synacks = new Set<string>();\n for (const p of deduped) {\n const isLocalSrc = p.sport !== undefined && localPorts.has(p.sport);\n const remoteHost = isLocalSrc ? p.dst : p.src;\n const r = remotes.get(remoteHost) ?? { remote: remoteHost, packets: 0, bytes: 0, rst: 0, syn: 0, fin: 0, retransmits: 0 };\n r.packets++;\n r.bytes += p.length ?? 0;\n bytes += p.length ?? 0;\n if (p.kind === \"tcp\" && p.flags) {\n if (p.flags.includes(\"R\")) {\n r.rst++;\n rst++;\n }\n if (p.flags === \"S\") {\n r.syn++;\n syns.set(`${p.src}:${p.sport}>${p.dst}:${p.dport}`, (syns.get(`${p.src}:${p.sport}>${p.dst}:${p.dport}`) ?? 0) + 1);\n }\n if (p.flags === \"S.\") synacks.add(`${p.dst}:${p.dport}>${p.src}:${p.sport}`);\n if (p.flags.includes(\"F\")) r.fin++;\n if ((p.length ?? 0) > 0 && p.seq) {\n const key = `${p.src}:${p.sport}>${p.dst}:${p.dport}|${p.seq}`;\n const first = seenSeq.get(key);\n if (first !== undefined && p.ts - first > 0.002) {\n r.retransmits++;\n retransmits++;\n } else if (first === undefined) seenSeq.set(key, p.ts);\n }\n }\n if (p.kind === \"dns\" && p.dnsQuery) dns.set(p.dnsQuery, (dns.get(p.dnsQuery) ?? 0) + 1);\n if (p.tlsSni) sni.set(p.tlsSni, (sni.get(p.tlsSni) ?? 0) + 1);\n remotes.set(remoteHost, r);\n }\n let synNoAck = 0;\n for (const [flow, n] of syns) if (!synacks.has(flow)) synNoAck += n;\n const ts = deduped.map((p) => p.ts);\n return {\n packets: deduped.length,\n bytes,\n byRemote: [...remotes.values()].sort((a, b) => b.bytes - a.bytes || b.packets - a.packets),\n rst,\n syn_no_synack: synNoAck,\n retransmits,\n dns: [...dns].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count),\n sni: [...sni].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count),\n duration_s: ts.length ? Math.round((Math.max(...ts) - Math.min(...ts)) * 100) / 100 : 0,\n };\n}\n\n/** Build the BPF filter from the target's ports; refuse an unbounded capture. Pure. */\nexport function buildFilter(ports: number[], extra?: string): string {\n const uniq = [...new Set(ports.filter((p) => p > 0 && p < 65536))].slice(0, 40);\n if (!uniq.length) throw new Error(\"target has no sockets/ports to scope the capture to; refusing an unbounded capture\");\n const portExpr = uniq.length === 1 ? `port ${uniq[0]}` : `(${uniq.map((p) => `port ${p}`).join(\" or \")})`;\n const base = `(${portExpr} or (udp and port 53))`;\n return extra ? `${base} and (${assertSafeBpfFragment(extra)})` : base;\n}\n\n/** Shared by capture_traffic and `debuganything import`: packets → evidence + findings. */\nexport function summarizeCaptureEvidence(b: ResultBuilder, pkts: PacketLine[], localPorts: Set<number>, meta: { filter: string; duration: number; pcapPath?: string; textPath: string }): void {\n const { filter, duration } = meta;\n const local = localPorts;\n const s = summarizeTraffic(pkts, local);\n const filterEv = b.evidenceOf(\"note\", `filter: ${filter}`, { filter, ports: [...local].slice(0, 40), duration_s: duration });\n const totalEv = b.evidenceOf(\"packet_summary\", `${s.packets} packets, ${humanBytes(s.bytes)} payload over ${s.duration_s}s; RST=${s.rst} retransmit≈${s.retransmits} unanswered SYN=${s.syn_no_synack}`, { name: \"packets\", packets: s.packets, bytes: s.bytes, rst: s.rst, retransmits: s.retransmits, syn_no_synack: s.syn_no_synack, duration_s: s.duration_s }, { artifact: (meta.pcapPath ?? meta.textPath) });\n const remoteEv = b.evidenceOf(\"packet_summary\", s.byRemote.length ? `per remote: ${s.byRemote.slice(0, 5).map((r2) => `${r2.remote} ${r2.packets}p/${humanBytes(r2.bytes)}${r2.rst ? ` RST×${r2.rst}` : \"\"}${r2.retransmits ? ` rtx×${r2.retransmits}` : \"\"}`).join(\"; \")}` : \"no packets matched\", s.byRemote.slice(0, 25), { artifact: meta.textPath });\n if (s.dns.length) b.evidenceOf(\"dns_query\", `DNS: ${s.dns.slice(0, 6).map((d) => `${d.name}×${d.count}`).join(\", \")}`, s.dns.slice(0, 30), { artifact: meta.textPath });\n if (s.sni.length) b.evidenceOf(\"tls_sni\", `TLS SNI: ${s.sni.slice(0, 6).map((d) => `${d.name}×${d.count}`).join(\", \")}`, s.sni.slice(0, 30), { artifact: meta.textPath });\n\n if (s.packets === 0) b.finding(\"info\", `no packets on the target's ports in ${duration}s`, [totalEv, filterEv]);\n if (s.rst > 0) {\n const worst = [...s.byRemote].sort((a, c) => c.rst - a.rst)[0]!;\n b.finding(s.rst >= 10 ? \"high\" : \"warn\", `${s.rst} TCP RST(s), most with ${worst.remote} (${worst.rst}) — connections are being refused or torn down abruptly`, [totalEv, remoteEv], \"observed\");\n }\n if (s.syn_no_synack > 0) b.finding(\"high\", `${s.syn_no_synack} SYN(s) never got a SYN-ACK — a remote is unreachable or firewalled`, [totalEv, remoteEv], \"observed\");\n if (s.retransmits >= 5) b.finding(\"warn\", `≈${s.retransmits} probable retransmissions — packet loss or a slow peer`, [totalEv], \"inferred\");\n const dnsRepeat = s.dns.find((d) => d.count >= 20);\n if (dnsRepeat) b.finding(\"warn\", `${dnsRepeat.name} resolved ${dnsRepeat.count}× in ${duration}s — no DNS caching`, [b.evidenceOf(\"dns_query\", \"repeated lookups\", dnsRepeat)], \"inferred\");\n if (b.findingCount === 0 && s.packets > 0) b.finding(\"info\", `${s.packets} packets, top remote ${s.byRemote[0]?.remote} (${humanBytes(s.byRemote[0]?.bytes ?? 0)})`, [remoteEv]);\n}\n\nasync function targetPorts(pids: number[]): Promise<number[]> {\n const r = await runCapped(\"lsof\", [\"-nP\", \"-w\", \"-a\", \"-F\", \"pcufatsinTP\", \"-i\", \"-p\", pids.join(\",\")], { timeoutMs: 15_000 });\n const ports: number[] = [];\n for (const e of parseLsofFields(r.stdout)) {\n if (e.type !== \"IPv4\" && e.type !== \"IPv6\") continue;\n const local = e.name.split(\"->\")[0]!;\n const port = Number(local.slice(local.lastIndexOf(\":\") + 1));\n if (port) ports.push(port);\n const remote = e.name.split(\"->\")[1];\n if (remote) {\n const rp = Number(remote.slice(remote.lastIndexOf(\":\") + 1));\n if (rp) ports.push(rp);\n }\n }\n return ports;\n}\n\nasync function captureTraffic(ctx: AdapterContext, args: { duration_s?: number; filter?: string }): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"capture_traffic\", session, target);\n const pids = targetPids(target);\n if (!pids.length) return b.fail(\"no pid; cannot derive the target's ports\").build();\n const duration = clampDuration(args.duration_s, 10, LIMITS.MAX_CAPTURE_WALL_MS);\n let filter: string;\n let ports: number[];\n try {\n ports = await targetPorts(pids);\n filter = buildFilter(ports, args.filter);\n } catch (err) {\n b.limitation((err as Error).message);\n return b.fail(\"refusing unbounded capture\").build();\n }\n const pcap = b.artifactPath(\"capture.pcap\");\n const iface = platform() === \"linux\" ? \"any\" : \"any\";\n const tdArgs = [\"-i\", iface, \"-nn\", \"-q\", \"-U\", \"-s\", \"256\", \"-w\", pcap, \"-G\", String(duration), \"-W\", \"1\", filter];\n const r = await runCapped(\"tcpdump\", tdArgs, { timeoutMs: duration * 1000 + LIMITS.DURATION_SLACK_MS + 3000 });\n if (looksLikePermissionError(r.stderr) || /You don't have permission|Operation not permitted|cannot open BPF device/i.test(r.stderr)) {\n b.limitation(rootRequiredLimitation(\"capture_traffic\", `tcpdump ${tdArgs.map((a) => (a === filter ? `'${a}'` : a)).join(\" \")}`));\n if (platform() === \"darwin\") b.limitation(\"macOS: add yourself to the access_bpf group (install Wireshark's ChmodBPF) or run with sudo\");\n if (platform() === \"linux\") b.limitation(\"Linux: sudo setcap cap_net_raw,cap_net_admin=eip $(which tcpdump) grants capture without root\");\n return b.fail(\"tcpdump needs permissions\").build();\n }\n const art = await b.addArtifact(pcap, \"pcap\", { description: `tcpdump ${duration}s, filter: ${filter}` });\n const read = await runCapped(\"tcpdump\", [\"-nn\", \"-tt\", \"-r\", pcap], { timeoutMs: 30_000 });\n const textPath = await b.writeArtifact(\"capture.txt\", read.stdout, \"raw_text\", \"tcpdump -nn -tt -r capture.pcap\");\n summarizeCaptureEvidence(b, parseTcpdump(read.stdout), new Set(ports), { filter, duration, pcapPath: art.path, textPath });\n b.limitation(\"retransmits = same flow and TCP seq range seen again >2 ms later (loopback In/Out duplicates collapsed); open the .pcap in Wireshark for exact analysis\");\n b.limitation(\"TLS SNI and payloads need a deeper snaplen/-v; this capture used -s 256 -q. Raw .pcap may contain secrets and is NOT redacted\");\n if (!isRoot()) b.limitation(\"capture ran without root — if it worked, your user has BPF access\");\n b.next(\"inspect_sockets\", \"trace_syscalls\");\n return b.build();\n}\n\nexport const tcpdumpAdapter: Adapter = {\n name: \"tcpdump\",\n tools: [\"capture_traffic\"],\n platforms: [\"linux\", \"darwin\"],\n requires: [\"tcpdump\", \"lsof\"],\n install: { linux: \"sudo apt install tcpdump\", darwin: \"preinstalled (/usr/sbin/tcpdump); needs sudo or access_bpf group\" },\n priority: 10,\n check(base, env) {\n if (!env.isRoot) base.notes.push(\"needs root or CAP_NET_RAW / access_bpf group; requires consent: true\");\n return base;\n },\n async run(tool, args, ctx) {\n if (tool !== \"capture_traffic\") throw new Error(`tcpdump adapter cannot run ${tool}`);\n return captureTraffic(ctx, args as { duration_s?: number; filter?: string });\n },\n};\n","/**\n * sample adapter (macOS): profile_cpu via `sample PID duration -file out`.\n * We convert sample's call tree into folded stacks and reuse the shared\n * flamegraph/frame summary.\n */\nimport { readFile } from \"node:fs/promises\";\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport type { ToolResult } from \"../contracts.js\";\nimport { ResultBuilder } from \"../evidence.js\";\nimport { runCapped, clampDuration, looksLikePermissionError, rootRequiredLimitation, LIMITS } from \"../safety.js\";\nimport { summarizeProfile } from \"./pyspy.js\";\n\n/**\n * Convert the \"Call graph:\" section of `sample` output into folded stacks.\n * sample prints an indented tree like:\n * 2000 Thread_12345 DispatchQueue_1: com.apple.main-thread (serial)\n * + 2000 start (in dyld) + 1234 [0x...]\n * + 2000 main (in node) + 56 [0x...]\n * + 1500 uv_run (in node) ...\n * + ! 400 foo (in node)\n * Each line's leading \"+ \" / \"! \" / \": \" / \"| \" characters encode depth.\n * Pure.\n */\nexport function sampleToFolded(raw: string): string {\n const start = raw.indexOf(\"Call graph:\");\n if (start < 0) return \"\";\n const end = raw.indexOf(\"\\nTotal number in stack\", start);\n const section = raw.slice(start, end > 0 ? end : undefined).split(\"\\n\").slice(1);\n const stack: Array<{ depth: number; name: string; count: number; childSum: number }> = [];\n const out: string[] = [];\n const flushLeaf = (node: { name: string; count: number; childSum: number }, path: string[]) => {\n const self = node.count - node.childSum;\n if (self > 0) out.push(`${[...path, node.name].join(\";\")} ${self}`);\n };\n for (const line of section) {\n if (!line.trim()) continue;\n // prefix = everything before the sample count: 4 spaces, then 2 chars per level (\"+ \", \"! \", \": \", \"| \" or \" \").\n const m = /^((?:\\s|[+!:|])*?)(\\d+)\\s+(.+?)(?:\\s{2}\\(in ([^)]+)\\))?(?:\\s+\\+\\s+\\d+)?(?:\\s+\\[0x[0-9a-f]+(?:,0x[0-9a-f]+)?\\])?\\s*$/.exec(line);\n if (!m) continue;\n const depth = Math.max(0, Math.floor((m[1]!.length - 4) / 2));\n const count = Number(m[2]);\n let name = m[3]!.trim();\n const dso = m[4];\n if (/^Thread_\\d+/.test(name)) name = name.replace(/\\s+DispatchQueue.*$/, \"\").replace(/\\s{2,}.*$/, \"\");\n if (dso && !/^Thread_/.test(name)) name = `${name} (${dso})`;\n name = name.replace(/;/g, \",\");\n while (stack.length && stack[stack.length - 1]!.depth >= depth) {\n const node = stack.pop()!;\n flushLeaf(node, stack.map((s) => s.name));\n }\n const parent = stack[stack.length - 1];\n if (parent) parent.childSum += count;\n stack.push({ depth, name, count, childSum: 0 });\n }\n while (stack.length) {\n const node = stack.pop()!;\n flushLeaf(node, stack.map((s) => s.name));\n }\n return out.join(\"\\n\") + (out.length ? \"\\n\" : \"\");\n}\n\nasync function profileCpu(ctx: AdapterContext, args: { duration_s?: number }): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"profile_cpu\", session, target);\n if (!target.pid) return b.fail(\"no pid\").build();\n const duration = clampDuration(args.duration_s, 15);\n const out = b.artifactPath(\"sample.txt\");\n const sArgs = [String(target.pid), String(duration), \"1\", \"-mayDie\", \"-file\", out];\n const r = await runCapped(\"sample\", sArgs, { timeoutMs: duration * 1000 + LIMITS.DURATION_SLACK_MS + 10_000 });\n const raw = await readFile(out, \"utf8\").catch(() => \"\");\n if (!raw) {\n if (looksLikePermissionError(r.stderr + r.stdout) || /Unable to sample|not permitted|failed to attach|Sampling failed/i.test(r.stderr + r.stdout)) {\n b.limitation(rootRequiredLimitation(\"profile_cpu\", `sample ${sArgs.join(\" \")}`));\n b.limitation(\"macOS: sampling another user's or a hardened process needs sudo\");\n return b.fail(\"sample could not attach\").build();\n }\n b.limitation(`sample: ${(r.stderr || r.stdout).trim().slice(0, 300)}`);\n return b.fail(\"sample produced no output\").build();\n }\n await b.addArtifact(out, \"raw_text\", { description: `sample ${duration}s` });\n const folded = sampleToFolded(raw);\n await b.writeArtifact(\"sample-folded.txt\", folded, \"folded_stacks\", \"folded stacks derived from sample call graph\");\n b.limitation(\"`sample` samples every 1 ms across all threads including idle ones; idle frames (kevent, __psynch_cvwait, mach_msg) are expected to dominate for servers\");\n return summarizeProfile(b, folded, duration, \"sample\", 1000);\n}\n\nexport const sampleMacosAdapter: Adapter = {\n name: \"sample\",\n tools: [\"profile_cpu\"],\n platforms: [\"darwin\"],\n requires: [\"sample\"],\n runtimes: [\"native\", \"node\", \"go\", \"java\", \"unknown\"],\n install: { darwin: \"preinstalled (/usr/bin/sample)\" },\n priority: 5,\n async run(tool, args, ctx) {\n if (tool !== \"profile_cpu\") throw new Error(`sample adapter cannot run ${tool}`);\n return profileCpu(ctx, args as { duration_s?: number });\n },\n};\n","/**\n * fs_usage adapter (macOS): trace_syscalls without strace.\n * fs_usage -w -f filesys,network -p PID\n * Works with SIP enabled but needs root. When Debug Anything is not root it returns the\n * exact command to run yourself plus `debuganything import fs_usage <file>`.\n */\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport type { SyscallCategory, ToolResult } from \"../contracts.js\";\nimport { ResultBuilder } from \"../evidence.js\";\nimport { runCapped, clampDuration, isRoot, looksLikePermissionError, rootRequiredLimitation, LIMITS } from \"../safety.js\";\nimport { summarizeSyscallRecords, type SyscallRecord } from \"./strace.js\";\n\n/** macOS errno numbers fs_usage prints in brackets, e.g. \"[ 2]\". */\nconst DARWIN_ERRNO: Record<number, string> = { 1: \"EPERM\", 2: \"ENOENT\", 4: \"EINTR\", 5: \"EIO\", 9: \"EBADF\", 11: \"EDEADLK\", 12: \"ENOMEM\", 13: \"EACCES\", 17: \"EEXIST\", 20: \"ENOTDIR\", 21: \"EISDIR\", 22: \"EINVAL\", 24: \"EMFILE\", 28: \"ENOSPC\", 32: \"EPIPE\", 35: \"EAGAIN\", 36: \"EINPROGRESS\", 54: \"ECONNRESET\", 57: \"ENOTCONN\", 60: \"ETIMEDOUT\", 61: \"ECONNREFUSED\", 65: \"EHOSTUNREACH\" };\n\n/**\n * Parse `fs_usage -w` lines into SyscallRecords. Pure.\n * 22:47:41.812345 read F=23 B=0x1000 0.000012 node.12345\n * 22:47:41.812400 RdData[A] /Users/x/payload.bin 0.000500 W node.12345\n * 22:47:41.813000 open [ 2] (R_____) /etc/missing 0.000030 node.12345\n * elapsed seconds is the last numeric token before an optional \"W\" (= the call blocked) and \"proc.tid\".\n */\nexport function parseFsUsage(raw: string): SyscallRecord[] {\n const out: SyscallRecord[] = [];\n const lines = raw.split(\"\\n\");\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!.trimEnd();\n const m = /^(\\d{2}:\\d{2}:\\d{2}\\.\\d+)\\s+(\\S+)\\s+(.*?)\\s+(\\d+\\.\\d{6})(?:\\s+(W))?\\s+(\\S+?)\\.(\\d+)\\s*$/.exec(line);\n if (!m) continue;\n const name = m[2]!.replace(/\\[.*$/, \"\");\n const args = m[3]!.trim();\n const err = /\\[\\s*(\\d+)\\]/.exec(args);\n const errno = err ? (DARWIN_ERRNO[Number(err[1])] ?? `E${err[1]}`) : undefined;\n out.push({ pid: Number(m[7]), time: m[1], name, args: args.replace(/\\[\\s*\\d+\\]\\s*/, \"\").replace(/^\\(\\S+\\)\\s*/, \"\"), result: errno ? `-1 ${errno}` : m[5] ? \"0 (blocked)\" : \"0\", errno, duration_s: Number(m[4]), line: i + 1 });\n }\n return out;\n}\n\nconst FS_FILTERS: Record<SyscallCategory, string | undefined> = { network: \"network\", file: \"filesys\", process: \"exec\", signal: undefined, memory: undefined, all: \"filesys,network,exec\" };\n\nasync function traceSyscalls(ctx: AdapterContext, args: { duration_s?: number; categories?: SyscallCategory[] }): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"trace_syscalls\", session, target);\n if (!target.pid) return b.fail(\"no pid\").build();\n const duration = clampDuration(args.duration_s, 10);\n const cats = args.categories?.length ? args.categories : ([\"all\"] as SyscallCategory[]);\n const filters = [...new Set(cats.map((c) => FS_FILTERS[c]).filter(Boolean))].join(\",\") || \"filesys,network\";\n const out = b.artifactPath(\"fs_usage.txt\");\n const fsArgs = [\"-w\", \"-f\", filters, \"-p\", String(target.pid)];\n const cmd = `sudo fs_usage ${fsArgs.join(\" \")} > ${out}`;\n if (!isRoot()) {\n b.limitation(rootRequiredLimitation(\"trace_syscalls\", `fs_usage ${fsArgs.join(\" \")}`));\n b.limitation(`macOS has no strace; fs_usage needs root. Run for ~${duration}s then Ctrl-C: ${cmd} and then: debuganything import fs_usage ${out} --session ${session.id}`);\n b.limitation(\"or run the target on Linux (docker/linux-lab) where strace gives the full breakdown\");\n b.next(`import_artifact (fs_usage, ${out})`, \"inspect_sockets\", \"profile_cpu\");\n return b.fail(\"fs_usage needs root; Debug Anything never escalates\").build();\n }\n const r = await runCapped(\"fs_usage\", fsArgs, { timeoutMs: duration * 1000, stdoutFile: out, captureInMemory: false });\n const { readFile } = await import(\"node:fs/promises\");\n const raw = await readFile(out, \"utf8\").catch(() => \"\");\n const art = await b.addArtifact(out, \"raw_text\", { description: `fs_usage ${fsArgs.join(\" \")} for ${duration}s`, truncated: r.outputCapped });\n if (!raw.trim()) {\n if (looksLikePermissionError(r.stderr)) {\n b.limitation(rootRequiredLimitation(\"trace_syscalls\", `fs_usage ${fsArgs.join(\" \")}`));\n return b.fail(\"fs_usage could not run (permission denied)\").build();\n }\n const ev = b.evidenceOf(\"syscall_stat\", `0 syscalls in ${duration}s`, { name: \"syscalls\", count: 0 });\n b.finding(\"info\", `no file/network syscalls in ${duration}s — idle, or spinning in user space`, [ev], \"inferred\");\n return b.build();\n }\n summarizeSyscallRecords(b, parseFsUsage(raw), duration, art.path);\n b.limitation(`fs_usage shows file and network calls only (filters: ${filters}); futex/select/kevent waits are not included — use dump_stacks for those`);\n if (r.outputCapped) b.limitation(`raw log hit the ${LIMITS.MAX_RAW_BYTES / 1024 / 1024} MB cap`);\n b.next(\"profile_cpu\", \"inspect_sockets\", \"inspect_files\");\n return b.build();\n}\n\nexport const fsUsageAdapter: Adapter = {\n name: \"fs_usage\",\n tools: [\"trace_syscalls\"],\n platforms: [\"darwin\"],\n requires: [\"fs_usage\"],\n install: { darwin: \"preinstalled (/usr/bin/fs_usage); needs sudo\" },\n priority: 5,\n check(base, env) {\n if (!env.isRoot) base.notes.push(\"needs root: Debug Anything will print the sudo command and you can `debuganything import fs_usage <file>`\");\n return base;\n },\n async run(tool, args, ctx) {\n if (tool !== \"trace_syscalls\") throw new Error(`fs_usage adapter cannot run ${tool}`);\n return traceSyscalls(ctx, args as { duration_s?: number; categories?: SyscallCategory[] });\n },\n};\n","/**\n * JVM thread dumps: parse `jstack <pid>` / `jcmd <pid> Thread.print` output\n * into threads + monitors, detect deadlocks and monitor contention.\n * Pure parsing/summarizing (used by debuganything import, the web analyzer, and the\n * live dump_stacks path when a JDK is present).\n */\nimport type { ToolResult } from \"../contracts.js\";\nimport { ResultBuilder } from \"../evidence.js\";\n\nexport type JavaFrame = { func: string; loc?: string };\nexport type JavaThread = {\n name: string;\n id?: number;\n daemon: boolean;\n state?: string; // NEW/RUNNABLE/BLOCKED/WAITING/TIMED_WAITING/TERMINATED\n frames: JavaFrame[];\n waitingToLock?: string; // monitor address\n holding: string[]; // monitors held\n};\n\nexport type JstackDump = { threads: JavaThread[]; deadlockText?: string; jniRefs?: number };\n\nexport function parseJstack(raw: string): JstackDump {\n const threads: JavaThread[] = [];\n let cur: JavaThread | undefined;\n let deadlock: string[] | undefined;\n const lines = raw.split(\"\\n\");\n for (const line of lines) {\n if (/^Found .* Java-level deadlock/i.test(line)) deadlock = [line.trim()];\n else if (deadlock && deadlock.length < 40 && line.trim()) deadlock.push(line.trim());\n\n const head = line.match(/^\"(.+)\"\\s+(#(\\d+)\\s+)?(daemon\\s+)?prio=/) ?? line.match(/^\"(.+)\"\\s+(#(\\d+))?.*(daemon)?.*\\bnid=/);\n if (head) {\n cur = { name: head[1]!, id: head[3] ? Number(head[3]) : undefined, daemon: /\\bdaemon\\b/.test(line), frames: [], holding: [] };\n threads.push(cur);\n continue;\n }\n if (!cur) continue;\n const st = line.match(/^\\s+java\\.lang\\.Thread\\.State:\\s+(\\w+)/);\n if (st) { cur.state = st[1]; continue; }\n const at = line.match(/^\\s+at\\s+([\\w.$/<>]+)\\((.*?)\\)/);\n if (at) { cur.frames.push({ func: at[1]!, loc: at[2] && at[2] !== \"Native Method\" ? at[2] : undefined }); continue; }\n const wait = line.match(/^\\s+-\\s+(?:waiting to lock|parking to wait for|waiting on)\\s+<(0x[0-9a-f]+)>/);\n if (wait) { cur.waitingToLock = wait[1]; continue; }\n const locked = line.match(/^\\s+-\\s+locked\\s+<(0x[0-9a-f]+)>/);\n if (locked) cur.holding.push(locked[1]!);\n }\n return { threads: threads.filter((t) => t.frames.length || t.state), deadlockText: deadlock?.join(\"\\n\") };\n}\n\nexport async function summarizeJavaStacks(b: ResultBuilder, dump: JstackDump, artifact: string): Promise<ToolResult> {\n const ts = dump.threads;\n if (!ts.length) {\n b.limitation(\"no Java threads parsed (expected `jstack <pid>` or `jcmd <pid> Thread.print` output)\");\n return b.fail(\"jstack: no threads parsed\").build();\n }\n const byState = new Map<string, JavaThread[]>();\n for (const t of ts) {\n const s = t.state ?? \"UNKNOWN\";\n byState.set(s, [...(byState.get(s) ?? []), t]);\n }\n const blocked = byState.get(\"BLOCKED\") ?? [];\n const runnable = byState.get(\"RUNNABLE\") ?? [];\n const summaryEv = b.evidenceOf(\n \"stack_summary\",\n `${ts.length} JVM thread(s): ${[...byState].map(([s, v]) => `${s}=${v.length}`).join(\" \")}`,\n ts.slice(0, 200).map((t) => ({ name: t.name, state: t.state, daemon: t.daemon, top: t.frames[0]?.func })),\n { artifact },\n );\n for (const t of ts.filter((x) => x.state === \"BLOCKED\" || x.name === \"main\").slice(0, 10)) {\n b.evidenceOf(\"stack\", `${t.name} [${t.state}]: ${t.frames.slice(0, 5).map((f) => f.func.split(\".\").slice(-2).join(\".\")).join(\" ← \")}`, { name: t.name, state: t.state, waiting_to_lock: t.waitingToLock, holding: t.holding, frames: t.frames.slice(0, 20).map((f) => `${f.func}${f.loc ? ` (${f.loc})` : \"\"}`) }, { artifact });\n }\n\n if (dump.deadlockText) {\n const dlEv = b.evidenceOf(\"lock_wait\", dump.deadlockText.split(\"\\n\")[0]!, { jstack_deadlock_section: dump.deadlockText }, { artifact });\n b.finding(\"high\", `the JVM itself reports a deadlock: ${dump.deadlockText.split(\"\\n\")[0]}`, [dlEv, summaryEv], \"observed\", dump.deadlockText);\n } else if (blocked.length >= 2) {\n // circular wait: A waits for a monitor B holds and vice versa\n const holders = new Map<string, JavaThread>();\n for (const t of ts) for (const m of t.holding) holders.set(m, t);\n const cycles = blocked.filter((t) => {\n const holder = t.waitingToLock ? holders.get(t.waitingToLock) : undefined;\n return holder && holder.waitingToLock && holders.get(holder.waitingToLock)?.name === t.name;\n });\n const lockEv = b.evidenceOf(\"lock_wait\", `${blocked.length} BLOCKED thread(s): ${blocked.slice(0, 6).map((t) => `${t.name} wants <${t.waitingToLock ?? \"?\"}> at ${t.frames[0]?.func ?? \"?\"}`).join(\"; \")}`, blocked.slice(0, 30).map((t) => ({ name: t.name, wants: t.waitingToLock, holds: t.holding, at: t.frames[0]?.func })), { artifact });\n if (cycles.length) b.finding(\"high\", `deadlock: circular monitor wait between ${cycles.map((t) => t.name).join(\" and \")}`, [lockEv, summaryEv], \"inferred\", \"Each thread holds the monitor the other wants.\");\n else {\n const wantCounts = new Map<string, number>();\n for (const t of blocked) if (t.waitingToLock) wantCounts.set(t.waitingToLock, (wantCounts.get(t.waitingToLock) ?? 0) + 1);\n const hot = [...wantCounts].sort((a, c) => c[1] - a[1])[0];\n if (hot && hot[1] >= 3) {\n const holder = holders.get(hot[0]);\n b.finding(\"high\", `monitor contention: ${hot[1]} threads blocked on <${hot[0]}>${holder ? `, held by ${holder.name} at ${holder.frames[0]?.func ?? \"?\"}` : \"\"}`, [lockEv], \"observed\");\n } else b.finding(\"warn\", `${blocked.length} thread(s) BLOCKED on monitors`, [lockEv], \"observed\");\n }\n }\n\n const main = ts.find((t) => t.name === \"main\");\n if (main && (main.state === \"WAITING\" || main.state === \"TIMED_WAITING\") && !dump.deadlockText) {\n const ev = b.evidenceOf(\"stack\", `main is ${main.state} in ${main.frames[0]?.func ?? \"?\"}`, main.frames.slice(0, 10).map((f) => f.func), { artifact });\n b.finding(\"info\", `main thread is ${main.state} in ${main.frames[0]?.func ?? \"?\"} — normal for servers; relevant if this process should be doing work`, [ev]);\n }\n if (ts.length >= 500) b.finding(\"warn\", `${ts.length} threads — likely an unbounded thread pool or a thread leak`, [summaryEv], \"inferred\");\n if (!b.findingCount) b.finding(\"info\", `${ts.length} threads, ${runnable.length} RUNNABLE, no monitor contention visible`, [summaryEv]);\n b.next(\"inspect_sockets\", \"snapshot_memory\", \"profile_cpu\");\n return b.build();\n}\n\n// ---------------------------------------------------------------------------\n// Live adapter: jstack/jcmd against a running JVM\n// ---------------------------------------------------------------------------\nimport type { Adapter, AdapterContext } from \"./types.js\";\nimport { runCapped, rootRequiredLimitation } from \"../safety.js\";\n\nasync function liveDump(ctx: AdapterContext): Promise<ToolResult> {\n const { session, target } = ctx;\n const b = new ResultBuilder(\"dump_stacks\", session, target);\n const pid = target.pid;\n if (!pid) return b.fail(\"no resolved pid for target\").build();\n // jcmd Thread.print includes lock info and is the modern entry; jstack is the fallback.\n const bad = (x: { exitCode: number | null; stdout: string }) => x.exitCode !== 0 || !/java\\.lang\\.Thread\\.State:|Full thread dump/.test(x.stdout);\n let r = await runCapped(\"jcmd\", [String(pid), \"Thread.print\", \"-l\"], { timeoutMs: 20_000 });\n if (bad(r)) r = await runCapped(\"jstack\", [\"-l\", String(pid)], { timeoutMs: 20_000 });\n if (bad(r)) {\n if (/Operation not permitted|AttachNotSupported|well-known file is not secure/i.test(r.stderr + r.stdout)) {\n b.limitation(rootRequiredLimitation(\"dump_stacks\", `jstack -l ${pid}`));\n b.limitation(\"the JVM attach mechanism requires the same user as the target (or root)\");\n b.next(`import_artifact (tool: jstack) after running it yourself`);\n return b.fail(\"jstack/jcmd could not attach\").build();\n }\n return b.fail(`jcmd/jstack failed: ${(r.stderr || r.stdout).slice(0, 300)}`).build();\n }\n const art = await b.writeArtifact(\"jstack.txt\", r.stdout, \"raw_text\", \"JVM thread dump\");\n return summarizeJavaStacks(b, parseJstack(r.stdout), art);\n}\n\nexport const jvmAdapter: Adapter = {\n name: \"jstack\",\n tools: [\"dump_stacks\"],\n platforms: [\"linux\", \"darwin\"],\n requires: [\"jcmd\"],\n runtimes: [\"java\"],\n install: { linux: \"install a JDK (jcmd/jstack ship with it)\", darwin: \"brew install openjdk\" },\n priority: 20,\n async run(tool, _args, ctx) {\n if (tool !== \"dump_stacks\") throw new Error(`jstack adapter cannot run ${tool}`);\n return liveDump(ctx);\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,oBAAoB;;;ACQtB,SAAS,YAAY,KAA4B;AACtD,QAAM,MAAqB,CAAC;AAC5B,aAAW,QAAQ,IAAI,MAAM,IAAI,GAAG;AAClC,UAAM,IAAI,KAAK,QAAQ;AACvB,QAAI,CAAC,EAAG;AACR,UAAM,KAAK,EAAE,YAAY,GAAG;AAC5B,QAAI,KAAK,EAAG;AACZ,UAAM,QAAQ,OAAO,EAAE,MAAM,KAAK,CAAC,CAAC;AACpC,QAAI,CAAC,OAAO,SAAS,KAAK,EAAG;AAC7B,UAAM,SAAS,EAAE,MAAM,GAAG,EAAE,EAAE,MAAM,GAAG,EAAE,OAAO,OAAO;AACvD,QAAI,OAAO,OAAQ,KAAI,KAAK,EAAE,QAAQ,MAAM,CAAC;AAAA,EAC/C;AACA,SAAO;AACT;AAWO,SAAS,gBAAgB,QAAuB,QAAQ,IAAmD;AAChH,QAAM,OAAO,oBAAI,IAAoB;AACrC,QAAM,QAAQ,oBAAI,IAAoB;AACtC,MAAI,eAAe;AACnB,aAAW,KAAK,QAAQ;AACtB,oBAAgB,EAAE;AAClB,UAAM,OAAO,EAAE,OAAO,EAAE,OAAO,SAAS,CAAC;AACzC,SAAK,IAAI,OAAO,KAAK,IAAI,IAAI,KAAK,KAAK,EAAE,KAAK;AAC9C,eAAW,KAAK,IAAI,IAAI,EAAE,MAAM,EAAG,OAAM,IAAI,IAAI,MAAM,IAAI,CAAC,KAAK,KAAK,EAAE,KAAK;AAAA,EAC/E;AACA,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