@wrongstack/tools 0.283.1 → 0.284.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/audit.js.map +1 -1
  2. package/dist/bash.js +4 -0
  3. package/dist/bash.js.map +1 -1
  4. package/dist/builtin.js +685 -253
  5. package/dist/builtin.js.map +1 -1
  6. package/dist/codebase-index/index.js +2 -2
  7. package/dist/codebase-index/index.js.map +1 -1
  8. package/dist/diff.js.map +1 -1
  9. package/dist/document.js.map +1 -1
  10. package/dist/edit.d.ts +43 -0
  11. package/dist/edit.js +386 -60
  12. package/dist/edit.js.map +1 -1
  13. package/dist/{exec-Ca3fnpUh.d.ts → exec-2OKoT6tk.d.ts} +1 -1
  14. package/dist/exec.d.ts +1 -1
  15. package/dist/exec.js +13 -14
  16. package/dist/exec.js.map +1 -1
  17. package/dist/fetch.js.map +1 -1
  18. package/dist/format.js.map +1 -1
  19. package/dist/git.js.map +1 -1
  20. package/dist/glob.js +10 -1
  21. package/dist/glob.js.map +1 -1
  22. package/dist/grep.js +4 -0
  23. package/dist/grep.js.map +1 -1
  24. package/dist/index.d.ts +13 -2
  25. package/dist/index.js +730 -268
  26. package/dist/index.js.map +1 -1
  27. package/dist/install.js.map +1 -1
  28. package/dist/json.js.map +1 -1
  29. package/dist/lint.js.map +1 -1
  30. package/dist/logs.js.map +1 -1
  31. package/dist/next-steps.d.ts +66 -0
  32. package/dist/next-steps.js +116 -0
  33. package/dist/next-steps.js.map +1 -0
  34. package/dist/outdated.js.map +1 -1
  35. package/dist/pack.js +685 -253
  36. package/dist/pack.js.map +1 -1
  37. package/dist/patch.js +43 -0
  38. package/dist/patch.js.map +1 -1
  39. package/dist/read.js +13 -4
  40. package/dist/read.js.map +1 -1
  41. package/dist/replace.js +14 -0
  42. package/dist/replace.js.map +1 -1
  43. package/dist/scaffold.js.map +1 -1
  44. package/dist/test.js.map +1 -1
  45. package/dist/tool-diff.d.ts +88 -0
  46. package/dist/tool-diff.js +229 -0
  47. package/dist/tool-diff.js.map +1 -0
  48. package/dist/tool-summary.d.ts +24 -0
  49. package/dist/tool-summary.js +208 -0
  50. package/dist/tool-summary.js.map +1 -0
  51. package/dist/tree.js.map +1 -1
  52. package/dist/typecheck.js.map +1 -1
  53. package/dist/write.d.ts +6 -0
  54. package/dist/write.js +118 -19
  55. package/dist/write.js.map +1 -1
  56. package/package.json +15 -2
package/dist/logs.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/_regex.ts","../src/_util.ts","../src/logs.ts"],"names":["resolve","path"],"mappings":";;;;;;;;AAuBA,IAAM,eAAA,GAAkB,GAAA;AAIxB,IAAM,kBAAA,GAA4C;AAAA;AAAA,EAEhD,0BAAA;AAAA,EACA,6BAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,2BAAA;AAAA;AAAA,EAEA;AACF,CAAA;AAYO,SAAS,gBAAA,CAAiB,SAAiB,KAAA,EAA4C;AAC5F,EAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,0BAAA,EAA2B;AAAA,EACzD;AACA,EAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,kBAAA,EAAmB;AAAA,EACjD;AACA,EAAA,IAAI,OAAA,CAAQ,SAAS,eAAA,EAAiB;AACpC,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,CAAA,gBAAA,EAAmB,eAAe,CAAA,WAAA,CAAA,EAAc;AAAA,EAC9E;AACA,EAAA,KAAA,MAAW,MAAM,kBAAA,EAAoB;AACnC,IAAA,IAAI,EAAA,CAAG,IAAA,CAAK,OAAO,CAAA,EAAG;AACpB,MAAA,OAAO;AAAA,QACL,EAAA,EAAI,KAAA;AAAA,QACJ,MAAA,EAC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(V8) is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length — practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc — nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind — (?!.*a+)\n /[([][^)\\]]*[+*][^)\\]]*[)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n","import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { compileUserRegex } from './_regex.js';\nimport { safeResolve } from './_util.js';\n\ninterface LogsInput {\n service?: string | undefined;\n path?: string | undefined;\n lines?: number | undefined;\n stream?: boolean | undefined;\n filter?: string | undefined;\n since?: '1h' | '6h' | '24h' | 'all' | undefined;\n cwd?: string | undefined;\n}\n\ninterface LogEntry {\n timestamp: string;\n level: string;\n message: string;\n source?: string | undefined;\n}\n\ninterface LogsOutput {\n source: string;\n entries: LogEntry[];\n total: number;\n truncated: boolean;\n stream_mode: boolean;\n}\n\nexport const logsTool: Tool<LogsInput, LogsOutput> = {\n name: 'logs',\n category: 'Logs',\n description:\n 'Read or stream logs from files, Docker containers, or systemd services. Useful for debugging running applications.',\n usageHint:\n 'DEBUGGING TOOL — USE CAREFULLY IN AUTONOMOUS MODE:\\n\\n' +\n '- Prefer `path` for local files or `service` for containers/systemd.\\n' +\n '- `stream: true` = live tail (can be expensive).\\n' +\n '- Always use `filter` (regex) when possible to reduce noise and token usage.\\n' +\n '- Long-running streams should be avoided unless the user explicitly wants live logs.',\n permission: 'confirm',\n mutating: false,\n timeoutMs: 30_000,\n capabilities: ['shell.restricted'],\n icon: 'logs',\n inputSchema: {\n type: 'object',\n properties: {\n service: {\n type: 'string',\n description: 'Service name for Docker or systemd journal',\n },\n path: {\n type: 'string',\n description: 'Path to log file (alternative to service)',\n },\n lines: {\n type: 'integer',\n description: 'Number of log lines to fetch (default: 100, 0 for all)',\n minimum: 0,\n maximum: 10000,\n },\n stream: {\n type: 'boolean',\n description: 'Stream logs continuously (like tail -f) (default: false)',\n },\n filter: {\n type: 'string',\n description: 'Regex pattern to filter log lines',\n },\n since: {\n type: 'string',\n enum: ['1h', '6h', '24h', 'all'],\n description: 'Only show logs since duration',\n },\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n },\n },\n async execute(input, ctx, opts) {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const lines = input.lines ?? 100;\n let filterRe: RegExp | null = null;\n if (input.filter) {\n const compiled = compileUserRegex(input.filter, 'i');\n if (!compiled.ok) {\n throw new Error(`logs: ${compiled.reason}`);\n }\n filterRe = compiled.regex;\n }\n\n if (input.service) {\n return await dockerLogs(input.service, lines, filterRe, cwd, opts.signal);\n }\n\n if (input.path) {\n return await fileLogs(safeResolve(input.path, ctx), lines, filterRe, input.stream ?? false);\n }\n\n return {\n source: 'none',\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n };\n },\n};\n\nasync function dockerLogs(\n service: string,\n lines: number,\n filterRe: RegExp | null,\n cwd: string,\n signal: AbortSignal,\n since?: string | undefined,\n): Promise<LogsOutput> {\n const args = ['logs'];\n if (lines > 0) args.push('--tail', String(lines));\n /* v8 ignore start -- execute() does not forward `since` to dockerLogs yet; this block is currently unreachable. */\n if (since) {\n const sinceMap: Record<string, string> = { '1h': '1h', '6h': '6h', '24h': '24h' };\n args.push('--since', sinceMap[since] ?? '1h');\n }\n /* v8 ignore stop */\n // Validate service name to prevent container name injection.\n // Docker container names are limited to [a-zA-Z0-9][a-zA-Z0-9._-]+.\n if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]+$/.test(service)) {\n return {\n source: `docker:${service}`,\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n };\n }\n args.push('--timestamps', service);\n\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n const MAX = 200_000;\n let settled = false;\n\n const empty = (): LogsOutput => ({\n source: `docker:${service}`,\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n });\n const finish = (result: LogsOutput) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(result);\n };\n\n const child = spawn('docker', args, { cwd, signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });\n\n // `docker logs --tail N` reads recent lines and exits — fast when the\n // daemon is up. But if the daemon is unreachable (common on CI runners\n // with no running Docker), the CLI can hang on the socket connection and\n // emit neither `close` nor `error`. Kill it and return empty so the tool\n // (and its tests) never hang.\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n finish(empty());\n }, DOCKER_LOGS_TIMEOUT_MS);\n\n child.stdout?.on('data', (c) => {\n if (stdout.length < MAX) stdout += c.toString();\n });\n child.stderr?.on('data', (c) => {\n if (stderr.length < MAX) stderr += c.toString();\n });\n // When the child is SIGTERM-killed on timeout (or aborted via `signal`),\n // its pipes can emit `error` (e.g. EPIPE on Windows). Without a listener\n // that surfaces as an unhandled error and can fail the host/test — swallow\n // it at debug level; `child.on('error')` and the timeout already drive the result.\n child.stdout?.on('error', (e) => {\n console.log(JSON.stringify({ level: 'debug', event: 'pipe_error', stream: 'stdout', error: e.message }));\n });\n child.stderr?.on('error', (e) => {\n console.log(JSON.stringify({ level: 'debug', event: 'pipe_error', stream: 'stderr', error: e.message }));\n });\n child.on('close', () => {\n const output = stdout + stderr;\n const entries = parseLogLines(output, filterRe);\n finish({\n source: `docker:${service}`,\n entries,\n total: entries.length,\n truncated: output.length >= MAX,\n stream_mode: false,\n });\n });\n child.on('error', () => finish(empty()));\n });\n}\n\n/**\n * Hard ceiling for a `docker logs` read. The daemon may be unreachable on CI\n * (no Docker running), where the CLI hangs on the socket without ever exiting.\n */\nconst DOCKER_LOGS_TIMEOUT_MS = 3_000;\n\n// Hard cap on tail-window size — `lines: 0` historically meant \"all\" and\n// happily buffered an entire multi-GB log into memory. Cap at 100k lines;\n// callers that need more should narrow with `filter`.\nconst MAX_TAIL_LINES = 100_000;\n\nasync function fileLogs(\n path: string,\n lines: number,\n filterRe: RegExp | null,\n stream: boolean,\n): Promise<LogsOutput> {\n const { createInterface } = await import('node:readline');\n const { createReadStream } = await import('node:fs');\n const entries: LogEntry[] = [];\n\n // Effective tail window: clamp to MAX_TAIL_LINES; treat 0 / negative as\n // \"max window\" rather than \"unlimited\" so a malicious /proc/kcore path\n // cannot OOM the worker.\n const effLines = lines > 0 ? Math.min(lines, MAX_TAIL_LINES) : MAX_TAIL_LINES;\n // Rolling window backed by a fixed-size circular buffer — at most\n // `effLines` strings live in memory regardless of file size.\n const window: string[] = new Array(effLines);\n let writeIdx = 0;\n let totalLines = 0;\n\n const rl = createInterface({\n input: createReadStream(path),\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n\n for await (const line of rl) {\n if (filterRe && !filterRe.test(line)) continue;\n window[writeIdx] = line;\n writeIdx = (writeIdx + 1) % effLines;\n totalLines++;\n }\n\n // Read the window back in arrival order.\n const ordered: string[] = [];\n const start = totalLines >= effLines ? writeIdx : 0;\n const count = Math.min(totalLines, effLines);\n for (let i = 0; i < count; i++) {\n const v = window[(start + i) % effLines];\n if (v !== undefined) ordered.push(v);\n }\n\n for (const line of ordered) {\n const parsed = parseLine(line);\n if (parsed) entries.push(parsed);\n }\n\n return {\n source: path,\n entries,\n total: entries.length,\n truncated: totalLines > effLines,\n stream_mode: stream,\n };\n}\n\nfunction parseLogLines(output: string, filterRe: RegExp | null): LogEntry[] {\n const lines = output.split('\\n').filter(Boolean);\n const entries: LogEntry[] = [];\n\n for (const line of lines) {\n if (filterRe && !filterRe.test(line)) continue;\n const parsed = parseLine(line);\n if (parsed) entries.push(parsed);\n }\n\n return entries;\n}\n\nfunction parseLine(line: string): LogEntry | null {\n const tsRe = /^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?)\\s+(?:\\[?(\\w+)\\]?)\\s*(.*)/;\n const match = tsRe.exec(line);\n\n if (match) {\n return {\n timestamp: match[1] ?? '',\n level: match[2]?.toLowerCase() ?? 'info',\n message: match[3] ?? '',\n };\n }\n\n const levelRe = /(ERROR|WARN|INFO|DEBUG|TRACE)\\s+(.*)/i;\n const levelMatch = levelRe.exec(line);\n\n if (levelMatch) {\n return {\n timestamp: '',\n level: levelMatch[1]?.toLowerCase() ?? 'info',\n message: levelMatch[2] ?? line,\n };\n }\n\n return {\n timestamp: '',\n level: 'info',\n message: line,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/_regex.ts","../src/_util.ts","../src/logs.ts"],"names":["resolve","path"],"mappings":";;;;;;;;AAuBA,IAAM,eAAA,GAAkB,GAAA;AAIxB,IAAM,kBAAA,GAA4C;AAAA;AAAA,EAEhD,0BAAA;AAAA,EACA,6BAAA;AAAA;AAAA,EAEA,UAAA;AAAA;AAAA,EAEA,2BAAA;AAAA;AAAA,EAEA;AACF,CAAA;AAYO,SAAS,gBAAA,CAAiB,SAAiB,KAAA,EAA4C;AAC5F,EAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,0BAAA,EAA2B;AAAA,EACzD;AACA,EAAA,IAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AACxB,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,MAAA,EAAQ,k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,OAAO;AAAA,MACL,SAAA,EAAW,EAAA;AAAA,MACX,KAAA,EAAO,UAAA,CAAW,CAAC,CAAA,EAAG,aAAY,IAAK,MAAA;AAAA,MACvC,OAAA,EAAS,UAAA,CAAW,CAAC,CAAA,IAAK;AAAA,KAC5B;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,EAAA;AAAA,IACX,KAAA,EAAO,MAAA;AAAA,IACP,OAAA,EAAS;AAAA,GACX;AACF","file":"logs.js","sourcesContent":["/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match — a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length — practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc — nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind — (?!.*a+)\n /[([][^)\\]]*[+*][^)\\]]*[)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking — rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n","import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` — the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { compileUserRegex } from './_regex.js';\nimport { safeResolve } from './_util.js';\n\ninterface LogsInput {\n service?: string | undefined;\n path?: string | undefined;\n lines?: number | undefined;\n stream?: boolean | undefined;\n filter?: string | undefined;\n since?: '1h' | '6h' | '24h' | 'all' | undefined;\n cwd?: string | undefined;\n}\n\ninterface LogEntry {\n timestamp: string;\n level: string;\n message: string;\n source?: string | undefined;\n}\n\ninterface LogsOutput {\n source: string;\n entries: LogEntry[];\n total: number;\n truncated: boolean;\n stream_mode: boolean;\n}\n\nexport const logsTool: Tool<LogsInput, LogsOutput> = {\n name: 'logs',\n category: 'Logs',\n description:\n 'Read or stream logs from files, Docker containers, or systemd services. Useful for debugging running applications.',\n usageHint:\n 'DEBUGGING TOOL — USE CAREFULLY IN AUTONOMOUS MODE:\\n\\n' +\n '- Prefer `path` for local files or `service` for containers/systemd.\\n' +\n '- `stream: true` = live tail (can be expensive).\\n' +\n '- Always use `filter` (regex) when possible to reduce noise and token usage.\\n' +\n '- Long-running streams should be avoided unless the user explicitly wants live logs.',\n permission: 'confirm',\n mutating: false,\n timeoutMs: 30_000,\n capabilities: ['shell.restricted'],\n icon: 'logs',\n inputSchema: {\n type: 'object',\n properties: {\n service: {\n type: 'string',\n description: 'Service name for Docker or systemd journal',\n },\n path: {\n type: 'string',\n description: 'Path to log file (alternative to service)',\n },\n lines: {\n type: 'integer',\n description: 'Number of log lines to fetch (default: 100, 0 for all)',\n minimum: 0,\n maximum: 10000,\n },\n stream: {\n type: 'boolean',\n description: 'Stream logs continuously (like tail -f) (default: false)',\n },\n filter: {\n type: 'string',\n description: 'Regex pattern to filter log lines',\n },\n since: {\n type: 'string',\n enum: ['1h', '6h', '24h', 'all'],\n description: 'Only show logs since duration',\n },\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n },\n },\n async execute(input, ctx, opts) {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const lines = input.lines ?? 100;\n let filterRe: RegExp | null = null;\n if (input.filter) {\n const compiled = compileUserRegex(input.filter, 'i');\n if (!compiled.ok) {\n throw new Error(`logs: ${compiled.reason}`);\n }\n filterRe = compiled.regex;\n }\n\n if (input.service) {\n return await dockerLogs(input.service, lines, filterRe, cwd, opts.signal);\n }\n\n if (input.path) {\n return await fileLogs(safeResolve(input.path, ctx), lines, filterRe, input.stream ?? false);\n }\n\n return {\n source: 'none',\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n };\n },\n};\n\nasync function dockerLogs(\n service: string,\n lines: number,\n filterRe: RegExp | null,\n cwd: string,\n signal: AbortSignal,\n since?: string | undefined,\n): Promise<LogsOutput> {\n const args = ['logs'];\n if (lines > 0) args.push('--tail', String(lines));\n /* v8 ignore start -- execute() does not forward `since` to dockerLogs yet; this block is currently unreachable. */\n if (since) {\n const sinceMap: Record<string, string> = { '1h': '1h', '6h': '6h', '24h': '24h' };\n args.push('--since', sinceMap[since] ?? '1h');\n }\n /* v8 ignore stop */\n // Validate service name to prevent container name injection.\n // Docker container names are limited to [a-zA-Z0-9][a-zA-Z0-9._-]+.\n if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]+$/.test(service)) {\n return {\n source: `docker:${service}`,\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n };\n }\n args.push('--timestamps', service);\n\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n const MAX = 200_000;\n let settled = false;\n\n const empty = (): LogsOutput => ({\n source: `docker:${service}`,\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n });\n const finish = (result: LogsOutput) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(result);\n };\n\n const child = spawn('docker', args, { cwd, signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });\n\n // `docker logs --tail N` reads recent lines and exits — fast when the\n // daemon is up. But if the daemon is unreachable (common on CI runners\n // with no running Docker), the CLI can hang on the socket connection and\n // emit neither `close` nor `error`. Kill it and return empty so the tool\n // (and its tests) never hang.\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n finish(empty());\n }, DOCKER_LOGS_TIMEOUT_MS);\n\n child.stdout?.on('data', (c) => {\n if (stdout.length < MAX) stdout += c.toString();\n });\n child.stderr?.on('data', (c) => {\n if (stderr.length < MAX) stderr += c.toString();\n });\n // When the child is SIGTERM-killed on timeout (or aborted via `signal`),\n // its pipes can emit `error` (e.g. EPIPE on Windows). Without a listener\n // that surfaces as an unhandled error and can fail the host/test — swallow\n // it at debug level; `child.on('error')` and the timeout already drive the result.\n child.stdout?.on('error', (e) => {\n console.log(JSON.stringify({ level: 'debug', event: 'pipe_error', stream: 'stdout', error: e.message }));\n });\n child.stderr?.on('error', (e) => {\n console.log(JSON.stringify({ level: 'debug', event: 'pipe_error', stream: 'stderr', error: e.message }));\n });\n child.on('close', () => {\n const output = stdout + stderr;\n const entries = parseLogLines(output, filterRe);\n finish({\n source: `docker:${service}`,\n entries,\n total: entries.length,\n truncated: output.length >= MAX,\n stream_mode: false,\n });\n });\n child.on('error', () => finish(empty()));\n });\n}\n\n/**\n * Hard ceiling for a `docker logs` read. The daemon may be unreachable on CI\n * (no Docker running), where the CLI hangs on the socket without ever exiting.\n */\nconst DOCKER_LOGS_TIMEOUT_MS = 3_000;\n\n// Hard cap on tail-window size — `lines: 0` historically meant \"all\" and\n// happily buffered an entire multi-GB log into memory. Cap at 100k lines;\n// callers that need more should narrow with `filter`.\nconst MAX_TAIL_LINES = 100_000;\n\nasync function fileLogs(\n path: string,\n lines: number,\n filterRe: RegExp | null,\n stream: boolean,\n): Promise<LogsOutput> {\n const { createInterface } = await import('node:readline');\n const { createReadStream } = await import('node:fs');\n const entries: LogEntry[] = [];\n\n // Effective tail window: clamp to MAX_TAIL_LINES; treat 0 / negative as\n // \"max window\" rather than \"unlimited\" so a malicious /proc/kcore path\n // cannot OOM the worker.\n const effLines = lines > 0 ? Math.min(lines, MAX_TAIL_LINES) : MAX_TAIL_LINES;\n // Rolling window backed by a fixed-size circular buffer — at most\n // `effLines` strings live in memory regardless of file size.\n const window: string[] = new Array(effLines);\n let writeIdx = 0;\n let totalLines = 0;\n\n const rl = createInterface({\n input: createReadStream(path),\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n\n for await (const line of rl) {\n if (filterRe && !filterRe.test(line)) continue;\n window[writeIdx] = line;\n writeIdx = (writeIdx + 1) % effLines;\n totalLines++;\n }\n\n // Read the window back in arrival order.\n const ordered: string[] = [];\n const start = totalLines >= effLines ? writeIdx : 0;\n const count = Math.min(totalLines, effLines);\n for (let i = 0; i < count; i++) {\n const v = window[(start + i) % effLines];\n if (v !== undefined) ordered.push(v);\n }\n\n for (const line of ordered) {\n const parsed = parseLine(line);\n if (parsed) entries.push(parsed);\n }\n\n return {\n source: path,\n entries,\n total: entries.length,\n truncated: totalLines > effLines,\n stream_mode: stream,\n };\n}\n\nfunction parseLogLines(output: string, filterRe: RegExp | null): LogEntry[] {\n const lines = output.split('\\n').filter(Boolean);\n const entries: LogEntry[] = [];\n\n for (const line of lines) {\n if (filterRe && !filterRe.test(line)) continue;\n const parsed = parseLine(line);\n if (parsed) entries.push(parsed);\n }\n\n return entries;\n}\n\nfunction parseLine(line: string): LogEntry | null {\n const tsRe = /^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?)\\s+(?:\\[?(\\w+)\\]?)\\s*(.*)/;\n const match = tsRe.exec(line);\n\n if (match) {\n return {\n timestamp: match[1] ?? '',\n level: match[2]?.toLowerCase() ?? 'info',\n message: match[3] ?? '',\n };\n }\n\n const levelRe = /(ERROR|WARN|INFO|DEBUG|TRACE)\\s+(.*)/i;\n const levelMatch = levelRe.exec(line);\n\n if (levelMatch) {\n return {\n timestamp: '',\n level: levelMatch[1]?.toLowerCase() ?? 'info',\n message: levelMatch[2] ?? line,\n };\n }\n\n return {\n timestamp: '',\n level: 'info',\n message: line,\n };\n}\n"]}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Canonical `<nextsteps>` block parser — the single source of truth shared by
3
+ * the TUI history renderer, the CLI REPL suggestion store, the CLI /suggest
4
+ * subagent output, and the WebUI MessageBubble/NextStepsBar.
5
+ *
6
+ * Three code paths feed into the parser:
7
+ * 1. TUI rendering — entry.tsx parses only "<nextsteps>" from assistant output
8
+ * 2. REPL store — repl.ts parses only "<nextsteps>" from final agent output
9
+ * 3. /suggest output — suggest.ts parses LLM-generated numbered lists (raw mode)
10
+ *
11
+ * Heading mode (`requireHeading = true`, the default):
12
+ * Assistant-output paths accept only balanced <nextsteps>...</nextsteps> blocks.
13
+ * Loose headings like "Next steps:" are intentionally ignored so `/next` only
14
+ * activates for the canonical machine-readable format.
15
+ *
16
+ * Raw mode (`requireHeading = false`):
17
+ * Parses numbered/bullet items from anywhere in text (subagent /suggest output).
18
+ *
19
+ * Supported assistant-output format:
20
+ * <nextsteps> (canonical XML tag format)
21
+ *
22
+ * This module is BROWSER-SAFE — no Node-only imports — so it is safe to import
23
+ * from Vite-bundled WebUI as well as Node-based CLI/TUI. Mirrors the proven
24
+ * `tool-summary` / `tool-icons` extraction pattern (PRs #236 / #237 / #238).
25
+ */
26
+ interface ParsedNextStep {
27
+ index: number;
28
+ text: string;
29
+ /** Whether this item has auto="true" attribute for YOLO+auto autonomy mode. */
30
+ auto?: boolean;
31
+ }
32
+ interface ParseNextStepsResult {
33
+ /** Matched steps with their original index and stripped text. */
34
+ steps: ParsedNextStep[];
35
+ /** Flat string array — what gets stored in the suggestion store. */
36
+ texts: string[];
37
+ /**
38
+ * Content with the entire canonical "<nextsteps>" block removed.
39
+ * Used by entry.tsx to strip suggestions from the rendered message body.
40
+ */
41
+ stripped: string;
42
+ /** Flat string array — texts of items with auto="true" attribute only. */
43
+ autoTexts: string[];
44
+ }
45
+ /**
46
+ * Parse canonical "<nextsteps>" blocks from assistant output (or raw numbered lines).
47
+ *
48
+ * @param content — raw assistant message text or subagent output
49
+ * @param strict — retained for compatibility; assistant-output paths always require the canonical XML tag.
50
+ * @param requireHeading — when true, a canonical XML tag must precede the item list.
51
+ * when false, numbered/bullet items are parsed from anywhere in text
52
+ * (used by /suggest subagent output which has no heading).
53
+ */
54
+ declare function parseNextSteps(content: string, strict?: boolean, requireHeading?: boolean): ParseNextStepsResult;
55
+ /**
56
+ * Strip <nextsteps>...</nextsteps> blocks from subagent output text.
57
+ * Subagent results should not contain suggestion blocks — those belong to
58
+ * the main assistant's output. This prevents raw XML tags from appearing
59
+ * as literal text in the fleet panel.
60
+ *
61
+ * Also strips the legacy `<next_steps>` spelling that older persisted
62
+ * subagent output may contain (WebUI parity).
63
+ */
64
+ declare function stripNextStepsBlock(text: string): string;
65
+
66
+ export { type ParseNextStepsResult, type ParsedNextStep, parseNextSteps, stripNextStepsBlock };
@@ -0,0 +1,116 @@
1
+ // src/next-steps.ts
2
+ var NEXT_STEPS_TAG_RE = /<nextsteps>\s*\n+/i;
3
+ var ITEM_RE = /^(?:(\d+)[.)]\s*|[-*•]\s*)(.+?)(\s+auto="true")?$/;
4
+ var MAX_STEPS = 6;
5
+ function parseNextSteps(content, strict = false, requireHeading = true) {
6
+ if (requireHeading) {
7
+ return parseWithHeading(content);
8
+ }
9
+ return parseRawNumbered(content);
10
+ }
11
+ function pushStep(steps, index, text, hasAuto) {
12
+ steps.push(hasAuto ? { index, text, auto: true } : { index, text });
13
+ }
14
+ function parseRawNumbered(content) {
15
+ const lines = content.split("\n");
16
+ const steps = [];
17
+ const seenNumbers = /* @__PURE__ */ new Set();
18
+ for (const rawLine of lines) {
19
+ const line = rawLine.trim();
20
+ if (!line) continue;
21
+ const m = ITEM_RE.exec(line);
22
+ if (!m) continue;
23
+ const numPart = m[1];
24
+ const text = m[2].trim();
25
+ const hasAuto = !!m[3];
26
+ let index;
27
+ if (numPart !== void 0) {
28
+ index = Number.parseInt(numPart, 10);
29
+ } else {
30
+ index = steps.length + 1;
31
+ }
32
+ if (seenNumbers.has(index)) continue;
33
+ seenNumbers.add(index);
34
+ pushStep(steps, index, text, hasAuto);
35
+ if (steps.length >= MAX_STEPS) break;
36
+ }
37
+ return {
38
+ steps,
39
+ texts: steps.map((s) => s.text),
40
+ stripped: content,
41
+ autoTexts: steps.filter((s) => s.auto).map((s) => s.text)
42
+ };
43
+ }
44
+ function parseWithHeading(content, _strict) {
45
+ const headingMatch = NEXT_STEPS_TAG_RE.exec(content);
46
+ if (!headingMatch) {
47
+ return { steps: [], texts: [], stripped: content, autoTexts: [] };
48
+ }
49
+ const headingEnd = headingMatch.index + headingMatch[0].length;
50
+ const afterHeading = content.slice(headingEnd);
51
+ const lines = afterHeading.split("\n");
52
+ const steps = [];
53
+ const seenNumbers = /* @__PURE__ */ new Set();
54
+ for (const rawLine of lines) {
55
+ const line = rawLine.trim();
56
+ if (!line) continue;
57
+ const m = ITEM_RE.exec(line);
58
+ if (!m) break;
59
+ const numPart = m[1];
60
+ const text = m[2].trim();
61
+ const hasAuto = !!m[3];
62
+ let index;
63
+ if (numPart !== void 0) {
64
+ index = Number.parseInt(numPart, 10);
65
+ } else {
66
+ index = steps.length + 1;
67
+ }
68
+ if (seenNumbers.has(index)) continue;
69
+ seenNumbers.add(index);
70
+ pushStep(steps, index, text, hasAuto);
71
+ if (steps.length >= MAX_STEPS) break;
72
+ }
73
+ if (steps.length === 0) {
74
+ return { steps: [], texts: [], stripped: content, autoTexts: [] };
75
+ }
76
+ if (!afterHeading.includes("</nextsteps>")) {
77
+ return { steps: [], texts: [], stripped: content, autoTexts: [] };
78
+ }
79
+ const texts = steps.map((s) => s.text);
80
+ const autoTexts = steps.filter((s) => s.auto).map((s) => s.text);
81
+ const blockStart = headingMatch.index;
82
+ const blockEnd = headingMatch[0].length + findBlockEnd(afterHeading, steps.length);
83
+ const stripped = (content.slice(0, blockStart) + content.slice(blockStart + blockEnd)).replace(/\n{3,}/g, "\n\n").trim();
84
+ return { steps, texts, stripped, autoTexts };
85
+ }
86
+ function findBlockEnd(afterHeading, stepCount) {
87
+ const closeIdx = afterHeading.indexOf("</nextsteps>");
88
+ if (closeIdx !== -1) {
89
+ let end = closeIdx + "</nextsteps>".length;
90
+ if (afterHeading[end] === "\n") end += 1;
91
+ return end;
92
+ }
93
+ const lines = afterHeading.split("\n");
94
+ let consumed = 0;
95
+ let found = 0;
96
+ for (const rawLine of lines) {
97
+ const line = rawLine.trim();
98
+ if (!line) break;
99
+ const m = ITEM_RE.exec(line);
100
+ if (!m) break;
101
+ consumed += rawLine.length + 1;
102
+ found++;
103
+ if (found >= stepCount) {
104
+ consumed -= 1;
105
+ break;
106
+ }
107
+ }
108
+ return consumed;
109
+ }
110
+ function stripNextStepsBlock(text) {
111
+ return text.replace(/<next_?steps\b[^>]*>[\s\S]*?<\/next_?steps>/gi, "").replace(/<next_?steps\b[^>]*\/?>/gi, "").replace(/\n{3,}/g, "\n\n").trim();
112
+ }
113
+
114
+ export { parseNextSteps, stripNextStepsBlock };
115
+ //# sourceMappingURL=next-steps.js.map
116
+ //# sourceMappingURL=next-steps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/next-steps.ts"],"names":[],"mappings":";AAoDA,IAAM,iBAAA,GAAoB,oBAAA;AAI1B,IAAM,OAAA,GAAU,mDAAA;AAEhB,IAAM,SAAA,GAAY,CAAA;AAaX,SAAS,cAAA,CACd,OAAA,EACA,MAAA,GAAS,KAAA,EACT,iBAAiB,IAAA,EACK;AACtB,EAAA,IAAI,cAAA,EAAgB;AAClB,IAAA,OAAO,gBAAA,CAAiB,OAAe,CAAA;AAAA,EACzC;AACA,EAAA,OAAO,iBAAiB,OAAO,CAAA;AACjC;AAGA,SAAS,QAAA,CACP,KAAA,EACA,KAAA,EACA,IAAA,EACA,OAAA,EACM;AACN,EAAA,KAAA,CAAM,IAAA,CAAK,OAAA,GAAU,EAAE,KAAA,EAAO,IAAA,EAAM,IAAA,EAAM,IAAA,EAAK,GAAI,EAAE,KAAA,EAAO,IAAA,EAAM,CAA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OAAA,CAAQ,SAAA,EAAW,MAAM,EACzB,IAAA,EAAK;AACV","file":"next-steps.js","sourcesContent":["/**\n * Canonical `<nextsteps>` block parser — the single source of truth shared by\n * the TUI history renderer, the CLI REPL suggestion store, the CLI /suggest\n * subagent output, and the WebUI MessageBubble/NextStepsBar.\n *\n * Three code paths feed into the parser:\n * 1. TUI rendering — entry.tsx parses only \"<nextsteps>\" from assistant output\n * 2. REPL store — repl.ts parses only \"<nextsteps>\" from final agent output\n * 3. /suggest output — suggest.ts parses LLM-generated numbered lists (raw mode)\n *\n * Heading mode (`requireHeading = true`, the default):\n * Assistant-output paths accept only balanced <nextsteps>...</nextsteps> blocks.\n * Loose headings like \"Next steps:\" are intentionally ignored so `/next` only\n * activates for the canonical machine-readable format.\n *\n * Raw mode (`requireHeading = false`):\n * Parses numbered/bullet items from anywhere in text (subagent /suggest output).\n *\n * Supported assistant-output format:\n * <nextsteps> (canonical XML tag format)\n *\n * This module is BROWSER-SAFE — no Node-only imports — so it is safe to import\n * from Vite-bundled WebUI as well as Node-based CLI/TUI. Mirrors the proven\n * `tool-summary` / `tool-icons` extraction pattern (PRs #236 / #237 / #238).\n */\n\n// ── Types ─────────────────────────────────────────────────────────────────\n\nexport interface ParsedNextStep {\n index: number;\n text: string;\n /** Whether this item has auto=\"true\" attribute for YOLO+auto autonomy mode. */\n auto?: boolean;\n}\n\nexport interface ParseNextStepsResult {\n /** Matched steps with their original index and stripped text. */\n steps: ParsedNextStep[];\n /** Flat string array — what gets stored in the suggestion store. */\n texts: string[];\n /**\n * Content with the entire canonical \"<nextsteps>\" block removed.\n * Used by entry.tsx to strip suggestions from the rendered message body.\n */\n stripped: string;\n /** Flat string array — texts of items with auto=\"true\" attribute only. */\n autoTexts: string[];\n}\n\n// ── Patterns ───────────────────────────────────────────────────────────────\n\n/** Matches the canonical <nextsteps> tag before numbered items. */\nconst NEXT_STEPS_TAG_RE = /<nextsteps>\\s*\\n+/i;\n\n/** Matches an item line: \"1. text\", \"1) text\", \"- text\", \"* text\". */\n/** Also captures optional auto=\"true\" attribute at the end. */\nconst ITEM_RE = /^(?:(\\d+)[.)]\\s*|[-*•]\\s*)(.+?)(\\s+auto=\"true\")?$/;\n\nconst MAX_STEPS = 6;\n\n// ── Core parser ─────────────────────────────────────────────────────────────\n\n/**\n * Parse canonical \"<nextsteps>\" blocks from assistant output (or raw numbered lines).\n *\n * @param content — raw assistant message text or subagent output\n * @param strict — retained for compatibility; assistant-output paths always require the canonical XML tag.\n * @param requireHeading — when true, a canonical XML tag must precede the item list.\n * when false, numbered/bullet items are parsed from anywhere in text\n * (used by /suggest subagent output which has no heading).\n */\nexport function parseNextSteps(\n content: string,\n strict = false,\n requireHeading = true,\n): ParseNextStepsResult {\n if (requireHeading) {\n return parseWithHeading(content, strict);\n }\n return parseRawNumbered(content);\n}\n\n/** Push a step into the array, omitting `auto` when false (cleaner shape, matches WebUI parity). */\nfunction pushStep(\n steps: ParsedNextStep[],\n index: number,\n text: string,\n hasAuto: boolean,\n): void {\n steps.push(hasAuto ? { index, text, auto: true } : { index, text });\n}\n\n/** Parse numbered/bullet items from raw text without a heading. */\nfunction parseRawNumbered(content: string): ParseNextStepsResult {\n const lines = content.split('\\n');\n const steps: ParsedNextStep[] = [];\n const seenNumbers = new Set<number>();\n\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line) continue;\n\n const m = ITEM_RE.exec(line);\n if (!m) continue; // skip non-item lines in raw mode\n\n const numPart = m[1];\n const text = m[2]!.trim();\n const hasAuto = !!m[3]; // auto=\"true\" captured in group 3\n let index: number;\n\n if (numPart !== undefined) {\n index = Number.parseInt(numPart, 10);\n } else {\n index = steps.length + 1; // bullet items get sequential indices\n }\n\n if (seenNumbers.has(index)) continue;\n seenNumbers.add(index);\n pushStep(steps, index, text, hasAuto);\n\n if (steps.length >= MAX_STEPS) break;\n }\n\n return {\n steps,\n texts: steps.map((s) => s.text),\n stripped: content,\n autoTexts: steps.filter((s) => s.auto).map((s) => s.text),\n };\n}\n\n/** Parse a heading + item block (the main assistant-message path). */\nfunction parseWithHeading(content: string, _strict: boolean): ParseNextStepsResult {\n const headingMatch = NEXT_STEPS_TAG_RE.exec(content);\n\n if (!headingMatch) {\n return { steps: [], texts: [], stripped: content, autoTexts: [] };\n }\n\n const headingEnd = headingMatch.index + headingMatch[0]!.length;\n const afterHeading = content.slice(headingEnd);\n const lines = afterHeading.split('\\n');\n const steps: ParsedNextStep[] = [];\n const seenNumbers = new Set<number>();\n\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line) continue;\n\n const m = ITEM_RE.exec(line);\n if (!m) break; // non-item line — block ends\n\n const numPart = m[1];\n const text = m[2]!.trim();\n const hasAuto = !!m[3]; // auto=\"true\" captured in group 3\n let index: number;\n\n if (numPart !== undefined) {\n index = Number.parseInt(numPart, 10);\n } else {\n index = steps.length + 1;\n }\n\n if (seenNumbers.has(index)) continue;\n seenNumbers.add(index);\n pushStep(steps, index, text, hasAuto);\n\n if (steps.length >= MAX_STEPS) break;\n }\n\n if (steps.length === 0) {\n return { steps: [], texts: [], stripped: content, autoTexts: [] };\n }\n\n // Require a closing tag. Malformed XML is rejected so raw text remains\n // visible instead of being partially consumed as automation input.\n if (!afterHeading.includes('</nextsteps>')) {\n return { steps: [], texts: [], stripped: content, autoTexts: [] };\n }\n\n const texts = steps.map((s) => s.text);\n const autoTexts = steps.filter((s) => s.auto).map((s) => s.text);\n\n // Strip the entire XML block from the content. `blockEnd` is the LENGTH of\n // that block, so `content.slice(blockStart + blockEnd)` is the rest of the content.\n const blockStart = headingMatch.index;\n const blockEnd = headingMatch[0]!.length + findBlockEnd(afterHeading, steps.length);\n const stripped =\n (content.slice(0, blockStart) + content.slice(blockStart + blockEnd))\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n\n return { steps, texts, stripped, autoTexts };\n}\n\n/**\n * Find the byte offset in `afterHeading` where the block ends.\n *\n * The block to strip is the items (one per line) plus the `</nextsteps>`\n * closing tag (and the trailing newline after it).\n *\n * Returns the byte offset of the first character AFTER the block. The\n * caller's `content.slice(0, blockStart) + content.slice(blockStart + offset)`\n * then produces the stripped content.\n *\n * Walks line-by-line. Stops at the first non-item line, the closing XML\n * tag, or the end of the input — whichever comes first.\n */\nfunction findBlockEnd(afterHeading: string, stepCount: number): number {\n // Fast path: if the block is the <nextsteps> XML form, find the closing\n // tag and return its end (consuming the tag + trailing newline).\n const closeIdx = afterHeading.indexOf('</nextsteps>');\n if (closeIdx !== -1) {\n let end = closeIdx + '</nextsteps>'.length;\n if (afterHeading[end] === '\\n') end += 1;\n return end;\n }\n\n // Defensive fallback for malformed input that reached this helper without a\n // closing tag. The caller rejects such input before using the stripped text.\n const lines = afterHeading.split('\\n');\n let consumed = 0;\n let found = 0;\n\n for (const rawLine of lines) {\n const line = rawLine.trim();\n if (!line) break; // blank line ends the block\n\n const m = ITEM_RE.exec(line);\n if (!m) break; // non-item line ends the block\n\n consumed += rawLine.length + 1; // +1 for the \\n separator\n found++;\n if (found >= stepCount) {\n // Don't include the trailing newline of the last item — the slice\n // logic in the caller handles whitespace cleanup.\n consumed -= 1;\n break;\n }\n }\n\n return consumed;\n}\n\n/**\n * Strip <nextsteps>...</nextsteps> blocks from subagent output text.\n * Subagent results should not contain suggestion blocks — those belong to\n * the main assistant's output. This prevents raw XML tags from appearing\n * as literal text in the fleet panel.\n *\n * Also strips the legacy `<next_steps>` spelling that older persisted\n * subagent output may contain (WebUI parity).\n */\nexport function stripNextStepsBlock(text: string): string {\n return text\n .replace(/<next_?steps\\b[^>]*>[\\s\\S]*?<\\/next_?steps>/gi, '')\n .replace(/<next_?steps\\b[^>]*\\/?>/gi, '')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/_util.ts","../src/_win32-resolve.ts","../src/outdated.ts"],"names":["path2","resolve"],"mappings":";;;;;;;AAaA,eAAsB,qBAAqB,GAAA,EAAsC;AAC/E,EAAA,MAAM,EAAE,IAAA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QACZ,IAAA;AAAA,QACA,OAAA,EAAS,KAAK,OAAA,IAAW,SAAA;AAAA,QACzB,MAAA,EAAQ,KAAK,MAAA,IAAU,SAAA;AAAA,QACvB,MAAA,EAAQ,KAAK,MAAA,IAAU,SAAA;AAAA,QACvB,IAAA,EAAM,KAAK,IAAA,IAAQ,SAAA;AAAA,QACnB,QAAA,EAAU,KAAK,QAAA,IAAY;AAAA,OAC5B,CAAA;AAAA,IACH;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,QAAA;AAAA,IACX,QAAA;AAAA,IACA,OAAO,QAAA,CAAS,MAAA;AAAA,IAChB,MAAA,EAAQ,IAAA;AAAA,IACR,SAAA,EAAW,KAAK,MAAA,IAAU;AAAA,GAC5B;AACF","file":"outdated.js","sourcesContent":["import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * On Windows, Node.js `spawn()` without a shell does NOT resolve .cmd/.bat\n * extensions through PATHEXT — it only auto-resolves .exe. Most Node.js CLI\n * tools (npx, pnpm, biome, tsc, vitest, etc.) ship as .cmd wrappers on\n * Windows. This function resolves the command name to its full path so spawn\n * can find it without relying on shell-mode argument concatenation.\n *\n * On non-Windows, returns the command unchanged.\n */\nexport function resolveWin32Command(cmd: string): string {\n if (process.platform !== 'win32') return cmd;\n\n // Already has a path or extension — use as-is\n // Normalize forward slashes so path.extname correctly detects extensions\n // even when a Unix-style path is passed on Windows.\n if (cmd.includes('/') || cmd.includes('\\\\') || path.extname(cmd.replace(/\\//g, '\\\\'))) {\n return cmd;\n }\n\n const pathext = (process.env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC')\n .toLowerCase()\n .split(';');\n\n const pathDirs = (process.env['PATH'] ?? '').split(path.delimiter);\n\n for (const dir of pathDirs) {\n const base = path.join(dir, cmd);\n // Check extensions in PATHEXT order. .EXE should win first because\n // it's typically listed first, and .exe doesn't need shell: true.\n for (const ext of pathext) {\n const full = `${base}${ext}`;\n try {\n fs.accessSync(full, fs.constants.X_OK);\n return full;\n } catch {\n // Not found with this extension — try next\n }\n }\n }\n\n // Not found — return original; let spawn report ENOENT with the\n // expected error message so tools can surface it properly.\n return cmd;\n}\n\n/**\n * Resolve a PowerShell binary by name. `pickShell` in `_shell-pick.ts`\n * already decides whether the user wants `'pwsh'` (PowerShell 7+) or\n * `'powershell'` (Windows PowerShell 5.1). This helper turns that decision\n * into a real on-disk path.\n *\n * Order:\n * 1. If `cmd` is `pwsh` and a `pwsh.exe` exists on PATH → return that.\n * 2. If `cmd` is `pwsh` and only `powershell.exe` exists → fall back to\n * that (the alternative is a cryptic ENOENT for the user).\n * 3. Symmetric for `powershell`: prefer `powershell.exe`, fall back to\n * `pwsh.exe` if installed and the legacy binary is missing.\n * 4. Anything else → delegate to `resolveWin32Command` (handles `.cmd`\n * shims a sysadmin might drop in place, etc.).\n *\n * Returns the original command on ENOENT — `spawn()` will surface a clean\n * ENOENT and the user sees \"PowerShell not installed\", which is the right\n * diagnostic. We never throw from here.\n */\nexport function resolvePowerShell(cmd: string): string {\n if (process.platform !== 'win32') return cmd;\n const lower = cmd.toLowerCase();\n if (lower !== 'pwsh' && lower !== 'powershell' && lower !== 'pwsh.exe' && lower !== 'powershell.exe') {\n return resolveWin32Command(cmd);\n }\n // Prefer the requested edition, fall back to the other one.\n const primary = lower.startsWith('pwsh') ? 'pwsh.exe' : 'powershell.exe';\n const fallback = lower.startsWith('pwsh') ? 'powershell.exe' : 'pwsh.exe';\n const resolved = resolveWin32Command(primary);\n if (resolved !== primary) {\n // resolveWin32Command returns the original string when not found.\n const fb = resolveWin32Command(fallback);\n return fb === fallback ? cmd : fb;\n }\n return resolved;\n}\n\n/**\n * cmd.exe metacharacters that chain a new command or redirect I/O. When a\n * `.cmd`/`.bat` wrapper is launched through `cmd.exe`, any argument carrying\n * one of these can break out of the intended command line and run an\n * attacker-chosen command (the CVE-2024-27980 / \"BatBadBut\" argument-injection\n * class). We use a single vetted command line for cmd shims, so this guard is\n * mandatory before spawning.\n *\n * The set is limited to the unambiguous command-separator / redirection chars\n * plus newlines and NUL. Legitimate package-manager / test-runner flags and\n * Windows file paths (which use `:` `\\` `/` `.` `-` `_` space `(` `)`) never\n * contain these, so the guard is false-positive-free. Double quotes are also\n * rejected because cmd.exe quote toggling can break argument grouping.\n */\nconst WIN32_SHELL_META = /[&|<>\"\\r\\n\\0]/;\n\nexport interface Win32CmdShimInvocation {\n command: string;\n args: string[];\n windowsVerbatimArguments: true;\n}\n\n/**\n * Throw if any argument contains a cmd.exe command-injection metacharacter.\n * Call this ONLY on the Windows `.cmd`/`.bat` shim path. A no-op for safe args.\n */\nexport function assertSafeWin32ShellArgs(args: readonly unknown[]): void {\n for (const arg of args) {\n if (typeof arg === 'string' && WIN32_SHELL_META.test(arg)) {\n throw new Error(\n 'win32 cmd shim spawn: argument contains a shell metacharacter ' +\n '(one of & | < > \", or a newline) that could enable command injection ' +\n 'through the .cmd/.bat wrapper - refusing to run. Offending argument: ' +\n JSON.stringify(arg),\n );\n }\n }\n}\n\nexport function buildWin32CmdShimInvocation(\n command: string,\n args: readonly string[] = [],\n): Win32CmdShimInvocation {\n assertSafeWin32ShellArgs([command, ...args]);\n const line = ['call', quoteWin32CmdArg(command), ...args.map(quoteWin32CmdArg)].join(' ');\n return {\n command: process.env['COMSPEC'] ?? 'cmd.exe',\n args: ['/d', '/c', line],\n windowsVerbatimArguments: true,\n };\n}\n\nfunction quoteWin32CmdArg(arg: string): string {\n return `\"${arg}\"`;\n}\n","import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { detectPackageManager, safeResolve } from './_util.js';\nimport {\n buildWin32CmdShimInvocation,\n resolveWin32Command,\n} from './_win32-resolve.js';\n\ninterface OutdatedInput {\n cwd?: string | undefined;\n format?: 'list' | 'table' | undefined;\n include_deprecated?: boolean | undefined;\n check?: string | string[] | undefined;\n}\n\ninterface OutdatedPackage {\n name: string;\n current: string;\n latest: string;\n wanted: string;\n type: string;\n location: string;\n}\n\ninterface OutdatedOutput {\n exit_code: number;\n packages: OutdatedPackage[];\n total: number;\n output: string;\n truncated: boolean;\n}\n\nexport const outdatedTool: Tool<OutdatedInput, OutdatedOutput> = {\n name: 'outdated',\n category: 'Package Management',\n description:\n 'Check for outdated dependencies in the project. Reports current, wanted (semver range), and latest versions available.',\n usageHint:\n 'MAINTENANCE & SECURITY TOOL:\\n\\n' +\n '- Run periodically or before dependency-related work.\\n' +\n '- Helps surface packages that may need updates for security or features.\\n' +\n '- Hits the package registry over HTTP, so it is NOT purely local — flagged as mutating for the confirmation gate.\\n' +\n 'Use the output to decide on upgrades. Prefer this over manual shell commands for dependency hygiene.',\n permission: 'confirm',\n icon: 'package',\n // Network side-effecting (registry HTTP). Pairs with `mutating: true`\n // so the H7 invariant test (`no auto-permission tool declares\n // mutating: true`) passes — a tool claiming `'auto'` must be purely\n // read-only, but `outdated` makes outbound HTTP calls to the\n // registry. The 'confirm' permission routes the call through the\n // tool.confirm_needed flow on every invocation. M-1 originally\n // fixed four sibling tools (mcp_control, shellcheck, shellcheck (scan mode),\n // search) but missed this one; applying the same contract here.\n mutating: true,\n // Capability is outbound network — the tool only hits the package\n // registry over HTTP, never touches the filesystem or runs shell.\n // Use the canonical `net.outbound` capability (not the non-existent\n // `network` string) so the subagent allowlist recognises it and\n // permits read-only registry lookups under a director.\n // The H7 invariant test requires this array to be non-empty for\n // any mutating:true tool (meta-tools whitelisted). See\n // tests/permission-mutating-invariant.test.ts:92.\n capabilities: ['net.outbound'],\n timeoutMs: 60_000,\n inputSchema: {\n type: 'object',\n properties: {\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n format: {\n type: 'string',\n enum: ['list', 'table'],\n description: 'Output format (default: list)',\n },\n include_deprecated: {\n type: 'boolean',\n description: 'Include deprecated packages (default: false)',\n },\n check: {\n type: 'string',\n description: 'Specific package(s) to check (comma-separated)',\n },\n },\n },\n async execute(input, ctx, opts) {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const manager = await detectPackageManager(cwd);\n\n const args: string[] = ['outdated', '--json'];\n if (input.format === 'table') args.push('--table');\n if (input.include_deprecated) args.push('--include', 'deprecated');\n\n return runOutdated(manager, args, cwd, opts.signal);\n },\n};\n\nfunction runOutdated(\n manager: string,\n args: string[],\n cwd: string,\n signal: AbortSignal,\n): Promise<OutdatedOutput> {\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n const MAX = 100_000;\n\n const resolved = resolveWin32Command(manager);\n const needsShell = process.platform === 'win32' && (resolved.endsWith('.cmd') || resolved.endsWith('.bat'));\n const shim = needsShell ? buildWin32CmdShimInvocation(resolved, args) : null;\n const spawnCmd = shim?.command ?? resolved;\n const spawnArgs = shim?.args ?? args;\n const child = spawn(spawnCmd, spawnArgs, { cwd, signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, ...(shim ? { windowsVerbatimArguments: shim.windowsVerbatimArguments } : {}) });\n child.stdout?.on('data', (c) => {\n if (stdout.length < MAX) stdout += c.toString();\n });\n child.stderr?.on('data', (c) => {\n if (stderr.length < MAX) stderr += c.toString();\n });\n child.on('close', (code) => {\n const result = parseOutdatedOutput(stdout, code ?? 0);\n resolve(result);\n });\n child.on('error', (e) => {\n resolve({\n exit_code: 1,\n packages: [],\n total: 0,\n output: e.message,\n truncated: false,\n });\n });\n });\n}\n\nfunction parseOutdatedOutput(json: string, exitCode: number): OutdatedOutput {\n const packages: OutdatedPackage[] = [];\n\n if (!json) {\n return {\n exit_code: exitCode,\n packages: [],\n total: 0,\n output: exitCode === 0 ? 'All packages up to date' : 'Could not check outdated packages',\n truncated: false,\n };\n }\n\n try {\n const data = JSON.parse(json);\n for (const name of Object.keys(data)) {\n const info = data[name];\n packages.push({\n name,\n current: info.current ?? 'unknown',\n latest: info.latest ?? 'unknown',\n wanted: info.wanted ?? 'unknown',\n type: info.type ?? 'unknown',\n location: info.location ?? name,\n });\n }\n } catch {\n // JSON parse failed, return raw output\n }\n\n return {\n exit_code: exitCode,\n packages,\n total: packages.length,\n output: json,\n truncated: json.length >= 100_000,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/_util.ts","../src/_win32-resolve.ts","../src/outdated.ts"],"names":["path2","resolve"],"mappings":";;;;;;;AAuBA,eAAsB,qBAAqB,GAAA,EAAsC;AAC/E,EAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,OAAO,kBAAkB,CAAA;AAChD,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,CAAK,CAAA,EAAG,GAAG,CAAA,eAAA,CAAiB,CAAA;AAClC,IAAA,OAAO,MAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,CAAK,CAAA,EAAG,GAAG,CAAA,UAAA,CAAY,CAAA;AAC7B,IAAA,OAAO,MAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AAAA,EAER;AACA,EAAA,OAAO,KAAA;AACT;AAEO,SAAS,WAAA,CAAY,OAAe,GAAA,EAAsB;AAC/D,EAAA,OAAY,IAAA,CAAA,UAAA,CAAW,KAAK,CAAA,GAAS,IAAA,CAAA,SAAA,CAAU,KAAK,CAAA,GAAS,IAAA,CAAA,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACvG;AAOA,SAAS,aAAa,GAAA,EAAwB;AAC5C,E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A,SAAS,mBAAA,CAAoB,MAAc,QAAA,EAAkC;AAC3E,EAAA,MAAM,WAA8B,EAAC;AAErC,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,OAAO;AAAA,MACL,SAAA,EAAW,QAAA;AAAA,MACX,UAAU,EAAC;AAAA,MACX,KAAA,EAAO,CAAA;AAAA,MACP,MAAA,EAAQ,QAAA,KAAa,CAAA,GAAI,yBAAA,GAA4B,mCAAA;AAAA,MACrD,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC5B,IAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,IAAA,CAAK,IAAI,CAAA,EAAG;AACpC,MAAA,MAAM,IAAA,GAAO,KAAK,IAAI,CAAA;AACtB,MAAA,QAAA,CAAS,IAAA,CAAK;AAAA,QACZ,IAAA;AAAA,QACA,OAAA,EAAS,KAAK,OAAA,IAAW,SAAA;AAAA,QACzB,MAAA,EAAQ,KAAK,MAAA,IAAU,SAAA;AAAA,QACvB,MAAA,EAAQ,KAAK,MAAA,IAAU,SAAA;AAAA,QACvB,IAAA,EAAM,KAAK,IAAA,IAAQ,SAAA;AAAA,QACnB,QAAA,EAAU,KAAK,QAAA,IAAY;AAAA,OAC5B,CAAA;AAAA,IACH;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,QAAA;AAAA,IACX,QAAA;AAAA,IACA,OAAO,QAAA,CAAS,MAAA;AAAA,IAChB,MAAA,EAAQ,IAAA;AAAA,IACR,SAAA,EAAW,KAAK,MAAA,IAAU;AAAA,GAC5B;AACF","file":"outdated.js","sourcesContent":["import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` — the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * On Windows, Node.js `spawn()` without a shell does NOT resolve .cmd/.bat\n * extensions through PATHEXT — it only auto-resolves .exe. Most Node.js CLI\n * tools (npx, pnpm, biome, tsc, vitest, etc.) ship as .cmd wrappers on\n * Windows. This function resolves the command name to its full path so spawn\n * can find it without relying on shell-mode argument concatenation.\n *\n * On non-Windows, returns the command unchanged.\n */\nexport function resolveWin32Command(cmd: string): string {\n if (process.platform !== 'win32') return cmd;\n\n // Already has a path or extension — use as-is\n // Normalize forward slashes so path.extname correctly detects extensions\n // even when a Unix-style path is passed on Windows.\n if (cmd.includes('/') || cmd.includes('\\\\') || path.extname(cmd.replace(/\\//g, '\\\\'))) {\n return cmd;\n }\n\n const pathext = (process.env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC')\n .toLowerCase()\n .split(';');\n\n const pathDirs = (process.env['PATH'] ?? '').split(path.delimiter);\n\n for (const dir of pathDirs) {\n const base = path.join(dir, cmd);\n // Check extensions in PATHEXT order. .EXE should win first because\n // it's typically listed first, and .exe doesn't need shell: true.\n for (const ext of pathext) {\n const full = `${base}${ext}`;\n try {\n fs.accessSync(full, fs.constants.X_OK);\n return full;\n } catch {\n // Not found with this extension — try next\n }\n }\n }\n\n // Not found — return original; let spawn report ENOENT with the\n // expected error message so tools can surface it properly.\n return cmd;\n}\n\n/**\n * Resolve a PowerShell binary by name. `pickShell` in `_shell-pick.ts`\n * already decides whether the user wants `'pwsh'` (PowerShell 7+) or\n * `'powershell'` (Windows PowerShell 5.1). This helper turns that decision\n * into a real on-disk path.\n *\n * Order:\n * 1. If `cmd` is `pwsh` and a `pwsh.exe` exists on PATH → return that.\n * 2. If `cmd` is `pwsh` and only `powershell.exe` exists → fall back to\n * that (the alternative is a cryptic ENOENT for the user).\n * 3. Symmetric for `powershell`: prefer `powershell.exe`, fall back to\n * `pwsh.exe` if installed and the legacy binary is missing.\n * 4. Anything else → delegate to `resolveWin32Command` (handles `.cmd`\n * shims a sysadmin might drop in place, etc.).\n *\n * Returns the original command on ENOENT — `spawn()` will surface a clean\n * ENOENT and the user sees \"PowerShell not installed\", which is the right\n * diagnostic. We never throw from here.\n */\nexport function resolvePowerShell(cmd: string): string {\n if (process.platform !== 'win32') return cmd;\n const lower = cmd.toLowerCase();\n if (lower !== 'pwsh' && lower !== 'powershell' && lower !== 'pwsh.exe' && lower !== 'powershell.exe') {\n return resolveWin32Command(cmd);\n }\n // Prefer the requested edition, fall back to the other one.\n const primary = lower.startsWith('pwsh') ? 'pwsh.exe' : 'powershell.exe';\n const fallback = lower.startsWith('pwsh') ? 'powershell.exe' : 'pwsh.exe';\n const resolved = resolveWin32Command(primary);\n if (resolved !== primary) {\n // resolveWin32Command returns the original string when not found.\n const fb = resolveWin32Command(fallback);\n return fb === fallback ? cmd : fb;\n }\n return resolved;\n}\n\n/**\n * cmd.exe metacharacters that chain a new command or redirect I/O. When a\n * `.cmd`/`.bat` wrapper is launched through `cmd.exe`, any argument carrying\n * one of these can break out of the intended command line and run an\n * attacker-chosen command (the CVE-2024-27980 / \"BatBadBut\" argument-injection\n * class). We use a single vetted command line for cmd shims, so this guard is\n * mandatory before spawning.\n *\n * The set is limited to the unambiguous command-separator / redirection chars\n * plus newlines and NUL. Legitimate package-manager / test-runner flags and\n * Windows file paths (which use `:` `\\` `/` `.` `-` `_` space `(` `)`) never\n * contain these, so the guard is false-positive-free. Double quotes are also\n * rejected because cmd.exe quote toggling can break argument grouping.\n */\nconst WIN32_SHELL_META = /[&|<>\"\\r\\n\\0]/;\n\nexport interface Win32CmdShimInvocation {\n command: string;\n args: string[];\n windowsVerbatimArguments: true;\n}\n\n/**\n * Throw if any argument contains a cmd.exe command-injection metacharacter.\n * Call this ONLY on the Windows `.cmd`/`.bat` shim path. A no-op for safe args.\n */\nexport function assertSafeWin32ShellArgs(args: readonly unknown[]): void {\n for (const arg of args) {\n if (typeof arg === 'string' && WIN32_SHELL_META.test(arg)) {\n throw new Error(\n 'win32 cmd shim spawn: argument contains a shell metacharacter ' +\n '(one of & | < > \", or a newline) that could enable command injection ' +\n 'through the .cmd/.bat wrapper - refusing to run. Offending argument: ' +\n JSON.stringify(arg),\n );\n }\n }\n}\n\nexport function buildWin32CmdShimInvocation(\n command: string,\n args: readonly string[] = [],\n): Win32CmdShimInvocation {\n assertSafeWin32ShellArgs([command, ...args]);\n const line = ['call', quoteWin32CmdArg(command), ...args.map(quoteWin32CmdArg)].join(' ');\n return {\n command: process.env['COMSPEC'] ?? 'cmd.exe',\n args: ['/d', '/c', line],\n windowsVerbatimArguments: true,\n };\n}\n\nfunction quoteWin32CmdArg(arg: string): string {\n return `\"${arg}\"`;\n}\n","import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { detectPackageManager, safeResolve } from './_util.js';\nimport {\n buildWin32CmdShimInvocation,\n resolveWin32Command,\n} from './_win32-resolve.js';\n\ninterface OutdatedInput {\n cwd?: string | undefined;\n format?: 'list' | 'table' | undefined;\n include_deprecated?: boolean | undefined;\n check?: string | string[] | undefined;\n}\n\ninterface OutdatedPackage {\n name: string;\n current: string;\n latest: string;\n wanted: string;\n type: string;\n location: string;\n}\n\ninterface OutdatedOutput {\n exit_code: number;\n packages: OutdatedPackage[];\n total: number;\n output: string;\n truncated: boolean;\n}\n\nexport const outdatedTool: Tool<OutdatedInput, OutdatedOutput> = {\n name: 'outdated',\n category: 'Package Management',\n description:\n 'Check for outdated dependencies in the project. Reports current, wanted (semver range), and latest versions available.',\n usageHint:\n 'MAINTENANCE & SECURITY TOOL:\\n\\n' +\n '- Run periodically or before dependency-related work.\\n' +\n '- Helps surface packages that may need updates for security or features.\\n' +\n '- Hits the package registry over HTTP, so it is NOT purely local — flagged as mutating for the confirmation gate.\\n' +\n 'Use the output to decide on upgrades. Prefer this over manual shell commands for dependency hygiene.',\n permission: 'confirm',\n icon: 'package',\n // Network side-effecting (registry HTTP). Pairs with `mutating: true`\n // so the H7 invariant test (`no auto-permission tool declares\n // mutating: true`) passes — a tool claiming `'auto'` must be purely\n // read-only, but `outdated` makes outbound HTTP calls to the\n // registry. The 'confirm' permission routes the call through the\n // tool.confirm_needed flow on every invocation. M-1 originally\n // fixed four sibling tools (mcp_control, shellcheck, shellcheck (scan mode),\n // search) but missed this one; applying the same contract here.\n mutating: true,\n // Capability is outbound network — the tool only hits the package\n // registry over HTTP, never touches the filesystem or runs shell.\n // Use the canonical `net.outbound` capability (not the non-existent\n // `network` string) so the subagent allowlist recognises it and\n // permits read-only registry lookups under a director.\n // The H7 invariant test requires this array to be non-empty for\n // any mutating:true tool (meta-tools whitelisted). See\n // tests/permission-mutating-invariant.test.ts:92.\n capabilities: ['net.outbound'],\n timeoutMs: 60_000,\n inputSchema: {\n type: 'object',\n properties: {\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n format: {\n type: 'string',\n enum: ['list', 'table'],\n description: 'Output format (default: list)',\n },\n include_deprecated: {\n type: 'boolean',\n description: 'Include deprecated packages (default: false)',\n },\n check: {\n type: 'string',\n description: 'Specific package(s) to check (comma-separated)',\n },\n },\n },\n async execute(input, ctx, opts) {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const manager = await detectPackageManager(cwd);\n\n const args: string[] = ['outdated', '--json'];\n if (input.format === 'table') args.push('--table');\n if (input.include_deprecated) args.push('--include', 'deprecated');\n\n return runOutdated(manager, args, cwd, opts.signal);\n },\n};\n\nfunction runOutdated(\n manager: string,\n args: string[],\n cwd: string,\n signal: AbortSignal,\n): Promise<OutdatedOutput> {\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n const MAX = 100_000;\n\n const resolved = resolveWin32Command(manager);\n const needsShell = process.platform === 'win32' && (resolved.endsWith('.cmd') || resolved.endsWith('.bat'));\n const shim = needsShell ? buildWin32CmdShimInvocation(resolved, args) : null;\n const spawnCmd = shim?.command ?? resolved;\n const spawnArgs = shim?.args ?? args;\n const child = spawn(spawnCmd, spawnArgs, { cwd, signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, ...(shim ? { windowsVerbatimArguments: shim.windowsVerbatimArguments } : {}) });\n child.stdout?.on('data', (c) => {\n if (stdout.length < MAX) stdout += c.toString();\n });\n child.stderr?.on('data', (c) => {\n if (stderr.length < MAX) stderr += c.toString();\n });\n child.on('close', (code) => {\n const result = parseOutdatedOutput(stdout, code ?? 0);\n resolve(result);\n });\n child.on('error', (e) => {\n resolve({\n exit_code: 1,\n packages: [],\n total: 0,\n output: e.message,\n truncated: false,\n });\n });\n });\n}\n\nfunction parseOutdatedOutput(json: string, exitCode: number): OutdatedOutput {\n const packages: OutdatedPackage[] = [];\n\n if (!json) {\n return {\n exit_code: exitCode,\n packages: [],\n total: 0,\n output: exitCode === 0 ? 'All packages up to date' : 'Could not check outdated packages',\n truncated: false,\n };\n }\n\n try {\n const data = JSON.parse(json);\n for (const name of Object.keys(data)) {\n const info = data[name];\n packages.push({\n name,\n current: info.current ?? 'unknown',\n latest: info.latest ?? 'unknown',\n wanted: info.wanted ?? 'unknown',\n type: info.type ?? 'unknown',\n location: info.location ?? name,\n });\n }\n } catch {\n // JSON parse failed, return raw output\n }\n\n return {\n exit_code: exitCode,\n packages,\n total: packages.length,\n output: json,\n truncated: json.length >= 100_000,\n };\n}\n"]}