@venizia/vulcan 0.4.10-2 → 0.4.10-21

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 (208) hide show
  1. package/README.md +30 -23
  2. package/base/checks/wiki-source-links.ts +17 -1
  3. package/base/claude/events.json +1 -11
  4. package/base/claude/settings.json +5 -76
  5. package/base/extensions/vulcan-guards.ts +81 -18
  6. package/base/hooks/guard-git.ts +95 -19
  7. package/base/hooks/guard-outside.ts +163 -43
  8. package/base/hooks/guard-writes.ts +15 -36
  9. package/base/hooks/session-start.ts +1 -1
  10. package/base/make/vulcan.mk +8 -5
  11. package/base/packs/venizia.md +16 -0
  12. package/base/references/delegation-brief.md +3 -5
  13. package/base/references/testing.md +1 -9
  14. package/base/rules.md +33 -38
  15. package/base/skills/build-a-feature/SKILL.md +4 -4
  16. package/base/skills/docs-update/SKILL.md +19 -8
  17. package/base/skills/fix-a-bug/SKILL.md +4 -2
  18. package/base/skills/plan-a-change/SKILL.md +1 -1
  19. package/base/skills/research/SKILL.md +1 -1
  20. package/base/skills/retro/SKILL.md +2 -2
  21. package/base/skills/review-a-change/SKILL.md +1 -1
  22. package/base/skills/visualize-work/SKILL.md +3 -3
  23. package/base/skills/visualize-work/references/spec.md +6 -3
  24. package/base/templates/AGENTS.md +9 -7
  25. package/base/templates/board.html +10 -110
  26. package/package.json +3 -3
  27. package/src/agents/atlas-block.ts +8 -31
  28. package/src/agents/codex-hooks.ts +1 -1
  29. package/src/agents/generated-block.ts +52 -0
  30. package/src/agents/hooks-json.ts +22 -3
  31. package/src/agents/index.ts +2 -0
  32. package/src/agents/render.ts +15 -2
  33. package/src/agents/resolve.ts +1 -0
  34. package/src/agents/rules-block.ts +92 -0
  35. package/src/board/command.ts +92 -30
  36. package/src/board/common/constants.ts +26 -0
  37. package/src/board/common/types.ts +10 -3
  38. package/src/board/fold.ts +1 -1
  39. package/src/board/github.ts +1 -2
  40. package/src/board/gitlab.ts +436 -0
  41. package/src/board/index.ts +1 -0
  42. package/src/board/logo.ts +49 -0
  43. package/src/board/open-file.ts +110 -0
  44. package/src/board/page.ts +57 -5
  45. package/src/board/schema.ts +4 -1
  46. package/src/board/server.ts +87 -3
  47. package/src/board/settings.ts +21 -24
  48. package/src/commands/changelog.command.ts +40 -0
  49. package/src/commands/clean.command.ts +6 -1
  50. package/src/commands/help.command.ts +2 -63
  51. package/src/commands/index.ts +6 -1
  52. package/src/commands/migrate.command.ts +71 -0
  53. package/src/commands/profile.command.ts +1 -1
  54. package/src/commands/runners.command.ts +43 -0
  55. package/src/commands/sync.command.ts +8 -4
  56. package/src/commands/table.ts +362 -0
  57. package/src/commit/check.ts +1 -0
  58. package/src/commit/common/constants.ts +4 -0
  59. package/src/commit/hook.ts +112 -8
  60. package/src/common/constants.ts +11 -9
  61. package/src/common/env-variables.ts +41 -0
  62. package/src/common/index.ts +1 -0
  63. package/src/common/layout-folder.ts +3 -4
  64. package/src/common/record.ts +5 -0
  65. package/src/config/common/constants.ts +28 -22
  66. package/src/config/loader.ts +22 -0
  67. package/src/config/schema.ts +330 -146
  68. package/src/create/add-app.ts +7 -2
  69. package/src/create/add-lib.ts +2 -4
  70. package/src/create/common/constants.ts +5 -3
  71. package/src/create/preset.ts +1 -0
  72. package/src/create/scratch.ts +2 -1
  73. package/src/doctor/checks.ts +277 -448
  74. package/src/doctor/common/constants.ts +27 -19
  75. package/src/doctor/private-values.ts +4 -1
  76. package/src/doctor/runner.ts +5 -12
  77. package/src/doctor/schema.ts +4 -0
  78. package/src/events/common/actor-names.ts +12 -0
  79. package/src/events/common/constants.ts +65 -38
  80. package/src/events/common/index.ts +1 -0
  81. package/src/events/hook.ts +5 -56
  82. package/src/events/text.ts +41 -6
  83. package/src/hooks/command-view.ts +80 -19
  84. package/src/hooks/common/constants.ts +26 -17
  85. package/src/hooks/common/types.ts +13 -24
  86. package/src/hooks/decision.ts +30 -12
  87. package/src/hooks/git-queries.ts +113 -0
  88. package/src/hooks/guard-git.ts +76 -24
  89. package/src/hooks/guard-outside.ts +334 -311
  90. package/src/hooks/guard-runner.ts +206 -0
  91. package/src/hooks/guard-writes.ts +87 -184
  92. package/src/hooks/hook-input.ts +57 -0
  93. package/src/hooks/index.ts +3 -6
  94. package/src/hooks/link-makers.ts +315 -0
  95. package/src/hooks/package-runners.ts +268 -0
  96. package/src/hooks/project-guards.ts +81 -44
  97. package/src/hooks/project-tmp.ts +39 -4
  98. package/src/hooks/runner-scan.ts +257 -0
  99. package/src/hooks/script-runners.ts +400 -0
  100. package/src/hooks/session-digest.ts +27 -117
  101. package/src/hooks/shell-folders.ts +760 -0
  102. package/src/hooks/shell-writes.ts +646 -0
  103. package/src/hooks/shell.ts +1421 -194
  104. package/src/hooks/subagent-card.ts +2 -2
  105. package/src/hooks/write-commands.ts +898 -0
  106. package/src/init/scaffold.ts +2 -3
  107. package/src/local/auto-clean.ts +2 -1
  108. package/src/local/browser-socket.ts +33 -0
  109. package/src/local/clean.ts +37 -6
  110. package/src/local/constants.ts +15 -1
  111. package/src/local/index.ts +1 -0
  112. package/src/local/scan.ts +41 -10
  113. package/src/manifest/render.ts +84 -30
  114. package/src/owner/constants.ts +4 -5
  115. package/src/owner/index.ts +0 -2
  116. package/src/owner/profile.ts +1 -0
  117. package/src/owner/schema.ts +51 -27
  118. package/src/owner/survey.ts +0 -3
  119. package/src/owner/view.ts +0 -9
  120. package/src/router.ts +8 -132
  121. package/src/rules/base.ts +12 -7
  122. package/src/rules/index.ts +1 -0
  123. package/src/rules/packs.ts +44 -0
  124. package/src/runners/check.ts +130 -0
  125. package/src/skills/frontmatter.ts +1 -0
  126. package/src/sync/agents-block.ts +104 -0
  127. package/src/sync/base-rules.ts +3 -3
  128. package/src/sync/claude-launch.ts +12 -12
  129. package/src/sync/common/constants.ts +0 -2
  130. package/src/sync/index.ts +1 -1
  131. package/src/sync/local-choice.ts +32 -3
  132. package/src/sync/planner.ts +2 -15
  133. package/src/sync/settings.ts +0 -17
  134. package/src/theme/index.ts +1 -0
  135. package/src/theme/tokens.ts +410 -0
  136. package/src/ui/prompt.ts +1 -0
  137. package/src/visualize/architecture.ts +504 -0
  138. package/src/visualize/assets.ts +41 -30
  139. package/src/visualize/compare-render.ts +22 -24
  140. package/src/visualize/constants.ts +27 -0
  141. package/src/visualize/diagrams.ts +13 -121
  142. package/src/visualize/kinds-render.ts +2 -2
  143. package/src/visualize/kinds-schema.ts +49 -0
  144. package/src/visualize/labels-vi.ts +25 -0
  145. package/src/visualize/labels.ts +2 -0
  146. package/src/visualize/layout.ts +415 -66
  147. package/src/visualize/page.ts +82 -15
  148. package/src/visualize/render.ts +2 -1
  149. package/src/visualize/schema.ts +29 -1
  150. package/src/visualize/sections.ts +78 -9
  151. package/src/visualize/theme.ts +49 -18
  152. package/src/wiki/anchors.ts +1 -0
  153. package/src/wiki/command.ts +10 -3
  154. package/src/wiki/source-links.ts +57 -18
  155. package/base/ci-global.json +0 -13
  156. package/base/claude/remote-hosts.json +0 -15
  157. package/base/hooks/guard-manifest.ts +0 -27
  158. package/base/hooks/guard-package.ts +0 -30
  159. package/base/hooks/guard-remote-hosts.ts +0 -70
  160. package/base/hooks/guard-scripting.ts +0 -32
  161. package/base/hooks/post-tool.ts +0 -37
  162. package/base/hooks/prompt-submit.ts +0 -54
  163. package/base/hooks/stop.ts +0 -40
  164. package/base/skills/build-a-feature/evals/evals.json +0 -29
  165. package/base/skills/docs-update/evals/evals.json +0 -23
  166. package/base/skills/docs-writing/evals/evals.json +0 -17
  167. package/base/skills/fix-a-bug/evals/evals.json +0 -17
  168. package/base/skills/knowledge-sync/SKILL.md +0 -81
  169. package/base/skills/knowledge-sync/knowledge-sync.workflow.js +0 -291
  170. package/base/skills/knowledge-sync/references/workflow.md +0 -44
  171. package/base/skills/plan-a-change/evals/evals.json +0 -47
  172. package/base/skills/report-back/evals/evals.json +0 -23
  173. package/base/skills/research/evals/evals.json +0 -17
  174. package/base/skills/retro/evals/evals.json +0 -17
  175. package/base/skills/review-a-change/evals/evals.json +0 -17
  176. package/base/skills/ship/evals/evals.json +0 -23
  177. package/base/skills/visualize-work/evals/evals.json +0 -17
  178. package/base/templates/ci/github-actions.yml +0 -75
  179. package/base/templates/ci/gitlab-ci.yml +0 -52
  180. package/base/templates/trusted-hosts.local.example +0 -11
  181. package/src/ci/affected.ts +0 -176
  182. package/src/ci/command.ts +0 -166
  183. package/src/ci/common/constants.ts +0 -76
  184. package/src/ci/common/index.ts +0 -2
  185. package/src/ci/common/types.ts +0 -37
  186. package/src/ci/git.ts +0 -72
  187. package/src/ci/global.ts +0 -48
  188. package/src/ci/graph.ts +0 -43
  189. package/src/ci/index.ts +0 -7
  190. package/src/ci/workspace.ts +0 -119
  191. package/src/commands/ci.command.ts +0 -4
  192. package/src/hooks/guard-manifest.ts +0 -109
  193. package/src/hooks/guard-package.ts +0 -226
  194. package/src/hooks/guard-scripting.ts +0 -36
  195. package/src/hooks/host-pattern.ts +0 -17
  196. package/src/hooks/owner-reply.ts +0 -162
  197. package/src/hooks/post-tool.ts +0 -138
  198. package/src/hooks/remote-hosts.ts +0 -1013
  199. package/src/hooks/trusted-scripts.ts +0 -212
  200. package/src/owner/shape.ts +0 -496
  201. package/src/owner/violations.ts +0 -332
  202. package/src/signals/claims.ts +0 -73
  203. package/src/signals/classify.ts +0 -137
  204. package/src/signals/constants.ts +0 -88
  205. package/src/signals/index.ts +0 -5
  206. package/src/signals/loop.ts +0 -48
  207. package/src/signals/state.ts +0 -271
  208. package/src/sync/atlas-block.ts +0 -56
@@ -1,87 +1,132 @@
1
- import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
1
+ import { lstatSync, readdirSync, readlinkSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
- import { ShellParser } from './shell.ts';
5
- import type { ISimpleCommand } from './shell.ts';
4
+ import { ShellParser, ShellUnread } from './shell.ts';
5
+ import { ShellFolders, loopCombinations } from './shell-folders.ts';
6
+ import type { TEnvironment } from './shell-folders.ts';
7
+ import { ShellWrites } from './shell-writes.ts';
8
+ import type { IWriteTarget } from './shell-writes.ts';
6
9
  import { HookConstants } from './common/index.ts';
7
10
  import { ProjectTmp } from './project-tmp.ts';
8
11
  import type { IManifestHookInput, IOutsideHit } from './common/index.ts';
9
12
 
10
13
  const FILE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
11
14
 
12
- type TEnvironment = Record<string, string | undefined>;
15
+ /** The links one path may pass through before it is taken for a loop, as the OS counts them. */
16
+ const MAX_LINKS = 40;
17
+
18
+ /** The components of a path, without the empty and `.` ones, last first, so `pop` takes the next. */
19
+ const partsOf = (opts: { path: string }): string[] =>
20
+ opts.path
21
+ .split('/')
22
+ .filter((part) => part !== '' && part !== '.')
23
+ .reverse();
13
24
 
14
25
  /**
15
- * `~` and `$NAME` / `${NAME}` expanded; `undefined` when a variable is unset or the word is not a plain path.
16
- * `$PWD` is the folder the command runs in (`cwd`), not the `PWD` of this hook's own process.
26
+ * The file the OS opens for an absolute path that has not been folded: each component in turn, a symlink
27
+ * followed where it stands, so a `..` after a link goes to the parent of the link's target and not to the
28
+ * parent of the link. What does not exist is kept as text, a dangling link followed to where it points. A path
29
+ * that goes through more links than the OS follows has no file: `undefined`.
17
30
  */
18
- const expandPath = (opts: {
19
- word: string;
20
- home: string;
21
- env: TEnvironment;
22
- cwd?: string;
23
- }): string | undefined => {
24
- if (opts.word === '' || /[`*?[]/.test(opts.word) || opts.word.includes('$(')) {
25
- return undefined;
26
- }
31
+ const realOf = (opts: { path: string }): string | undefined => {
32
+ const pending = partsOf({ path: opts.path });
33
+ let current = '/';
34
+ let links = 0;
27
35
 
28
- let unresolved = false;
29
- const home = opts.word === '~' || opts.word.startsWith('~/') ? opts.home : undefined;
30
- const withHome = home === undefined ? opts.word : `${home}${opts.word.slice(1)}`;
31
- const expanded = withHome.replace(/\$\{?(\w+)\}?/g, (_, name: string) => {
32
- const value = name === 'PWD' && opts.cwd !== undefined ? opts.cwd : opts.env[name];
36
+ while (pending.length > 0) {
37
+ const part = pending.pop() ?? '';
33
38
 
34
- if (value === undefined || value === '') {
35
- unresolved = true;
39
+ if (part === '..') {
40
+ current = dirname(current);
41
+ continue;
36
42
  }
37
43
 
38
- return value ?? '';
39
- });
40
-
41
- return unresolved ? undefined : expanded;
42
- };
44
+ const next = join(current, part);
45
+ let target: string | undefined;
43
46
 
44
- /**
45
- * The path with the nearest existing ancestor resolved through symlinks, so a link cannot walk out of the
46
- * project; a dangling link is followed to where it points.
47
- */
48
- const realOf = (opts: { path: string; depth?: number }): string => {
49
- const depth = opts.depth ?? 0;
50
- let existing = opts.path;
51
- const rest: string[] = [];
52
-
53
- while (dirname(existing) !== existing) {
54
47
  try {
55
- lstatSync(existing);
56
- break;
48
+ target = lstatSync(next).isSymbolicLink() ? readlinkSync(next) : undefined;
57
49
  } catch {
58
- rest.unshift(existing.slice(dirname(existing).length + 1));
59
- existing = dirname(existing);
50
+ target = undefined;
60
51
  }
61
- }
62
52
 
63
- let base: string;
53
+ if (target === undefined) {
54
+ current = next;
55
+ continue;
56
+ }
64
57
 
65
- try {
66
- base = realpathSync(existing);
67
- } catch {
68
- // A dangling link: its target is where a write through it lands; a chain this long is a loop.
69
- if (depth >= 8) {
70
- return join(existing, ...rest);
58
+ links += 1;
59
+
60
+ if (links > MAX_LINKS) {
61
+ return undefined;
71
62
  }
72
63
 
73
- base = realOf({
74
- path: resolve(dirname(existing), readlinkSync(existing)),
75
- depth: depth + 1,
76
- });
64
+ if (isAbsolute(target)) {
65
+ current = '/';
66
+ }
67
+
68
+ pending.push(...partsOf({ path: target }));
77
69
  }
78
70
 
79
- return join(base, ...rest);
71
+ return current;
72
+ };
73
+ /**
74
+ * A path of plain folders (no `..`) whose last name holds one `[...]` of plain characters: a VitePress route file such as
75
+ * `content/[version].md`. Nothing else in it is a pattern, an expansion or a shell metacharacter (a zsh glob qualifier
76
+ * needs one), and the only glob is in the last name.
77
+ */
78
+ const BRACKET_NAME = /^\/?(?:(?!\.\.\/)[\w.-]+\/)*[\w.-]*\[[\w.-]+\][\w.-]*$/;
79
+ /** The files that name a process by number or as `self`: their target depends on who opens them. */
80
+ const PROCESS_FILES = /^\/(?:proc(?:\/|$)|dev\/fd(?:\/|$))/;
81
+
82
+ /**
83
+ * Whether the `[...]` name of `word` (a `BRACKET_NAME`) matches no entry of its folder, so the shell takes it as written:
84
+ * a match is written through, symlink and all, and is the existing file's business. An unreadable folder is not a miss.
85
+ */
86
+ const matchesNothing = (opts: { word: string; base: string }): boolean => {
87
+ const at = opts.word.lastIndexOf('/');
88
+ const folder = opts.word.startsWith('/')
89
+ ? opts.word.slice(0, at + 1)
90
+ : join(opts.base, opts.word.slice(0, at + 1));
91
+
92
+ try {
93
+ // both sides in lower case: bash `nocaseglob` matches without regard to case, so this can only ask more often
94
+ const glob = new Bun.Glob(opts.word.slice(at + 1).toLowerCase());
95
+
96
+ return !readdirSync(folder).some((entry) => glob.match(entry.toLowerCase()));
97
+ } catch {
98
+ return false;
99
+ }
80
100
  };
81
101
 
82
102
  const isInside = (opts: { path: string; root: string }): boolean =>
83
103
  opts.path === opts.root || opts.path.startsWith(`${opts.root}${sep}`);
84
104
 
105
+ /**
106
+ * Whether `path` is one of the files the guards read their policy from (`HookConstants.PROTECTED_FILES`), relative to the project
107
+ * root. A removal or a move also takes a folder that holds one of them (`rm -rf .claude`), bar `node_modules`, whose removal leaves
108
+ * the guards missing and the call blocked until `bun install`.
109
+ */
110
+ const isProtectedFile = (opts: { path: string; root: string; isRemoval: boolean }): boolean => {
111
+ if (!isInside({ path: opts.path, root: opts.root }) || opts.path === opts.root) {
112
+ return false;
113
+ }
114
+
115
+ // Without regard to case: on a case-insensitive file system `.claude/Settings.local.json` is the real file.
116
+ const relative = opts.path.slice(opts.root.length + 1).toLowerCase();
117
+ const globs = HookConstants.PROTECTED_FILES.map((pattern) => pattern.toLowerCase());
118
+
119
+ if (globs.some((pattern) => new Bun.Glob(pattern).match(relative))) {
120
+ return true;
121
+ }
122
+
123
+ return (
124
+ opts.isRemoval &&
125
+ !relative.startsWith('node_modules') &&
126
+ globs.some((pattern) => pattern.startsWith(`${relative}/`))
127
+ );
128
+ };
129
+
85
130
  /**
86
131
  * A tool-owned pattern as an absolute glob: `~` and variables expanded, a bare directory taking everything
87
132
  * below it. A pattern with an unset variable is dropped - it would otherwise match from the root.
@@ -115,230 +160,6 @@ const allowPatterns = (opts: { patterns: string[]; home: string; env: TEnvironme
115
160
  const matchesAny = (opts: { path: string; patterns: string[] }): boolean =>
116
161
  opts.patterns.some((pattern) => new Bun.Glob(pattern).match(opts.path));
117
162
 
118
- interface ITarget {
119
- word: string;
120
- message: string;
121
- /** The directory a relative `word` is taken from: the hook's, moved by `cd` and `git -C`. */
122
- base: string;
123
- /** What `$PWD` is in `word`: the shell's folder, moved by `cd` but not by `git -C`; undefined when it is not known. */
124
- pwd?: string;
125
- }
126
-
127
- const positional = (opts: { args: string[] }): string[] =>
128
- opts.args.filter((word) => !word.startsWith('-'));
129
-
130
- /** The value of a flag, long (`--output X`, `--output=X`) or short, alone or last in a cluster (`-sLo X`). */
131
- const valueOf = (opts: {
132
- args: string[];
133
- long?: string[];
134
- short?: string[];
135
- }): string | undefined => {
136
- for (const [index, word] of opts.args.entries()) {
137
- for (const flag of opts.long ?? []) {
138
- if (word === flag) {
139
- return opts.args[index + 1];
140
- }
141
-
142
- if (word.startsWith(`${flag}=`)) {
143
- return word.slice(flag.length + 1);
144
- }
145
- }
146
-
147
- for (const letter of opts.short ?? []) {
148
- if (new RegExp(`^-[a-zA-Z]*${letter}$`).test(word)) {
149
- return opts.args[index + 1];
150
- }
151
- }
152
- }
153
-
154
- return undefined;
155
- };
156
-
157
- /** Options of `git clone` that take the next word, so it is not the URL or the directory. */
158
- const CLONE_VALUE_FLAGS = new Set([
159
- '-b',
160
- '--branch',
161
- '--depth',
162
- '-c',
163
- '--config',
164
- '-o',
165
- '--origin',
166
- '--reference',
167
- '--separate-git-dir',
168
- '--template',
169
- '-j',
170
- '--jobs',
171
- '-u',
172
- '--upload-pack',
173
- '--filter',
174
- '--shallow-since',
175
- '--shallow-exclude',
176
- ]);
177
-
178
- /** Words after `git`'s global options (`-C dir`, `-c k=v`, `--no-pager`) and the directory `-C` names. */
179
- const gitArguments = (opts: { args: string[] }): { rest: string[]; dir: string | undefined } => {
180
- let dir: string | undefined;
181
- let index = 0;
182
-
183
- while (index < opts.args.length && opts.args[index].startsWith('-')) {
184
- const word = opts.args[index];
185
-
186
- if (word === '-C') {
187
- dir = opts.args[index + 1];
188
- index += 2;
189
- } else if (['-c', '--git-dir', '--work-tree', '--namespace'].includes(word)) {
190
- index += 2;
191
- } else {
192
- index += 1;
193
- }
194
- }
195
-
196
- return { rest: opts.args.slice(index), dir };
197
- };
198
-
199
- const gitTargets = (opts: { rest: string[]; base: string; dir: string | undefined }): ITarget[] => {
200
- const base = opts.dir === undefined ? opts.base : resolve(opts.base, opts.dir);
201
- const [sub, second] = positional({ args: opts.rest });
202
-
203
- if (sub === 'worktree' && second === 'add') {
204
- const afterAdd = opts.rest.slice(opts.rest.indexOf('add') + 1);
205
- const skipped = new Set<number>();
206
-
207
- for (const [index, word] of afterAdd.entries()) {
208
- if (word === '-b' || word === '-B') {
209
- skipped.add(index);
210
- skipped.add(index + 1);
211
- }
212
- }
213
-
214
- const path = afterAdd.find((word, index) => !word.startsWith('-') && !skipped.has(index));
215
-
216
- return path === undefined
217
- ? []
218
- : [{ word: path, base, message: `git worktree add creates ${path}` }];
219
- }
220
-
221
- if (sub === 'clone') {
222
- const afterClone = opts.rest.slice(opts.rest.indexOf('clone') + 1);
223
- const words: string[] = [];
224
-
225
- for (let index = 0; index < afterClone.length; index += 1) {
226
- if (CLONE_VALUE_FLAGS.has(afterClone[index])) {
227
- index += 1;
228
- } else if (!afterClone[index].startsWith('-')) {
229
- words.push(afterClone[index]);
230
- }
231
- }
232
-
233
- const [, destination] = words;
234
-
235
- return words.length === 0
236
- ? []
237
- : [
238
- {
239
- word: destination ?? '.',
240
- base,
241
- message:
242
- destination === undefined
243
- ? 'git clone writes into the current directory'
244
- : `git clone writes ${destination}`,
245
- },
246
- ];
247
- }
248
-
249
- return [];
250
- };
251
-
252
- /** The words a simple command would create or write, with a name for what writes them. */
253
- const targetsOf = (opts: { command: ISimpleCommand; base: string; tmp: string }): ITarget[] => {
254
- const program = ShellParser.programOf({ command: opts.command });
255
- const name = ShellParser.basenameOf({ word: program.name });
256
- const { args } = program;
257
- const { base } = opts;
258
- const targets: ITarget[] = opts.command.redirects.map((word) => ({
259
- word,
260
- base,
261
- message: `a shell redirect writes ${word}`,
262
- }));
263
- const assignments = [
264
- ...opts.command.assignments,
265
- ...(['export', 'declare', 'typeset', 'local', 'readonly'].includes(name) ? args : []),
266
- ];
267
-
268
- for (const assignment of assignments.filter((word) => word.startsWith('TMPDIR='))) {
269
- targets.push({
270
- word: assignment.slice('TMPDIR='.length),
271
- base,
272
- message: 'TMPDIR points outside the project',
273
- });
274
- }
275
-
276
- const last = positional({ args }).at(-1);
277
- const add = (word: string, message: string): number => targets.push({ word, base, message });
278
-
279
- if (['mkdir', 'touch'].includes(name)) {
280
- for (const word of positional({ args })) {
281
- add(word, `${name} creates ${word}`);
282
- }
283
- } else if (['cp', 'mv', 'install', 'ln', 'rsync'].includes(name)) {
284
- const directory = valueOf({ args, long: ['--target-directory'], short: ['t'] });
285
-
286
- if (directory !== undefined) {
287
- add(directory, `${name} writes into ${directory}`);
288
- } else if (last !== undefined) {
289
- add(last, `${name} writes ${last}`);
290
- }
291
- } else if (name === 'tee') {
292
- for (const word of positional({ args })) {
293
- add(word, `tee writes ${word}`);
294
- }
295
- } else if (name === 'dd') {
296
- const output = args.find((word) => word.startsWith('of='));
297
-
298
- if (output !== undefined) {
299
- add(output.slice(3), `dd writes ${output.slice(3)}`);
300
- }
301
- } else if (name === 'curl') {
302
- const output = valueOf({ args, long: ['--output'], short: ['o'] });
303
- const directory = valueOf({ args, long: ['--output-dir'] });
304
-
305
- if (output !== undefined) {
306
- add(output, `curl saves to ${output}`);
307
- }
308
-
309
- if (directory !== undefined) {
310
- add(directory, `curl saves into ${directory}`);
311
- }
312
- } else if (name === 'wget') {
313
- const output = valueOf({ args, long: ['--output-document'], short: ['O'] });
314
- const directory = valueOf({ args, long: ['--directory-prefix'], short: ['P'] });
315
-
316
- for (const word of [output, directory]) {
317
- if (word !== undefined) {
318
- add(word, `wget saves to ${word}`);
319
- }
320
- }
321
- } else if (name === 'mktemp') {
322
- const directory = valueOf({ args, long: ['--tmpdir'], short: ['p'] });
323
- const inTmpdir = args.some((word) => /^-[a-zA-Z]*t[a-zA-Z]*$/.test(word));
324
- const [template] = positional({ args }).filter((word) => word !== directory);
325
-
326
- if (directory !== undefined) {
327
- add(directory, 'mktemp creates a temporary file');
328
- } else if (inTmpdir || template === undefined) {
329
- add(opts.tmp, 'mktemp creates a file in the system temp directory');
330
- } else {
331
- add(template, 'mktemp creates a temporary file');
332
- }
333
- } else if (name === 'git') {
334
- const { rest, dir } = gitArguments({ args });
335
-
336
- targets.push(...gitTargets({ rest, base, dir }));
337
- }
338
-
339
- return targets;
340
- };
341
-
342
163
  /**
343
164
  * The folder a bare `mktemp` uses in the command: the `TMPDIR` this hook runs with (Claude Code started
344
165
  * with the launch file or the variables), else the project's own folder when Claude Code's session-start
@@ -371,7 +192,7 @@ export class OutsideGuard {
371
192
  }): IOutsideHit[] {
372
193
  const env = opts.env ?? process.env;
373
194
  const home = opts.home ?? env.HOME ?? '';
374
- const root = realOf({ path: resolve(opts.projectRoot) });
195
+ const root = realOf({ path: resolve(opts.projectRoot) }) ?? resolve(opts.projectRoot);
375
196
  const patterns = allowPatterns({
376
197
  patterns: [...HookConstants.TOOL_OWNED_PATHS, ...(opts.toolOwnedPaths ?? [])],
377
198
  home,
@@ -381,7 +202,7 @@ export class OutsideGuard {
381
202
  // `$PWD` is the call's folder only when the host said which one it is; otherwise the hook's own `PWD` stays the fallback.
382
203
  const startPwd = opts.input.cwd === undefined ? undefined : start;
383
204
  const tmp = commandTmpdirOf({ env, projectRoot: opts.projectRoot });
384
- const targets: ITarget[] = [];
205
+ const targets: IWriteTarget[] = [];
385
206
 
386
207
  if (FILE_TOOLS.has(opts.input.tool) && opts.input.filePath !== undefined) {
387
208
  targets.push({
@@ -392,56 +213,251 @@ export class OutsideGuard {
392
213
  });
393
214
  }
394
215
 
395
- let isUnread = false;
216
+ let unread: string | undefined;
217
+ let assigned = new Set<string>();
396
218
 
397
219
  if (opts.input.command !== undefined) {
398
- let base = start;
399
- let pwd = startPwd;
400
-
401
220
  const parsed = ShellParser.parseChecked({ command: opts.input.command });
221
+ const folders = ShellFolders.foldersOf({
222
+ commands: parsed.commands,
223
+ cwd: start,
224
+ pwd: startPwd,
225
+ home,
226
+ env,
227
+ });
402
228
 
403
- isUnread = parsed.isOverBudget;
404
-
405
- for (const command of parsed.commands) {
406
- const program = ShellParser.programOf({ command });
229
+ unread = ShellUnread.reasonOf(parsed);
230
+ assigned = ShellFolders.assignedNames({ commands: parsed.commands });
407
231
 
408
- if (ShellParser.basenameOf({ word: program.name }) === 'cd') {
409
- const [destination] = positional({ args: program.args });
410
- const expanded =
411
- destination === undefined
412
- ? undefined
413
- : expandPath({ word: destination, home, env, cwd: pwd });
232
+ // A command's own redirects open in the folder it starts in, a `cd`'s included.
233
+ for (const [index, command] of parsed.commands.entries()) {
234
+ const folder = folders[index];
414
235
 
415
- base = expanded === undefined ? base : resolve(base, expanded);
416
- // A `cd` the guard cannot work out leaves the shell's folder unknown.
417
- pwd = expanded === undefined ? undefined : base;
236
+ if (folder === undefined) {
418
237
  continue;
419
238
  }
420
239
 
421
- targets.push(...targetsOf({ command, base, tmp }).map((target) => ({ ...target, pwd })));
240
+ for (const target of ShellWrites.targetsOf({ command, base: folder.base, tmp })) {
241
+ // A word that names a `for` variable stands for each of its values in turn.
242
+ for (const vars of loopCombinations({ word: target.word, loops: folder.loops })) {
243
+ targets.push({
244
+ ...target,
245
+ pwd: folder.pwd,
246
+ vars: { ...folder.vars, ...vars },
247
+ isKnown: folder.isKnown,
248
+ links: folder.links,
249
+ hasUnknownLink: folder.hasUnknownLink,
250
+ // The text of a word reads `'$S'` as a live `$S`; the shell takes the `$` as a character.
251
+ hasLiteralDollar:
252
+ target.word.includes('$') &&
253
+ (command.literalDollars ?? []).some(
254
+ (literal) => literal.includes(target.word) || target.word.includes(literal),
255
+ ),
256
+ });
257
+ }
258
+ }
422
259
  }
423
260
  }
424
261
 
425
262
  // Part of the line was not read: never an allow.
426
- const hits: IOutsideHit[] = isUnread
427
- ? [
428
- {
429
- path: '(the command line)',
430
- message:
431
- 'this command line is larger, or nests deeper, than the guard reads, so it could not be checked',
432
- isAgentToolScratchpad: false,
433
- },
434
- ]
435
- : [];
263
+ const hits: IOutsideHit[] =
264
+ unread === undefined
265
+ ? []
266
+ : [
267
+ {
268
+ path: '(the command line)',
269
+ message: unread,
270
+ isAgentToolScratchpad: false,
271
+ isUnread: true,
272
+ },
273
+ ];
436
274
 
437
275
  for (const target of targets) {
438
- const expanded = expandPath({ word: target.word, home, env, cwd: target.pwd });
276
+ if (target.hasUnreadBrace === true && target.isProtectedOnly !== true) {
277
+ hits.push({
278
+ path: target.word,
279
+ message: `${target.message}: the word has a brace pattern this check cannot expand`,
280
+ isAgentToolScratchpad: false,
281
+ isUnread: true,
282
+ });
283
+ }
284
+
285
+ // A link the line made under a name this check could not work out may be on any path that follows.
286
+ if (target.hasUnknownLink === true && target.isLinkRead !== true) {
287
+ hits.push({
288
+ path: target.word,
289
+ message: `${target.message}: the line made a symbolic link under a name this check cannot work out, so the path may go through it`,
290
+ isAgentToolScratchpad: false,
291
+ isUnread: true,
292
+ });
293
+ continue;
294
+ }
295
+
296
+ if (target.hasLiteralDollar === true) {
297
+ hits.push({
298
+ path: target.word,
299
+ message: `${target.message}: the word has a quoted or escaped $, which this check does not follow`,
300
+ isAgentToolScratchpad: false,
301
+ isUnread: true,
302
+ });
303
+ continue;
304
+ }
305
+
306
+ // A redirect to `dir/[version].md` (a VitePress route file) names that file when the pattern matches nothing in `dir`:
307
+ // the shell takes the word as written, and the written path is checked as it is. A match is written through, so it asks.
308
+ const isLiteralBracket =
309
+ target.isRedirect === true &&
310
+ target.isKnown !== false &&
311
+ BRACKET_NAME.test(target.word) &&
312
+ matchesNothing({ word: target.word, base: target.base });
313
+ const expanded = isLiteralBracket
314
+ ? target.word
315
+ : ShellFolders.expandPath({
316
+ word: target.word,
317
+ home,
318
+ env: { ...env, ...target.vars },
319
+ cwd: target.pwd,
320
+ });
321
+
322
+ if (expanded === undefined && target.isProtectedOnly === true) {
323
+ // A removal or an edit in place of a word this check cannot work out: nothing says it is a guard file.
324
+ continue;
325
+ }
439
326
 
440
327
  if (expanded === undefined) {
328
+ // Part of the word is unknown, but the folder in front of it may not be: that folder decides.
329
+ const lands = ShellFolders.folderOfUnknown({
330
+ word: target.word,
331
+ home,
332
+ env: { ...env, ...target.vars },
333
+ cwd: target.pwd,
334
+ base: target.base,
335
+ isKnown: target.isKnown ?? true,
336
+ assigned,
337
+ });
338
+ const folder = lands === undefined ? undefined : realOf({ path: lands });
339
+
340
+ if (
341
+ folder !== undefined &&
342
+ !isInside({ path: folder, root }) &&
343
+ !matchesAny({ path: `${folder}/x`, patterns })
344
+ ) {
345
+ hits.push({
346
+ path: folder,
347
+ message: `${target.message}: it lands in ${folder}, outside the project, whatever the expansion is`,
348
+ isAgentToolScratchpad: matchesAny({
349
+ path: folder,
350
+ patterns: HookConstants.AGENT_TOOL_SCRATCHPAD_PATTERNS,
351
+ }),
352
+ isUnread: false,
353
+ isLink: target.isLinkSource === true,
354
+ });
355
+
356
+ continue;
357
+ }
358
+
359
+ // A redirect to a word that cannot be worked out (`> $f`, `&>$fd`, `>&$fd`) may write a file outside the project.
360
+ if (target.isAmbiguous === true || target.isRedirect === true) {
361
+ hits.push({
362
+ path: target.word,
363
+ message: `${target.message}: the target has an expansion this check cannot work out`,
364
+ isAgentToolScratchpad: false,
365
+ isUnread: true,
366
+ });
367
+ }
368
+
441
369
  continue;
442
370
  }
443
371
 
444
- const path = realOf({ path: resolve(target.base, expanded) });
372
+ // A path at or through a link the line made is where the link points, which is not on disk yet to be followed. The name a
373
+ // link command makes is its own, so it is the command's destination and not a path through an earlier link.
374
+ const through = ShellFolders.passesThrough({
375
+ path: expanded,
376
+ base: target.base,
377
+ links: target.links ?? [],
378
+ isLastCounted: target.isLinkName !== true,
379
+ });
380
+
381
+ if (through !== undefined) {
382
+ hits.push({
383
+ path: target.word,
384
+ message:
385
+ through === 'dangling'
386
+ ? `${target.message}: the path is, or goes through, a dangling link, which may lead where this line makes a link`
387
+ : `${target.message}: the path is, or goes through, a link this line made, which this check does not follow`,
388
+ isAgentToolScratchpad: false,
389
+ isUnread: true,
390
+ });
391
+
392
+ continue;
393
+ }
394
+
395
+ // What a copy or a move reads is not written, and a link it reads has been looked at above.
396
+ if (target.isLinkRead === true) {
397
+ continue;
398
+ }
399
+
400
+ // After a `cd` this check could not work out, `base` is only the last folder it knew: a relative path cannot be placed.
401
+ if (!isAbsolute(expanded) && target.isKnown === false) {
402
+ hits.push({
403
+ path: target.word,
404
+ message: `${target.message}: it is a relative path after a \`cd\` this check cannot work out`,
405
+ isAgentToolScratchpad: false,
406
+ isUnread: true,
407
+ });
408
+
409
+ continue;
410
+ }
411
+
412
+ const written = isAbsolute(expanded) ? expanded : `${target.base}/${expanded}`;
413
+
414
+ // `/proc/self` and `/dev/fd` name the hook's own process, not the shell the command runs in.
415
+ if (PROCESS_FILES.test(written)) {
416
+ hits.push({
417
+ path: written,
418
+ message: `${target.message}: a path under /proc or /dev/fd names a process, which this check cannot follow`,
419
+ isAgentToolScratchpad: false,
420
+ isUnread: true,
421
+ });
422
+
423
+ continue;
424
+ }
425
+
426
+ // Not folded here: a `..` after a symlink goes where the link points, which `realOf` follows.
427
+ const path = realOf({ path: written });
428
+
429
+ if (path === undefined) {
430
+ hits.push({
431
+ path: written,
432
+ message: `${target.message}: the path goes through more links than the system follows`,
433
+ isAgentToolScratchpad: false,
434
+ isUnread: true,
435
+ });
436
+
437
+ continue;
438
+ }
439
+
440
+ // A write to a file the guards read their policy from switches a guard off: denied whatever the project sets.
441
+ const isRemoval = target.isProtectedOnly === true;
442
+
443
+ if (
444
+ isProtectedFile({ path, root, isRemoval }) ||
445
+ isProtectedFile({ path: resolve(written), root, isRemoval })
446
+ ) {
447
+ hits.push({
448
+ path,
449
+ message: `${target.message}: it is one of the files the guards read their policy from`,
450
+ isAgentToolScratchpad: false,
451
+ isUnread: false,
452
+ isProtected: true,
453
+ });
454
+
455
+ continue;
456
+ }
457
+
458
+ if (isRemoval) {
459
+ continue;
460
+ }
445
461
 
446
462
  if (!isInside({ path, root }) && !matchesAny({ path, patterns })) {
447
463
  hits.push({
@@ -451,10 +467,17 @@ export class OutsideGuard {
451
467
  path,
452
468
  patterns: HookConstants.AGENT_TOOL_SCRATCHPAD_PATTERNS,
453
469
  }),
470
+ isUnread: false,
471
+ isLink: target.isLinkSource === true,
454
472
  });
455
473
  }
456
474
  }
457
475
 
458
- return hits;
476
+ // A loop makes one target of a word for each value it takes: a finding is told once.
477
+ return hits.filter(
478
+ (hit, index) =>
479
+ hits.findIndex((other) => other.message === hit.message && other.path === hit.path) ===
480
+ index,
481
+ );
459
482
  }
460
483
  }