@wrongstack/tools 0.283.1 → 0.284.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/audit.js.map +1 -1
  2. package/dist/bash.js +4 -0
  3. package/dist/bash.js.map +1 -1
  4. package/dist/builtin.js +685 -253
  5. package/dist/builtin.js.map +1 -1
  6. package/dist/codebase-index/index.js +2 -2
  7. package/dist/codebase-index/index.js.map +1 -1
  8. package/dist/diff.js.map +1 -1
  9. package/dist/document.js.map +1 -1
  10. package/dist/edit.d.ts +43 -0
  11. package/dist/edit.js +386 -60
  12. package/dist/edit.js.map +1 -1
  13. package/dist/{exec-Ca3fnpUh.d.ts → exec-2OKoT6tk.d.ts} +1 -1
  14. package/dist/exec.d.ts +1 -1
  15. package/dist/exec.js +13 -14
  16. package/dist/exec.js.map +1 -1
  17. package/dist/fetch.js.map +1 -1
  18. package/dist/format.js.map +1 -1
  19. package/dist/git.js.map +1 -1
  20. package/dist/glob.js +10 -1
  21. package/dist/glob.js.map +1 -1
  22. package/dist/grep.js +4 -0
  23. package/dist/grep.js.map +1 -1
  24. package/dist/index.d.ts +13 -2
  25. package/dist/index.js +730 -268
  26. package/dist/index.js.map +1 -1
  27. package/dist/install.js.map +1 -1
  28. package/dist/json.js.map +1 -1
  29. package/dist/lint.js.map +1 -1
  30. package/dist/logs.js.map +1 -1
  31. package/dist/next-steps.d.ts +66 -0
  32. package/dist/next-steps.js +116 -0
  33. package/dist/next-steps.js.map +1 -0
  34. package/dist/outdated.js.map +1 -1
  35. package/dist/pack.js +685 -253
  36. package/dist/pack.js.map +1 -1
  37. package/dist/patch.js +43 -0
  38. package/dist/patch.js.map +1 -1
  39. package/dist/read.js +13 -4
  40. package/dist/read.js.map +1 -1
  41. package/dist/replace.js +14 -0
  42. package/dist/replace.js.map +1 -1
  43. package/dist/scaffold.js.map +1 -1
  44. package/dist/test.js.map +1 -1
  45. package/dist/tool-diff.d.ts +88 -0
  46. package/dist/tool-diff.js +229 -0
  47. package/dist/tool-diff.js.map +1 -0
  48. package/dist/tool-summary.d.ts +24 -0
  49. package/dist/tool-summary.js +208 -0
  50. package/dist/tool-summary.js.map +1 -0
  51. package/dist/tree.js.map +1 -1
  52. package/dist/typecheck.js.map +1 -1
  53. package/dist/write.d.ts +6 -0
  54. package/dist/write.js +118 -19
  55. package/dist/write.js.map +1 -1
  56. package/package.json +15 -2
package/dist/diff.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/_util.ts","../src/diff.ts"],"names":["stat","path2","resolve"],"mappings":";;;;;;;;AA8BO,SAAS,WAAA,CAAY,OAAe,GAAA,EAAsB;AAC/D,EAAA,OAAY,IAAA,CAAA,UAAA,CAAW,KAAK,CAAA,GAAS,IAAA,CAAA,SAAA,CAAU,KAAK,CAAA,GAAS,IAAA,CAAA,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACvG;AAOA,SAAS,aAAa,GAAA,EAAwB;AAC5C,EAAA,OAAO,CAAM,aAAQ,GAAA,CAAI,WAAW,GAAQ,IAAA,CAAA,OAAA,CAAa,IAAA,CAAA,gBAAA,EAAkB,CAAC,CAAA;AAC9E;AAGA,SAAS,WAAA,CAAY,QAAgB,KAAA,EAA0B;AAC7D,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,CAAC,IAAA,KAAS;AAC1B,IAAA,MAAM,GAAA,GAAW,IAAA,CAAA,QAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AACtC,IAAA,OAAO,GAAA,KAAQ,MAAO,CAAC,GAAA,CAAI,WAAW,IAAI,CAAA,IAAK,CAAM,IAAA,CAAA,UAAA,CAAW,GAAG,CAAA;AAAA,EACrE,CAAC,CAAA;AACH;AAEO,SAAS,gBAAA,CAAiB,SAAiB,GAAA,EAAsB;AACtE,EAAA,MAAM,MAAA,GAAc,aAAQ,OAAO,CAAA;AAEnC,EAAA,IAAI,G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EAAM,OAAA,CAAQ,IAAA,CAAK,MAAM,CAAA;AAAA,IACzB,KAAA;AAAA,IACA,SAAA,EAAW,KAAA;AAAA,IACX,IAAA,EAAM,MAAM,IAAA,IAAQ;AAAA,GACtB;AACF;AAWA,SAAS,qBAAA,CAAsB,MAAc,KAAA,EAAyB;AACpE,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,KAAA,CAAM,MAAM,CAAA,CAAE,MAAA;AACnC,EAAA,MAAM,WAAW,KAAA,CAAM,GAAA,CAAI,CAAC,IAAA,EAAM,CAAA,KAAM,GAAG,MAAA,CAAO,CAAA,GAAI,CAAC,CAAA,CAAE,QAAA,CAAS,KAAK,CAAC,CAAA,GAAA,EAAM,IAAI,CAAA,CAAE,CAAA,CAAE,KAAK,IAAI,CAAA;AAC/F,EAAA,OAAO,OAAO,IAAI,CAAA;AAAA,EAAkD,QAAQ,CAAA,CAAA;AAC9E","file":"diff.js","sourcesContent":["import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import { spawn } from 'node:child_process';\nimport { statSync } from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\n\ninterface DiffInput {\n path?: string | undefined;\n files?: string | string[] | undefined;\n a?: string | undefined;\n b?: string | undefined;\n staged?: boolean | undefined;\n mode?: 'unified' | 'side-by-side' | 'stat' | undefined;\n context?: number | undefined;\n}\n\ninterface DiffOutput {\n diff: string;\n files: string[];\n truncated: boolean;\n mode: string;\n}\n\nexport const diffTool: Tool<DiffInput, DiffOutput> = {\n name: 'diff',\n category: 'Filesystem',\n description:\n 'Show file content with line numbers, staged/working-tree diffs via git, or commit/branch diffs. A safer and more structured alternative to raw `git diff` via shell.',\n usageHint:\n 'USE FOR CODE REVIEW AND CHANGE INSPECTION:\\n\\n' +\n '- `files` + no `a`/`b` → show file content with line numbers (NOT a unified diff; no +/- prefixes).\\n' +\n '- `a` and/or `b` → git-style commit/branch diff (unified format, real +/- prefixes).\\n' +\n '- `staged: true` → only show staged changes.\\n' +\n '- `mode` can be \"unified\", \"stat\", or \"side-by-side\" (only affects the git-diff path).\\n' +\n '\\n' +\n 'NOTE: For a true file-vs-file unified diff, supply `a` and `b` so the tool ' +\n 'delegates to `git diff`. The `files`-only path is a line-numbered dump, not a diff.\\n' +\n '\\n' +\n 'This tool has important safety guards against flag injection (see previous security findings).',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'diff',\n timeoutMs: 10_000,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Working directory for the diff operation (defaults to project root).',\n },\n files: {\n type: 'string',\n description: 'Files or globs to diff (e.g. \"src/**/*.ts\" or comma-separated list).',\n },\n a: {\n type: 'string',\n description: 'First ref/commit/branch for git diff (e.g. HEAD, main, a commit hash).',\n },\n b: {\n type: 'string',\n description: 'Second ref/commit/branch for git diff.',\n },\n staged: {\n type: 'boolean',\n description: 'If true, only show changes that are staged in git.',\n },\n mode: {\n type: 'string',\n enum: ['unified', 'side-by-side', 'stat'],\n description: 'Output format. \"unified\" is default, \"stat\" shows summary only.',\n },\n context: {\n type: 'integer',\n description: 'Number of context lines for unified diffs (default: 3).',\n },\n },\n },\n async execute(input, ctx, opts) {\n if (input.a !== undefined || input.b !== undefined) {\n return await gitDiff(input, ctx, opts.signal);\n }\n\n return await fileDiff(input, ctx, opts.signal);\n },\n};\n\nasync function gitDiff(\n input: DiffInput,\n ctx: import('@wrongstack/core').Context,\n signal: AbortSignal,\n): Promise<DiffOutput> {\n // Flag injection: a/b are passed as positional args BEFORE the `--`\n // separator, so a leading '-' would be parsed as a git option. The most\n // dangerous is `--output=<path>`, which makes `git diff` write to an\n // arbitrary path (outside the project root, with no confirmation since this\n // tool is permission:'auto'). Reject leading-dash refs unconditionally —\n // mirrors the guard in git.ts (validateWorktreeInput) and install.ts.\n if (input.a?.startsWith('-')) {\n throw new Error(`diff: unsafe ref \"${input.a}\" — refs may not begin with '-' (flag injection)`);\n }\n if (input.b?.startsWith('-')) {\n throw new Error(`diff: unsafe ref \"${input.b}\" — refs may not begin with '-' (flag injection)`);\n }\n\n const gitDir = findGitDir(ctx.cwd);\n if (!gitDir) {\n return { diff: '', files: [], truncated: false, mode: 'unified' };\n }\n\n const args: string[] = ['diff', '--no-color'];\n if (input.staged) args.push('--staged');\n if (input.a) args.push(input.a);\n if (input.b) args.push(input.b);\n if (input.files) {\n const files = Array.isArray(input.files) ? input.files : input.files.split(',');\n args.push('--', ...files.map((f) => f.trim()));\n }\n\n const result = await runGit(args, gitDir, signal);\n return {\n diff: result.stdout,\n files: [],\n truncated: result.stdout.length > 100_000,\n mode: 'unified',\n };\n}\n\nfunction findGitDir(cwd: string): string | null {\n let dir = cwd;\n for (let i = 0; i < 20; i++) {\n try {\n const stat = statSync(path.join(dir, '.git'));\n if (stat.isDirectory()) return dir;\n } catch {\n // continue\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction runGit(\n args: string[],\n cwd: string,\n signal: AbortSignal,\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('git', args, {\n cwd,\n signal,\n env: buildChildEnv(),\n stdio: ['ignore', 'pipe', 'pipe'],\n windowsHide: true,\n });\n child.stdout?.on('data', (c) => {\n stdout += c.toString();\n });\n child.stderr?.on('data', (c) => {\n stderr += c.toString();\n });\n child.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? 0 }));\n /* v8 ignore next -- spawn 'error' only fires when the git binary is missing; defensive. */\n child.on('error', (e) => resolve({ stdout: '', stderr: e.message, exitCode: 1 }));\n });\n}\n\nasync function fileDiff(\n input: DiffInput,\n ctx: import('@wrongstack/core').Context,\n _signal: AbortSignal,\n): Promise<DiffOutput> {\n // `context` is accepted on the input schema for API stability but is\n // unused in the line-dump path — there is no notion of \"context lines\"\n // when there is no real diff. The git-diff path (`a`/`b`) ignores it too.\n void input.context;\n\n const files = input.files\n ? (Array.isArray(input.files) ? input.files : input.files.split(','))\n .map((f) => f.trim())\n .filter(Boolean)\n : [];\n\n if (files.length === 0) {\n return {\n diff: 'No files specified',\n files: [],\n truncated: false,\n mode: input.mode ?? 'unified',\n };\n }\n\n const results: string[] = [];\n\n for (const file of files) {\n const absPath = safeResolve(file, ctx);\n const stat = await fs.stat(absPath).catch(() => null);\n if (!stat?.isFile()) continue;\n\n const content = await fs.readFile(absPath, 'utf8');\n const lines = content.split(/\\r?\\n/);\n results.push(formatWithLineNumbers(file, lines));\n }\n\n return {\n diff: results.join('\\n\\n'),\n files,\n truncated: false,\n mode: input.mode ?? 'unified',\n };\n}\n\n/**\n * Render a file's content as a line-numbered dump. This is intentionally\n * NOT a unified diff — it has no `-`/`+` prefixes. For a real diff\n * between two revisions, use the `a`/`b` params (delegates to `git diff`).\n *\n * Format: ` N | content` with the line number right-aligned. The\n * `context` parameter is accepted for API compatibility but unused —\n * a line dump has no notion of \"context lines\".\n */\nfunction formatWithLineNumbers(file: string, lines: string[]): string {\n const width = String(lines.length).length;\n const numbered = lines.map((line, i) => `${String(i + 1).padStart(width)} | ${line}`).join('\\n');\n return `--- ${file} (line-numbered dump, not a unified diff) ---\\n${numbered}`;\n}\n"]}
1
+ {"version":3,"sources":["../src/_util.ts","../src/diff.ts"],"names":["stat","path2","resolve"],"mappings":";;;;;;;;AAwCO,SAAS,WAAA,CAAY,OAAe,GAAA,EAAsB;AAC/D,EAAA,OAAY,IAAA,CAAA,UAAA,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AA,CAAE,KAAK,IAAI,CAAA;AAC/F,EAAA,OAAO,OAAO,IAAI,CAAA;AAAA,EAAkD,QAAQ,CAAA,CAAA;AAC9E","file":"diff.js","sourcesContent":["import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` — the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import { spawn } from 'node:child_process';\nimport { statSync } from 'node:fs';\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\n\ninterface DiffInput {\n path?: string | undefined;\n files?: string | string[] | undefined;\n a?: string | undefined;\n b?: string | undefined;\n staged?: boolean | undefined;\n mode?: 'unified' | 'side-by-side' | 'stat' | undefined;\n context?: number | undefined;\n}\n\ninterface DiffOutput {\n diff: string;\n files: string[];\n truncated: boolean;\n mode: string;\n}\n\nexport const diffTool: Tool<DiffInput, DiffOutput> = {\n name: 'diff',\n category: 'Filesystem',\n description:\n 'Show file content with line numbers, staged/working-tree diffs via git, or commit/branch diffs. A safer and more structured alternative to raw `git diff` via shell.',\n usageHint:\n 'USE FOR CODE REVIEW AND CHANGE INSPECTION:\\n\\n' +\n '- `files` + no `a`/`b` → show file content with line numbers (NOT a unified diff; no +/- prefixes).\\n' +\n '- `a` and/or `b` → git-style commit/branch diff (unified format, real +/- prefixes).\\n' +\n '- `staged: true` → only show staged changes.\\n' +\n '- `mode` can be \"unified\", \"stat\", or \"side-by-side\" (only affects the git-diff path).\\n' +\n '\\n' +\n 'NOTE: For a true file-vs-file unified diff, supply `a` and `b` so the tool ' +\n 'delegates to `git diff`. The `files`-only path is a line-numbered dump, not a diff.\\n' +\n '\\n' +\n 'This tool has important safety guards against flag injection (see previous security findings).',\n permission: 'auto',\n mutating: false,\n capabilities: ['fs.read'],\n icon: 'diff',\n timeoutMs: 10_000,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Working directory for the diff operation (defaults to project root).',\n },\n files: {\n type: 'string',\n description: 'Files or globs to diff (e.g. \"src/**/*.ts\" or comma-separated list).',\n },\n a: {\n type: 'string',\n description: 'First ref/commit/branch for git diff (e.g. HEAD, main, a commit hash).',\n },\n b: {\n type: 'string',\n description: 'Second ref/commit/branch for git diff.',\n },\n staged: {\n type: 'boolean',\n description: 'If true, only show changes that are staged in git.',\n },\n mode: {\n type: 'string',\n enum: ['unified', 'side-by-side', 'stat'],\n description: 'Output format. \"unified\" is default, \"stat\" shows summary only.',\n },\n context: {\n type: 'integer',\n description: 'Number of context lines for unified diffs (default: 3).',\n },\n },\n },\n async execute(input, ctx, opts) {\n if (input.a !== undefined || input.b !== undefined) {\n return await gitDiff(input, ctx, opts.signal);\n }\n\n return await fileDiff(input, ctx, opts.signal);\n },\n};\n\nasync function gitDiff(\n input: DiffInput,\n ctx: import('@wrongstack/core').Context,\n signal: AbortSignal,\n): Promise<DiffOutput> {\n // Flag injection: a/b are passed as positional args BEFORE the `--`\n // separator, so a leading '-' would be parsed as a git option. The most\n // dangerous is `--output=<path>`, which makes `git diff` write to an\n // arbitrary path (outside the project root, with no confirmation since this\n // tool is permission:'auto'). Reject leading-dash refs unconditionally —\n // mirrors the guard in git.ts (validateWorktreeInput) and install.ts.\n if (input.a?.startsWith('-')) {\n throw new Error(`diff: unsafe ref \"${input.a}\" — refs may not begin with '-' (flag injection)`);\n }\n if (input.b?.startsWith('-')) {\n throw new Error(`diff: unsafe ref \"${input.b}\" — refs may not begin with '-' (flag injection)`);\n }\n\n const gitDir = findGitDir(ctx.cwd);\n if (!gitDir) {\n return { diff: '', files: [], truncated: false, mode: 'unified' };\n }\n\n const args: string[] = ['diff', '--no-color'];\n if (input.staged) args.push('--staged');\n if (input.a) args.push(input.a);\n if (input.b) args.push(input.b);\n if (input.files) {\n const files = Array.isArray(input.files) ? input.files : input.files.split(',');\n args.push('--', ...files.map((f) => f.trim()));\n }\n\n const result = await runGit(args, gitDir, signal);\n return {\n diff: result.stdout,\n files: [],\n truncated: result.stdout.length > 100_000,\n mode: 'unified',\n };\n}\n\nfunction findGitDir(cwd: string): string | null {\n let dir = cwd;\n for (let i = 0; i < 20; i++) {\n try {\n const stat = statSync(path.join(dir, '.git'));\n if (stat.isDirectory()) return dir;\n } catch {\n // continue\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\nfunction runGit(\n args: string[],\n cwd: string,\n signal: AbortSignal,\n): Promise<{ stdout: string; stderr: string; exitCode: number }> {\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('git', args, {\n cwd,\n signal,\n env: buildChildEnv(),\n stdio: ['ignore', 'pipe', 'pipe'],\n windowsHide: true,\n });\n child.stdout?.on('data', (c) => {\n stdout += c.toString();\n });\n child.stderr?.on('data', (c) => {\n stderr += c.toString();\n });\n child.on('close', (code) => resolve({ stdout, stderr, exitCode: code ?? 0 }));\n /* v8 ignore next -- spawn 'error' only fires when the git binary is missing; defensive. */\n child.on('error', (e) => resolve({ stdout: '', stderr: e.message, exitCode: 1 }));\n });\n}\n\nasync function fileDiff(\n input: DiffInput,\n ctx: import('@wrongstack/core').Context,\n _signal: AbortSignal,\n): Promise<DiffOutput> {\n // `context` is accepted on the input schema for API stability but is\n // unused in the line-dump path — there is no notion of \"context lines\"\n // when there is no real diff. The git-diff path (`a`/`b`) ignores it too.\n void input.context;\n\n const files = input.files\n ? (Array.isArray(input.files) ? input.files : input.files.split(','))\n .map((f) => f.trim())\n .filter(Boolean)\n : [];\n\n if (files.length === 0) {\n return {\n diff: 'No files specified',\n files: [],\n truncated: false,\n mode: input.mode ?? 'unified',\n };\n }\n\n const results: string[] = [];\n\n for (const file of files) {\n const absPath = safeResolve(file, ctx);\n const stat = await fs.stat(absPath).catch(() => null);\n if (!stat?.isFile()) continue;\n\n const content = await fs.readFile(absPath, 'utf8');\n const lines = content.split(/\\r?\\n/);\n results.push(formatWithLineNumbers(file, lines));\n }\n\n return {\n diff: results.join('\\n\\n'),\n files,\n truncated: false,\n mode: input.mode ?? 'unified',\n };\n}\n\n/**\n * Render a file's content as a line-numbered dump. This is intentionally\n * NOT a unified diff — it has no `-`/`+` prefixes. For a real diff\n * between two revisions, use the `a`/`b` params (delegates to `git diff`).\n *\n * Format: ` N | content` with the line number right-aligned. The\n * `context` parameter is accepted for API compatibility but unused —\n * a line dump has no notion of \"context lines\".\n */\nfunction formatWithLineNumbers(file: string, lines: string[]): string {\n const width = String(lines.length).length;\n const numbered = lines.map((line, i) => `${String(i + 1).padStart(width)} | ${line}`).join('\\n');\n return `--- ${file} (line-numbered dump, not a unified diff) ---\\n${numbered}`;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/_util.ts","../src/document.ts"],"names":["stat"],"mappings":";;;;;AA8BO,SAAS,WAAA,CAAY,OAAe,GAAA,EAAsB;AAC/D,EAAA,OAAY,IAAA,CAAA,UAAA,CAAW,KAAK,CAAA,GAAS,IAAA,CAAA,SAAA,CAAU,KAAK,CAAA,GAAS,IAAA,CAAA,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACvG;AAOA,SAAS,aAAa,GAAA,EAAwB;AAC5C,EAAA,OAAO,CAAM,aAAQ,GAAA,CAAI,WAAW,GAAQ,IAAA,CA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AAA;AAAA,QACT,GAAA,EAAK,CAAA,CAAE,CAAC,CAAA,IAAK,EAAA;AAAA,QACb,IAAA,EAAM,MAAA;AAAA,QACN,IAAA,EAAM,QAAQ,KAAA,CAAM,CAAA,EAAG,EAAE,KAAK,CAAA,CAAE,KAAA,CAAM,IAAI,CAAA,CAAE;AAAA,OAC7C,CAAA;AAAA,IACH;AAAA,EACF;AAEA,EAAA,KAAA,MAAW,KAAK,UAAA,EAAY;AAC1B,IAAA,OAAA,CAAQ,IAAA,CAAK;AAAA,MACX,IAAA,EAAM,OAAA;AAAA,MACN,MAAM,CAAA,CAAE,IAAA;AAAA,MACR,WAAW,CAAA,CAAE,GAAA;AAAA,MACb,WAAW,CAAA,IAAA,EAAO,CAAA,CAAE,IAAI,CAAA,sBAAA,EAAyB,EAAE,IAAI,CAAA,GAAA,CAAA;AAAA,MACvD,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,OAAA;AACT","file":"document.js","sourcesContent":["import * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import * as fs from 'node:fs/promises';\nimport type { Tool } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\n\ninterface DocumentInput {\n target: 'file' | 'function' | 'class' | 'type' | 'all';\n path?: string | undefined;\n files?: string | string[] | undefined;\n style?: 'jsdoc' | 'tsdoc' | 'block' | undefined;\n overwrite?: boolean | undefined;\n cwd?: string | undefined;\n}\n\ninterface DocumentedItem {\n path: string;\n name: string;\n signature: string;\n docstring: string;\n status: 'documented' | 'skipped' | 'error';\n error?: string | undefined;\n}\n\ninterface DocumentOutput {\n files_processed: number;\n items_documented: number;\n results: DocumentedItem[];\n style: string;\n}\n\nexport const documentTool: Tool<DocumentInput, DocumentOutput> = {\n name: 'document',\n category: 'Project',\n description:\n 'DEPRECATED — use the `auto_doc` tool with `dryRun: true` instead. ' +\n 'This tool is a read-only preview stub that returns `skipped` candidates without generating real docstrings.',\n usageHint:\n 'Deprecated: prefer `auto_doc` with `dryRun: true` for previewing, or `auto_doc` without dryRun for writing. ' +\n 'This tool only lists undocumented symbols with placeholder comments — it does not generate real JSDoc/TSDoc.',\n permission: 'auto',\n mutating: false,\n timeoutMs: 30_000,\n capabilities: ['fs.read'],\n icon: 'document',\n inputSchema: {\n type: 'object',\n properties: {\n target: {\n type: 'string',\n enum: ['file', 'function', 'class', 'type', 'all'],\n description: 'What to document',\n },\n path: {\n type: 'string',\n description: 'Specific file path to document',\n },\n files: {\n type: 'string',\n description: 'File(s) to process: single path, comma-separated list, or glob',\n },\n style: {\n type: 'string',\n enum: ['jsdoc', 'tsdoc', 'block'],\n description: 'Documentation style (default: jsdoc)',\n },\n\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n },\n },\n async execute(input, ctx) {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const style = input.style ?? 'jsdoc';\n const results: DocumentedItem[] = [];\n let filesProcessed = 0;\n let itemsDocumented = 0;\n\n const fileList = input.files\n ? await resolveFiles(Array.isArray(input.files) ? input.files.join(',') : input.files, cwd)\n : input.path\n ? [safeResolve(input.path, ctx)]\n : [];\n\n for (const absPath of fileList) {\n try {\n const content = await fs.readFile(absPath, 'utf8');\n filesProcessed++;\n const processed = processFile(\n content,\n absPath,\n style,\n input.overwrite ?? false,\n input.target ?? 'all',\n );\n results.push(...processed);\n itemsDocumented += processed.filter((r) => r.status === 'documented').length;\n } catch (e) {\n results.push({\n path: absPath,\n name: absPath.split('/').pop() ?? absPath,\n signature: '',\n docstring: '',\n status: 'error',\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n return {\n files_processed: filesProcessed,\n items_documented: itemsDocumented,\n results,\n style,\n };\n },\n};\n\nasync function resolveFiles(filesInput: string, cwd: string): Promise<string[]> {\n const files = Array.isArray(filesInput) ? filesInput : filesInput.split(',');\n const resolved: string[] = [];\n\n for (const f of files) {\n const absPath = f.trim().startsWith('/') ? f.trim() : `${cwd}/${f.trim()}`;\n try {\n const stat = await fs.stat(absPath);\n if (stat.isFile()) resolved.push(absPath);\n } catch {\n // skip\n }\n }\n\n return resolved;\n}\n\nfunction processFile(\n content: string,\n absPath: string,\n _style: string,\n _overwrite: boolean,\n target: string,\n): DocumentedItem[] {\n const results: DocumentedItem[] = [];\n // These must be global — `String.prototype.matchAll` throws on a non-global\n // RegExp, which previously made processFile throw and report every file as an\n // error instead of returning documentation candidates.\n const functionRegex = /(?:async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/g;\n const arrowRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s+)?\\(([^)]*)\\)\\s*=>/g;\n const classRegex = /class\\s+(\\w+)/g;\n const typeRegex = /(?:type|interface)\\s+(\\w+)\\s*[=<]/g;\n\n const allMatches: { name: string; sig: string; type: string; line: number }[] = [];\n\n if (target === 'all' || target === 'function') {\n for (const m of content.matchAll(functionRegex)) {\n /* v8 ignore next -- capture group (\\w+) is mandatory, so m[1] is always defined; defensive. */\n if (!m[1]) continue;\n allMatches.push({\n name: m[1],\n sig: m[2] ?? '',\n type: 'function',\n line: content.slice(0, m.index).split('\\n').length,\n });\n }\n for (const m of content.matchAll(arrowRegex)) {\n /* v8 ignore next -- capture group (\\w+) is mandatory, so m[1] is always defined; defensive. */\n if (!m[1]) continue;\n allMatches.push({\n name: m[1],\n sig: m[2] ?? '',\n type: 'arrow',\n line: content.slice(0, m.index).split('\\n').length,\n });\n }\n }\n\n if (target === 'all' || target === 'class') {\n for (const m of content.matchAll(classRegex)) {\n /* v8 ignore next -- capture group (\\w+) is mandatory, so m[1] is always defined; defensive. */\n if (!m[1]) continue;\n allMatches.push({\n name: m[1],\n sig: '',\n type: 'class',\n line: content.slice(0, m.index).split('\\n').length,\n });\n }\n }\n\n if (target === 'all' || target === 'type') {\n for (const m of content.matchAll(typeRegex)) {\n /* v8 ignore next -- capture group (\\w+) is mandatory, so m[1] is always defined; defensive. */\n if (!m[1]) continue;\n allMatches.push({\n name: m[1],\n sig: m[0] ?? '',\n type: 'type',\n line: content.slice(0, m.index).split('\\n').length,\n });\n }\n }\n\n for (const m of allMatches) {\n results.push({\n path: absPath,\n name: m.name,\n signature: m.sig,\n docstring: `/** ${m.name} - documented at line ${m.line} */`,\n status: 'skipped',\n });\n }\n\n return results;\n}\n"]}
1
+ {"version":3,"sources":["../src/_util.ts","../src/document.ts"],"names":["stat"],"mappings":";;;;;AAwCO,SAAS,WAAA,CAAY,OAAe,GAAA,EAAsB;AAC/D,EAAA,OAAY,IAAA,CAAA,UAAA,CAAW,KAAK,CAAA,GAAS,IAAA,CAAA,SAAA,CAAU,KAAK,CAAA,GAAS,IAAA,CAAA,OAAA,CAAQ,GAAA,CAAI,UAAA,IAAc,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AACvG;AAOA,SAAS,aAAa,GAAA,EAAwB;AAC5C,EAAA,OAAO,CAAM,aAAQ,GAAA,CAAI,WAAW,GAAQ,IAAA,CAAA,OAAA,CAAa,IAAA,CAAA,gBAAA,EAAkB,CAAC,CAAA;AAC9E;AAGA,SAAS,WAAA,CAAY,QAAgB,KAAA,EAA0B;AAC7D,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,CAAC,IAAA,KAAS;AAC1B,IAAA,MAAM,GAAA,GAAW,IAAA,CAAA,QAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AACtC,IAAA,OAAO,GAAA,KAAQ,MAAO,CAAC,GAAA,CAAI,WAAW,IAAI,CAAA,IAAK,CAAM,IAAA,CAAA,UAAA,CAAW,GAAG,CAAA;AAAA,EACrE,CAAC,CAAA;AACH;AAEO,S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CAAA,CAAE,GAAA;AAAA,MACb,WAAW,CAAA,IAAA,EAAO,CAAA,CAAE,IAAI,CAAA,sBAAA,EAAyB,EAAE,IAAI,CAAA,GAAA,CAAA;AAAA,MACvD,MAAA,EAAQ;AAAA,KACT,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,OAAA;AACT","file":"document.js","sourcesContent":["import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` — the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm → yarn → npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root→out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink — macOS `/var`→`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n…[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]…\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// ─── Command-output normalization (token-saving) ────────────────────────────\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) — never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only — it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `… ⟨repeated ${run}×⟩`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends — the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n…[truncated ${total - kept} bytes]…\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI → collapse\n * carriage-return progress → trim trailing whitespace → collapse identical\n * consecutive lines → squeeze blank-line runs → head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines → 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n","import * as fs from 'node:fs/promises';\nimport type { Tool } from '@wrongstack/core';\nimport { safeResolve } from './_util.js';\n\ninterface DocumentInput {\n target: 'file' | 'function' | 'class' | 'type' | 'all';\n path?: string | undefined;\n files?: string | string[] | undefined;\n style?: 'jsdoc' | 'tsdoc' | 'block' | undefined;\n overwrite?: boolean | undefined;\n cwd?: string | undefined;\n}\n\ninterface DocumentedItem {\n path: string;\n name: string;\n signature: string;\n docstring: string;\n status: 'documented' | 'skipped' | 'error';\n error?: string | undefined;\n}\n\ninterface DocumentOutput {\n files_processed: number;\n items_documented: number;\n results: DocumentedItem[];\n style: string;\n}\n\nexport const documentTool: Tool<DocumentInput, DocumentOutput> = {\n name: 'document',\n category: 'Project',\n description:\n 'DEPRECATED — use the `auto_doc` tool with `dryRun: true` instead. ' +\n 'This tool is a read-only preview stub that returns `skipped` candidates without generating real docstrings.',\n usageHint:\n 'Deprecated: prefer `auto_doc` with `dryRun: true` for previewing, or `auto_doc` without dryRun for writing. ' +\n 'This tool only lists undocumented symbols with placeholder comments — it does not generate real JSDoc/TSDoc.',\n permission: 'auto',\n mutating: false,\n timeoutMs: 30_000,\n capabilities: ['fs.read'],\n icon: 'document',\n inputSchema: {\n type: 'object',\n properties: {\n target: {\n type: 'string',\n enum: ['file', 'function', 'class', 'type', 'all'],\n description: 'What to document',\n },\n path: {\n type: 'string',\n description: 'Specific file path to document',\n },\n files: {\n type: 'string',\n description: 'File(s) to process: single path, comma-separated list, or glob',\n },\n style: {\n type: 'string',\n enum: ['jsdoc', 'tsdoc', 'block'],\n description: 'Documentation style (default: jsdoc)',\n },\n\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n },\n },\n async execute(input, ctx) {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const style = input.style ?? 'jsdoc';\n const results: DocumentedItem[] = [];\n let filesProcessed = 0;\n let itemsDocumented = 0;\n\n const fileList = input.files\n ? await resolveFiles(Array.isArray(input.files) ? input.files.join(',') : input.files, cwd)\n : input.path\n ? [safeResolve(input.path, ctx)]\n : [];\n\n for (const absPath of fileList) {\n try {\n const content = await fs.readFile(absPath, 'utf8');\n filesProcessed++;\n const processed = processFile(\n content,\n absPath,\n style,\n input.overwrite ?? false,\n input.target ?? 'all',\n );\n results.push(...processed);\n itemsDocumented += processed.filter((r) => r.status === 'documented').length;\n } catch (e) {\n results.push({\n path: absPath,\n name: absPath.split('/').pop() ?? absPath,\n signature: '',\n docstring: '',\n status: 'error',\n error: e instanceof Error ? e.message : String(e),\n });\n }\n }\n\n return {\n files_processed: filesProcessed,\n items_documented: itemsDocumented,\n results,\n style,\n };\n },\n};\n\nasync function resolveFiles(filesInput: string, cwd: string): Promise<string[]> {\n const files = Array.isArray(filesInput) ? filesInput : filesInput.split(',');\n const resolved: string[] = [];\n\n for (const f of files) {\n const absPath = f.trim().startsWith('/') ? f.trim() : `${cwd}/${f.trim()}`;\n try {\n const stat = await fs.stat(absPath);\n if (stat.isFile()) resolved.push(absPath);\n } catch {\n // skip\n }\n }\n\n return resolved;\n}\n\nfunction processFile(\n content: string,\n absPath: string,\n _style: string,\n _overwrite: boolean,\n target: string,\n): DocumentedItem[] {\n const results: DocumentedItem[] = [];\n // These must be global — `String.prototype.matchAll` throws on a non-global\n // RegExp, which previously made processFile throw and report every file as an\n // error instead of returning documentation candidates.\n const functionRegex = /(?:async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/g;\n const arrowRegex = /(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s+)?\\(([^)]*)\\)\\s*=>/g;\n const classRegex = /class\\s+(\\w+)/g;\n const typeRegex = /(?:type|interface)\\s+(\\w+)\\s*[=<]/g;\n\n const allMatches: { name: string; sig: string; type: string; line: number }[] = [];\n\n if (target === 'all' || target === 'function') {\n for (const m of content.matchAll(functionRegex)) {\n /* v8 ignore next -- capture group (\\w+) is mandatory, so m[1] is always defined; defensive. */\n if (!m[1]) continue;\n allMatches.push({\n name: m[1],\n sig: m[2] ?? '',\n type: 'function',\n line: content.slice(0, m.index).split('\\n').length,\n });\n }\n for (const m of content.matchAll(arrowRegex)) {\n /* v8 ignore next -- capture group (\\w+) is mandatory, so m[1] is always defined; defensive. */\n if (!m[1]) continue;\n allMatches.push({\n name: m[1],\n sig: m[2] ?? '',\n type: 'arrow',\n line: content.slice(0, m.index).split('\\n').length,\n });\n }\n }\n\n if (target === 'all' || target === 'class') {\n for (const m of content.matchAll(classRegex)) {\n /* v8 ignore next -- capture group (\\w+) is mandatory, so m[1] is always defined; defensive. */\n if (!m[1]) continue;\n allMatches.push({\n name: m[1],\n sig: '',\n type: 'class',\n line: content.slice(0, m.index).split('\\n').length,\n });\n }\n }\n\n if (target === 'all' || target === 'type') {\n for (const m of content.matchAll(typeRegex)) {\n /* v8 ignore next -- capture group (\\w+) is mandatory, so m[1] is always defined; defensive. */\n if (!m[1]) continue;\n allMatches.push({\n name: m[1],\n sig: m[0] ?? '',\n type: 'type',\n line: content.slice(0, m.index).split('\\n').length,\n });\n }\n }\n\n for (const m of allMatches) {\n results.push({\n path: absPath,\n name: m.name,\n signature: m.sig,\n docstring: `/** ${m.name} - documented at line ${m.line} */`,\n status: 'skipped',\n });\n }\n\n return results;\n}\n"]}
package/dist/edit.d.ts CHANGED
@@ -1,5 +1,36 @@
1
1
  import { Tool } from '@wrongstack/core';
2
2
 
3
+ /**
4
+ * Matching ladder for the `edit` tool.
5
+ *
6
+ * Models routinely hallucinate whitespace when reproducing code they read
7
+ * many turns ago: trailing spaces appear, indentation shifts by a level,
8
+ * tabs become spaces. A strict exact-match `old_string` fails on all of
9
+ * these even though the intended target is unambiguous. This module
10
+ * implements a graded fallback chain — each tier is strictly more permissive
11
+ * and strictly lower-confidence than the previous one:
12
+ *
13
+ * 1. `exact` — substring match (the classic behavior).
14
+ * 2. `trailing-whitespace` — whole-line window match ignoring trailing
15
+ * whitespace per line. Zero ambiguity risk
16
+ * beyond exact (trailing blanks never carry
17
+ * meaning in the languages we edit).
18
+ * 3. `whitespace-normalized` — whole-line window match ignoring leading
19
+ * AND trailing whitespace per line. The
20
+ * replacement is re-indented to the file's
21
+ * actual indentation.
22
+ * 4. `fuzzy` — block-anchor match: first and last lines
23
+ * must match (trimmed), interior lines are
24
+ * compared by Levenshtein similarity. Only a
25
+ * single candidate with a clear margin over
26
+ * the runner-up is accepted.
27
+ *
28
+ * The caller (edit.ts) enforces per-tier uniqueness, restricts `replace_all`
29
+ * to tiers 1–2, and surfaces the tier + confidence in the tool output so the
30
+ * model and the session log both see when a fallback fired.
31
+ */
32
+ type MatchTier = 'exact' | 'trailing-whitespace' | 'whitespace-normalized' | 'fuzzy';
33
+
3
34
  interface EditInput {
4
35
  path: string;
5
36
  old_string: string;
@@ -16,6 +47,18 @@ interface EditOutput {
16
47
  path: string;
17
48
  replacements: number;
18
49
  diff: string;
50
+ /**
51
+ * How `old_string` was located. Anything other than 'exact' means a
52
+ * whitespace/fuzzy fallback fired — the note carries the confidence level
53
+ * and the diff shows exactly what was replaced.
54
+ */
55
+ matched_by: MatchTier;
56
+ /**
57
+ * Parse errors found in the file AFTER the edit was applied (TS/JS/JSON
58
+ * only). The edit is still on disk — fix these in a follow-up edit now,
59
+ * before doing anything else.
60
+ */
61
+ syntax_errors?: string[] | undefined;
19
62
  note?: string | undefined;
20
63
  }
21
64
  declare const editTool: Tool<EditInput, EditOutput>;