@crewhaus/tool-changeset 0.7.0 → 0.8.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ CrewHaus Factory
2
+ Copyright 2026 Max Meier
3
+
4
+ This product includes software developed by Max Meier
5
+ (operating as StudioMax — https://studiomax.io) and contributors.
6
+
7
+ The CrewHaus name and logo are trademarks of Max Meier. See
8
+ https://github.com/crewhaus/factory/blob/main/TRADEMARK.md for the
9
+ use-of-marks policy.
package/README.md CHANGED
@@ -41,6 +41,15 @@ The rules:
41
41
  | `oversizedFile` | warning | a file adding more than 800 lines |
42
42
  | `commentedCode` | warning | **off by default** — see below |
43
43
 
44
+ `ticketPattern` replaces what counts as a ticket, and `machinePathPatterns`
45
+ adds path shapes of your own. Both are regular expressions the caller writes,
46
+ so each is screened before it is accepted (a shape that backtracks
47
+ catastrophically, such as `(a+)+` or `(a|a)*`, is refused with the reason) and
48
+ then run in `@crewhaus/tool-safety`'s regex worker under a deadline, never on
49
+ the harness's own thread. A line the worker could not answer is listed under
50
+ `undetermined` with a warning: it is neither a finding nor clean, so `clean`
51
+ is not set.
52
+
44
53
  Disable any of them by name with `disable`, and turn the opt-in ones on with
45
54
  `enable`. An id that is not a rule is rejected by the schema rather than
46
55
  ignored, because a typo that silently disables nothing is how a team ends up
@@ -125,6 +134,16 @@ git selector (`cwd`, `ref`, `range`, `staged`, `paths`) and the tool runs
125
134
  nobody here reads. Passing both is refused: with the text in hand there is
126
135
  nothing for git to do.
127
136
 
137
+ That `git diff` goes through `@crewhaus/tool-git`'s runner, so it is a read
138
+ in the strong sense: no program the repository's own config names runs. The
139
+ fsmonitor hook, external diff drivers, textconv and the repository's own
140
+ filter drivers are switched off (a result says `repoConfigNote` when a filter
141
+ was skipped), a submodule's change is shown as its pointer (`Subproject
142
+ commit …`) rather than by running git inside the submodule under the
143
+ submodule's own config, a repository directory committed inside another one is refused
144
+ rather than run in, and git gets the environment without the harness's
145
+ credentials.
146
+
128
147
  The tool declares `scope: "external"` and `ioCapability: "process"` whichever
129
148
  way it is called. A static flag describes the worst case, and a capability
130
149
  that is sometimes true is true.
@@ -133,7 +152,12 @@ A ref or range that begins with `-` is refused, because git would read it as
133
152
  an option and `git diff --output=<file>` writes anywhere on the disk. A
134
153
  pathspec that is absolute, contains `..` or starts with git's `:` magic is
135
154
  refused for the same reason. The directory git runs in is resolved against
136
- the workspace root, symlinks included.
155
+ the workspace root, symlinks included, and so is the repository git finds
156
+ from there: a workspace nested inside a larger checkout, a `.git` file naming
157
+ another repository, or a `.git` directory whose history is linked or borrowed
158
+ from outside is refused. A linked worktree or submodule whose git directory
159
+ lives outside still works, because git's own bookkeeping there names this
160
+ checkout.
137
161
 
138
162
  ## DocsSymbolCheck is built to under-report
139
163
 
package/dist/git.d.ts CHANGED
@@ -30,20 +30,6 @@ export declare function checkRefArgs(toolName: string, values: ReadonlyArray<str
30
30
  * pathspec magic, and `:/` means "from the top of the repository".
31
31
  */
32
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
33
  export type DiffRequest = {
48
34
  readonly cwd?: string;
49
35
  readonly ref?: string;
@@ -56,15 +42,21 @@ export type CollectedDiff = {
56
42
  readonly diff: string;
57
43
  readonly truncated: boolean;
58
44
  readonly command: string;
45
+ /**
46
+ * Set when the repository's own config names filter programs, which this
47
+ * read did not run: a filtered file's diff is of its unfiltered bytes.
48
+ */
49
+ readonly repoConfigNote?: string;
59
50
  };
60
51
  /**
61
52
  * Ask git for the change set, as `-U0` unified diff text.
62
53
  *
63
54
  * `-U0` because this tool reads added lines and nothing else: context lines
64
55
  * 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.
56
+ * the patch. `--no-ext-diff` (and, from the shared runner, `--no-textconv`
57
+ * and the repository's own filter drivers switched off) because a
58
+ * repository-configured driver is a program the repository names, and a
59
+ * read runs none.
68
60
  *
69
61
  * Every failure comes back as a sentence, never a throw: a caller mistake —
70
62
  * a ref that does not exist, a directory that is not a repository — is normal
package/dist/git.js CHANGED
@@ -16,22 +16,24 @@
16
16
  * signal, and stdout is read under a cap while the pipe keeps draining —
17
17
  * a git whose output nobody reads blocks forever, deadline or no.
18
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.
19
+ * The spawn itself is tool-git's runner (`@crewhaus/tool-git/run`), not a
20
+ * copy of it. This package used to keep a second copy, and the copy is where
21
+ * a hardening lands last: 0.7.0's lacked even what tool-git had, so a
22
+ * repository's own config (an fsmonitor hook, a textconv, a clean filter) or
23
+ * an embedded bare repository made DiffLint — a read — run a program the
24
+ * repository named (C007). The shared runner switches all of that off for a
25
+ * read and spawns git without the harness's credentials. What is also not
26
+ * copied twice is the diff parser — that one comes from `@crewhaus/tool-text`,
27
+ * because two parsers mean two line numberings and one of them is wrong.
25
28
  */
26
29
  import { statSync } from "node:fs";
27
30
  import * as path from "node:path";
31
+ import { LITERAL_PATHSPEC, bareRefusal, inheritedIndexEnv, locateRepository, neutralisedNote, probeRepositoryFilters, runGit, } from "@crewhaus/tool-git/run";
28
32
  import { ToolPermissionError, resolveSafe } from "./paths";
29
33
  export const DEFAULT_TIMEOUT_MS = 30_000;
30
34
  export const MAX_TIMEOUT_MS = 120_000;
31
35
  /** Largest patch this package will read, from a spawn or from the caller. */
32
36
  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
37
  export const refuse = (message) => ({ ok: false, message });
36
38
  /** How much of an offending value an error message repeats back. */
37
39
  const ECHO_CHARS = 80;
@@ -78,144 +80,24 @@ export function checkPathspecs(toolName, paths, cwdAbs) {
78
80
  // and then decides containment, which is exactly the question.
79
81
  resolveSafe(toolName, path.join(cwdAbs, spec));
80
82
  }
81
- catch {
83
+ catch (err) {
84
+ if (err instanceof ToolPermissionError && err.reason !== undefined) {
85
+ return refuse(`${toolName} refused the path filter "${echo(spec)}": ${err.reason}.`);
86
+ }
82
87
  return refuse(`${toolName} refused the path filter "${echo(spec)}": it resolves outside the workspace root.`);
83
88
  }
84
89
  }
85
90
  return undefined;
86
91
  }
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
92
  /**
212
93
  * Ask git for the change set, as `-U0` unified diff text.
213
94
  *
214
95
  * `-U0` because this tool reads added lines and nothing else: context lines
215
96
  * 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.
97
+ * the patch. `--no-ext-diff` (and, from the shared runner, `--no-textconv`
98
+ * and the repository's own filter drivers switched off) because a
99
+ * repository-configured driver is a program the repository names, and a
100
+ * read runs none.
219
101
  *
220
102
  * Every failure comes back as a sentence, never a throw: a caller mistake —
221
103
  * a ref that does not exist, a directory that is not a repository — is normal
@@ -234,7 +116,9 @@ export async function collectDiff(toolName, request, signal) {
234
116
  }
235
117
  catch (err) {
236
118
  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.`);
119
+ return refuse(err.reason !== undefined
120
+ ? err.message
121
+ : `${toolName} refused the directory "${request.cwd ?? "."}": it resolves outside the workspace root. Pass a path inside the working directory.`);
238
122
  }
239
123
  throw err;
240
124
  }
@@ -259,12 +143,45 @@ export async function collectDiff(toolName, request, signal) {
259
143
  ...(request.staged === true ? ["--cached"] : []),
260
144
  ...(request.range !== undefined ? [request.range] : []),
261
145
  ...(request.ref !== undefined ? [request.ref] : []),
262
- ...(paths.length > 0 ? ["--", ...paths] : []),
146
+ // Literal, as a permission rule reads them: to git a pathspec is
147
+ // otherwise a glob, so `secret*` diffed everything a rule on `secrets/**`
148
+ // denies (see tool-git's checkPathspecs).
149
+ ...(paths.length > 0 ? ["--", ...paths.map((p) => `${LITERAL_PATHSPEC}${p}`)] : []),
263
150
  ];
264
151
  const timeoutMs = Math.min(request.timeout ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS);
152
+ // git works on the repository it discovers from `cwd`, which can enclose
153
+ // the workspace or be named by a planted .git file: tool-git's check
154
+ // refuses any repository that is not the workspace's (C071).
155
+ const located = await locateRepository(toolName, request.cwd ?? ".", cwd, {
156
+ timeoutMs,
157
+ ...(signal !== undefined ? { signal } : {}),
158
+ });
159
+ if (!located.ok) {
160
+ // DiffLint's own wording for "not a repository" says what to do instead.
161
+ if (/it is not a git repository/.test(located.message)) {
162
+ return refuse(`${toolName} refused "${request.cwd ?? "."}": it is not a git repository. Pass \`diff\` text instead, or run from inside a checkout.`);
163
+ }
164
+ return refuse(located.message);
165
+ }
166
+ // The repository's own filter drivers are switched off for this read; a
167
+ // driver git cannot be told to skip refuses the call instead.
168
+ const filters = await probeRepositoryFilters(toolName, cwd, {
169
+ timeoutMs,
170
+ ...(signal !== undefined ? { signal } : {}),
171
+ });
172
+ if (!filters.ok)
173
+ return refuse(filters.message);
174
+ // Run from a pre-commit or prepare-commit-msg hook, the index being
175
+ // committed is the one git named in GIT_INDEX_FILE: keep it when it is this
176
+ // repository's, so a staged lint sees what is about to be committed.
177
+ const indexEnv = inheritedIndexEnv(located.value);
265
178
  const run = await runGit(args, {
266
179
  cwd,
267
180
  timeoutMs,
181
+ readOnly: true,
182
+ maxOutputChars: MAX_DIFF_CHARS,
183
+ ...(Object.keys(indexEnv).length > 0 ? { env: indexEnv } : {}),
184
+ ...(filters.value.configArgs.length > 0 ? { configArgs: filters.value.configArgs } : {}),
268
185
  ...(signal !== undefined ? { signal } : {}),
269
186
  });
270
187
  if (run.timedOut) {
@@ -274,9 +191,24 @@ export async function collectDiff(toolName, request, signal) {
274
191
  return refuse(`${toolName} could not run git. ${run.stderr.trim()}`);
275
192
  if (run.code !== 0) {
276
193
  const detail = (run.stderr.trim() === "" ? run.stdout : run.stderr).trim();
277
- // The two failures a caller can actually act on are worth naming, because
194
+ // The failures a caller can actually act on are worth naming, because
278
195
  // "exit 128" sends them looking for the wrong problem.
196
+ if (/cannot use bare repository/i.test(detail)) {
197
+ return refuse(bareRefusal(toolName, request.cwd ?? "."));
198
+ }
279
199
  if (/not a git repository/i.test(detail)) {
200
+ // `git diff` in a repository directory that safe.bareRepository refused
201
+ // falls back to --no-index mode and says only "Not a git repository";
202
+ // ask git which of the two it was, so the refusal names the real reason.
203
+ const probe = await runGit(["rev-parse", "--git-dir"], {
204
+ cwd,
205
+ timeoutMs,
206
+ readOnly: true,
207
+ ...(signal !== undefined ? { signal } : {}),
208
+ });
209
+ if (/cannot use bare repository/i.test(probe.stderr)) {
210
+ return refuse(bareRefusal(toolName, request.cwd ?? "."));
211
+ }
280
212
  return refuse(`${toolName} refused "${request.cwd ?? "."}": it is not a git repository. Pass \`diff\` text instead, or run from inside a checkout.`);
281
213
  }
282
214
  if (/unknown revision|bad revision|ambiguous argument/i.test(detail)) {
@@ -284,12 +216,14 @@ export async function collectDiff(toolName, request, signal) {
284
216
  }
285
217
  return refuse(`${toolName} failed (git exit ${run.code}): ${detail === "" ? "no output" : detail}`);
286
218
  }
219
+ const note = neutralisedNote(filters.value.neutralised);
287
220
  return {
288
221
  ok: true,
289
222
  value: {
290
223
  diff: run.stdout,
291
224
  truncated: run.truncated,
292
225
  command: `git ${args.join(" ")}`,
226
+ ...(note !== undefined ? { repoConfigNote: note } : {}),
293
227
  },
294
228
  };
295
229
  }