@crewhaus/tool-changeset 0.7.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.
package/README.md ADDED
@@ -0,0 +1,231 @@
1
+ # @crewhaus/tool-changeset
2
+
3
+ Everything you can decide about a change set before it becomes a pull request.
4
+
5
+ | Tool | Answers |
6
+ |---|---|
7
+ | `DiffLint` | does this change add anything the team already decided it does not want |
8
+ | `DocsSymbolCheck` | do the docs still name things the code still has |
9
+
10
+ Both are review passes, and a review pass earns its place by being boring:
11
+ the same change set produces the same findings every time, with no opinion
12
+ about whether the code is any good.
13
+
14
+ ## DiffLint reads added lines only
15
+
16
+ A change set is not a codebase. A linter that reports the `console.log`
17
+ somebody else left behind three years ago gets turned off in a week, and then
18
+ it catches nothing at all. `DiffLint` runs its rules on `+` lines and on
19
+ nothing else — not on context, not on removals, not on the rest of the file.
20
+
21
+ **Every finding carries the line number in the NEW file.** That number is the
22
+ product: it is what lets a caller fix the finding without re-reading anything
23
+ first. It comes from `parseUnifiedDiff` in
24
+ [`@crewhaus/tool-text`](https://github.com/crewhaus/factory/tree/main/packages/tool-text),
25
+ which is the one diff parser in this repository. A second parser would mean a
26
+ second numbering, and one of the two would be wrong.
27
+
28
+ The rules:
29
+
30
+ | Rule | Severity | Applies to |
31
+ |---|---|---|
32
+ | `conflictMarker` | error | every text file |
33
+ | `debugger` | error | JavaScript and TypeScript |
34
+ | `focusedTest` | error | JavaScript and TypeScript (`.only`, `fit`, `fdescribe`) |
35
+ | `consoleLog` | warning | JavaScript and TypeScript (`log`/`debug`/`dir`/`trace`) |
36
+ | `suppression` | warning | `@ts-ignore`, `@ts-nocheck`, `eslint-disable`, `# type: ignore`, in a comment |
37
+ | `ticketlessTodo` | warning | a TODO/FIXME/HACK/XXX that opens a comment, with no ticket or URL |
38
+ | `machinePath` | error / warning | a home directory (error), a temp directory (warning) |
39
+ | `crlf` | warning | one finding per file, with the count |
40
+ | `longLine` | warning | an added line over 1000 characters |
41
+ | `oversizedFile` | warning | a file adding more than 800 lines |
42
+ | `commentedCode` | warning | **off by default** — see below |
43
+
44
+ Disable any of them by name with `disable`, and turn the opt-in ones on with
45
+ `enable`. An id that is not a rule is rejected by the schema rather than
46
+ ignored, because a typo that silently disables nothing is how a team ends up
47
+ believing a rule has been running for a year.
48
+
49
+ ### Where the comment starts is most of the precision
50
+
51
+ With the whole file in hand the honest way to tell code from commentary is a
52
+ mask — `maskSource` in `@crewhaus/tool-code` does exactly that, which is how
53
+ `TodoScan` ignores string literals. With one line in hand, the position of the
54
+ first comment opener is what there is, and it carries three rules:
55
+
56
+ - `debugger`, `focusedTest` and `consoleLog` are STATEMENTS, so a match at or
57
+ after the opener is not one. That silences the trailing `// debugger;` and
58
+ the `"// debugger;"` in a test fixture alike.
59
+ - A suppression directive only suppresses inside a comment. `@ts-ignore` in a
60
+ rule table, a string or a test name is talk *about* one.
61
+ - A TODO marker has to OPEN the comment. `// TODO: fix this` is a note to a
62
+ maintainer; "a TODO with no ticket is how work gets lost", mid-sentence, is
63
+ prose about todos — and prose about todos is what a repository's comments
64
+ are full of.
65
+
66
+ Each of these is wrong in one direction only: an opener inside a string
67
+ literal reads as a comment, so the rule goes quiet. That is the direction to
68
+ be wrong in.
69
+
70
+ Two rules are deliberately absent. `@ts-expect-error` is not reported: it
71
+ fails once the error it covers is gone, which is the behaviour to encourage.
72
+ `biome-ignore` is not reported either — its syntax already requires a stated
73
+ reason.
74
+
75
+ ### The commented-out-code rule is a heuristic, and ships as one
76
+
77
+ `commentedCode` guesses. It fires on a comment whose body has a code shape —
78
+ a statement keyword, an assignment, a bare call, a line ending in `;`, `{` or
79
+ `}` — and it vetoes anything that reads like a sentence. That veto is a word
80
+ count rather than a word list, because a comment in German is still prose.
81
+
82
+ It still has a real false-positive rate: `// see runTests()` is a note, not
83
+ dead code. So it is **opt-in**, it warns rather than errors, and it never runs
84
+ on config files or markdown, where a commented-out key looks exactly like a
85
+ commented-out statement. A lint that cries wolf gets disabled wholesale, and a
86
+ disabled lint finds nothing.
87
+
88
+ ### What it skips, and what it deliberately does not
89
+
90
+ - **Binary stanzas** are skipped and reported as skipped.
91
+ - **A pure rename** has no content to scan, so there is nothing to say.
92
+ - **A rename WITH edits is scanned.** This is a deliberate departure from the
93
+ obvious "skip renames" rule: git reports a move-plus-edit as a rename whose
94
+ hunks hold only the lines that really changed, and those lines are new code.
95
+ Skipping them would make a `debugger` added while moving a file the one
96
+ finding a review never sees.
97
+ - **A combined (merge) diff** cannot be numbered per parent, so the parser
98
+ refuses it and the refusal is returned as a warning. A change set that was
99
+ only partly readable never comes back as `clean`.
100
+
101
+ ### Limits worth knowing
102
+
103
+ - **A rule sees one line, without the file around it.** `console.log(` inside
104
+ a multi-line string literal reads exactly like a call. The rules are
105
+ anchored tightly and lean toward silence, but this is the honest limit of
106
+ linting a diff rather than a file.
107
+ - **Language is guessed from the extension**, which is all a diff carries.
108
+ - **A fixture that contains a rule's own pattern is reported.** This package's
109
+ tests are the clearest example: `'it.only("x")'` inside a string is a
110
+ fixture, and `DiffLint` run over this package reports it. Exclude test paths
111
+ with `paths`, or read the finding and move on.
112
+ - **`=======` alone is not a conflict marker.** It underlines a markdown
113
+ heading and divides half the ASCII art in the world, so it only counts in a
114
+ file that also gained an unmistakable `<<<<<<<` or `>>>>>>>`.
115
+ - **A CRLF diff transported as CRLF cannot be detected.** When every line of
116
+ the patch ends in `\r`, including its headers, the line endings belong to
117
+ the transport and the parser strips them. The rule then reports nothing —
118
+ a miss, never a false positive.
119
+
120
+ ### Where the diff comes from
121
+
122
+ Pass `diff` text when you already have the patch; nothing is spawned. Pass a
123
+ git selector (`cwd`, `ref`, `range`, `staged`, `paths`) and the tool runs
124
+ `git diff --no-ext-diff -U0` for you — `-U0` because context lines are bytes
125
+ nobody here reads. Passing both is refused: with the text in hand there is
126
+ nothing for git to do.
127
+
128
+ The tool declares `scope: "external"` and `ioCapability: "process"` whichever
129
+ way it is called. A static flag describes the worst case, and a capability
130
+ that is sometimes true is true.
131
+
132
+ A ref or range that begins with `-` is refused, because git would read it as
133
+ an option and `git diff --output=<file>` writes anywhere on the disk. A
134
+ pathspec that is absolute, contains `..` or starts with git's `:` magic is
135
+ refused for the same reason. The directory git runs in is resolved against
136
+ the workspace root, symlinks included.
137
+
138
+ ## DocsSymbolCheck is built to under-report
139
+
140
+ A missed stale symbol costs a reader a confusing minute. A wrong "this symbol
141
+ is gone" costs the tool its readers — and a tool nobody reads catches nothing.
142
+ Every decision here is taken in the direction of saying less.
143
+
144
+ **What counts as a symbol reference** is narrow, and it is the answer to the
145
+ question this tool has to get right:
146
+
147
+ 1. A **named import inside a fenced code block**, from a project-local module
148
+ (a relative specifier, or one matching `localPrefixes`). The writer named
149
+ the module and the export together, so there is nothing to infer.
150
+ `import { a as b }` records `a`: the alias is the document's invention.
151
+ 2. A **backticked identifier in prose**, if it survives the shape filters: at
152
+ least 4 characters, not in the stoplist, and shaped like an API name —
153
+ camelCase, PascalCase, an underscore, a `$`, a member path, or written as a
154
+ call. `` `build` `` is skipped; `` `build()` `` is not. Set
155
+ `requireDistinctive: false` to take the plain words too.
156
+
157
+ Everything else inside a fence is ignored: a fence usually holds shell
158
+ commands, sample output or JSON, and mining it for identifiers produces
159
+ exactly the noise this tool exists not to produce.
160
+
161
+ **What counts as "still exists"** is wide. The question asked of the source
162
+ tree is *does this identifier appear anywhere at all* — in code, in a comment,
163
+ in a string literal, in a config file. A symbol that survives only as a string
164
+ key is not reported. This is why the tool does not parse the sources: a parser
165
+ answers the narrower "is it declared", and every narrowing is a new way to be
166
+ wrong out loud. `SymbolOutline` and `AstQuery` in
167
+ [`@crewhaus/tool-code`](https://github.com/crewhaus/factory/tree/main/packages/tool-code)
168
+ are the tools for the declaration question.
169
+
170
+ A reference to another package's API resolves only if that package is inside
171
+ `source`. Running this tool over this package's own README reports `TodoScan`,
172
+ which lives in `@crewhaus/tool-code` — a true statement about a narrow
173
+ `source`, and the reason `ignore` exists.
174
+
175
+ For a member path, only the head is checked. If `Foo` exists but `Foo.bar`
176
+ does not, the tool says nothing rather than guessing at a method it cannot see
177
+ lexically.
178
+
179
+ ### The wrong-tree guard
180
+
181
+ The most expensive failure this tool has is being pointed at the wrong source
182
+ tree and confidently reporting every symbol in a document as deleted. So a
183
+ document must resolve at least a quarter of its references (`minResolvedRatio`)
184
+ before any of its misses are reported. Below that, the document is reported as
185
+ probably describing a different tree and its findings are withheld with the
186
+ count and the reason. The guard is per document, so one stray page does not
187
+ silence a good one, and `reportUnmatchedDocs` turns it off for a caller who
188
+ knows better.
189
+
190
+ ### It refuses rather than guess
191
+
192
+ An incomplete index invents missing symbols, so a scan that could not read the
193
+ whole tree is refused by name:
194
+
195
+ - more source files than `maxFiles` — the index is short, and a symbol it
196
+ never read reads as deleted;
197
+ - a directory under `source` that could not be listed — the largest hole an
198
+ index can have, and everything inside it would be reported as gone;
199
+ - a source file too large to read — the last two are refused unless
200
+ `allowUnreadableSources` says the gap is acceptable, in which case the gap
201
+ is reported as a warning;
202
+ - no source files at all under `source` — every documented symbol would look
203
+ deleted.
204
+
205
+ Each refusal is a sentence naming what to change.
206
+
207
+ What is reported as a warning instead, because it under-reports rather than
208
+ invents: a document walk that stopped at its own 500-file cap, a `missing`
209
+ list cut by `maxFindings` (`findingsTruncated`), and a symlink that points out
210
+ of the workspace.
211
+
212
+ ### Containment survives the walk, not just the path you typed
213
+
214
+ `docs` and `source` are resolved against the workspace root, symlinks
215
+ included. So is every symlinked file the walk *finds* underneath them:
216
+ `readFileSync` follows a link, and this tool quotes a document's own line back
217
+ in `context`, so a `docs/notes.md -> ~/.ssh/known_hosts` would be a read of a
218
+ file outside the workspace and an echo of its contents. Such a link is named
219
+ in the warnings and never opened. A symlinked directory is not walked at all.
220
+
221
+ ## What this package does not do
222
+
223
+ - **It does not decide whether a change is good.** No complexity scores, no
224
+ style opinions, no "consider extracting this".
225
+ - **It does not fetch anything.** No issue tracker is consulted to see whether
226
+ a TODO's ticket exists; the rule checks that a reference was written down.
227
+ - **It does not write.** Both tools are read-only. `DiffLint` runs `git diff`,
228
+ which takes no locks (`GIT_OPTIONAL_LOCKS=0`) and changes nothing.
229
+ - **It does not replace the whole-tree tools.** `TodoScan` inventories every
230
+ TODO in a repository; `DiffLint` asks whether *this change* adds one without
231
+ a ticket. Two different questions, deliberately.
package/dist/git.d.ts ADDED
@@ -0,0 +1,73 @@
1
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
2
+ export declare const MAX_TIMEOUT_MS = 120000;
3
+ /** Largest patch this package will read, from a spawn or from the caller. */
4
+ export declare const MAX_DIFF_CHARS = 8000000;
5
+ export type Refusal = {
6
+ readonly ok: false;
7
+ readonly message: string;
8
+ };
9
+ export type Resolved<T> = {
10
+ readonly ok: true;
11
+ readonly value: T;
12
+ } | Refusal;
13
+ export declare const refuse: (message: string) => Refusal;
14
+ /**
15
+ * Refuse a caller value that git would read as an option rather than as data
16
+ * (CWE-88, argument injection).
17
+ *
18
+ * An argv array keeps a caller away from the shell; it does not keep them
19
+ * away from git's own option parser. `git diff --output=<file>` writes
20
+ * anywhere on the disk, which defeats containment entirely, and no legal
21
+ * revision expression begins with `-`, so refusing the shape costs nothing.
22
+ */
23
+ export declare function checkRefArgs(toolName: string, values: ReadonlyArray<string | undefined>): Refusal | undefined;
24
+ /**
25
+ * Validate the pathspecs a caller wants to limit the diff to.
26
+ *
27
+ * git resolves a pathspec relative to the directory it runs in, so an
28
+ * absolute one, or one with `..`, reaches outside the workspace without ever
29
+ * passing through `resolveSafe`. A leading `:` is refused too: that is git's
30
+ * pathspec magic, and `:/` means "from the top of the repository".
31
+ */
32
+ export declare function checkPathspecs(toolName: string, paths: ReadonlyArray<string>, cwdAbs: string): Refusal | undefined;
33
+ export type GitRun = {
34
+ readonly code: number;
35
+ readonly stdout: string;
36
+ readonly stderr: string;
37
+ readonly timedOut: boolean;
38
+ readonly truncated: boolean;
39
+ };
40
+ /** Run git once, bounded by a deadline and the caller's abort signal. */
41
+ export declare function runGit(args: ReadonlyArray<string>, opts: {
42
+ cwd: string;
43
+ timeoutMs: number;
44
+ signal?: AbortSignal;
45
+ maxOutputChars?: number;
46
+ }): Promise<GitRun>;
47
+ export type DiffRequest = {
48
+ readonly cwd?: string;
49
+ readonly ref?: string;
50
+ readonly range?: string;
51
+ readonly staged?: boolean;
52
+ readonly paths?: ReadonlyArray<string>;
53
+ readonly timeout?: number;
54
+ };
55
+ export type CollectedDiff = {
56
+ readonly diff: string;
57
+ readonly truncated: boolean;
58
+ readonly command: string;
59
+ };
60
+ /**
61
+ * Ask git for the change set, as `-U0` unified diff text.
62
+ *
63
+ * `-U0` because this tool reads added lines and nothing else: context lines
64
+ * are bytes nobody here looks at, and on a large change set they are most of
65
+ * the patch. `--no-ext-diff` because a repository-configured external diff
66
+ * driver can print anything at all, which would make the result depend on
67
+ * local config.
68
+ *
69
+ * Every failure comes back as a sentence, never a throw: a caller mistake —
70
+ * a ref that does not exist, a directory that is not a repository — is normal
71
+ * traffic for this tool, and a model recovers from a sentence.
72
+ */
73
+ export declare function collectDiff(toolName: string, request: DiffRequest, signal?: AbortSignal): Promise<Resolved<CollectedDiff>>;
package/dist/git.js ADDED
@@ -0,0 +1,295 @@
1
+ /**
2
+ * The one place this package crosses a boundary: asking `git` for a diff.
3
+ *
4
+ * `DiffLint` can be handed diff text directly, and a caller that already has
5
+ * the patch should do exactly that. But the common case is "lint what I am
6
+ * about to commit", and making the caller shell out, capture, and pass a
7
+ * megabyte of patch back through a context window to get an answer about it
8
+ * is the waste the deterministic tools exist to remove. So this module
9
+ * spawns git, under the same two invariants `@crewhaus/tool-git` uses:
10
+ *
11
+ * 1. Containment. The directory git runs in is resolved against the
12
+ * workspace root and refused if it escapes, symlinks included (see
13
+ * `./paths`). Pathspecs are checked separately, because git resolves
14
+ * those itself and would happily walk out of the workspace.
15
+ * 2. Boundedness. Every spawn has a deadline and forwards the caller's abort
16
+ * signal, and stdout is read under a cap while the pipe keeps draining —
17
+ * a git whose output nobody reads blocks forever, deadline or no.
18
+ *
19
+ * This is a deliberate second copy of tool-git's runner rather than an
20
+ * import: `@crewhaus/tool-git` publishes its tools, not its spawn helper, and
21
+ * a dependency on a package for one unexported function would be worse than
22
+ * seventy lines that do one thing. What is NOT copied twice is the diff
23
+ * parser — that one comes from `@crewhaus/tool-text`, because two parsers
24
+ * mean two line numberings and one of them is wrong.
25
+ */
26
+ import { statSync } from "node:fs";
27
+ import * as path from "node:path";
28
+ import { ToolPermissionError, resolveSafe } from "./paths";
29
+ export const DEFAULT_TIMEOUT_MS = 30_000;
30
+ export const MAX_TIMEOUT_MS = 120_000;
31
+ /** Largest patch this package will read, from a spawn or from the caller. */
32
+ export const MAX_DIFF_CHARS = 8_000_000;
33
+ /** Grace period for draining a pipe whose writer was killed on the deadline. */
34
+ const DRAIN_GRACE_MS = 500;
35
+ export const refuse = (message) => ({ ok: false, message });
36
+ /** How much of an offending value an error message repeats back. */
37
+ const ECHO_CHARS = 80;
38
+ const echo = (value) => value.length > ECHO_CHARS ? `${value.slice(0, ECHO_CHARS)}…` : value;
39
+ /**
40
+ * Refuse a caller value that git would read as an option rather than as data
41
+ * (CWE-88, argument injection).
42
+ *
43
+ * An argv array keeps a caller away from the shell; it does not keep them
44
+ * away from git's own option parser. `git diff --output=<file>` writes
45
+ * anywhere on the disk, which defeats containment entirely, and no legal
46
+ * revision expression begins with `-`, so refusing the shape costs nothing.
47
+ */
48
+ export function checkRefArgs(toolName, values) {
49
+ for (const value of values) {
50
+ if (value === undefined)
51
+ continue;
52
+ if (value.startsWith("-")) {
53
+ return refuse(`${toolName} refused "${echo(value)}": a ref or range may not begin with "-", because git would read it as an option rather than as a name.`);
54
+ }
55
+ if (/[\0\n\r]/.test(value)) {
56
+ return refuse(`${toolName} refused "${echo(value.replace(/[\0\n\r]/g, "?"))}": a ref may not contain a newline or a NUL — git forbids both in a refname.`);
57
+ }
58
+ }
59
+ return undefined;
60
+ }
61
+ /**
62
+ * Validate the pathspecs a caller wants to limit the diff to.
63
+ *
64
+ * git resolves a pathspec relative to the directory it runs in, so an
65
+ * absolute one, or one with `..`, reaches outside the workspace without ever
66
+ * passing through `resolveSafe`. A leading `:` is refused too: that is git's
67
+ * pathspec magic, and `:/` means "from the top of the repository".
68
+ */
69
+ export function checkPathspecs(toolName, paths, cwdAbs) {
70
+ for (const spec of paths) {
71
+ if (spec === "")
72
+ return refuse(`${toolName} refused an empty path filter.`);
73
+ if (path.isAbsolute(spec) || spec.split(/[\\/]/).includes("..") || spec.startsWith(":")) {
74
+ return refuse(`${toolName} refused the path filter "${echo(spec)}": pathspecs must be relative to the working directory, without ".." or git pathspec magic.`);
75
+ }
76
+ try {
77
+ // An absolute path is fine here: `resolveSafe` resolves it as written
78
+ // and then decides containment, which is exactly the question.
79
+ resolveSafe(toolName, path.join(cwdAbs, spec));
80
+ }
81
+ catch {
82
+ return refuse(`${toolName} refused the path filter "${echo(spec)}": it resolves outside the workspace root.`);
83
+ }
84
+ }
85
+ return undefined;
86
+ }
87
+ /**
88
+ * Read a pipe into a string that can never exceed `cap` characters.
89
+ *
90
+ * The obvious `new Response(stream).text()` buffers everything before
91
+ * anything can be capped, so a diff of a vendored tree would be in memory
92
+ * whole before a single character was dropped. This keeps the first `cap`
93
+ * characters and goes on draining: the writer never blocks on a full pipe,
94
+ * the exit code stays truthful, and memory is bounded by the cap.
95
+ */
96
+ async function readCapped(stream, cap) {
97
+ if (stream === null || stream === undefined)
98
+ return { text: "", truncated: false };
99
+ const reader = stream.getReader();
100
+ const decoder = new TextDecoder();
101
+ let text = "";
102
+ let truncated = false;
103
+ try {
104
+ while (true) {
105
+ const chunk = await reader.read();
106
+ if (chunk.done === true)
107
+ break;
108
+ if (truncated)
109
+ continue;
110
+ text += decoder.decode(chunk.value, { stream: true });
111
+ if (text.length > cap) {
112
+ text = text.slice(0, cap);
113
+ truncated = true;
114
+ }
115
+ }
116
+ if (!truncated)
117
+ text += decoder.decode();
118
+ }
119
+ finally {
120
+ reader.releaseLock();
121
+ }
122
+ return { text, truncated };
123
+ }
124
+ /**
125
+ * Await a pipe's text, giving up after the grace period instead of hanging.
126
+ * A killed git can leave a grandchild holding the write end open, in which
127
+ * case the read never ends. A given-up read is reported as truncated rather
128
+ * than passed off as "git printed nothing".
129
+ */
130
+ async function drain(pending) {
131
+ let timer;
132
+ const fallback = new Promise((resolve) => {
133
+ timer = setTimeout(() => resolve(null), DRAIN_GRACE_MS);
134
+ });
135
+ try {
136
+ const settled = await Promise.race([pending.catch(() => null), fallback]);
137
+ return settled === null ? { text: "", truncated: true } : settled;
138
+ }
139
+ finally {
140
+ if (timer !== undefined)
141
+ clearTimeout(timer);
142
+ }
143
+ }
144
+ /**
145
+ * Flags applied before the subcommand. A pager or ANSI colour would be
146
+ * unparseable and would depend on the operator's config; `core.quotepath=false`
147
+ * keeps a non-ASCII filename from coming back octal-escaped.
148
+ */
149
+ const GLOBAL_ARGS = [
150
+ "--no-pager",
151
+ "-c",
152
+ "core.quotepath=false",
153
+ "-c",
154
+ "color.ui=false",
155
+ ];
156
+ /** Run git once, bounded by a deadline and the caller's abort signal. */
157
+ export async function runGit(args, opts) {
158
+ const cap = opts.maxOutputChars ?? MAX_DIFF_CHARS;
159
+ let proc;
160
+ try {
161
+ proc = Bun.spawn(["git", ...GLOBAL_ARGS, ...args], {
162
+ cwd: opts.cwd,
163
+ env: {
164
+ ...process.env,
165
+ // LC_ALL=C pins git's own diagnostics to one language, so the message
166
+ // this module matches on does not change with the operator's locale.
167
+ LC_ALL: "C",
168
+ GIT_TERMINAL_PROMPT: "0",
169
+ // A read must never contend for the index lock with a sibling run.
170
+ GIT_OPTIONAL_LOCKS: "0",
171
+ },
172
+ stdout: "pipe",
173
+ stderr: "pipe",
174
+ stdin: "ignore",
175
+ ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
176
+ });
177
+ }
178
+ catch (err) {
179
+ const message = err instanceof Error ? err.message : String(err);
180
+ return {
181
+ code: 127,
182
+ stdout: "",
183
+ stderr: `could not start git: ${message}. Is git installed and on PATH?`,
184
+ timedOut: false,
185
+ truncated: false,
186
+ };
187
+ }
188
+ let timedOut = false;
189
+ const timer = setTimeout(() => {
190
+ timedOut = true;
191
+ try {
192
+ proc.kill("SIGKILL");
193
+ }
194
+ catch {
195
+ // Already exited between the timer firing and the kill.
196
+ }
197
+ }, opts.timeoutMs);
198
+ try {
199
+ // Both pipes are read concurrently with the wait on exit: a git that
200
+ // fills one pipe while nobody reads it blocks forever.
201
+ const stdoutRead = readCapped(proc.stdout, cap);
202
+ const stderrRead = readCapped(proc.stderr, 8_000);
203
+ const code = await proc.exited;
204
+ const [out, err] = await Promise.all([drain(stdoutRead), drain(stderrRead)]);
205
+ return { code, stdout: out.text, stderr: err.text, timedOut, truncated: out.truncated };
206
+ }
207
+ finally {
208
+ clearTimeout(timer);
209
+ }
210
+ }
211
+ /**
212
+ * Ask git for the change set, as `-U0` unified diff text.
213
+ *
214
+ * `-U0` because this tool reads added lines and nothing else: context lines
215
+ * are bytes nobody here looks at, and on a large change set they are most of
216
+ * the patch. `--no-ext-diff` because a repository-configured external diff
217
+ * driver can print anything at all, which would make the result depend on
218
+ * local config.
219
+ *
220
+ * Every failure comes back as a sentence, never a throw: a caller mistake —
221
+ * a ref that does not exist, a directory that is not a repository — is normal
222
+ * traffic for this tool, and a model recovers from a sentence.
223
+ */
224
+ export async function collectDiff(toolName, request, signal) {
225
+ if (request.ref !== undefined && request.range !== undefined) {
226
+ return refuse(`${toolName} takes either \`ref\` or \`range\`, not both — a range already names both endpoints.`);
227
+ }
228
+ const badRef = checkRefArgs(toolName, [request.ref, request.range]);
229
+ if (badRef !== undefined)
230
+ return badRef;
231
+ let cwd;
232
+ try {
233
+ cwd = resolveSafe(toolName, request.cwd ?? ".").real;
234
+ }
235
+ catch (err) {
236
+ if (err instanceof ToolPermissionError) {
237
+ return refuse(`${toolName} refused the directory "${request.cwd ?? "."}": it resolves outside the workspace root. Pass a path inside the working directory.`);
238
+ }
239
+ throw err;
240
+ }
241
+ let isDir = false;
242
+ try {
243
+ isDir = statSync(cwd).isDirectory();
244
+ }
245
+ catch {
246
+ isDir = false;
247
+ }
248
+ if (!isDir) {
249
+ return refuse(`${toolName} refused "${request.cwd ?? "."}": it is not an existing directory.`);
250
+ }
251
+ const paths = request.paths ?? [];
252
+ const badPath = checkPathspecs(toolName, paths, cwd);
253
+ if (badPath !== undefined)
254
+ return badPath;
255
+ const args = [
256
+ "diff",
257
+ "--no-ext-diff",
258
+ "-U0",
259
+ ...(request.staged === true ? ["--cached"] : []),
260
+ ...(request.range !== undefined ? [request.range] : []),
261
+ ...(request.ref !== undefined ? [request.ref] : []),
262
+ ...(paths.length > 0 ? ["--", ...paths] : []),
263
+ ];
264
+ const timeoutMs = Math.min(request.timeout ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS);
265
+ const run = await runGit(args, {
266
+ cwd,
267
+ timeoutMs,
268
+ ...(signal !== undefined ? { signal } : {}),
269
+ });
270
+ if (run.timedOut) {
271
+ return refuse(`${toolName} timed out: \`git ${args.join(" ")}\` did not finish in ${timeoutMs}ms and was killed. Narrow the change set with \`paths\`, or raise \`timeout\`.`);
272
+ }
273
+ if (run.code === 127)
274
+ return refuse(`${toolName} could not run git. ${run.stderr.trim()}`);
275
+ if (run.code !== 0) {
276
+ const detail = (run.stderr.trim() === "" ? run.stdout : run.stderr).trim();
277
+ // The two failures a caller can actually act on are worth naming, because
278
+ // "exit 128" sends them looking for the wrong problem.
279
+ if (/not a git repository/i.test(detail)) {
280
+ return refuse(`${toolName} refused "${request.cwd ?? "."}": it is not a git repository. Pass \`diff\` text instead, or run from inside a checkout.`);
281
+ }
282
+ if (/unknown revision|bad revision|ambiguous argument/i.test(detail)) {
283
+ return refuse(`${toolName} could not resolve ${request.range ?? request.ref ?? "the requested revision"}: ${detail.split("\n")[0] ?? detail}`);
284
+ }
285
+ return refuse(`${toolName} failed (git exit ${run.code}): ${detail === "" ? "no output" : detail}`);
286
+ }
287
+ return {
288
+ ok: true,
289
+ value: {
290
+ diff: run.stdout,
291
+ truncated: run.truncated,
292
+ command: `git ${args.join(" ")}`,
293
+ },
294
+ };
295
+ }
@@ -0,0 +1,11 @@
1
+ import type { RegisteredTool } from "@crewhaus/tool-catalog";
2
+ export declare const diffLint: RegisteredTool;
3
+ export declare const docsSymbolCheck: RegisteredTool;
4
+ /** Every tool this package registers, in the order a catalog should list them. */
5
+ export declare const CHANGESET_TOOLS: ReadonlyArray<RegisteredTool>;
6
+ /**
7
+ * The rule vocabulary, for a caller that builds its own `enable`/`disable`
8
+ * list and wants to validate it before the call rather than read a schema
9
+ * rejection afterwards.
10
+ */
11
+ export { RULE_IDS, type RuleId, unknownRuleIds } from "./lib/rules";