@wrongstack/tools 0.155.0 → 0.236.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/audit.js +21 -1
  2. package/dist/audit.js.map +1 -1
  3. package/dist/bash.js +116 -24
  4. package/dist/bash.js.map +1 -1
  5. package/dist/builtin.js +673 -202
  6. package/dist/builtin.js.map +1 -1
  7. package/dist/circuit-breaker.d.ts +9 -2
  8. package/dist/circuit-breaker.js +11 -2
  9. package/dist/circuit-breaker.js.map +1 -1
  10. package/dist/codebase-index/index.js +19 -10
  11. package/dist/codebase-index/index.js.map +1 -1
  12. package/dist/diff.js +1 -1
  13. package/dist/diff.js.map +1 -1
  14. package/dist/document.js +1 -1
  15. package/dist/document.js.map +1 -1
  16. package/dist/edit.js +1 -1
  17. package/dist/edit.js.map +1 -1
  18. package/dist/exec.js +60 -11
  19. package/dist/exec.js.map +1 -1
  20. package/dist/fetch.js.map +1 -1
  21. package/dist/format.js +21 -1
  22. package/dist/format.js.map +1 -1
  23. package/dist/git.js.map +1 -1
  24. package/dist/glob.js +1 -1
  25. package/dist/glob.js.map +1 -1
  26. package/dist/grep.js +1 -1
  27. package/dist/grep.js.map +1 -1
  28. package/dist/index.d.ts +4 -3
  29. package/dist/index.js +680 -209
  30. package/dist/index.js.map +1 -1
  31. package/dist/install.js +65 -14
  32. package/dist/install.js.map +1 -1
  33. package/dist/lint.js +21 -1
  34. package/dist/lint.js.map +1 -1
  35. package/dist/logs.js +1 -1
  36. package/dist/logs.js.map +1 -1
  37. package/dist/outdated.js +1 -1
  38. package/dist/outdated.js.map +1 -1
  39. package/dist/pack.js +673 -202
  40. package/dist/pack.js.map +1 -1
  41. package/dist/patch.js +1 -1
  42. package/dist/patch.js.map +1 -1
  43. package/dist/process-registry.d.ts +21 -16
  44. package/dist/process-registry.js +48 -10
  45. package/dist/process-registry.js.map +1 -1
  46. package/dist/read.js +1 -1
  47. package/dist/read.js.map +1 -1
  48. package/dist/replace.js +1 -1
  49. package/dist/replace.js.map +1 -1
  50. package/dist/scaffold.js +1 -1
  51. package/dist/scaffold.js.map +1 -1
  52. package/dist/search.js +19 -16
  53. package/dist/search.js.map +1 -1
  54. package/dist/test.js +21 -1
  55. package/dist/test.js.map +1 -1
  56. package/dist/todo.js +44 -0
  57. package/dist/todo.js.map +1 -1
  58. package/dist/tree.js +1 -1
  59. package/dist/tree.js.map +1 -1
  60. package/dist/typecheck.js +21 -1
  61. package/dist/typecheck.js.map +1 -1
  62. package/dist/write.js +1 -1
  63. package/dist/write.js.map +1 -1
  64. package/package.json +5 -5
package/dist/test.js CHANGED
@@ -30,6 +30,7 @@ function resolveWin32Command(cmd) {
30
30
  async function* spawnStream(opts) {
31
31
  const max = opts.maxBytes;
32
32
  const flushAt = opts.flushBytes ?? 4 * 1024;
33
+ const maxQueue = opts.maxQueueSize ?? 500;
33
34
  let stdout = "";
34
35
  let stderr = "";
35
36
  let pending = "";
@@ -45,6 +46,7 @@ async function* spawnStream(opts) {
45
46
  });
46
47
  const queue = [];
47
48
  let waiter;
49
+ let paused = false;
48
50
  const wake = () => {
49
51
  if (waiter) {
50
52
  const w = waiter;
@@ -52,17 +54,34 @@ async function* spawnStream(opts) {
52
54
  w();
53
55
  }
54
56
  };
57
+ const resume = () => {
58
+ if (paused && queue.length < maxQueue) {
59
+ paused = false;
60
+ child.stdout?.resume();
61
+ child.stderr?.resume();
62
+ }
63
+ };
55
64
  child.stdout?.on("data", (c) => {
56
65
  const s = c.toString();
57
66
  if (stdout.length < max) stdout += s;
58
67
  queue.push({ kind: "out", data: s });
59
68
  wake();
69
+ if (!paused && queue.length >= maxQueue) {
70
+ paused = true;
71
+ child.stdout?.pause();
72
+ child.stderr?.pause();
73
+ }
60
74
  });
61
75
  child.stderr?.on("data", (c) => {
62
76
  const s = c.toString();
63
77
  if (stderr.length < max) stderr += s;
64
78
  queue.push({ kind: "err", data: s });
65
79
  wake();
80
+ if (!paused && queue.length >= maxQueue) {
81
+ paused = true;
82
+ child.stdout?.pause();
83
+ child.stderr?.pause();
84
+ }
66
85
  });
67
86
  child.on("error", (e) => {
68
87
  error = e.message;
@@ -82,6 +101,7 @@ async function* spawnStream(opts) {
82
101
  });
83
102
  }
84
103
  const chunk = queue.shift();
104
+ resume();
85
105
  if (chunk.kind === "close") {
86
106
  if (!spawnFailed) exitCode = chunk.code ?? 0;
87
107
  break;
@@ -109,7 +129,7 @@ async function* spawnStream(opts) {
109
129
  };
110
130
  }
111
131
  function resolvePath(input, ctx) {
112
- return path2.isAbsolute(input) ? path2.normalize(input) : path2.resolve(ctx.cwd, input);
132
+ return path2.isAbsolute(input) ? path2.normalize(input) : path2.resolve(ctx.workingDir ?? ctx.cwd, input);
113
133
  }
114
134
  function ensureInsideRoot(absPath, ctx) {
115
135
  const root = path2.resolve(ctx.projectRoot);
package/dist/test.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/_win32-resolve.ts","../src/_spawn-stream.ts","../src/_util.ts","../src/test.ts"],"names":["path","resolve","path3"],"mappings":";;;;;;;AAYO,SAAS,oBAAoB,GAAA,EAAqB;AACvD,EAAA,IAAI,OAAA,CAAQ,QAAA,KAAa,OAAA,EAAS,OAAO,GAAA;AAGzC,EAAA,IAAI,GAAA,CAAI,QAAA,CAAS,GAAG,CAAA,IAAK,GAAA,CAAI,SAAS,IAAI,CAAA,IAAUA,KAAA,CAAA,OAAA,CAAQ,GAAG,CAAA,EAAG;AAChE,IAAA,OAAO,GAAA;AAAA,EACT;AAEA,EAAA,MAAM,OAAA,GAAA,CAAW,QAAQ,GAAA,CAAI,SAAS,KAAK,uCAAA,EACxC,WAAA,EAAY,CACZ,KAAA,CAAM,GAAG,CAAA;AAEZ,EAAA,MAAM,YAAY,OAAA,CAAQ,GAAA,CAAI,MAAM,CAAA,IAAK,EAAA,EAAI,MAAWA,KAAA,CAAA,SAAS,CAAA;AAEjE,EAAA,KAAA,MAAW,OAAO,QAAA,EAAU;AAC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S,WAAA,GAAc,CAAC,CAAA,IAAK,KAAK,EAAE,CAAA;AAAA,EACtD;AAEA,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,WAAW,MAAA,CAAO,QAAA;AAAA,IAClB,SAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,WAAA,EAAa,QAAA;AAAA,IACb,QAAQ,sBAAA,CAAuB,MAAA,CAAO,MAAA,IAAU,MAAA,CAAO,SAAS,EAAE,CAAA;AAAA,IAClE,WAAW,MAAA,CAAO;AAAA,GACpB;AACF","file":"test.js","sourcesContent":["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 if (cmd.includes('/') || cmd.includes('\\\\') || path.extname(cmd)) {\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","import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { ToolProgressEvent } from '@wrongstack/core';\nimport { resolveWin32Command } from './_win32-resolve.js';\nexport interface SpawnStreamResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n truncated: boolean;\n error?: string | undefined;\n}\n\nexport interface SpawnStreamOptions {\n cmd: string;\n args: string[];\n cwd: string;\n signal: AbortSignal;\n maxBytes?: number | undefined;\n /** Bytes of new stdout/stderr to accumulate before yielding a `partial_output` event. */\n flushBytes?: number | undefined;\n}\n\n/**\n * Spawn a child process and yield `partial_output` progress events as\n * stdout/stderr arrive (batched by byte threshold), then return the full\n * buffered result. Shared between install/lint/format/typecheck/test/audit\n * so the TUI live tail sees consistent progress regardless of which tool\n * is running.\n */\nexport async function* spawnStream(\n opts: SpawnStreamOptions,\n): AsyncGenerator<ToolProgressEvent, SpawnStreamResult> {\n const max = opts.maxBytes ?? 200_000;\n const flushAt = opts.flushBytes ?? 4 * 1024;\n let stdout = '';\n let stderr = '';\n let pending = '';\n let error: string | undefined;\n\n const cmd = resolveWin32Command(opts.cmd);\n const needsShell = process.platform === 'win32' && (cmd.endsWith('.cmd') || cmd.endsWith('.bat'));\n\n const child = spawn(cmd, opts.args, {\n cwd: opts.cwd,\n signal: opts.signal,\n env: buildChildEnv(),\n stdio: ['ignore', 'pipe', 'pipe'],\n ...(needsShell ? { shell: true, windowsVerbatimArguments: true } : {}),\n });\n\n type Chunk = { kind: 'out' | 'err' | 'close' | 'error'; data: string; code?: number | undefined };\n const queue: Chunk[] = [];\n let waiter: (() => void) | undefined;\n const wake = () => {\n if (waiter) {\n const w = waiter;\n waiter = undefined;\n w();\n }\n };\n\n child.stdout?.on('data', (c) => {\n const s = c.toString();\n if (stdout.length < max) stdout += s;\n queue.push({ kind: 'out', data: s });\n wake();\n });\n child.stderr?.on('data', (c) => {\n const s = c.toString();\n if (stderr.length < max) stderr += s;\n queue.push({ kind: 'err', data: s });\n wake();\n });\n child.on('error', (e) => {\n error = e.message;\n queue.push({ kind: 'error', data: e.message });\n wake();\n });\n child.on('close', (code) => {\n queue.push({ kind: 'close', data: '', code: code ?? 0 });\n wake();\n });\n\n let exitCode = 0;\n let spawnFailed = false;\n for (;;) {\n while (queue.length === 0) {\n await new Promise<void>((resolve) => {\n waiter = resolve;\n });\n }\n const chunk = queue.shift()!;\n if (chunk.kind === 'close') {\n // If we already saw a spawn error (ENOENT etc.), keep exitCode=1\n // rather than the negative platform code Node fabricates.\n if (!spawnFailed) exitCode = chunk.code ?? 0;\n break;\n }\n if (chunk.kind === 'error') {\n spawnFailed = true;\n exitCode = 1;\n // close usually follows\n continue;\n }\n pending += chunk.data;\n if (pending.length >= flushAt) {\n yield { type: 'partial_output', text: pending };\n pending = '';\n }\n }\n if (pending.length > 0) {\n yield { type: 'partial_output', text: pending };\n }\n\n return {\n stdout,\n stderr,\n exitCode,\n truncated: stdout.length >= max || stderr.length >= max,\n error,\n };\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.cwd, input);\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\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 const realRoot = await fsp.realpath(ctx.projectRoot).catch(() => path.resolve(ctx.projectRoot));\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 const rel = path.relative(realRoot, real);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoot}\"`,\n );\n }\n return;\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 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 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 path from 'node:path';\nimport type { Tool, ToolStreamEvent } from '@wrongstack/core';\nimport { spawnStream } from './_spawn-stream.js';\nimport { normalizeCommandOutput, safeResolve } from './_util.js';\n\ninterface TestInput {\n files?: string | string[] | undefined;\n runner?: 'vitest' | 'jest' | 'mocha' | 'auto' | undefined;\n watch?: boolean | undefined;\n coverage?: boolean | undefined;\n cwd?: string | undefined;\n grep?: string | undefined;\n timeout?: number | undefined;\n}\n\ninterface TestOutput {\n runner: string;\n exit_code: number;\n tests_run: number;\n passed: number;\n failed: number;\n duration_ms: number;\n output: string;\n truncated: boolean;\n}\n\nexport const testTool: Tool<TestInput, TestOutput> = {\n name: 'test',\n category: 'Code Quality',\n description:\n 'Execute the project\\'s test suite. This is one of the most critical tools for validating that your changes are correct.',\n usageHint:\n 'ESSENTIAL BEFORE CONSIDERING WORK DONE:\\n\\n' +\n '- Use `files` or `grep` to run only relevant tests during development.\\n' +\n '- `coverage: true` is useful when working on critical paths.\\n' +\n 'Run tests frequently. A clean test run is usually required before the task can be considered complete.',\n permission: 'confirm',\n mutating: false,\n timeoutMs: 120_000,\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'string',\n description: 'Test files: single path, comma-separated list, or glob (e.g. \"**/*.test.ts\")',\n },\n runner: {\n type: 'string',\n enum: ['vitest', 'jest', 'mocha', 'auto'],\n description: 'Test runner (default: auto-detect)',\n },\n watch: { type: 'boolean', description: 'Run in watch mode (default: false)' },\n coverage: { type: 'boolean', description: 'Generate coverage report (default: false)' },\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n grep: { type: 'string', description: 'Filter tests by name pattern (default: none)' },\n timeout: { type: 'integer', description: 'Test timeout in ms (default: 30000)' },\n },\n },\n async execute(input, ctx, opts) {\n let final: TestOutput | undefined;\n const executeStream = testTool.executeStream;\n if (!executeStream) throw new Error('testTool: stream execution unavailable');\n for await (const ev of executeStream(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('test: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx, opts): AsyncGenerator<ToolStreamEvent<TestOutput>> {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const runner = input.runner ?? 'auto';\n\n const detected = runner === 'auto' ? await detectRunner(cwd) : runner;\n if (!detected) {\n yield {\n type: 'final',\n output: {\n runner: 'none',\n exit_code: 0,\n tests_run: 0,\n passed: 0,\n failed: 0,\n duration_ms: 0,\n output: 'No test runner found (vitest.config.ts, jest.config.js, .mocharc.json)',\n truncated: false,\n },\n };\n return;\n }\n\n yield { type: 'log', text: `Running ${detected}…`, data: { runner: detected } };\n\n const start = Date.now();\n const args = buildArgs(detected, input);\n\n const result = yield* spawnStream({\n cmd: detected,\n args,\n cwd,\n signal: opts.signal,\n maxBytes: 200_000,\n });\n const duration = Date.now() - start;\n\n yield { type: 'final', output: parseResult(detected, result, duration) };\n },\n};\n\nasync function detectRunner(cwd: string): Promise<string | null> {\n const { stat } = await import('node:fs/promises');\n const candidates = ['vitest.config.ts', 'jest.config.js', '.mocharc.json'];\n for (const f of candidates) {\n try {\n await stat(path.join(cwd, f));\n if (f.includes('vitest')) return 'vitest';\n if (f.includes('jest')) return 'jest';\n if (f.includes('mocha')) return 'mocha';\n } catch {\n // continue\n }\n }\n return null;\n}\n\nfunction buildArgs(runner: string, input: TestInput): string[] {\n const args: string[] = [];\n const timeout = input.timeout ?? 30000;\n\n switch (runner) {\n case 'vitest':\n args.push('run', '--reporter=verbose');\n if (input.watch) {\n args[1] = '';\n args.push('watch');\n }\n if (input.coverage) args.push('--coverage');\n if (input.grep) args.push('--testNamePattern', input.grep);\n args.push('--testTimeout', String(timeout));\n break;\n case 'jest':\n args.push('--verbose');\n if (input.watch) args.push('--watch');\n if (input.coverage) args.push('--coverage');\n if (input.grep) args.push('--testPathPattern', input.grep);\n args.push('--testTimeout', String(timeout));\n break;\n case 'mocha':\n args.push('--reporter', 'spec');\n if (input.grep) args.push('--grep', input.grep);\n args.push('--timeout', String(timeout));\n break;\n }\n\n if (input.files) {\n const files = Array.isArray(input.files) ? input.files : input.files.split(',');\n args.push('--', ...files.map((f) => f.trim()));\n }\n\n return args;\n}\n\nfunction parseResult(\n runner: string,\n result: { stdout: string; stderr: string; exitCode: number; truncated: boolean; error?: string | undefined },\n duration: number,\n): TestOutput {\n const out = result.stdout + result.stderr;\n\n let tests_run = 0;\n let passed = 0;\n let failed = 0;\n\n if (runner === 'vitest') {\n const passedMatch = out.match(/(\\d+) passed/);\n const failedMatch = out.match(/(\\d+) failed/);\n if (passedMatch?.[1]) passed = Number.parseInt(passedMatch[1], 10);\n if (failedMatch?.[1]) failed = Number.parseInt(failedMatch[1], 10);\n tests_run = passed + failed;\n } else if (runner === 'jest') {\n const suitesMatch = out.match(/Test Suites:\\s+(\\d+)\\s+total/);\n const passedMatch = out.match(/Tests:\\s+(\\d+)\\s+passed/);\n const failedMatch = out.match(/Tests:\\s+(\\d+)\\s+failed/);\n tests_run = Number.parseInt(suitesMatch?.[1] ?? '0', 10);\n passed = Number.parseInt(passedMatch?.[1] ?? '0', 10);\n failed = Number.parseInt(failedMatch?.[1] ?? '0', 10);\n }\n\n return {\n runner,\n exit_code: result.exitCode,\n tests_run,\n passed,\n failed,\n duration_ms: duration,\n output: normalizeCommandOutput(result.stdout || result.error || ''),\n truncated: result.truncated,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/_win32-resolve.ts","../src/_spawn-stream.ts","../src/_util.ts","../src/test.ts"],"names":["path","resolve","path3"],"mappings":";;;;;;;AAYO,SAAS,oBAAoB,GAAA,EAAqB;AACvD,EAAA,IAAI,OAAA,CAAQ,QAAA,KAAa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MAAA,GAAS,OAAO,QAAA,CAAS,WAAA,GAAc,CAAC,CAAA,IAAK,KAAK,EAAE,CAAA;AAAA,EACtD;AAEA,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,WAAW,MAAA,CAAO,QAAA;AAAA,IAClB,SAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,WAAA,EAAa,QAAA;AAAA,IACb,QAAQ,sBAAA,CAAuB,MAAA,CAAO,MAAA,IAAU,MAAA,CAAO,SAAS,EAAE,CAAA;AAAA,IAClE,WAAW,MAAA,CAAO;AAAA,GACpB;AACF","file":"test.js","sourcesContent":["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 if (cmd.includes('/') || cmd.includes('\\\\') || path.extname(cmd)) {\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","import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { ToolProgressEvent } from '@wrongstack/core';\nimport { resolveWin32Command } from './_win32-resolve.js';\nexport interface SpawnStreamResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n truncated: boolean;\n error?: string | undefined;\n}\n\nexport interface SpawnStreamOptions {\n cmd: string;\n args: string[];\n cwd: string;\n signal: AbortSignal;\n maxBytes?: number | undefined;\n /** Bytes of new stdout/stderr to accumulate before yielding a `partial_output` event. */\n flushBytes?: number | undefined;\n /** Maximum chunks to buffer before applying backpressure to the child. Default 500. */\n maxQueueSize?: number | undefined;\n}\n\n/**\n * Spawn a child process and yield `partial_output` progress events as\n * stdout/stderr arrive (batched by byte threshold), then return the full\n * buffered result. Shared between install/lint/format/typecheck/test/audit\n * so the TUI live tail sees consistent progress regardless of which tool\n * is running.\n */\nexport async function* spawnStream(\n opts: SpawnStreamOptions,\n): AsyncGenerator<ToolProgressEvent, SpawnStreamResult> {\n const max = opts.maxBytes ?? 200_000;\n const flushAt = opts.flushBytes ?? 4 * 1024;\n const maxQueue = opts.maxQueueSize ?? 500;\n let stdout = '';\n let stderr = '';\n let pending = '';\n let error: string | undefined;\n\n const cmd = resolveWin32Command(opts.cmd);\n const needsShell = process.platform === 'win32' && (cmd.endsWith('.cmd') || cmd.endsWith('.bat'));\n\n const child = spawn(cmd, opts.args, {\n cwd: opts.cwd,\n signal: opts.signal,\n env: buildChildEnv(),\n stdio: ['ignore', 'pipe', 'pipe'],\n ...(needsShell ? { shell: true, windowsVerbatimArguments: true } : {}),\n });\n\n type Chunk = { kind: 'out' | 'err' | 'close' | 'error'; data: string; code?: number | undefined };\n const queue: Chunk[] = [];\n let waiter: (() => void) | undefined;\n let paused = false;\n const wake = () => {\n if (waiter) {\n const w = waiter;\n waiter = undefined;\n w();\n }\n };\n\n // Resume the stream when there's room in the queue\n const resume = () => {\n if (paused && queue.length < maxQueue) {\n paused = false;\n child.stdout?.resume();\n child.stderr?.resume();\n }\n };\n\n // Note: chunks may still arrive briefly after pause() (already in flight) —\n // they are accumulated and queued rather than dropped, so the queue can\n // overshoot maxQueue by a few entries but no output is silently lost.\n child.stdout?.on('data', (c) => {\n const s = c.toString();\n if (stdout.length < max) stdout += s;\n queue.push({ kind: 'out', data: s });\n wake();\n // Apply backpressure if queue is growing faster than we consume\n if (!paused && queue.length >= maxQueue) {\n paused = true;\n child.stdout?.pause();\n child.stderr?.pause();\n }\n });\n child.stderr?.on('data', (c) => {\n const s = c.toString();\n if (stderr.length < max) stderr += s;\n queue.push({ kind: 'err', data: s });\n wake();\n if (!paused && queue.length >= maxQueue) {\n paused = true;\n child.stdout?.pause();\n child.stderr?.pause();\n }\n });\n child.on('error', (e) => {\n error = e.message;\n queue.push({ kind: 'error', data: e.message });\n wake();\n });\n child.on('close', (code) => {\n queue.push({ kind: 'close', data: '', code: code ?? 0 });\n wake();\n });\n\n let exitCode = 0;\n let spawnFailed = false;\n for (;;) {\n while (queue.length === 0) {\n await new Promise<void>((resolve) => {\n waiter = resolve;\n });\n }\n const chunk = queue.shift()!;\n // Resume reading after consuming a chunk\n resume();\n if (chunk.kind === 'close') {\n // If we already saw a spawn error (ENOENT etc.), keep exitCode=1\n // rather than the negative platform code Node fabricates.\n if (!spawnFailed) exitCode = chunk.code ?? 0;\n break;\n }\n if (chunk.kind === 'error') {\n spawnFailed = true;\n exitCode = 1;\n // close usually follows\n continue;\n }\n pending += chunk.data;\n if (pending.length >= flushAt) {\n yield { type: 'partial_output', text: pending };\n pending = '';\n }\n }\n if (pending.length > 0) {\n yield { type: 'partial_output', text: pending };\n }\n\n return {\n stdout,\n stderr,\n exitCode,\n truncated: stdout.length >= max || stderr.length >= max,\n error,\n };\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\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\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 const realRoot = await fsp.realpath(ctx.projectRoot).catch(() => path.resolve(ctx.projectRoot));\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 const rel = path.relative(realRoot, real);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoot}\"`,\n );\n }\n return;\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 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 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 path from 'node:path';\nimport type { Tool, ToolStreamEvent } from '@wrongstack/core';\nimport { spawnStream } from './_spawn-stream.js';\nimport { normalizeCommandOutput, safeResolve } from './_util.js';\n\ninterface TestInput {\n files?: string | string[] | undefined;\n runner?: 'vitest' | 'jest' | 'mocha' | 'auto' | undefined;\n watch?: boolean | undefined;\n coverage?: boolean | undefined;\n cwd?: string | undefined;\n grep?: string | undefined;\n timeout?: number | undefined;\n}\n\ninterface TestOutput {\n runner: string;\n exit_code: number;\n tests_run: number;\n passed: number;\n failed: number;\n duration_ms: number;\n output: string;\n truncated: boolean;\n}\n\nexport const testTool: Tool<TestInput, TestOutput> = {\n name: 'test',\n category: 'Code Quality',\n description:\n 'Execute the project\\'s test suite. This is one of the most critical tools for validating that your changes are correct.',\n usageHint:\n 'ESSENTIAL BEFORE CONSIDERING WORK DONE:\\n\\n' +\n '- Use `files` or `grep` to run only relevant tests during development.\\n' +\n '- `coverage: true` is useful when working on critical paths.\\n' +\n 'Run tests frequently. A clean test run is usually required before the task can be considered complete.',\n permission: 'confirm',\n mutating: false,\n timeoutMs: 120_000,\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'string',\n description: 'Test files: single path, comma-separated list, or glob (e.g. \"**/*.test.ts\")',\n },\n runner: {\n type: 'string',\n enum: ['vitest', 'jest', 'mocha', 'auto'],\n description: 'Test runner (default: auto-detect)',\n },\n watch: { type: 'boolean', description: 'Run in watch mode (default: false)' },\n coverage: { type: 'boolean', description: 'Generate coverage report (default: false)' },\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n grep: { type: 'string', description: 'Filter tests by name pattern (default: none)' },\n timeout: { type: 'integer', description: 'Test timeout in ms (default: 30000)' },\n },\n },\n async execute(input, ctx, opts) {\n let final: TestOutput | undefined;\n const executeStream = testTool.executeStream;\n if (!executeStream) throw new Error('testTool: stream execution unavailable');\n for await (const ev of executeStream(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('test: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx, opts): AsyncGenerator<ToolStreamEvent<TestOutput>> {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const runner = input.runner ?? 'auto';\n\n const detected = runner === 'auto' ? await detectRunner(cwd) : runner;\n if (!detected) {\n yield {\n type: 'final',\n output: {\n runner: 'none',\n exit_code: 0,\n tests_run: 0,\n passed: 0,\n failed: 0,\n duration_ms: 0,\n output: 'No test runner found (vitest.config.ts, jest.config.js, .mocharc.json)',\n truncated: false,\n },\n };\n return;\n }\n\n yield { type: 'log', text: `Running ${detected}…`, data: { runner: detected } };\n\n const start = Date.now();\n const args = buildArgs(detected, input);\n\n const result = yield* spawnStream({\n cmd: detected,\n args,\n cwd,\n signal: opts.signal,\n maxBytes: 200_000,\n });\n const duration = Date.now() - start;\n\n yield { type: 'final', output: parseResult(detected, result, duration) };\n },\n};\n\nasync function detectRunner(cwd: string): Promise<string | null> {\n const { stat } = await import('node:fs/promises');\n const candidates = ['vitest.config.ts', 'jest.config.js', '.mocharc.json'];\n for (const f of candidates) {\n try {\n await stat(path.join(cwd, f));\n if (f.includes('vitest')) return 'vitest';\n if (f.includes('jest')) return 'jest';\n if (f.includes('mocha')) return 'mocha';\n } catch {\n // continue\n }\n }\n return null;\n}\n\nfunction buildArgs(runner: string, input: TestInput): string[] {\n const args: string[] = [];\n const timeout = input.timeout ?? 30000;\n\n switch (runner) {\n case 'vitest':\n args.push('run', '--reporter=verbose');\n if (input.watch) {\n args[1] = '';\n args.push('watch');\n }\n if (input.coverage) args.push('--coverage');\n if (input.grep) args.push('--testNamePattern', input.grep);\n args.push('--testTimeout', String(timeout));\n break;\n case 'jest':\n args.push('--verbose');\n if (input.watch) args.push('--watch');\n if (input.coverage) args.push('--coverage');\n if (input.grep) args.push('--testPathPattern', input.grep);\n args.push('--testTimeout', String(timeout));\n break;\n case 'mocha':\n args.push('--reporter', 'spec');\n if (input.grep) args.push('--grep', input.grep);\n args.push('--timeout', String(timeout));\n break;\n }\n\n if (input.files) {\n const files = Array.isArray(input.files) ? input.files : input.files.split(',');\n args.push('--', ...files.map((f) => f.trim()));\n }\n\n return args;\n}\n\nfunction parseResult(\n runner: string,\n result: { stdout: string; stderr: string; exitCode: number; truncated: boolean; error?: string | undefined },\n duration: number,\n): TestOutput {\n const out = result.stdout + result.stderr;\n\n let tests_run = 0;\n let passed = 0;\n let failed = 0;\n\n if (runner === 'vitest') {\n const passedMatch = out.match(/(\\d+) passed/);\n const failedMatch = out.match(/(\\d+) failed/);\n if (passedMatch?.[1]) passed = Number.parseInt(passedMatch[1], 10);\n if (failedMatch?.[1]) failed = Number.parseInt(failedMatch[1], 10);\n tests_run = passed + failed;\n } else if (runner === 'jest') {\n const suitesMatch = out.match(/Test Suites:\\s+(\\d+)\\s+total/);\n const passedMatch = out.match(/Tests:\\s+(\\d+)\\s+passed/);\n const failedMatch = out.match(/Tests:\\s+(\\d+)\\s+failed/);\n tests_run = Number.parseInt(suitesMatch?.[1] ?? '0', 10);\n passed = Number.parseInt(passedMatch?.[1] ?? '0', 10);\n failed = Number.parseInt(failedMatch?.[1] ?? '0', 10);\n }\n\n return {\n runner,\n exit_code: result.exitCode,\n tests_run,\n passed,\n failed,\n duration_ms: duration,\n output: normalizeCommandOutput(result.stdout || result.error || ''),\n truncated: result.truncated,\n };\n}\n"]}
package/dist/todo.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { loadPlan, setPlanItemStatus, savePlan, loadTasks, saveTasks } from '@wrongstack/core';
2
+
1
3
  // src/todo.ts
2
4
  var todoTool = {
3
5
  name: "todo",
@@ -57,6 +59,48 @@ var todoTool = {
57
59
  }
58
60
  }
59
61
  ctx.state.replaceTodos(items);
62
+ const completedPlanIds = /* @__PURE__ */ new Set();
63
+ const completedTaskIds = /* @__PURE__ */ new Set();
64
+ const pendingPlanIds = /* @__PURE__ */ new Set();
65
+ const pendingTaskIds = /* @__PURE__ */ new Set();
66
+ for (const item of items) {
67
+ if (item.promotedFromPlan) {
68
+ (item.status === "completed" ? completedPlanIds : pendingPlanIds).add(item.promotedFromPlan);
69
+ }
70
+ if (item.promotedFromTask) {
71
+ (item.status === "completed" ? completedTaskIds : pendingTaskIds).add(item.promotedFromTask);
72
+ }
73
+ }
74
+ for (const planId of completedPlanIds) {
75
+ if (pendingPlanIds.has(planId)) continue;
76
+ const planPath = ctx.meta["plan.path"];
77
+ if (typeof planPath !== "string" || !planPath) continue;
78
+ try {
79
+ const plan = await loadPlan(planPath);
80
+ if (plan) {
81
+ const updated = setPlanItemStatus(plan, planId, "done");
82
+ await savePlan(planPath, updated);
83
+ }
84
+ } catch {
85
+ }
86
+ }
87
+ for (const taskId of completedTaskIds) {
88
+ if (pendingTaskIds.has(taskId)) continue;
89
+ const taskPath = ctx.meta["task.path"];
90
+ if (typeof taskPath !== "string" || !taskPath) continue;
91
+ try {
92
+ const file = await loadTasks(taskPath);
93
+ if (file) {
94
+ const task = file.tasks.find((t) => t.id === taskId);
95
+ if (task && task.status !== "completed") {
96
+ task.status = "completed";
97
+ task.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
98
+ await saveTasks(taskPath, file);
99
+ }
100
+ }
101
+ } catch {
102
+ }
103
+ }
60
104
  return {
61
105
  count: items.length,
62
106
  in_progress: items.filter((t) => t.status === "in_progress").length
package/dist/todo.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/todo.ts"],"names":[],"mappings":";AAWO,IAAM,QAAA,GAAwC;AAAA,EACnD,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU,SAAA;AAAA,EACV,WAAA,EACE,0JAAA;AAAA,EAEF,SAAA,EACE,ssBAAA;AAAA,EAQF,UAAA,EAAY,MAAA;AAAA,EACZ,QAAA,EAAU,KAAA;AAAA;AAAA,EACV,SAAA,EAAW,GAAA;AAAA,EACX,WAAA,EAAa;AAAA,IACX,IAAA,EAAM,QAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,OAAA;AAAA,QACN,KAAA,EAAO;AAAA,UACL,IAAA,EAAM,QAAA;AAAA,UACN,UAAA,EAAY;AAAA,YACV,EAAA,EAAI;AAAA,cACF,IAAA,EAAM,QAAA;AAAA,cACN,WAAA,EAAa;AAAA,aACf;AAAA,YACA,OAAA,EAAS;AAAA,cACP,IAAA,EAAM,QAAA;AAAA,cACN,WAAA,EAAa;AAAA,aACf;AAAA,YACA,MAAA,EAAQ;AAAA,cACN,IAAA,EAAM,QAAA;AAAA,cACN,IAAA,EAAM,CAAC,SAAA,EAAW,aAAA,EAAe,WAAW,CAAA;AAAA,cAC5C,WAAA,EAAa;AAAA,aACf;AAAA,YACA,UAAA,EAAY;AAAA,cACV,IAAA,EAAM,QAAA;AAAA,cACN,WAAA,EAAa;AAAA;AACf,WACF;AAAA,UACA,QAAA,EAAU,CAAC,IAAA,EAAM,SAAA,EAAW,QAAQ;AAAA,SACtC;AAAA,QACA,WAAA,EAAa;AAAA;AACf,KACF;AAAA,IACA,QAAA,EAAU,CAAC,OAAO;AAAA,GACpB;AAAA,EACA,MAAM,OAAA,CAAQ,KAAA,EAAO,GAAA,EAAK;AACxB,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAA,EAAO,KAAK,CAAA,EAAG;AAChC,MAAA,MAAM,IAAI,MAAM,8BAA8B,CAAA;AAAA,IAChD;AACA,IAAA,MAAM,KAAA,GAAQ,KAAA,CAAM,KAAA,CAAM,MAAA,CAAO,CAAC,CAAA,KAAqB,OAAA,CAAQ,CAAA,EAAG,EAAA,IAAM,CAAA,CAAE,OAAO,CAAC,CAAA;AAClF,IAAA,MAAM,aAAa,KAAA,CAAM,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,WAAW,aAAa,CAAA;AACjE,IAAA,IAAI,UAAA,CAAW,SAAS,CAAA,EAAG;AAEzB,MAAA,IAAI,cAAA,GAAiB,KAAA;AACrB,MAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,QAAA,IAAI,IAAA,CAAK,WAAW,aAAA,EAAe;AACjC,UAAA,IAAI,cAAA,OAAqB,MAAA,GAAS,SAAA;AAClC,UAAA,cAAA,GAAiB,IAAA;AAAA,QACnB;AAAA,MACF;AAAA,IACF;AACA,IAAA,GAAA,CAAI,KAAA,CAAM,aAAa,KAAK,CAAA;AAC5B,IAAA,OAAO;AAAA,MACL,OAAO,KAAA,CAAM,MAAA;AAAA,MACb,WAAA,EAAa,MAAM,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,MAAA,KAAW,aAAa,CAAA,CAAE;AAAA,KAC/D;AAAA,EACF;AACF","file":"todo.js","sourcesContent":["import type { TodoItem, Tool } from '@wrongstack/core';\n\ninterface TodoInput {\n todos: TodoItem[];\n}\n\ninterface TodoOutput {\n count: number;\n in_progress: number;\n}\n\nexport const todoTool: Tool<TodoInput, TodoOutput> = {\n name: 'todo',\n category: 'Session',\n description:\n 'Manage the session-level todo list. This is the primary mechanism for tracking multi-step work. ' +\n 'The list is fully replaced on every call (not appended).',\n usageHint:\n 'BEST PRACTICE for complex tasks:\\n' +\n '- At the beginning of a non-trivial task, create a clear todo list with specific, actionable items.\\n' +\n '- Only **one** item should be `in_progress` at any time.\\n' +\n '- Update the list frequently as work progresses (mark items done, add new ones, change status).\\n' +\n '- **Re-order items** to reflect current priorities — the full list is replaced each call, so item order is entirely under your control.\\n' +\n '- When all items are completed the board auto-clears — you do NOT need to send an empty list.\\n' +\n '- The system and user can see this list, so keep it honest and up-to-date.\\n' +\n 'This tool is extremely valuable for maintaining focus and giving the user visibility into your plan.',\n permission: 'auto',\n mutating: false, // mutates only conversation state (ctx.todos), not external state — no confirmation needed\n timeoutMs: 1_000,\n inputSchema: {\n type: 'object',\n properties: {\n todos: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Unique identifier for the todo item (e.g. \"1\", \"auth-flow\").',\n },\n content: {\n type: 'string',\n description: 'Clear, actionable description of the task.',\n },\n status: {\n type: 'string',\n enum: ['pending', 'in_progress', 'completed'],\n description: 'Current status. Only one item should be \"in_progress\" at a time.',\n },\n activeForm: {\n type: 'string',\n description: 'Optional present-tense form shown while the task is active (e.g. \"Fixing auth bug\").',\n },\n },\n required: ['id', 'content', 'status'],\n },\n description: 'The complete new list of todos. This replaces the previous list entirely.',\n },\n },\n required: ['todos'],\n },\n async execute(input, ctx) {\n if (!Array.isArray(input?.todos)) {\n throw new Error('todo: todos must be an array');\n }\n const items = input.todos.filter((t): t is TodoItem => Boolean(t?.id && t.content));\n const inProgress = items.filter((t) => t.status === 'in_progress');\n if (inProgress.length > 1) {\n // Keep only the first as in_progress, mark rest pending\n let seenInProgress = false;\n for (const item of items) {\n if (item.status === 'in_progress') {\n if (seenInProgress) item.status = 'pending';\n seenInProgress = true;\n }\n }\n }\n ctx.state.replaceTodos(items);\n return {\n count: items.length,\n in_progress: items.filter((t) => t.status === 'in_progress').length,\n };\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/todo.ts"],"names":[],"mappings":";;;AAaO,IAAM,QAAA,GAAwC;AAAA,EACnD,IAAA,EAAM,MAAA;AAAA,EACN,QAAA,EAAU,SAAA;AAAA,EACV,WAAA,EACE,0JAAA;AAAA,EAEF,SAAA,EACE,ssBAAA;AAAA,EAQF,UAAA,EAAY,MAAA;AAAA,EACZ,QAAA,EAAU,KAAA;AAAA;AAAA,EACV,SAAA,EAAW,GAAA;AAAA,EACX,WAAA,EAAa;AAAA,IACX,IAAA,EAAM,QAAA;AAAA,IACN,UAAA,EAAY;AAAA,MACV,KAAA,EAAO;AAAA,QACL,IAAA,EAAM,OAAA;AAAA,QACN,KAAA,EAAO;AAAA,UACL,IAAA,EAAM,QAAA;AAAA,UACN,UAAA,EAAY;AAAA,YACV,EAAA,EAAI;AAAA,cACF,IAAA,EAAM,QAAA;AAAA,cACN,WAAA,EAAa;AAAA,aACf;AAAA,YACA,OAAA,EAAS;AAAA,cACP,IAAA,EAAM,QAAA;AAAA,cACN,WAAA,EAAa;AAAA,aACf;AAAA,YACA,MAAA,EAAQ;AAAA,cACN,IAAA,EAAM,QAAA;AAAA,cACN,IAAA,EAAM,CAAC,SAAA,EAAW,aAAA,EAAe,WAAW,CAAA;AAAA,cAC5C,WAAA,EAAa;AAAA,aACf;AAAA,YACA,UAAA,EAAY;AAAA,cACV,IAAA,EAAM,QAAA;AAAA,cACN,WAAA,EAAa;AAAA;AACf,WACF;AAAA,UACA,QAAA,EAAU,CAAC,IAAA,EAAM,SAAA,EAAW,QAAQ;AAAA,SACtC;AAAA,QACA,WAAA,EAAa;AAAA;AACf,KACF;AAAA,IACA,QAAA,EAAU,CAAC,OAAO;AAAA,GACpB;AAAA,EACA,MAAM,OAAA,CAAQ,KAAA,EAAO,GAAA,EAAK;AACxB,IAAA,IAA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SAAA,CAAU,UAAU,IAAI,CAAA;AAAA,UAChC;AAAA,QACF;AAAA,MACF,CAAA,CAAA,MAAQ;AAAA,MAAoB;AAAA,IAC9B;AAEA,IAAA,OAAO;AAAA,MACL,OAAO,KAAA,CAAM,MAAA;AAAA,MACb,WAAA,EAAa,MAAM,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,MAAA,KAAW,aAAa,CAAA,CAAE;AAAA,KAC/D;AAAA,EACF;AACF","file":"todo.js","sourcesContent":["import type { TodoItem, Tool } from '@wrongstack/core';\nimport { loadPlan, savePlan, setPlanItemStatus } from '@wrongstack/core';\nimport { loadTasks, saveTasks } from '@wrongstack/core';\n\ninterface TodoInput {\n todos: TodoItem[];\n}\n\ninterface TodoOutput {\n count: number;\n in_progress: number;\n}\n\nexport const todoTool: Tool<TodoInput, TodoOutput> = {\n name: 'todo',\n category: 'Session',\n description:\n 'Manage the session-level todo list. This is the primary mechanism for tracking multi-step work. ' +\n 'The list is fully replaced on every call (not appended).',\n usageHint:\n 'BEST PRACTICE for complex tasks:\\n' +\n '- At the beginning of a non-trivial task, create a clear todo list with specific, actionable items.\\n' +\n '- Only **one** item should be `in_progress` at any time.\\n' +\n '- Update the list frequently as work progresses (mark items done, add new ones, change status).\\n' +\n '- **Re-order items** to reflect current priorities — the full list is replaced each call, so item order is entirely under your control.\\n' +\n '- When all items are completed the board auto-clears — you do NOT need to send an empty list.\\n' +\n '- The system and user can see this list, so keep it honest and up-to-date.\\n' +\n 'This tool is extremely valuable for maintaining focus and giving the user visibility into your plan.',\n permission: 'auto',\n mutating: false, // mutates only conversation state (ctx.todos), not external state — no confirmation needed\n timeoutMs: 1_000,\n inputSchema: {\n type: 'object',\n properties: {\n todos: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Unique identifier for the todo item (e.g. \"1\", \"auth-flow\").',\n },\n content: {\n type: 'string',\n description: 'Clear, actionable description of the task.',\n },\n status: {\n type: 'string',\n enum: ['pending', 'in_progress', 'completed'],\n description: 'Current status. Only one item should be \"in_progress\" at a time.',\n },\n activeForm: {\n type: 'string',\n description: 'Optional present-tense form shown while the task is active (e.g. \"Fixing auth bug\").',\n },\n },\n required: ['id', 'content', 'status'],\n },\n description: 'The complete new list of todos. This replaces the previous list entirely.',\n },\n },\n required: ['todos'],\n },\n async execute(input, ctx) {\n if (!Array.isArray(input?.todos)) {\n throw new Error('todo: todos must be an array');\n }\n const items = input.todos.filter((t): t is TodoItem => Boolean(t?.id && t.content));\n const inProgress = items.filter((t) => t.status === 'in_progress');\n if (inProgress.length > 1) {\n // Keep only the first as in_progress, mark rest pending\n let seenInProgress = false;\n for (const item of items) {\n if (item.status === 'in_progress') {\n if (seenInProgress) item.status = 'pending';\n seenInProgress = true;\n }\n }\n }\n ctx.state.replaceTodos(items);\n\n // Auto-complete parent plan items / tasks when all their promoted\n // todos are done. Runs after state mutation so the UI sees the new\n // todo list before we touch the plan/task files.\n const completedPlanIds = new Set<string>();\n const completedTaskIds = new Set<string>();\n const pendingPlanIds = new Set<string>();\n const pendingTaskIds = new Set<string>();\n\n for (const item of items) {\n if (item.promotedFromPlan) {\n (item.status === 'completed' ? completedPlanIds : pendingPlanIds).add(item.promotedFromPlan);\n }\n if (item.promotedFromTask) {\n (item.status === 'completed' ? completedTaskIds : pendingTaskIds).add(item.promotedFromTask);\n }\n }\n\n // Mark fully-completed plan items as done\n for (const planId of completedPlanIds) {\n if (pendingPlanIds.has(planId)) continue; // not all done yet\n const planPath = (ctx.meta as Record<string, unknown>)['plan.path'];\n if (typeof planPath !== 'string' || !planPath) continue;\n try {\n const plan = await loadPlan(planPath);\n if (plan) {\n const updated = setPlanItemStatus(plan, planId, 'done');\n await savePlan(planPath, updated);\n }\n } catch { /* best-effort */ }\n }\n\n // Mark fully-completed tasks as completed\n for (const taskId of completedTaskIds) {\n if (pendingTaskIds.has(taskId)) continue; // not all done yet\n const taskPath = (ctx.meta as Record<string, unknown>)['task.path'];\n if (typeof taskPath !== 'string' || !taskPath) continue;\n try {\n const file = await loadTasks(taskPath);\n if (file) {\n const task = file.tasks.find((t) => t.id === taskId);\n if (task && task.status !== 'completed') {\n task.status = 'completed';\n task.updatedAt = new Date().toISOString();\n await saveTasks(taskPath, file);\n }\n }\n } catch { /* best-effort */ }\n }\n\n return {\n count: items.length,\n in_progress: items.filter((t) => t.status === 'in_progress').length,\n };\n },\n};\n"]}
package/dist/tree.js CHANGED
@@ -4,7 +4,7 @@ import * as path from 'node:path';
4
4
 
5
5
  // src/tree.ts
6
6
  function resolvePath(input, ctx) {
7
- return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.cwd, input);
7
+ return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);
8
8
  }
9
9
  function ensureInsideRoot(absPath, ctx) {
10
10
  const root = path.resolve(ctx.projectRoot);
package/dist/tree.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/_util.ts","../src/tree.ts"],"names":["path2"],"mappings":";;;;;AA8BO,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,GAAA,EAAK,KAAK,CAAA;AACrF;AAEO,SAAS,gBAAA,CAAiB,SAAiB,GAAA,EAAsB;AACtE,EAAA,MAAM,IAAA,GAAY,IAAA,CAAA,OAAA,CAAQ,GAAA,CAAI,WAAW,CAAA;AACzC,EAAA,MAAM,MAAA,GAAc,aAAQ,OAAO,CAAA;AACnC,EAAA,MAAM,GAAA,GAAW,IAAA,CAAA,QAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AACtC,EAAA,IAAI,IAAI,UAAA,CAAW,IAAI,CAAA,IAAU,IAAA,CAAA,UAAA,CAAW,GAAG,CAAA,EAAG;AAChD,IAAA,MAAM,IAAI,KAAA,CA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GAAQ,MAAM,CAAC,CAAA;AACrB,IAAA,IAAI,CAAC,KAAA,EAAO;AACZ,IAAA,MAAM,MAAA,GAAS,CAAA,KAAM,KAAA,CAAM,MAAA,GAAS,CAAA;AACpC,IAAA,MAAM,SAAA,GAAY,IAAA,CAAK,MAAA,GAAS,MAAA,GAAS,WAAA;AACzC,IAAA,MAAM,MAAA,GAAS,SAAS,qBAAA,GAAS,qBAAA;AACjC,IAAA,MAAM,cAAc,KAAA,CAAM,IAAA,IAAQ,KAAA,CAAM,WAAA,KAAgB,GAAA,GAAM,EAAA,CAAA;AAE9D,IAAA,IAAI,CAAC,IAAA,CAAK,QAAA,IAAY,KAAA,CAAM,aAAY,EAAG;AAC3C,IAAA,IAAI,CAAC,IAAA,CAAK,SAAA,IAAa,KAAA,CAAM,QAAO,EAAG;AAEvC,IAAA,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,MAAA,GAAS,SAAS,WAAW,CAAA;AAElD,IAAA,IAAI,KAAA,CAAM,aAAY,KAAM,IAAA,CAAK,aAAa,CAAA,IAAK,KAAA,GAAQ,KAAK,QAAA,CAAA,EAAW;AACzE,MAAA,MAAM,WAAA,GAAc,KAAK,MAAA,GAAS,SAAA;AAClC,MAAA,MAAM,QAAaA,IAAA,CAAA,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA,EAAG,QAAQ,CAAA,EAAG;AAAA,QACnD,GAAG,IAAA;AAAA,QACH,MAAA,EAAQ,WAAA;AAAA,QACR;AAAA,OACD,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"tree.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.cwd, input);\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\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 const realRoot = await fsp.realpath(ctx.projectRoot).catch(() => path.resolve(ctx.projectRoot));\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 const rel = path.relative(realRoot, real);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoot}\"`,\n );\n }\n return;\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 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 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 { expectDefined } from '@wrongstack/core';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Tool, ToolProgressEvent, ToolStreamEvent } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\nconst DEFAULT_IGNORE = [\n 'node_modules',\n '.git',\n 'dist',\n 'build',\n '.next',\n 'coverage',\n '__pycache__',\n '.wrongstack',\n '.ssh',\n '.gnupg',\n '.aws',\n];\n\ninterface TreeInput {\n path?: string | undefined;\n depth?: number | undefined;\n glob?: string | undefined;\n exclude?: string[] | undefined;\n show_files?: boolean | undefined;\n show_dirs?: boolean | undefined;\n show_hidden?: boolean | undefined;\n}\n\ninterface TreeOutput {\n tree: string;\n total_files: number;\n total_dirs: number;\n truncated: boolean;\n path: string;\n}\n\nexport const treeTool: Tool<TreeInput, TreeOutput> = {\n name: 'tree',\n category: 'Filesystem',\n description:\n 'Display a directory tree of the project (or a subpath). This is the recommended way to explore the high-level structure of a codebase before reading specific files.',\n usageHint:\n 'BEST PRACTICE FOR INITIAL EXPLORATION:\\n\\n' +\n '- Call early when working with an unfamiliar project or module.\\n' +\n '- Tune `depth` (default 3) and use `glob`/`exclude` to focus the view.\\n' +\n '- Prefer this over raw `bash find` or `glob` + manual reading when you need a quick structural overview.\\n' +\n 'Output is truncated for very large trees.',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n timeoutMs: 15_000,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Root directory to display the tree from (defaults to project root).',\n },\n depth: {\n type: 'integer',\n description: 'Maximum directory depth to traverse (default 3, use 0 for unlimited).',\n minimum: 0,\n maximum: 20,\n },\n glob: {\n type: 'string',\n description: 'Only include files matching this glob pattern.',\n },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of directory names to completely ignore.',\n },\n show_files: {\n type: 'boolean',\n description: 'Whether to show individual files (default true).',\n },\n show_dirs: {\n type: 'boolean',\n description: 'Whether to show directories (default true).',\n },\n show_hidden: {\n type: 'boolean',\n description: 'Show hidden files starting with . (default: false)',\n },\n },\n },\n async execute(input, ctx, opts) {\n let final: TreeOutput | undefined;\n const executeStream = treeTool.executeStream;\n if (!executeStream) throw new Error('treeTool: stream execution unavailable');\n for await (const ev of executeStream(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('tree: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx): AsyncGenerator<ToolStreamEvent<TreeOutput>> {\n const basePath = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const maxDepth = input.depth ?? 3;\n const showFiles = input.show_files ?? true;\n const showDirs = input.show_dirs ?? true;\n const showHidden = input.show_hidden ?? false;\n const exclude = new Set([...DEFAULT_IGNORE, ...(input.exclude ?? [])]);\n const filterGlob = input.glob;\n\n const lines: string[] = [basePath];\n const totals = { totalFiles: { value: 0 }, totalDirs: { value: 0 } };\n\n // Walker pushes progress into an async queue; the generator drains it.\n const queue: ToolProgressEvent[] = [];\n const FLUSH_EVERY = 200; // emit metric every 200 entries seen\n let lastEmittedTotal = 0;\n\n const tickProgress = () => {\n const seen = totals.totalFiles.value + totals.totalDirs.value;\n if (seen - lastEmittedTotal >= FLUSH_EVERY) {\n queue.push({\n type: 'metric',\n text: `${seen} entries`,\n data: { files: totals.totalFiles.value, dirs: totals.totalDirs.value },\n });\n lastEmittedTotal = seen;\n }\n };\n\n const walkPromise = walkDir(basePath, 0, {\n maxDepth,\n exclude,\n showFiles,\n showDirs,\n showHidden,\n filterGlob,\n lines,\n prefix: '',\n isLast: true,\n totalFiles: totals.totalFiles,\n totalDirs: totals.totalDirs,\n onProgress: tickProgress,\n });\n\n // Race the walk against periodic flushes — yield metrics while it runs.\n let walkDone = false;\n walkPromise.finally(() => {\n walkDone = true;\n });\n\n while (!walkDone || queue.length > 0) {\n if (queue.length > 0) {\n yield expectDefined(queue.shift());\n } else {\n // Race the walk completion against a short tick so we don't busy-\n // spin while the producer fills the queue. Previously the\n // setTimeout was never cleared when walkPromise won — one stray\n // timer per drain iteration accumulated on the event loop.\n let pollTimer: ReturnType<typeof setTimeout> | undefined;\n const poll = new Promise<void>((r) => {\n pollTimer = setTimeout(r, 50);\n });\n try {\n await Promise.race([walkPromise, poll]).catch(() => undefined);\n } finally {\n if (pollTimer) clearTimeout(pollTimer);\n }\n }\n }\n await walkPromise; // surface any error\n\n yield {\n type: 'final',\n output: {\n tree: lines.join('\\n'),\n total_files: totals.totalFiles.value,\n total_dirs: totals.totalDirs.value,\n truncated: false,\n path: basePath,\n },\n };\n },\n};\n\ninterface WalkOptions {\n maxDepth: number;\n exclude: Set<string>;\n showFiles: boolean;\n showDirs: boolean;\n showHidden: boolean;\n filterGlob?: string | undefined;\n lines: string[];\n prefix: string;\n isLast: boolean;\n totalFiles: { value: number };\n totalDirs: { value: number };\n onProgress?: (() => void) | undefined;\n}\n\nasync function walkDir(dir: string, depth: number, opts: WalkOptions): Promise<void> {\n const entries = await fs\n .readdir(dir, { withFileTypes: true })\n .catch(() => [] as import('node:fs').Dirent[]);\n\n const filtered = entries.filter((e) => {\n if (!opts.showHidden && e.name.startsWith('.')) return false;\n if (opts.exclude.has(e.name)) return false;\n return true;\n });\n\n if (depth > 0) {\n const dirCount = filtered.filter((e) => e.isDirectory()).length;\n const fileCount = filtered.filter((e) => e.isFile()).length;\n opts.totalDirs.value += dirCount;\n opts.totalFiles.value += fileCount;\n opts.onProgress?.();\n }\n\n const items = filtered.sort((a, b) => {\n if (a.isDirectory() && !b.isDirectory()) return -1;\n if (!a.isDirectory() && b.isDirectory()) return 1;\n return a.name.localeCompare(b.name);\n });\n\n for (let i = 0; i < items.length; i++) {\n const entry = items[i];\n if (!entry) continue;\n const isLast = i === items.length - 1;\n const connector = opts.isLast ? ' ' : '│ ';\n const branch = isLast ? '└── ' : '├── ';\n const displayName = entry.name + (entry.isDirectory() ? '/' : '');\n\n if (!opts.showDirs && entry.isDirectory()) continue;\n if (!opts.showFiles && entry.isFile()) continue;\n\n opts.lines.push(opts.prefix + branch + displayName);\n\n if (entry.isDirectory() && (opts.maxDepth === 0 || depth < opts.maxDepth)) {\n const childPrefix = opts.prefix + connector;\n await walkDir(path.join(dir, entry.name), depth + 1, {\n ...opts,\n prefix: childPrefix,\n isLast,\n });\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/_util.ts","../src/tree.ts"],"names":["path2"],"mappings":";;;;;AA8BO,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;AAEO,SAAS,gBAAA,CAAiB,SAAiB,GAAA,EAAsB;AACtE,EAAA,MAAM,IAAA,GAAY,I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QACR;AAAA,OACD,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"tree.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\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const root = path.resolve(ctx.projectRoot);\n const target = path.resolve(absPath);\n const rel = path.relative(root, target);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`Path \"${absPath}\" is outside project root \"${root}\"`);\n }\n return target;\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 const realRoot = await fsp.realpath(ctx.projectRoot).catch(() => path.resolve(ctx.projectRoot));\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 const rel = path.relative(realRoot, real);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoot}\"`,\n );\n }\n return;\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 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 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 { expectDefined } from '@wrongstack/core';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Tool, ToolProgressEvent, ToolStreamEvent } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\nconst DEFAULT_IGNORE = [\n 'node_modules',\n '.git',\n 'dist',\n 'build',\n '.next',\n 'coverage',\n '__pycache__',\n '.wrongstack',\n '.ssh',\n '.gnupg',\n '.aws',\n];\n\ninterface TreeInput {\n path?: string | undefined;\n depth?: number | undefined;\n glob?: string | undefined;\n exclude?: string[] | undefined;\n show_files?: boolean | undefined;\n show_dirs?: boolean | undefined;\n show_hidden?: boolean | undefined;\n}\n\ninterface TreeOutput {\n tree: string;\n total_files: number;\n total_dirs: number;\n truncated: boolean;\n path: string;\n}\n\nexport const treeTool: Tool<TreeInput, TreeOutput> = {\n name: 'tree',\n category: 'Filesystem',\n description:\n 'Display a directory tree of the project (or a subpath). This is the recommended way to explore the high-level structure of a codebase before reading specific files.',\n usageHint:\n 'BEST PRACTICE FOR INITIAL EXPLORATION:\\n\\n' +\n '- Call early when working with an unfamiliar project or module.\\n' +\n '- Tune `depth` (default 3) and use `glob`/`exclude` to focus the view.\\n' +\n '- Prefer this over raw `bash find` or `glob` + manual reading when you need a quick structural overview.\\n' +\n 'Output is truncated for very large trees.',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n timeoutMs: 15_000,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Root directory to display the tree from (defaults to project root).',\n },\n depth: {\n type: 'integer',\n description: 'Maximum directory depth to traverse (default 3, use 0 for unlimited).',\n minimum: 0,\n maximum: 20,\n },\n glob: {\n type: 'string',\n description: 'Only include files matching this glob pattern.',\n },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of directory names to completely ignore.',\n },\n show_files: {\n type: 'boolean',\n description: 'Whether to show individual files (default true).',\n },\n show_dirs: {\n type: 'boolean',\n description: 'Whether to show directories (default true).',\n },\n show_hidden: {\n type: 'boolean',\n description: 'Show hidden files starting with . (default: false)',\n },\n },\n },\n async execute(input, ctx, opts) {\n let final: TreeOutput | undefined;\n const executeStream = treeTool.executeStream;\n if (!executeStream) throw new Error('treeTool: stream execution unavailable');\n for await (const ev of executeStream(input, ctx, opts)) {\n if (ev.type === 'final') final = ev.output;\n }\n if (!final) throw new Error('tree: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx): AsyncGenerator<ToolStreamEvent<TreeOutput>> {\n const basePath = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const maxDepth = input.depth ?? 3;\n const showFiles = input.show_files ?? true;\n const showDirs = input.show_dirs ?? true;\n const showHidden = input.show_hidden ?? false;\n const exclude = new Set([...DEFAULT_IGNORE, ...(input.exclude ?? [])]);\n const filterGlob = input.glob;\n\n const lines: string[] = [basePath];\n const totals = { totalFiles: { value: 0 }, totalDirs: { value: 0 } };\n\n // Walker pushes progress into an async queue; the generator drains it.\n const queue: ToolProgressEvent[] = [];\n const FLUSH_EVERY = 200; // emit metric every 200 entries seen\n let lastEmittedTotal = 0;\n\n const tickProgress = () => {\n const seen = totals.totalFiles.value + totals.totalDirs.value;\n if (seen - lastEmittedTotal >= FLUSH_EVERY) {\n queue.push({\n type: 'metric',\n text: `${seen} entries`,\n data: { files: totals.totalFiles.value, dirs: totals.totalDirs.value },\n });\n lastEmittedTotal = seen;\n }\n };\n\n const walkPromise = walkDir(basePath, 0, {\n maxDepth,\n exclude,\n showFiles,\n showDirs,\n showHidden,\n filterGlob,\n lines,\n prefix: '',\n isLast: true,\n totalFiles: totals.totalFiles,\n totalDirs: totals.totalDirs,\n onProgress: tickProgress,\n });\n\n // Race the walk against periodic flushes — yield metrics while it runs.\n let walkDone = false;\n walkPromise.finally(() => {\n walkDone = true;\n });\n\n while (!walkDone || queue.length > 0) {\n if (queue.length > 0) {\n yield expectDefined(queue.shift());\n } else {\n // Race the walk completion against a short tick so we don't busy-\n // spin while the producer fills the queue. Previously the\n // setTimeout was never cleared when walkPromise won — one stray\n // timer per drain iteration accumulated on the event loop.\n let pollTimer: ReturnType<typeof setTimeout> | undefined;\n const poll = new Promise<void>((r) => {\n pollTimer = setTimeout(r, 50);\n });\n try {\n await Promise.race([walkPromise, poll]).catch(() => undefined);\n } finally {\n if (pollTimer) clearTimeout(pollTimer);\n }\n }\n }\n await walkPromise; // surface any error\n\n yield {\n type: 'final',\n output: {\n tree: lines.join('\\n'),\n total_files: totals.totalFiles.value,\n total_dirs: totals.totalDirs.value,\n truncated: false,\n path: basePath,\n },\n };\n },\n};\n\ninterface WalkOptions {\n maxDepth: number;\n exclude: Set<string>;\n showFiles: boolean;\n showDirs: boolean;\n showHidden: boolean;\n filterGlob?: string | undefined;\n lines: string[];\n prefix: string;\n isLast: boolean;\n totalFiles: { value: number };\n totalDirs: { value: number };\n onProgress?: (() => void) | undefined;\n}\n\nasync function walkDir(dir: string, depth: number, opts: WalkOptions): Promise<void> {\n const entries = await fs\n .readdir(dir, { withFileTypes: true })\n .catch(() => [] as import('node:fs').Dirent[]);\n\n const filtered = entries.filter((e) => {\n if (!opts.showHidden && e.name.startsWith('.')) return false;\n if (opts.exclude.has(e.name)) return false;\n return true;\n });\n\n if (depth > 0) {\n const dirCount = filtered.filter((e) => e.isDirectory()).length;\n const fileCount = filtered.filter((e) => e.isFile()).length;\n opts.totalDirs.value += dirCount;\n opts.totalFiles.value += fileCount;\n opts.onProgress?.();\n }\n\n const items = filtered.sort((a, b) => {\n if (a.isDirectory() && !b.isDirectory()) return -1;\n if (!a.isDirectory() && b.isDirectory()) return 1;\n return a.name.localeCompare(b.name);\n });\n\n for (let i = 0; i < items.length; i++) {\n const entry = items[i];\n if (!entry) continue;\n const isLast = i === items.length - 1;\n const connector = opts.isLast ? ' ' : '│ ';\n const branch = isLast ? '└── ' : '├── ';\n const displayName = entry.name + (entry.isDirectory() ? '/' : '');\n\n if (!opts.showDirs && entry.isDirectory()) continue;\n if (!opts.showFiles && entry.isFile()) continue;\n\n opts.lines.push(opts.prefix + branch + displayName);\n\n if (entry.isDirectory() && (opts.maxDepth === 0 || depth < opts.maxDepth)) {\n const childPrefix = opts.prefix + connector;\n await walkDir(path.join(dir, entry.name), depth + 1, {\n ...opts,\n prefix: childPrefix,\n isLast,\n });\n }\n }\n}\n"]}
package/dist/typecheck.js CHANGED
@@ -30,6 +30,7 @@ function resolveWin32Command(cmd) {
30
30
  async function* spawnStream(opts) {
31
31
  const max = opts.maxBytes;
32
32
  const flushAt = opts.flushBytes ?? 4 * 1024;
33
+ const maxQueue = opts.maxQueueSize ?? 500;
33
34
  let stdout = "";
34
35
  let stderr = "";
35
36
  let pending = "";
@@ -45,6 +46,7 @@ async function* spawnStream(opts) {
45
46
  });
46
47
  const queue = [];
47
48
  let waiter;
49
+ let paused = false;
48
50
  const wake = () => {
49
51
  if (waiter) {
50
52
  const w = waiter;
@@ -52,17 +54,34 @@ async function* spawnStream(opts) {
52
54
  w();
53
55
  }
54
56
  };
57
+ const resume = () => {
58
+ if (paused && queue.length < maxQueue) {
59
+ paused = false;
60
+ child.stdout?.resume();
61
+ child.stderr?.resume();
62
+ }
63
+ };
55
64
  child.stdout?.on("data", (c) => {
56
65
  const s = c.toString();
57
66
  if (stdout.length < max) stdout += s;
58
67
  queue.push({ kind: "out", data: s });
59
68
  wake();
69
+ if (!paused && queue.length >= maxQueue) {
70
+ paused = true;
71
+ child.stdout?.pause();
72
+ child.stderr?.pause();
73
+ }
60
74
  });
61
75
  child.stderr?.on("data", (c) => {
62
76
  const s = c.toString();
63
77
  if (stderr.length < max) stderr += s;
64
78
  queue.push({ kind: "err", data: s });
65
79
  wake();
80
+ if (!paused && queue.length >= maxQueue) {
81
+ paused = true;
82
+ child.stdout?.pause();
83
+ child.stderr?.pause();
84
+ }
66
85
  });
67
86
  child.on("error", (e) => {
68
87
  error = e.message;
@@ -82,6 +101,7 @@ async function* spawnStream(opts) {
82
101
  });
83
102
  }
84
103
  const chunk = queue.shift();
104
+ resume();
85
105
  if (chunk.kind === "close") {
86
106
  if (!spawnFailed) exitCode = chunk.code ?? 0;
87
107
  break;
@@ -109,7 +129,7 @@ async function* spawnStream(opts) {
109
129
  };
110
130
  }
111
131
  function resolvePath(input, ctx) {
112
- return path2.isAbsolute(input) ? path2.normalize(input) : path2.resolve(ctx.cwd, input);
132
+ return path2.isAbsolute(input) ? path2.normalize(input) : path2.resolve(ctx.workingDir ?? ctx.cwd, input);
113
133
  }
114
134
  function ensureInsideRoot(absPath, ctx) {
115
135
  const root = path2.resolve(ctx.projectRoot);