@wrongstack/tools 0.287.0 → 0.289.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 (93) hide show
  1. package/dist/_fetch-guard.d.ts.map +1 -1
  2. package/dist/_redact-command.d.ts.map +1 -1
  3. package/dist/_spawn-stream.d.ts.map +1 -1
  4. package/dist/audit.js +61 -14
  5. package/dist/audit.js.map +3 -3
  6. package/dist/bash.d.ts +1 -1
  7. package/dist/bash.d.ts.map +1 -1
  8. package/dist/bash.js +97 -19
  9. package/dist/bash.js.map +3 -3
  10. package/dist/builtin.d.ts +12 -10
  11. package/dist/builtin.d.ts.map +1 -1
  12. package/dist/builtin.js +1620 -803
  13. package/dist/builtin.js.map +3 -3
  14. package/dist/codebase-index/background-indexer.d.ts.map +1 -1
  15. package/dist/codebase-index/bm25.d.ts +1 -2
  16. package/dist/codebase-index/bm25.d.ts.map +1 -1
  17. package/dist/codebase-index/codebase-index-tool.d.ts.map +1 -1
  18. package/dist/codebase-index/codebase-search-tool.d.ts.map +1 -1
  19. package/dist/codebase-index/codebase-stats-tool.d.ts +7 -0
  20. package/dist/codebase-index/codebase-stats-tool.d.ts.map +1 -1
  21. package/dist/codebase-index/index-service.d.ts +11 -1
  22. package/dist/codebase-index/index-service.d.ts.map +1 -1
  23. package/dist/codebase-index/index.d.ts +2 -1
  24. package/dist/codebase-index/index.d.ts.map +1 -1
  25. package/dist/codebase-index/index.js +749 -192
  26. package/dist/codebase-index/index.js.map +3 -3
  27. package/dist/codebase-index/indexer.d.ts.map +1 -1
  28. package/dist/codebase-index/schema.d.ts +43 -1
  29. package/dist/codebase-index/schema.d.ts.map +1 -1
  30. package/dist/codebase-index/ts-parser.d.ts.map +1 -1
  31. package/dist/codebase-index/worker-protocol.d.ts +1 -0
  32. package/dist/codebase-index/worker-protocol.d.ts.map +1 -1
  33. package/dist/codebase-index/worker.js +610 -152
  34. package/dist/codebase-index/worker.js.map +3 -3
  35. package/dist/codebase-index/writer.d.ts +27 -1
  36. package/dist/codebase-index/writer.d.ts.map +1 -1
  37. package/dist/e2e.js +477 -0
  38. package/dist/e2e.js.map +7 -0
  39. package/dist/exec.d.ts +1 -1
  40. package/dist/exec.d.ts.map +1 -1
  41. package/dist/exec.js +60 -5
  42. package/dist/exec.js.map +3 -3
  43. package/dist/fetch.js +2 -2
  44. package/dist/fetch.js.map +2 -2
  45. package/dist/format.js +61 -14
  46. package/dist/format.js.map +3 -3
  47. package/dist/glob.js +2 -2
  48. package/dist/glob.js.map +1 -1
  49. package/dist/grep.d.ts.map +1 -1
  50. package/dist/grep.js +2 -2
  51. package/dist/grep.js.map +2 -2
  52. package/dist/index.d.ts +3 -2
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +1786 -809
  55. package/dist/index.js.map +3 -3
  56. package/dist/install.js +61 -14
  57. package/dist/install.js.map +3 -3
  58. package/dist/kanban.d.ts +11 -2
  59. package/dist/kanban.d.ts.map +1 -1
  60. package/dist/kanban.js +695 -571
  61. package/dist/kanban.js.map +3 -3
  62. package/dist/languages/detect.d.ts.map +1 -1
  63. package/dist/languages/index.js +61 -14
  64. package/dist/languages/index.js.map +3 -3
  65. package/dist/languages/types.d.ts +7 -0
  66. package/dist/languages/types.d.ts.map +1 -1
  67. package/dist/lint.js +61 -14
  68. package/dist/lint.js.map +3 -3
  69. package/dist/outdated.js +61 -14
  70. package/dist/outdated.js.map +3 -3
  71. package/dist/pack.js +1617 -800
  72. package/dist/pack.js.map +3 -3
  73. package/dist/plan.js +4 -0
  74. package/dist/plan.js.map +2 -2
  75. package/dist/process-registry.js +12 -5
  76. package/dist/process-registry.js.map +2 -2
  77. package/dist/search.js +2 -2
  78. package/dist/search.js.map +2 -2
  79. package/dist/session-kanban.d.ts +9 -0
  80. package/dist/session-kanban.d.ts.map +1 -1
  81. package/dist/session-kanban.js +137 -0
  82. package/dist/session-kanban.js.map +2 -2
  83. package/dist/task.js +4 -0
  84. package/dist/task.js.map +2 -2
  85. package/dist/test.js +61 -14
  86. package/dist/test.js.map +3 -3
  87. package/dist/todo.js +4 -0
  88. package/dist/todo.js.map +2 -2
  89. package/dist/tree.js +2 -2
  90. package/dist/tree.js.map +1 -1
  91. package/dist/typecheck.js +61 -14
  92. package/dist/typecheck.js.map +3 -3
  93. package/package.json +7 -3
package/dist/glob.js CHANGED
@@ -82,8 +82,8 @@ var WALK_CONCURRENCY = 16;
82
82
  var globTool = {
83
83
  name: "glob",
84
84
  category: "Filesystem",
85
- description: "Find files matching a glob pattern. Fast way to discover relevant files before reading, grepping, or editing them.",
86
- usageHint: "RECOMMENDED FOR SCOPING SEARCHES:\n\n- Use early to get a list of files you actually care about.\n- Combine with `path` and `limit`.\n- Default ignores common build/dependency directories.\nMuch more efficient than shell `find` for most use cases inside the agent.",
85
+ description: "Find files by path pattern. Use index-backed `codebase-search` first for code symbols or concepts when it is live.",
86
+ usageHint: "PATH DISCOVERY AND SEARCH SCOPING:\n\n- When `codebase-search` is live, use it first for code concepts; use `glob` for filenames, path patterns, and non-indexed files.\n- Combine with `path` and `limit`.\n- Default ignores common build/dependency directories.\nMuch more efficient than shell `find` for most use cases inside the agent.",
87
87
  selection: {
88
88
  doNotUseWhen: "you need to search inside file contents.",
89
89
  useInstead: ["grep"]
package/dist/glob.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/glob.ts", "../src/_concurrency.ts", "../src/_util.ts"],
4
- "sourcesContent": ["import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { compileGlob } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { mapWithConcurrency } from './_concurrency.js';\nimport { assertRealInsideRoot, safeResolveReal } from './_util.js';\n\ninterface GlobInput {\n pattern: string;\n path?: string | undefined;\n limit?: number | undefined;\n}\n\ninterface GlobOutput {\n files: string[];\n truncated: boolean;\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage', '.turbo'];\nconst WALK_CONCURRENCY = 16;\n\nexport const globTool: Tool<GlobInput, GlobOutput> = {\n name: 'glob',\n category: 'Filesystem',\n description:\n 'Find files matching a glob pattern. Fast way to discover relevant files before reading, grepping, or editing them.',\n usageHint:\n 'RECOMMENDED FOR SCOPING SEARCHES:\\n\\n' +\n '- Use early to get a list of files you actually care about.\\n' +\n '- Combine with `path` and `limit`.\\n' +\n '- Default ignores common build/dependency directories.\\n' +\n 'Much more efficient than shell `find` for most use cases inside the agent.',\n selection: {\n doNotUseWhen: 'you need to search inside file contents.',\n useInstead: ['grep'],\n },\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'folder',\n maxOutputBytes: 65_536,\n timeoutMs: 5_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**\").',\n },\n path: {\n type: 'string',\n description: 'Base directory to search from (defaults to project root).',\n },\n limit: {\n type: 'integer',\n description: 'Maximum number of results to return (default 1000, max 5000).',\n },\n },\n required: ['pattern'],\n },\n async execute(input, ctx, opts) {\n if (!input?.pattern) throw new Error('glob: pattern is required');\n const signal = opts?.signal;\n // `safeResolveReal` validates that the input base \u2014 even if symlinked \u2014\n // resolves to a real path inside the project root (or `~/.wrongstack`).\n // Throws on escape, matching how single-file tools (`read`, `edit`,\n // `write`) reject out-of-root paths: the caller named the base explicitly.\n const base = input.path ? await safeResolveReal(input.path, ctx) : ctx.cwd;\n const limit = Math.max(1, Math.min(input.limit ?? 1000, 5000));\n\n const ignored = await readGitignore(base);\n const re = compileGlob(input.pattern);\n\n const results: { rel: string; mtime: number }[] = [];\n let truncated = false;\n const pushResult = async (full: string): Promise<void> => {\n // Bail before stat if a concurrent worker has already filled the budget \u2014\n // the limit is a global cap across all parallel walkers, not per-worker.\n if (truncated || results.length >= limit) {\n truncated = true;\n return;\n }\n try {\n const st = await fs.stat(full);\n // Re-check after the await: another worker may have filled the budget\n // while we were waiting on fs.stat.\n if (truncated || results.length >= limit) {\n truncated = true;\n return;\n }\n results.push({ rel: full, mtime: st.mtimeMs });\n if (results.length >= limit) truncated = true;\n } catch {\n // skip stat error\n }\n };\n const walk = async (dir: string, relPrefix: string): Promise<void> => {\n // Abort check per directory: a huge tree walk must stop promptly on\n // Ctrl+C instead of running to completion with a discarded result.\n if (signal?.aborted) {\n truncated = true;\n return;\n }\n /* v8 ignore start -- the inner limit guards (file push + post-recursion return) always stop first; this re-entry guard is defensive. */\n if (results.length >= limit) {\n truncated = true;\n return;\n }\n /* v8 ignore stop */\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n const subdirs: Array<{ full: string; rel: string }> = [];\n const matchedFiles: string[] = [];\n for (const e of entries) {\n const name = e.name;\n if (DEFAULT_IGNORE.includes(name)) continue;\n if (ignored.includes(name)) continue;\n const rel = relPrefix ? `${relPrefix}/${name}` : name;\n const full = path.join(dir, name);\n if (e.isDirectory()) {\n subdirs.push({ full, rel });\n } else if (e.isFile()) {\n re.lastIndex = 0;\n const relMatch = re.test(rel);\n re.lastIndex = 0;\n const nameMatch = re.test(name);\n if (relMatch || nameMatch) {\n matchedFiles.push(full);\n }\n } else if (e.isSymbolicLink()) {\n try {\n const st = await fs.stat(full);\n if (st.isDirectory()) {\n // CWE-59 containment: a symlink inside the workspace can point\n // outside it. Before recursing into it (or including the\n // resolved file in results), realpath the symlink and verify\n // its target is still inside the project root. Skip silently\n // on escape so a single bad symlink doesn't poison the whole\n // walk.\n const real = await fs.realpath(full);\n await assertRealInsideRoot(real, ctx);\n subdirs.push({ full, rel });\n } else if (st.isFile()) {\n const real = await fs.realpath(full);\n await assertRealInsideRoot(real, ctx);\n re.lastIndex = 0;\n const relMatch = re.test(rel);\n re.lastIndex = 0;\n const nameMatch = re.test(name);\n if (relMatch || nameMatch) matchedFiles.push(full);\n }\n } catch {\n // Skip broken symlink, stat error, OR out-of-root target. All\n // three should fail the walk without aborting the whole search.\n }\n }\n if (truncated) return;\n }\n await mapWithConcurrency(matchedFiles, WALK_CONCURRENCY, pushResult);\n if (truncated) return;\n // Subdir walks: each one re-checks the limit at entry (re-entry guard),\n // but we also stop dispatching new walks once truncated, so siblings of\n // a hit-limit subdir don't keep adding results.\n const remainingSubdirs = truncated ? [] : subdirs;\n await mapWithConcurrency(remainingSubdirs, WALK_CONCURRENCY, ({ full, rel }) => walk(full, rel));\n };\n await walk(base, '');\n results.sort((a, b) => b.mtime - a.mtime);\n return { files: results.map((r) => r.rel), truncated };\n },\n};\n\nasync function readGitignore(dir: string): Promise<string[]> {\n try {\n const raw = await fs.readFile(path.join(dir, '.gitignore'), 'utf8');\n return raw\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l && !l.startsWith('#'));\n } catch {\n return [];\n }\n}\n", "/**\n * Bounded-concurrency async map.\n *\n * Runs `fn` over `items` with at most `limit` in-flight promises. Order of\n * results matches input order. Errors reject the returned promise on the first\n * failure \u2014 the remaining in-flight work is not awaited; this matches\n * `Promise.all` semantics for callers that want fail-fast behavior.\n *\n * Lives here (rather than imported from `@wrongstack/bench`) because:\n * 1. tools sits below bench in the dependency graph \u2014 bench is a consumer of\n * tools, never the other way around.\n * 2. The semantics used by grep/glob are deliberately simple (fail-fast,\n * no cancellation, no progress) and don't need bench's richer options.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) return [];\n const effectiveLimit = Math.max(1, Math.min(limit | 0, items.length));\n const results: R[] = new Array(items.length);\n let nextIndex = 0;\n\n const worker = async (): Promise<void> => {\n while (true) {\n const i = nextIndex++;\n if (i >= items.length) return;\n results[i] = await fn(items[i] as T);\n }\n };\n\n await Promise.all(Array.from({ length: effectiveLimit }, worker));\n return results;\n}\n", "import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` \u2014 the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm \u2192 yarn \u2192 npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root\u2192out-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 \u2014 macOS `/var`\u2192`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n\u2026[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]\u2026\\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// \u2500\u2500\u2500 Command-output normalization (token-saving) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// 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) \u2014 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 \u2014 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]!, `\u2026 \u27E8repeated ${run}\u00D7\u27E9`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends \u2014 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\u2026[truncated ${total - kept} bytes]\u2026\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI \u2192 collapse\n * carriage-return progress \u2192 trim trailing whitespace \u2192 collapse identical\n * consecutive lines \u2192 squeeze blank-line runs \u2192 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 \u2192 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n"],
4
+ "sourcesContent": ["import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { compileGlob } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { mapWithConcurrency } from './_concurrency.js';\nimport { assertRealInsideRoot, safeResolveReal } from './_util.js';\n\ninterface GlobInput {\n pattern: string;\n path?: string | undefined;\n limit?: number | undefined;\n}\n\ninterface GlobOutput {\n files: string[];\n truncated: boolean;\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage', '.turbo'];\nconst WALK_CONCURRENCY = 16;\n\nexport const globTool: Tool<GlobInput, GlobOutput> = {\n name: 'glob',\n category: 'Filesystem',\n description:\n 'Find files by path pattern. Use index-backed `codebase-search` first for code symbols or concepts when it is live.',\n usageHint:\n 'PATH DISCOVERY AND SEARCH SCOPING:\\n\\n' +\n '- When `codebase-search` is live, use it first for code concepts; use `glob` for filenames, path patterns, and non-indexed files.\\n' +\n '- Combine with `path` and `limit`.\\n' +\n '- Default ignores common build/dependency directories.\\n' +\n 'Much more efficient than shell `find` for most use cases inside the agent.',\n selection: {\n doNotUseWhen: 'you need to search inside file contents.',\n useInstead: ['grep'],\n },\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'folder',\n maxOutputBytes: 65_536,\n timeoutMs: 5_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Glob pattern to match (e.g. \"**/*.ts\", \"src/**\").',\n },\n path: {\n type: 'string',\n description: 'Base directory to search from (defaults to project root).',\n },\n limit: {\n type: 'integer',\n description: 'Maximum number of results to return (default 1000, max 5000).',\n },\n },\n required: ['pattern'],\n },\n async execute(input, ctx, opts) {\n if (!input?.pattern) throw new Error('glob: pattern is required');\n const signal = opts?.signal;\n // `safeResolveReal` validates that the input base \u2014 even if symlinked \u2014\n // resolves to a real path inside the project root (or `~/.wrongstack`).\n // Throws on escape, matching how single-file tools (`read`, `edit`,\n // `write`) reject out-of-root paths: the caller named the base explicitly.\n const base = input.path ? await safeResolveReal(input.path, ctx) : ctx.cwd;\n const limit = Math.max(1, Math.min(input.limit ?? 1000, 5000));\n\n const ignored = await readGitignore(base);\n const re = compileGlob(input.pattern);\n\n const results: { rel: string; mtime: number }[] = [];\n let truncated = false;\n const pushResult = async (full: string): Promise<void> => {\n // Bail before stat if a concurrent worker has already filled the budget \u2014\n // the limit is a global cap across all parallel walkers, not per-worker.\n if (truncated || results.length >= limit) {\n truncated = true;\n return;\n }\n try {\n const st = await fs.stat(full);\n // Re-check after the await: another worker may have filled the budget\n // while we were waiting on fs.stat.\n if (truncated || results.length >= limit) {\n truncated = true;\n return;\n }\n results.push({ rel: full, mtime: st.mtimeMs });\n if (results.length >= limit) truncated = true;\n } catch {\n // skip stat error\n }\n };\n const walk = async (dir: string, relPrefix: string): Promise<void> => {\n // Abort check per directory: a huge tree walk must stop promptly on\n // Ctrl+C instead of running to completion with a discarded result.\n if (signal?.aborted) {\n truncated = true;\n return;\n }\n /* v8 ignore start -- the inner limit guards (file push + post-recursion return) always stop first; this re-entry guard is defensive. */\n if (results.length >= limit) {\n truncated = true;\n return;\n }\n /* v8 ignore stop */\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n const subdirs: Array<{ full: string; rel: string }> = [];\n const matchedFiles: string[] = [];\n for (const e of entries) {\n const name = e.name;\n if (DEFAULT_IGNORE.includes(name)) continue;\n if (ignored.includes(name)) continue;\n const rel = relPrefix ? `${relPrefix}/${name}` : name;\n const full = path.join(dir, name);\n if (e.isDirectory()) {\n subdirs.push({ full, rel });\n } else if (e.isFile()) {\n re.lastIndex = 0;\n const relMatch = re.test(rel);\n re.lastIndex = 0;\n const nameMatch = re.test(name);\n if (relMatch || nameMatch) {\n matchedFiles.push(full);\n }\n } else if (e.isSymbolicLink()) {\n try {\n const st = await fs.stat(full);\n if (st.isDirectory()) {\n // CWE-59 containment: a symlink inside the workspace can point\n // outside it. Before recursing into it (or including the\n // resolved file in results), realpath the symlink and verify\n // its target is still inside the project root. Skip silently\n // on escape so a single bad symlink doesn't poison the whole\n // walk.\n const real = await fs.realpath(full);\n await assertRealInsideRoot(real, ctx);\n subdirs.push({ full, rel });\n } else if (st.isFile()) {\n const real = await fs.realpath(full);\n await assertRealInsideRoot(real, ctx);\n re.lastIndex = 0;\n const relMatch = re.test(rel);\n re.lastIndex = 0;\n const nameMatch = re.test(name);\n if (relMatch || nameMatch) matchedFiles.push(full);\n }\n } catch {\n // Skip broken symlink, stat error, OR out-of-root target. All\n // three should fail the walk without aborting the whole search.\n }\n }\n if (truncated) return;\n }\n await mapWithConcurrency(matchedFiles, WALK_CONCURRENCY, pushResult);\n if (truncated) return;\n // Subdir walks: each one re-checks the limit at entry (re-entry guard),\n // but we also stop dispatching new walks once truncated, so siblings of\n // a hit-limit subdir don't keep adding results.\n const remainingSubdirs = truncated ? [] : subdirs;\n await mapWithConcurrency(remainingSubdirs, WALK_CONCURRENCY, ({ full, rel }) => walk(full, rel));\n };\n await walk(base, '');\n results.sort((a, b) => b.mtime - a.mtime);\n return { files: results.map((r) => r.rel), truncated };\n },\n};\n\nasync function readGitignore(dir: string): Promise<string[]> {\n try {\n const raw = await fs.readFile(path.join(dir, '.gitignore'), 'utf8');\n return raw\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l && !l.startsWith('#'));\n } catch {\n return [];\n }\n}\n", "/**\n * Bounded-concurrency async map.\n *\n * Runs `fn` over `items` with at most `limit` in-flight promises. Order of\n * results matches input order. Errors reject the returned promise on the first\n * failure \u2014 the remaining in-flight work is not awaited; this matches\n * `Promise.all` semantics for callers that want fail-fast behavior.\n *\n * Lives here (rather than imported from `@wrongstack/bench`) because:\n * 1. tools sits below bench in the dependency graph \u2014 bench is a consumer of\n * tools, never the other way around.\n * 2. The semantics used by grep/glob are deliberately simple (fail-fast,\n * no cancellation, no progress) and don't need bench's richer options.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) return [];\n const effectiveLimit = Math.max(1, Math.min(limit | 0, items.length));\n const results: R[] = new Array(items.length);\n let nextIndex = 0;\n\n const worker = async (): Promise<void> => {\n while (true) {\n const i = nextIndex++;\n if (i >= items.length) return;\n results[i] = await fn(items[i] as T);\n }\n };\n\n await Promise.all(Array.from({ length: effectiveLimit }, worker));\n return results;\n}\n", "import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` \u2014 the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm \u2192 yarn \u2192 npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root\u2192out-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 \u2014 macOS `/var`\u2192`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n\u2026[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]\u2026\\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// \u2500\u2500\u2500 Command-output normalization (token-saving) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// 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) \u2014 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 \u2014 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]!, `\u2026 \u27E8repeated ${run}\u00D7\u27E9`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends \u2014 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\u2026[truncated ${total - kept} bytes]\u2026\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI \u2192 collapse\n * carriage-return progress \u2192 trim trailing whitespace \u2192 collapse identical\n * consecutive lines \u2192 squeeze blank-line runs \u2192 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 \u2192 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n"],
5
5
  "mappings": ";AAAA,YAAY,QAAQ;AACpB,YAAYA,WAAU;AACtB,SAAS,mBAAmB;;;ACY5B,eAAsB,mBACpB,OACA,OACA,IACc;AACd,MAAI,MAAM,WAAW,EAAG,QAAO,CAAC;AAChC,QAAM,iBAAiB,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,GAAG,MAAM,MAAM,CAAC;AACpE,QAAM,UAAe,IAAI,MAAM,MAAM,MAAM;AAC3C,MAAI,YAAY;AAEhB,QAAM,SAAS,YAA2B;AACxC,WAAO,MAAM;AACX,YAAM,IAAI;AACV,UAAI,KAAK,MAAM,OAAQ;AACvB,cAAQ,CAAC,IAAI,MAAM,GAAG,MAAM,CAAC,CAAM;AAAA,IACrC;AAAA,EACF;AAEA,QAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,eAAe,GAAG,MAAM,CAAC;AAChE,SAAO;AACT;;;ACjCA,YAAY,SAAS;AACrB,YAAY,UAAU;AACtB,YAAY,UAAU;AAqCf,SAAS,YAAY,OAAe,KAAsB;AAC/D,SAAY,gBAAW,KAAK,IAAS,eAAU,KAAK,IAAS,aAAQ,IAAI,cAAc,IAAI,KAAK,KAAK;AACvG;AAOA,SAAS,aAAa,KAAwB;AAC5C,SAAO,CAAM,aAAQ,IAAI,WAAW,GAAQ,aAAa,sB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,IAAI,GAAG,QAAQ,CAAC;CACvB;AAOD,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,EAAE,UAAU,CAqGhD,CAAC"}
package/dist/grep.js CHANGED
@@ -107,8 +107,8 @@ var NATIVE_MAX_FILE_BYTES = 1e6;
107
107
  var grepTool = {
108
108
  name: "grep",
109
109
  category: "Search",
110
- description: "Search across files using a regular expression. This is one of the primary code search tools. Prefers ripgrep for speed and features when available.",
111
- usageHint: 'POWERFUL CODE SEARCH TOOL:\n\n- `pattern` is a regular expression.\n- Use `output_mode: "content"` (default) to get matching lines with context.\n- Use `"files_with_matches"` when you only need the list of files.\n- Use `"count"` for quick statistics.\n- `glob` and `path` let you narrow the search scope significantly.\n- Always prefer this over `bash grep` when searching code.',
110
+ description: "Search exact file contents using a regular expression. Use index-backed `codebase-search` first for symbol or concept discovery when it is live. Prefers ripgrep for speed and features when available.",
111
+ usageHint: 'EXACT-TEXT AND REGEX SEARCH:\n\n- When `codebase-search` is live, use it first for symbols and concepts; use `grep` for exact text, regexes, unsupported content, and concrete usage sites.\n- `pattern` is a regular expression.\n- Use `output_mode: "content"` (default) to get matching lines with context.\n- Use `"files_with_matches"` when you only need the list of files.\n- Use `"count"` for quick statistics.\n- `glob` and `path` let you narrow the search scope significantly.\n- Always prefer this over `bash grep` when searching code.',
112
112
  selection: {
113
113
  doNotUseWhen: "you only need to locate files by name or path pattern.",
114
114
  useInstead: ["glob"]
package/dist/grep.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/grep.ts", "../src/_concurrency.ts", "../src/_regex.ts", "../src/_util.ts"],
4
- "sourcesContent": ["import { expectDefined } from '@wrongstack/core';\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Tool, ToolStreamEvent } from '@wrongstack/core';\nimport { buildChildEnv, compileGlob, ToolValidationError } from '@wrongstack/core';\nimport { mapWithConcurrency } from './_concurrency.js';\nimport { capSubject, compileUserRegex } from './_regex.js';\nimport { isBinaryBuffer, safeResolve } from './_util.js';\ninterface GrepInput {\n pattern: string;\n path?: string | undefined;\n glob?: string | undefined;\n output_mode?: 'content' | 'files_with_matches' | 'count' | undefined;\n context_lines?: number | undefined;\n case_insensitive?: boolean | undefined;\n limit?: number | undefined;\n}\n\ninterface GrepOutput {\n matches: string[];\n count: number;\n truncated: boolean;\n used: 'rg' | 'native';\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage'];\nconst NATIVE_SCAN_CONCURRENCY = 32;\nconst NATIVE_READ_CHUNK_BYTES = 64 * 1024;\nconst NATIVE_MAX_FILE_BYTES = 1_000_000;\n\nexport const grepTool: Tool<GrepInput, GrepOutput> = {\n name: 'grep',\n category: 'Search',\n description:\n 'Search across files using a regular expression. This is one of the primary code search tools. ' +\n 'Prefers ripgrep for speed and features when available.',\n usageHint:\n 'POWERFUL CODE SEARCH TOOL:\\n\\n' +\n '- `pattern` is a regular expression.\\n' +\n '- Use `output_mode: \"content\"` (default) to get matching lines with context.\\n' +\n '- Use `\"files_with_matches\"` when you only need the list of files.\\n' +\n '- Use `\"count\"` for quick statistics.\\n' +\n '- `glob` and `path` let you narrow the search scope significantly.\\n' +\n '- Always prefer this over `bash grep` when searching code.',\n selection: {\n doNotUseWhen: 'you only need to locate files by name or path pattern.',\n useInstead: ['glob'],\n },\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'search',\n maxOutputBytes: 131_072,\n timeoutMs: 10_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Regular expression pattern to search for in file contents.',\n },\n path: {\n type: 'string',\n description: 'Limit search to this directory or file (relative to project root).',\n },\n glob: {\n type: 'string',\n description: 'Glob filter for which files to include (e.g. \"**/*.ts\", \"src/**\").',\n },\n output_mode: {\n type: 'string',\n enum: ['content', 'files_with_matches', 'count'],\n description: 'Return style: detailed matches, just file list, or count only.',\n },\n context_lines: {\n type: 'integer',\n description: 'How many lines of surrounding context to include with each match.',\n },\n case_insensitive: {\n type: 'boolean',\n description: 'Ignore case when matching.',\n },\n limit: {\n type: 'integer',\n description: 'Maximum number of matches to return.',\n },\n },\n required: ['pattern'],\n },\n async execute(input, ctx, opts) {\n let final: GrepOutput | undefined;\n const executeStream = grepTool.executeStream;\n if (!executeStream) throw new Error('grepTool: 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('grep: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx, opts): AsyncGenerator<ToolStreamEvent<GrepOutput>> {\n if (!input?.pattern) {\n throw new ToolValidationError({\n message: 'grep: pattern is required',\n field: 'pattern',\n });\n }\n const base = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const mode = input.output_mode ?? 'content';\n const limit = Math.max(1, Math.min(input.limit ?? 200, 2000));\n const validation = compileUserRegex(input.pattern, input.case_insensitive ? 'i' : '');\n if (!validation.ok) {\n throw new ToolValidationError({\n message: `grep: ${validation.reason}`,\n field: 'pattern',\n });\n }\n\n const rgAvailable = await detectRg(opts.signal);\n if (rgAvailable) {\n try {\n yield* runRgStream(input, base, mode, limit, opts.signal);\n return;\n } catch {\n // fall through to native\n }\n }\n yield { type: 'log', text: 'Falling back to native grep\u2026' };\n const out = await runNative(input, base, mode, limit, opts.signal);\n yield { type: 'final', output: out };\n },\n};\n\nasync function detectRg(signal: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n try {\n const p = spawn('rg', ['--version'], { env: buildChildEnv(), stdio: 'ignore', signal, windowsHide: true });\n p.on('error', () => resolve(false));\n p.on('close', (code) => resolve(code === 0));\n } catch {\n resolve(false);\n }\n });\n}\n\nasync function* runRgStream(\n input: GrepInput,\n base: string,\n mode: 'content' | 'files_with_matches' | 'count',\n limit: number,\n signal: AbortSignal,\n): AsyncGenerator<ToolStreamEvent<GrepOutput>> {\n const args: string[] = ['--no-heading'];\n if (input.case_insensitive) args.push('-i');\n if (mode === 'files_with_matches') args.push('-l');\n if (mode === 'count') args.push('-c');\n if (mode === 'content') {\n args.push('-n');\n if (input.context_lines) args.push('-C', String(input.context_lines));\n }\n for (const ignored of DEFAULT_IGNORE) {\n args.push('--glob', `!${ignored}/**`, '--glob', `!**/${ignored}/**`);\n }\n if (input.glob) args.push('--glob', input.glob);\n args.push('--', input.pattern, base);\n\n const matches: string[] = [];\n let buf = '';\n let totalLines = 0;\n let totalCount = 0;\n let batchSinceFlush = 0;\n const FLUSH_AT = 16; // yield a partial_output every 16 matches\n // Cap on the in-progress line buffer. Without this, a single huge \"line\"\n // (e.g. a file with no newlines under a symlink) plus a fast producer\n // would let `buf` grow unbounded. 1 MB comfortably holds any realistic\n // grep hit; beyond that we kill the child and surface a truncation.\n const MAX_BUF_BYTES = 1_000_000;\n let bufOverflow = false;\n\n const child = spawn('rg', args, { signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });\n\n type Chunk = { kind: 'out' | 'close' | 'error'; data: string };\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 child.stdout?.on('data', (c) => {\n queue.push({ kind: 'out', data: c.toString() });\n wake();\n });\n child.on('error', (e) => {\n queue.push({ kind: 'error', data: e.message });\n wake();\n });\n child.on('close', () => {\n queue.push({ kind: 'close', data: '' });\n wake();\n });\n\n let pendingBatch: string[] = [];\n let errored = false;\n for (;;) {\n while (queue.length === 0) {\n await new Promise<void>((r) => {\n waiter = r;\n });\n }\n const c = expectDefined(queue.shift());\n if (c.kind === 'error') {\n errored = true;\n continue;\n }\n if (c.kind === 'close') break;\n buf += c.data;\n // Guard against a pathological producer (e.g. matching a huge binary\n // without newlines) pinning memory. Kill the child and mark the result\n // truncated; whatever we already captured stays intact.\n if (buf.length > MAX_BUF_BYTES && !bufOverflow) {\n bufOverflow = true;\n buf = buf.slice(-MAX_BUF_BYTES);\n try {\n child.kill('SIGTERM');\n } catch {\n /* ignore */\n }\n }\n const idx = buf.lastIndexOf('\\n');\n if (idx === -1) continue;\n const ready = buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n for (const line of ready.split('\\n')) {\n if (!line) continue;\n totalLines++;\n if (mode === 'count') totalCount += parseRgCountLine(line);\n if (matches.length < limit) {\n matches.push(line);\n pendingBatch.push(line);\n batchSinceFlush++;\n }\n }\n if (batchSinceFlush >= FLUSH_AT) {\n yield {\n type: 'partial_output',\n text: pendingBatch.join('\\n'),\n data: { matches_so_far: matches.length },\n };\n pendingBatch = [];\n batchSinceFlush = 0;\n }\n }\n\n if (buf.trim()) {\n for (const line of buf.split('\\n')) {\n if (!line) continue;\n totalLines++;\n if (mode === 'count') totalCount += parseRgCountLine(line);\n if (matches.length < limit) {\n matches.push(line);\n pendingBatch.push(line);\n }\n }\n }\n if (pendingBatch.length > 0) {\n yield {\n type: 'partial_output',\n text: pendingBatch.join('\\n'),\n data: { matches_so_far: matches.length },\n };\n }\n if (errored) throw new Error('rg: spawn error');\n\n yield {\n type: 'final',\n output: {\n matches,\n count: mode === 'count' ? totalCount : totalLines,\n truncated: totalLines > limit || bufOverflow,\n used: 'rg',\n },\n };\n}\n\nfunction parseRgCountLine(line: string): number {\n const idx = line.lastIndexOf(':');\n if (idx === -1) return 0;\n const n = Number.parseInt(line.slice(idx + 1), 10);\n return Number.isFinite(n) ? n : 0;\n}\n\nasync function runNative(\n input: GrepInput,\n base: string,\n mode: 'content' | 'files_with_matches' | 'count',\n limit: number,\n signal: AbortSignal,\n): Promise<GrepOutput> {\n const flags = input.case_insensitive ? 'i' : '';\n const compiled = compileUserRegex(input.pattern, flags);\n if (!compiled.ok) {\n throw new ToolValidationError({\n message: `grep: ${compiled.reason}`,\n field: 'pattern',\n });\n }\n const re = compiled.regex;\n const globRe = input.glob ? compileGlob(input.glob) : null;\n const matches: string[] = [];\n const countOnlyFirstHit = mode === 'count' && limit === 1;\n const maxBytes = mode === 'content' ? NATIVE_MAX_FILE_BYTES : Math.min(NATIVE_MAX_FILE_BYTES, 256 * 1024);\n let total = 0;\n let stopped = false;\n\n const scanFile = async (full: string, name: string): Promise<void> => {\n if (stopped || signal.aborted) return;\n if (globRe && !globRe.test(name) && !globRe.test(full)) return;\n if (globRe) globRe.lastIndex = 0;\n\n try {\n const stat = await fs.stat(full);\n if (!stat.isFile() || stat.size > maxBytes || stopped || signal.aborted) return;\n\n const file = await fs.open(full, 'r');\n try {\n let bytesReadTotal = 0;\n let lineNumber = 0;\n let fileHits = 0;\n let leftover = '';\n let binaryChecked = false;\n const buffer = Buffer.allocUnsafe(Math.min(NATIVE_READ_CHUNK_BYTES, maxBytes));\n\n while (!stopped && !signal.aborted && bytesReadTotal < maxBytes) {\n const remaining = maxBytes - bytesReadTotal;\n const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, remaining), null);\n if (bytesRead === 0) break;\n const chunk = buffer.subarray(0, bytesRead);\n if (!binaryChecked) {\n binaryChecked = true;\n if (isBinaryBuffer(chunk)) return;\n }\n bytesReadTotal += bytesRead;\n const text = leftover + chunk.toString('utf8');\n const lines = text.split(/\\r?\\n/);\n leftover = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n if (stopped || signal.aborted) break;\n lineNumber++;\n const ln = capSubject(rawLine);\n re.lastIndex = 0;\n if (!re.test(ln)) continue;\n\n fileHits++;\n total++;\n\n if (mode === 'content') {\n if (matches.length < limit) matches.push(`${full}:${lineNumber}:${ln}`);\n } else if (mode === 'files_with_matches') {\n if (fileHits === 1 && matches.length < limit) matches.push(full);\n break;\n } else if (fileHits === 1 && matches.length < limit) {\n matches.push(`${full}:${countOnlyFirstHit ? 1 : 0}`);\n }\n\n if (countOnlyFirstHit || (mode !== 'content' && matches.length >= limit)) {\n stopped = true;\n break;\n }\n }\n\n if (mode === 'files_with_matches' && fileHits > 0) break;\n }\n\n if (!stopped && !signal.aborted && leftover.length > 0) {\n lineNumber++;\n const ln = capSubject(leftover);\n re.lastIndex = 0;\n if (re.test(ln)) {\n fileHits++;\n total++;\n if (mode === 'content') {\n if (matches.length < limit) matches.push(`${full}:${lineNumber}:${ln}`);\n } else if (mode === 'files_with_matches') {\n if (matches.length < limit) matches.push(full);\n } else if (matches.length < limit) {\n matches.push(`${full}:${countOnlyFirstHit ? 1 : fileHits}`);\n }\n }\n }\n\n if (fileHits > 0) {\n if (mode === 'count') {\n const idx = matches.findIndex((entry) => entry.startsWith(`${full}:`));\n if (idx !== -1) matches[idx] = `${full}:${fileHits}`;\n }\n if (mode === 'files_with_matches' && matches.length >= limit) stopped = true;\n }\n\n if (mode === 'content' && matches.length >= limit) stopped = true;\n if (mode === 'count' && matches.length >= limit && (countOnlyFirstHit || mode !== 'count')) stopped = true;\n } finally {\n await file.close();\n }\n } catch {\n // skip read errors\n }\n };\n\n const walk = async (dir: string): Promise<void> => {\n if (stopped || signal.aborted) return;\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n const files: Array<{ full: string; name: string }> = [];\n const subdirs: string[] = [];\n for (const e of entries) {\n if (stopped) return;\n if (DEFAULT_IGNORE.includes(e.name)) continue;\n if (e.isSymbolicLink()) continue;\n const full = path.join(dir, e.name);\n if (e.isDirectory()) {\n subdirs.push(full);\n } else if (e.isFile()) {\n files.push({ full, name: e.name });\n }\n }\n await mapWithConcurrency(files, NATIVE_SCAN_CONCURRENCY, ({ full, name }) => scanFile(full, name));\n await mapWithConcurrency(subdirs, Math.min(16, NATIVE_SCAN_CONCURRENCY), walk);\n };\n await walk(base);\n\n return {\n matches,\n count: total,\n truncated: stopped,\n used: 'native',\n };\n}\n", "/**\n * Bounded-concurrency async map.\n *\n * Runs `fn` over `items` with at most `limit` in-flight promises. Order of\n * results matches input order. Errors reject the returned promise on the first\n * failure \u2014 the remaining in-flight work is not awaited; this matches\n * `Promise.all` semantics for callers that want fail-fast behavior.\n *\n * Lives here (rather than imported from `@wrongstack/bench`) because:\n * 1. tools sits below bench in the dependency graph \u2014 bench is a consumer of\n * tools, never the other way around.\n * 2. The semantics used by grep/glob are deliberately simple (fail-fast,\n * no cancellation, no progress) and don't need bench's richer options.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) return [];\n const effectiveLimit = Math.max(1, Math.min(limit | 0, items.length));\n const results: R[] = new Array(items.length);\n let nextIndex = 0;\n\n const worker = async (): Promise<void> => {\n while (true) {\n const i = nextIndex++;\n if (i >= items.length) return;\n results[i] = await fn(items[i] as T);\n }\n };\n\n await Promise.all(Array.from({ length: effectiveLimit }, worker));\n return results;\n}\n", "/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match \u2014 a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length \u2014 practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc \u2014 nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind \u2014 (?!.*a+)\n /[([][^)\\]]*[+*][^)\\]]*[)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking \u2014 rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n", "import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` \u2014 the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm \u2192 yarn \u2192 npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root\u2192out-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 \u2014 macOS `/var`\u2192`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n\u2026[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]\u2026\\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// \u2500\u2500\u2500 Command-output normalization (token-saving) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// 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) \u2014 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 \u2014 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]!, `\u2026 \u27E8repeated ${run}\u00D7\u27E9`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends \u2014 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\u2026[truncated ${total - kept} bytes]\u2026\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI \u2192 collapse\n * carriage-return progress \u2192 trim trailing whitespace \u2192 collapse identical\n * consecutive lines \u2192 squeeze blank-line runs \u2192 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 \u2192 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n"],
5
- "mappings": ";AAAA,SAAS,qBAAqB;AAC9B,SAAS,aAAa;AACtB,YAAY,QAAQ;AACpB,YAAYA,WAAU;AAEtB,SAAS,eAAe,aAAa,2BAA2B;;;ACShE,eAAsB,mBACpB,OACA,OACA,IACc;AACd,MAAI,MAAM,WAAW,EAAG,QAAO,CAAC;AAChC,QAAM,iBAAiB,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,GAAG,MAAM,MAAM,CAAC;AACpE,QAAM,UAAe,IAAI,MAAM,MAAM,MAAM;AAC3C,MAAI,YAAY;AAEhB,QAAM,SAAS,YAA2B;AACxC,WAAO,MAAM;AACX,YAAM,IAAI;AACV,UAAI,KAAK,MAAM,OAAQ;AACvB,cAAQ,CAAC,IAAI,MAAM,GAAG,MAAM,CAAC,CAAM;AAAA,IACrC;AAAA,EACF;AAEA,QAAM,QAAQ,IAAI,MAAM,KAAK,EAAE,QAAQ,eAAe,GAAG,MAAM,CAAC;AAChE,SAAO;AACT;;;ACXA,IAAM,kBAAkB;AAIxB,IAAM,qBAA4C;AAAA;AAAA,EAEhD;AAAA,EACA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AAAA;AAAA,EAEA;AACF;AAYO,SAAS,iBAAiB,SAAiB,OAA4C;AAC5F,MAAI,OAAO,YAAY,UAAU;AAC/B,WAAO,EAAE,IAAI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AAA,MACnB,WAAW,EAAE,OAAO,GAAG;AACrB,cAAM,KAAK,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AAAA,MACnC;AAAA,IACF;AACA,UAAM,mBAAmB,OAAO,yBAAyB,CAAC,EAAE,MAAM,KAAK,MAAM,SAAS,MAAM,IAAI,CAAC;AACjG,UAAM,mBAAmB,SAAS,KAAK,IAAI,IAAI,uBAAuB,GAAG,IAAI;AAAA,EAC/E;AACA,QAAM,KAAK,IAAI;AAEf,SAAO;AAAA,IACL;AAAA,IACA,OAAO;AAAA,IACP,WAAW;AAAA,IACX,MAAM;AAAA,EACR;AACF;",
4
+ "sourcesContent": ["import { expectDefined } from '@wrongstack/core';\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport type { Tool, ToolStreamEvent } from '@wrongstack/core';\nimport { buildChildEnv, compileGlob, ToolValidationError } from '@wrongstack/core';\nimport { mapWithConcurrency } from './_concurrency.js';\nimport { capSubject, compileUserRegex } from './_regex.js';\nimport { isBinaryBuffer, safeResolve } from './_util.js';\ninterface GrepInput {\n pattern: string;\n path?: string | undefined;\n glob?: string | undefined;\n output_mode?: 'content' | 'files_with_matches' | 'count' | undefined;\n context_lines?: number | undefined;\n case_insensitive?: boolean | undefined;\n limit?: number | undefined;\n}\n\ninterface GrepOutput {\n matches: string[];\n count: number;\n truncated: boolean;\n used: 'rg' | 'native';\n}\n\nconst DEFAULT_IGNORE = ['node_modules', '.git', 'dist', 'build', '.next', 'coverage'];\nconst NATIVE_SCAN_CONCURRENCY = 32;\nconst NATIVE_READ_CHUNK_BYTES = 64 * 1024;\nconst NATIVE_MAX_FILE_BYTES = 1_000_000;\n\nexport const grepTool: Tool<GrepInput, GrepOutput> = {\n name: 'grep',\n category: 'Search',\n description:\n 'Search exact file contents using a regular expression. Use index-backed `codebase-search` first for symbol or concept discovery when it is live. ' +\n 'Prefers ripgrep for speed and features when available.',\n usageHint:\n 'EXACT-TEXT AND REGEX SEARCH:\\n\\n' +\n '- When `codebase-search` is live, use it first for symbols and concepts; use `grep` for exact text, regexes, unsupported content, and concrete usage sites.\\n' +\n '- `pattern` is a regular expression.\\n' +\n '- Use `output_mode: \"content\"` (default) to get matching lines with context.\\n' +\n '- Use `\"files_with_matches\"` when you only need the list of files.\\n' +\n '- Use `\"count\"` for quick statistics.\\n' +\n '- `glob` and `path` let you narrow the search scope significantly.\\n' +\n '- Always prefer this over `bash grep` when searching code.',\n selection: {\n doNotUseWhen: 'you only need to locate files by name or path pattern.',\n useInstead: ['glob'],\n },\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'search',\n maxOutputBytes: 131_072,\n timeoutMs: 10_000,\n inputSchema: {\n type: 'object',\n properties: {\n pattern: {\n type: 'string',\n description: 'Regular expression pattern to search for in file contents.',\n },\n path: {\n type: 'string',\n description: 'Limit search to this directory or file (relative to project root).',\n },\n glob: {\n type: 'string',\n description: 'Glob filter for which files to include (e.g. \"**/*.ts\", \"src/**\").',\n },\n output_mode: {\n type: 'string',\n enum: ['content', 'files_with_matches', 'count'],\n description: 'Return style: detailed matches, just file list, or count only.',\n },\n context_lines: {\n type: 'integer',\n description: 'How many lines of surrounding context to include with each match.',\n },\n case_insensitive: {\n type: 'boolean',\n description: 'Ignore case when matching.',\n },\n limit: {\n type: 'integer',\n description: 'Maximum number of matches to return.',\n },\n },\n required: ['pattern'],\n },\n async execute(input, ctx, opts) {\n let final: GrepOutput | undefined;\n const executeStream = grepTool.executeStream;\n if (!executeStream) throw new Error('grepTool: 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('grep: stream ended without final event');\n return final;\n },\n async *executeStream(input, ctx, opts): AsyncGenerator<ToolStreamEvent<GrepOutput>> {\n if (!input?.pattern) {\n throw new ToolValidationError({\n message: 'grep: pattern is required',\n field: 'pattern',\n });\n }\n const base = input.path ? safeResolve(input.path, ctx) : ctx.cwd;\n const mode = input.output_mode ?? 'content';\n const limit = Math.max(1, Math.min(input.limit ?? 200, 2000));\n const validation = compileUserRegex(input.pattern, input.case_insensitive ? 'i' : '');\n if (!validation.ok) {\n throw new ToolValidationError({\n message: `grep: ${validation.reason}`,\n field: 'pattern',\n });\n }\n\n const rgAvailable = await detectRg(opts.signal);\n if (rgAvailable) {\n try {\n yield* runRgStream(input, base, mode, limit, opts.signal);\n return;\n } catch {\n // fall through to native\n }\n }\n yield { type: 'log', text: 'Falling back to native grep\u2026' };\n const out = await runNative(input, base, mode, limit, opts.signal);\n yield { type: 'final', output: out };\n },\n};\n\nasync function detectRg(signal: AbortSignal): Promise<boolean> {\n return new Promise((resolve) => {\n try {\n const p = spawn('rg', ['--version'], { env: buildChildEnv(), stdio: 'ignore', signal, windowsHide: true });\n p.on('error', () => resolve(false));\n p.on('close', (code) => resolve(code === 0));\n } catch {\n resolve(false);\n }\n });\n}\n\nasync function* runRgStream(\n input: GrepInput,\n base: string,\n mode: 'content' | 'files_with_matches' | 'count',\n limit: number,\n signal: AbortSignal,\n): AsyncGenerator<ToolStreamEvent<GrepOutput>> {\n const args: string[] = ['--no-heading'];\n if (input.case_insensitive) args.push('-i');\n if (mode === 'files_with_matches') args.push('-l');\n if (mode === 'count') args.push('-c');\n if (mode === 'content') {\n args.push('-n');\n if (input.context_lines) args.push('-C', String(input.context_lines));\n }\n for (const ignored of DEFAULT_IGNORE) {\n args.push('--glob', `!${ignored}/**`, '--glob', `!**/${ignored}/**`);\n }\n if (input.glob) args.push('--glob', input.glob);\n args.push('--', input.pattern, base);\n\n const matches: string[] = [];\n let buf = '';\n let totalLines = 0;\n let totalCount = 0;\n let batchSinceFlush = 0;\n const FLUSH_AT = 16; // yield a partial_output every 16 matches\n // Cap on the in-progress line buffer. Without this, a single huge \"line\"\n // (e.g. a file with no newlines under a symlink) plus a fast producer\n // would let `buf` grow unbounded. 1 MB comfortably holds any realistic\n // grep hit; beyond that we kill the child and surface a truncation.\n const MAX_BUF_BYTES = 1_000_000;\n let bufOverflow = false;\n\n const child = spawn('rg', args, { signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });\n\n type Chunk = { kind: 'out' | 'close' | 'error'; data: string };\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 child.stdout?.on('data', (c) => {\n queue.push({ kind: 'out', data: c.toString() });\n wake();\n });\n child.on('error', (e) => {\n queue.push({ kind: 'error', data: e.message });\n wake();\n });\n child.on('close', () => {\n queue.push({ kind: 'close', data: '' });\n wake();\n });\n\n let pendingBatch: string[] = [];\n let errored = false;\n for (;;) {\n while (queue.length === 0) {\n await new Promise<void>((r) => {\n waiter = r;\n });\n }\n const c = expectDefined(queue.shift());\n if (c.kind === 'error') {\n errored = true;\n continue;\n }\n if (c.kind === 'close') break;\n buf += c.data;\n // Guard against a pathological producer (e.g. matching a huge binary\n // without newlines) pinning memory. Kill the child and mark the result\n // truncated; whatever we already captured stays intact.\n if (buf.length > MAX_BUF_BYTES && !bufOverflow) {\n bufOverflow = true;\n buf = buf.slice(-MAX_BUF_BYTES);\n try {\n child.kill('SIGTERM');\n } catch {\n /* ignore */\n }\n }\n const idx = buf.lastIndexOf('\\n');\n if (idx === -1) continue;\n const ready = buf.slice(0, idx);\n buf = buf.slice(idx + 1);\n for (const line of ready.split('\\n')) {\n if (!line) continue;\n totalLines++;\n if (mode === 'count') totalCount += parseRgCountLine(line);\n if (matches.length < limit) {\n matches.push(line);\n pendingBatch.push(line);\n batchSinceFlush++;\n }\n }\n if (batchSinceFlush >= FLUSH_AT) {\n yield {\n type: 'partial_output',\n text: pendingBatch.join('\\n'),\n data: { matches_so_far: matches.length },\n };\n pendingBatch = [];\n batchSinceFlush = 0;\n }\n }\n\n if (buf.trim()) {\n for (const line of buf.split('\\n')) {\n if (!line) continue;\n totalLines++;\n if (mode === 'count') totalCount += parseRgCountLine(line);\n if (matches.length < limit) {\n matches.push(line);\n pendingBatch.push(line);\n }\n }\n }\n if (pendingBatch.length > 0) {\n yield {\n type: 'partial_output',\n text: pendingBatch.join('\\n'),\n data: { matches_so_far: matches.length },\n };\n }\n if (errored) throw new Error('rg: spawn error');\n\n yield {\n type: 'final',\n output: {\n matches,\n count: mode === 'count' ? totalCount : totalLines,\n truncated: totalLines > limit || bufOverflow,\n used: 'rg',\n },\n };\n}\n\nfunction parseRgCountLine(line: string): number {\n const idx = line.lastIndexOf(':');\n if (idx === -1) return 0;\n const n = Number.parseInt(line.slice(idx + 1), 10);\n return Number.isFinite(n) ? n : 0;\n}\n\nasync function runNative(\n input: GrepInput,\n base: string,\n mode: 'content' | 'files_with_matches' | 'count',\n limit: number,\n signal: AbortSignal,\n): Promise<GrepOutput> {\n const flags = input.case_insensitive ? 'i' : '';\n const compiled = compileUserRegex(input.pattern, flags);\n if (!compiled.ok) {\n throw new ToolValidationError({\n message: `grep: ${compiled.reason}`,\n field: 'pattern',\n });\n }\n const re = compiled.regex;\n const globRe = input.glob ? compileGlob(input.glob) : null;\n const matches: string[] = [];\n const countOnlyFirstHit = mode === 'count' && limit === 1;\n const maxBytes = mode === 'content' ? NATIVE_MAX_FILE_BYTES : Math.min(NATIVE_MAX_FILE_BYTES, 256 * 1024);\n let total = 0;\n let stopped = false;\n\n const scanFile = async (full: string, name: string): Promise<void> => {\n if (stopped || signal.aborted) return;\n if (globRe && !globRe.test(name) && !globRe.test(full)) return;\n if (globRe) globRe.lastIndex = 0;\n\n try {\n const stat = await fs.stat(full);\n if (!stat.isFile() || stat.size > maxBytes || stopped || signal.aborted) return;\n\n const file = await fs.open(full, 'r');\n try {\n let bytesReadTotal = 0;\n let lineNumber = 0;\n let fileHits = 0;\n let leftover = '';\n let binaryChecked = false;\n const buffer = Buffer.allocUnsafe(Math.min(NATIVE_READ_CHUNK_BYTES, maxBytes));\n\n while (!stopped && !signal.aborted && bytesReadTotal < maxBytes) {\n const remaining = maxBytes - bytesReadTotal;\n const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, remaining), null);\n if (bytesRead === 0) break;\n const chunk = buffer.subarray(0, bytesRead);\n if (!binaryChecked) {\n binaryChecked = true;\n if (isBinaryBuffer(chunk)) return;\n }\n bytesReadTotal += bytesRead;\n const text = leftover + chunk.toString('utf8');\n const lines = text.split(/\\r?\\n/);\n leftover = lines.pop() ?? '';\n\n for (const rawLine of lines) {\n if (stopped || signal.aborted) break;\n lineNumber++;\n const ln = capSubject(rawLine);\n re.lastIndex = 0;\n if (!re.test(ln)) continue;\n\n fileHits++;\n total++;\n\n if (mode === 'content') {\n if (matches.length < limit) matches.push(`${full}:${lineNumber}:${ln}`);\n } else if (mode === 'files_with_matches') {\n if (fileHits === 1 && matches.length < limit) matches.push(full);\n break;\n } else if (fileHits === 1 && matches.length < limit) {\n matches.push(`${full}:${countOnlyFirstHit ? 1 : 0}`);\n }\n\n if (countOnlyFirstHit || (mode !== 'content' && matches.length >= limit)) {\n stopped = true;\n break;\n }\n }\n\n if (mode === 'files_with_matches' && fileHits > 0) break;\n }\n\n if (!stopped && !signal.aborted && leftover.length > 0) {\n lineNumber++;\n const ln = capSubject(leftover);\n re.lastIndex = 0;\n if (re.test(ln)) {\n fileHits++;\n total++;\n if (mode === 'content') {\n if (matches.length < limit) matches.push(`${full}:${lineNumber}:${ln}`);\n } else if (mode === 'files_with_matches') {\n if (matches.length < limit) matches.push(full);\n } else if (matches.length < limit) {\n matches.push(`${full}:${countOnlyFirstHit ? 1 : fileHits}`);\n }\n }\n }\n\n if (fileHits > 0) {\n if (mode === 'count') {\n const idx = matches.findIndex((entry) => entry.startsWith(`${full}:`));\n if (idx !== -1) matches[idx] = `${full}:${fileHits}`;\n }\n if (mode === 'files_with_matches' && matches.length >= limit) stopped = true;\n }\n\n if (mode === 'content' && matches.length >= limit) stopped = true;\n if (mode === 'count' && matches.length >= limit && (countOnlyFirstHit || mode !== 'count')) stopped = true;\n } finally {\n await file.close();\n }\n } catch {\n // skip read errors\n }\n };\n\n const walk = async (dir: string): Promise<void> => {\n if (stopped || signal.aborted) return;\n let entries: import('node:fs').Dirent[];\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n const files: Array<{ full: string; name: string }> = [];\n const subdirs: string[] = [];\n for (const e of entries) {\n if (stopped) return;\n if (DEFAULT_IGNORE.includes(e.name)) continue;\n if (e.isSymbolicLink()) continue;\n const full = path.join(dir, e.name);\n if (e.isDirectory()) {\n subdirs.push(full);\n } else if (e.isFile()) {\n files.push({ full, name: e.name });\n }\n }\n await mapWithConcurrency(files, NATIVE_SCAN_CONCURRENCY, ({ full, name }) => scanFile(full, name));\n await mapWithConcurrency(subdirs, Math.min(16, NATIVE_SCAN_CONCURRENCY), walk);\n };\n await walk(base);\n\n return {\n matches,\n count: total,\n truncated: stopped,\n used: 'native',\n };\n}\n", "/**\n * Bounded-concurrency async map.\n *\n * Runs `fn` over `items` with at most `limit` in-flight promises. Order of\n * results matches input order. Errors reject the returned promise on the first\n * failure \u2014 the remaining in-flight work is not awaited; this matches\n * `Promise.all` semantics for callers that want fail-fast behavior.\n *\n * Lives here (rather than imported from `@wrongstack/bench`) because:\n * 1. tools sits below bench in the dependency graph \u2014 bench is a consumer of\n * tools, never the other way around.\n * 2. The semantics used by grep/glob are deliberately simple (fail-fast,\n * no cancellation, no progress) and don't need bench's richer options.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n if (items.length === 0) return [];\n const effectiveLimit = Math.max(1, Math.min(limit | 0, items.length));\n const results: R[] = new Array(items.length);\n let nextIndex = 0;\n\n const worker = async (): Promise<void> => {\n while (true) {\n const i = nextIndex++;\n if (i >= items.length) return;\n results[i] = await fn(items[i] as T);\n }\n };\n\n await Promise.all(Array.from({ length: effectiveLimit }, worker));\n return results;\n}\n", "/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match \u2014 a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length \u2014 practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc \u2014 nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind \u2014 (?!.*a+)\n /[([][^)\\]]*[+*][^)\\]]*[)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking \u2014 rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n", "import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` \u2014 the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm \u2192 yarn \u2192 npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root\u2192out-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 \u2014 macOS `/var`\u2192`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n\u2026[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]\u2026\\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// \u2500\u2500\u2500 Command-output normalization (token-saving) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// 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) \u2014 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 \u2014 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]!, `\u2026 \u27E8repeated ${run}\u00D7\u27E9`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends \u2014 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\u2026[truncated ${total - kept} bytes]\u2026\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI \u2192 collapse\n * carriage-return progress \u2192 trim trailing whitespace \u2192 collapse identical\n * consecutive lines \u2192 squeeze blank-line runs \u2192 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 \u2192 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n"],
5
+ "mappings": ";AAAA,SAAS,qBAAqB;AAC9B,SAAS,aAAa;AACtB,YAAY,QAAQ;AACpB,YAAYA,WAAU;AAEtB,SAAS,eAAe,aAAa,2BAA2B;;;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AS,wBAAwB,QAAQ,UAAU,MAAO,WAAU;AAAA,QAC1E;AAEA,YAAI,SAAS,aAAa,QAAQ,UAAU,MAAO,WAAU;AAC7D,YAAI,SAAS,WAAW,QAAQ,UAAU,UAAU,qBAAqB,SAAS,SAAU,WAAU;AAAA,MACxG,UAAE;AACA,cAAM,KAAK,MAAM;AAAA,MACnB;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,QAAM,OAAO,OAAO,QAA+B;AACjD,QAAI,WAAW,OAAO,QAAS;AAC/B,QAAI;AACJ,QAAI;AACF,gBAAU,MAAS,WAAQ,KAAK,EAAE,eAAe,KAAK,CAAC;AAAA,IACzD,QAAQ;AACN;AAAA,IACF;AACA,UAAM,QAA+C,CAAC;AACtD,UAAM,UAAoB,CAAC;AAC3B,eAAW,KAAK,SAAS;AACvB,UAAI,QAAS;AACb,UAAI,eAAe,SAAS,EAAE,IAAI,EAAG;AACrC,UAAI,EAAE,eAAe,EAAG;AACxB,YAAM,OAAY,WAAK,KAAK,EAAE,IAAI;AAClC,UAAI,EAAE,YAAY,GAAG;AACnB,gBAAQ,KAAK,IAAI;AAAA,MACnB,WAAW,EAAE,OAAO,GAAG;AACrB,cAAM,KAAK,EAAE,MAAM,MAAM,EAAE,KAAK,CAAC;AAAA,MACnC;AAAA,IACF;AACA,UAAM,mBAAmB,OAAO,yBAAyB,CAAC,EAAE,MAAM,KAAK,MAAM,SAAS,MAAM,IAAI,CAAC;AACjG,UAAM,mBAAmB,SAAS,KAAK,IAAI,IAAI,uBAAuB,GAAG,IAAI;AAAA,EAC/E;AACA,QAAM,KAAK,IAAI;AAEf,SAAO;AAAA,IACL;AAAA,IACA,OAAO;AAAA,IACP,WAAW;AAAA,IACX,MAAM;AAAA,EACR;AACF;",
6
6
  "names": ["path", "resolve", "stat"]
7
7
  }
package/dist/index.d.ts CHANGED
@@ -8,7 +8,8 @@ export * from './browser/index.js';
8
8
  export { builtinTools, OPTIONAL_TOOLS, TIER1_TOOLS, TIER2_TOOLS, TIER3_TOOLS } from './builtin.js';
9
9
  export { CircuitBreaker, type CircuitBreakerConfig, type CircuitBreakerSnapshot, } from './circuit-breaker.js';
10
10
  export type { CircuitSnapshot, CircuitState } from './codebase-index/index.js';
11
- export { CircuitOpenError, cancelPendingReindexes, codebaseIndexStats, codebaseIndexTool, codebaseSearchTool, codebaseStatsTool, enqueueReindex, getIndexState, IndexCircuitBreaker, IndexTimeoutError, indexCircuitBreaker, isIndexableFile, isIndexing, isIndexReady, onIndexStateChange, resetIndexCircuitBreaker, runStartupIndex, searchCodebaseIndex, shutdownCodebaseIndexHost, } from './codebase-index/index.js';
11
+ export { CircuitOpenError, cancelPendingReindexes, codebaseIndexStats, codebaseIndexTool, codebaseSearchTool, codebaseStatsTool, enqueueReindex, getIndexState, IndexCircuitBreaker, IndexTimeoutError, indexCircuitBreaker, isIndexableFile, isIndexing, isIndexReady, onIndexStateChange, resetIndexCircuitBreaker, runStartupIndex, searchCodebaseIndex, shutdownCodebaseIndexHost, fileGraphService, packageGraphService, symbolGraphService, } from './codebase-index/index.js';
12
+ export type { CodeMapGraph, GraphEdge, GraphNode, } from './codebase-index/index.js';
12
13
  export { designTool } from './design.js';
13
14
  export { diffTool } from './diff.js';
14
15
  export { documentTool } from './document.js';
@@ -40,7 +41,7 @@ export { readTool } from './read.js';
40
41
  export { replaceTool } from './replace.js';
41
42
  export { scaffoldTool } from './scaffold.js';
42
43
  export { searchTool } from './search.js';
43
- export { applySessionKanbanTaskToSource, attachSessionKanbanMirror, ensureSessionKanbanBoard, hydrateSessionKanban, mirrorSessionPlanToKanban, mirrorSessionTasksToKanban, mirrorSessionTodosToKanban, projectSessionPlanToKanban, projectSessionTasksToKanban, projectSessionTodosToKanban, SESSION_KANBAN_COLUMNS, } from './session-kanban.js';
44
+ export { applySessionKanbanBoardToTodos, applySessionKanbanTaskToSource, attachSessionKanbanMirror, ensureSessionKanbanBoard, hydrateSessionKanban, mirrorSessionPlanToKanban, mirrorSessionTasksToKanban, mirrorSessionTodosToKanban, projectSessionPlanToKanban, projectSessionTasksToKanban, projectSessionTodosToKanban, SESSION_KANBAN_COLUMNS, } from './session-kanban.js';
44
45
  export { makeSkillTool } from './skill.js';
45
46
  export { testTool } from './test.js';
46
47
  export { todoTool } from './todo.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,gBAAgB,EAAE,KAAK,WAAW,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAC5F,OAAO,EACL,KAAK,yBAAyB,EAC9B,kBAAkB,EAClB,cAAc,EACd,KAAK,uBAAuB,EAC5B,mBAAmB,GACpB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,cAAc,oBAAoB,CAAC;AAGnC,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,WAAW,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACnG,OAAO,EACL,cAAc,EACd,KAAK,oBAAoB,EACzB,KAAK,sBAAsB,GAC5B,MAAM,sBAAsB,CAAC;AAC9B,YAAY,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACtB,kBAAkB,EAClB,iBAAiB,EACjB,kBAAkB,EAClB,iBAAiB,EACjB,cAAc,EACd,aAAa,EACb,mBAAmB,EACnB,iBAAiB,EACjB,mBAAmB,EACnB,eAAe,EACf,UAAU,EACV,YAAY,EACZ,kBAAkB,EAClB,wBAAwB,EACxB,eAAe,EACf,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,2BAA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