@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
@@ -0,0 +1,760 @@
1
+ import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
+ import { ShellParser } from './shell.ts';
4
+ import type { ISimpleCommand } from './shell.ts';
5
+ import { LinkMakers } from './link-makers.ts';
6
+
7
+ export type TEnvironment = Record<string, string | undefined>;
8
+
9
+ /** The folder a simple command runs in, as far as the line shows it. */
10
+ export interface IShellFolder {
11
+ /** The folder a relative word is taken from: the start, moved by every `cd` the guard could work out. */
12
+ base: string;
13
+ /** What `$PWD` is in a word; `undefined` when it is not known. */
14
+ pwd: string | undefined;
15
+ /** False after a `cd` the guard could not work out: `base` is then only the last folder it knew. */
16
+ isKnown: boolean;
17
+ /** The plain `NAME=value` words an earlier command of this same shell set; they win over the environment in a word. */
18
+ vars: Record<string, string>;
19
+ /**
20
+ * The variables of the `for NAME in a b` loops the command sits in, with the literal values each takes. The word of a
21
+ * command that names one stands for every value in turn.
22
+ */
23
+ loops: Record<string, string[]>;
24
+ /** The absolute names of the symbolic links the line made (`ln -s`) before this command: the system reads them when the command runs. */
25
+ links: string[];
26
+ /** Whether the line made a symbolic link whose name this check could not work out, or ran `ln` where it cannot read it: any path after it may go through one. */
27
+ hasUnknownLink: boolean;
28
+ }
29
+
30
+ interface IFolderState extends Omit<IShellFolder, 'loops' | 'links' | 'hasUnknownLink'> {
31
+ /** The folders `pushd` saved, for `popd`. */
32
+ stack: Omit<IShellFolder, 'vars' | 'loops' | 'links' | 'hasUnknownLink'>[];
33
+ /** A `cd`, `pushd` or `popd` ran in this scope. */
34
+ hasMoved: boolean;
35
+ }
36
+
37
+ /** A value the guard may hold as written: no expansion, quote, glob or tilde in it. */
38
+ const PLAIN_VALUE = /^[\w@%+=:,./-]+$/;
39
+
40
+ /** The most values of loop variables one word is checked for; a word with more is left unread. */
41
+ const MAX_COMBINATIONS = 64;
42
+
43
+ /**
44
+ * The values the loop variables `word` names take, one set per combination: `[{}]` when it names none. A word that would
45
+ * need more than `MAX_COMBINATIONS` is checked with no value, so its variable stays unknown and the word is not read.
46
+ */
47
+ export const loopCombinations = (opts: {
48
+ word: string;
49
+ loops: Record<string, string[]>;
50
+ }): Record<string, string>[] => {
51
+ const named = [
52
+ ...new Set(
53
+ [...opts.word.matchAll(/\$(?:([A-Za-z_]\w*)|\{([A-Za-z_]\w*)\})/g)].map(
54
+ (match) => match[1] ?? match[2] ?? '',
55
+ ),
56
+ ),
57
+ ].filter((name) => Object.hasOwn(opts.loops, name));
58
+ let combinations: Record<string, string>[] = [{}];
59
+
60
+ for (const name of named) {
61
+ const values = opts.loops[name] ?? [];
62
+
63
+ combinations = combinations.flatMap((combination) =>
64
+ values.map((value) => ({ ...combination, [name]: value })),
65
+ );
66
+
67
+ if (combinations.length > MAX_COMBINATIONS) {
68
+ return [{}];
69
+ }
70
+ }
71
+
72
+ return combinations;
73
+ };
74
+
75
+ /** A variable as the shell takes it with no operator: `$NAME` or `${NAME}`. */
76
+ const VARIABLE = /\$(?:([A-Za-z_]\w*)|\{([A-Za-z_]\w*)\})/g;
77
+
78
+ /** Programs that run the command they are given as words: a link made through one is not read where it is made. */
79
+ const RUNNERS_OF_COMMANDS = new Set([
80
+ 'xargs',
81
+ 'find',
82
+ 'parallel',
83
+ 'env',
84
+ 'sudo',
85
+ 'doas',
86
+ 'nohup',
87
+ 'nice',
88
+ 'time',
89
+ 'timeout',
90
+ 'command',
91
+ 'exec',
92
+ 'setsid',
93
+ 'stdbuf',
94
+ 'watch',
95
+ 'chroot',
96
+ 'nsenter',
97
+ 'unshare',
98
+ ]);
99
+
100
+ /** The links one path may pass through before it is taken for a loop, as the system counts them. */
101
+ const MAX_LINK_HOPS = 40;
102
+
103
+ /** The most values one `for` list may hold before the guard stops following it. */
104
+ const MAX_LOOP_VALUES = 16;
105
+
106
+ /** The words that may stand in front of a command on its line (`do echo`, `then for`), as the parser keeps them. */
107
+ const LEADING_KEYWORDS = new Set(['do', 'then', 'else', '{', '!']);
108
+
109
+ /** Words of a command that start a loop closed by `done`. */
110
+ const LOOP_STARTS = new Set(['for', 'while', 'until', 'select']);
111
+
112
+ /** The commands that can set a variable of the shell by name or by text: a loop variable is not followed past them. */
113
+ const REBINDING_PROGRAMS = new Set([
114
+ 'eval',
115
+ 'source',
116
+ '.',
117
+ 'declare',
118
+ 'typeset',
119
+ 'local',
120
+ 'nameref',
121
+ ]);
122
+
123
+ interface IOpenLoop {
124
+ /** The variable and its literal values; `undefined` for a loop whose variable the guard does not follow. */
125
+ bound?: { name: string; values: string[] };
126
+ }
127
+
128
+ /** `words` without the keywords in front of the command. */
129
+ const commandWordsOf = (opts: { words: string[] }): string[] => {
130
+ const at = opts.words.findIndex((word) => !LEADING_KEYWORDS.has(word));
131
+
132
+ return at === -1 ? [] : opts.words.slice(at);
133
+ };
134
+
135
+ /** The value of an assignment with the variables the line already holds put in; `undefined` when it is not plain. */
136
+ const literalOf = (opts: { value: string; vars: Record<string, string> }): string | undefined => {
137
+ let unresolved = false;
138
+ const value = opts.value.replace(
139
+ VARIABLE,
140
+ (_, bare: string | undefined, braced: string | undefined) => {
141
+ const name = bare ?? braced ?? '';
142
+ const known = Object.hasOwn(opts.vars, name) ? opts.vars[name] : undefined;
143
+
144
+ if (known === undefined) {
145
+ unresolved = true;
146
+ }
147
+
148
+ return known ?? '';
149
+ },
150
+ );
151
+
152
+ return unresolved || !PLAIN_VALUE.test(value) ? undefined : value;
153
+ };
154
+
155
+ export class ShellFolders {
156
+ /** The builtins that change the shell's folder. */
157
+ static readonly MOVING_COMMANDS: ReadonlySet<string> = new Set(['cd', 'pushd', 'popd']);
158
+
159
+ /** The home folder of a user, read from the password file; `undefined` for a name it does not list. */
160
+ private static homeOf(opts: { name: string }): string | undefined {
161
+ try {
162
+ for (const line of readFileSync('/etc/passwd', 'utf8').split('\n')) {
163
+ const fields = line.split(':');
164
+
165
+ if (fields[0] === opts.name) {
166
+ return fields[5];
167
+ }
168
+ }
169
+ } catch {
170
+ return undefined;
171
+ }
172
+
173
+ return undefined;
174
+ }
175
+
176
+ /**
177
+ * `~` and `$NAME` / `${NAME}` expanded; `undefined` when a variable is unset or the word is not a plain path.
178
+ * `$PWD` is the folder the command runs in (`cwd`), not the `PWD` of this hook's own process.
179
+ */
180
+ static expandPath(opts: {
181
+ word: string;
182
+ home: string;
183
+ env: TEnvironment;
184
+ cwd?: string;
185
+ }): string | undefined {
186
+ if (opts.word === '' || /[`*?[]/.test(opts.word) || opts.word.includes('$(')) {
187
+ return undefined;
188
+ }
189
+
190
+ let unresolved = false;
191
+ // `~` is the home folder, `~+` the working folder, `~name` the home of that user. A name the password file does
192
+ // not list, and `~-` (the shell's previous folder, not known here), stay as written: a plain path, as bash
193
+ // leaves an unknown `~name`.
194
+ const tilde = opts.word.startsWith('~') ? /^~([^/]*)/.exec(opts.word) : null;
195
+ const user = tilde?.[1] ?? '';
196
+ let home: string | undefined = user === '' ? opts.home : undefined;
197
+
198
+ if (user === '+') {
199
+ home = opts.cwd;
200
+ } else if (user !== '' && user !== '-') {
201
+ home = ShellFolders.homeOf({ name: user });
202
+ }
203
+
204
+ const withHome =
205
+ tilde === null || home === undefined
206
+ ? opts.word
207
+ : `${home}${opts.word.slice(tilde[0].length)}`;
208
+ const expanded = withHome.replace(
209
+ VARIABLE,
210
+ (_, bare: string | undefined, braced: string | undefined) => {
211
+ const name = bare ?? braced ?? '';
212
+ const value = name === 'PWD' && opts.cwd !== undefined ? opts.cwd : opts.env[name];
213
+
214
+ if (value === undefined || value === '') {
215
+ unresolved = true;
216
+ }
217
+
218
+ return value ?? '';
219
+ },
220
+ );
221
+
222
+ // A `$` left over is an expansion with an operator (`${S/a/..}`, `${S#x}`, `${!S}`) or a special parameter (`$$`, `$?`):
223
+ // the value is not the plain text of a variable, so the word is not worked out.
224
+ return unresolved || expanded.includes('$') ? undefined : expanded;
225
+ }
226
+
227
+ /** The name as the system sees it: the real path of the part that exists, then the rest as written. */
228
+ static physicalOf(opts: { path: string }): string {
229
+ const rest: string[] = [];
230
+ let existing = opts.path;
231
+
232
+ while (existing !== dirname(existing)) {
233
+ try {
234
+ return join(realpathSync(existing), ...rest.reverse());
235
+ } catch {
236
+ rest.push(basename(existing));
237
+ existing = dirname(existing);
238
+ }
239
+ }
240
+
241
+ return opts.path;
242
+ }
243
+
244
+ /**
245
+ * Whether the path, read name by name from `base`, passes through one of `links` (absolute names): a link is followed where it
246
+ * points, so what comes after it, a `..` included, is not where the text says. The last name counts only when `isLastCounted` (a
247
+ * `cd` into the link itself), not for a file written at the link's own name.
248
+ */
249
+ static passesThrough(opts: {
250
+ path: string;
251
+ base: string;
252
+ links: string[];
253
+ isLastCounted: boolean;
254
+ }): 'made' | 'dangling' | undefined {
255
+ interface IStep {
256
+ part: string;
257
+ /** A link of the line at this name counts. */
258
+ counts: boolean;
259
+ /** The last name of the path being read. */
260
+ isEnd: boolean;
261
+ }
262
+
263
+ const parts = opts.path.split('/').filter((part) => part !== '' && part !== '.');
264
+ const pending: IStep[] = parts
265
+ .map((part, index) => ({
266
+ part,
267
+ counts: index < parts.length - 1 || opts.isLastCounted,
268
+ isEnd: index === parts.length - 1,
269
+ }))
270
+ .reverse();
271
+ let current = isAbsolute(opts.path) ? '/' : opts.base;
272
+ let hops = 0;
273
+
274
+ for (;;) {
275
+ const step = pending.pop();
276
+
277
+ if (step === undefined) {
278
+ return undefined;
279
+ }
280
+
281
+ if (step.part === '..') {
282
+ if (opts.links.includes(current)) {
283
+ return 'made';
284
+ }
285
+
286
+ current = dirname(current);
287
+ continue;
288
+ }
289
+
290
+ current = join(current, step.part);
291
+
292
+ if (step.counts && opts.links.includes(current)) {
293
+ return 'made';
294
+ }
295
+
296
+ // A link already on disk is followed where it points: it may lead to a link this line makes, and a link that points at
297
+ // nothing yet, in the middle of a path, is where this line may make the folder it needs.
298
+ let target: string | undefined;
299
+
300
+ try {
301
+ target = lstatSync(current).isSymbolicLink() ? readlinkSync(current) : undefined;
302
+ } catch {
303
+ target = undefined;
304
+ }
305
+
306
+ if (target === undefined) {
307
+ continue;
308
+ }
309
+
310
+ hops += 1;
311
+
312
+ // A name the command makes itself is not a path through a link of the line, even when it dangles.
313
+ if (hops > MAX_LINK_HOPS) {
314
+ return 'made';
315
+ }
316
+
317
+ if ((!step.isEnd || step.counts) && !existsSync(current)) {
318
+ return 'dangling';
319
+ }
320
+
321
+ current = isAbsolute(target) ? '/' : dirname(current);
322
+
323
+ const followed = target.split('/').filter((part) => part !== '' && part !== '.');
324
+
325
+ pending.push(
326
+ ...followed
327
+ .map((part, index) => ({
328
+ part,
329
+ counts: true,
330
+ isEnd: step.isEnd && index === followed.length - 1,
331
+ }))
332
+ .reverse(),
333
+ );
334
+ }
335
+ }
336
+
337
+ /**
338
+ * The folder a word lands in when part of it cannot be worked out (`/etc/$X`, `~/.ssh/key$N`, `/etc/*.conf`): the
339
+ * longest run of folders in front of the unknown part that `expandPath` can work out; a name with no folder in
340
+ * front of it is in `base`. `undefined` when the first folder is the unknown part (`$D/x`; `$f` when the line
341
+ * assigned `f`, whose value may be a path of its own), the word is `~` followed by an unknown name, or it is taken
342
+ * from a `base` the guard lost (`isKnown` false).
343
+ */
344
+ static folderOfUnknown(opts: {
345
+ word: string;
346
+ home: string;
347
+ env: TEnvironment;
348
+ cwd?: string;
349
+ base: string;
350
+ isKnown: boolean;
351
+ /** The names the line assigned. */
352
+ assigned: ReadonlySet<string>;
353
+ }): string | undefined {
354
+ const parts = opts.word.split('/');
355
+
356
+ for (let count = parts.length - 1; count >= 1; count -= 1) {
357
+ const folder = ShellFolders.expandPath({
358
+ word: `${parts.slice(0, count).join('/')}/`,
359
+ home: opts.home,
360
+ env: opts.env,
361
+ cwd: opts.cwd,
362
+ });
363
+
364
+ if (folder !== undefined) {
365
+ return isAbsolute(folder) ? folder : opts.isKnown ? `${opts.base}/${folder}` : undefined;
366
+ }
367
+ }
368
+
369
+ const name = /^\$\{?(\w+)/.exec(opts.word)?.[1];
370
+ const isUnknown =
371
+ !opts.isKnown ||
372
+ parts.length > 1 ||
373
+ opts.word.startsWith('~') ||
374
+ (name !== undefined && opts.assigned.has(name));
375
+
376
+ return isUnknown ? undefined : opts.base;
377
+ }
378
+
379
+ /**
380
+ * How often each name is assigned on the line. A word `NAME=value` counts as an assignment too, because the parser
381
+ * keeps it as a word where a keyword (`do`, `then`) stands in front of it.
382
+ */
383
+ private static assignmentCounts(opts: { commands: ISimpleCommand[] }): Map<string, number> {
384
+ const counts = new Map<string, number>();
385
+
386
+ for (const command of opts.commands) {
387
+ for (const word of [...command.assignments, ...command.words]) {
388
+ const name = /^([A-Za-z_]\w*)=/.exec(word)?.[1];
389
+
390
+ if (name !== undefined) {
391
+ counts.set(name, (counts.get(name) ?? 0) + 1);
392
+ }
393
+ }
394
+ }
395
+
396
+ return counts;
397
+ }
398
+
399
+ /**
400
+ * How often each name is the variable of a `for NAME in ...` header, or is named as a word of any other command (`read NAME`,
401
+ * `unset NAME`, `NAME=value` inside a word): a loop variable is followed only when its header is the one place that sets it.
402
+ */
403
+ private static loopNamesOf(opts: { commands: ISimpleCommand[] }): Map<string, number> {
404
+ const counts = new Map<string, number>();
405
+ const bump = (name: string): void => {
406
+ counts.set(name, (counts.get(name) ?? 0) + 1);
407
+ };
408
+
409
+ for (const command of opts.commands) {
410
+ const words = commandWordsOf({ words: command.words });
411
+ const isHeader = words[0] === 'for' && /^[A-Za-z_]\w*$/.test(words[1] ?? '');
412
+
413
+ if (isHeader) {
414
+ bump(words[1] ?? '');
415
+ }
416
+
417
+ for (const word of isHeader ? words.slice(2) : command.words) {
418
+ if (/^[A-Za-z_]\w*$/.test(word)) {
419
+ bump(word);
420
+ } else {
421
+ const assigned = /^([A-Za-z_]\w*)\+?=/.exec(word)?.[1];
422
+
423
+ if (assigned !== undefined) {
424
+ bump(assigned);
425
+ }
426
+ }
427
+ }
428
+ }
429
+
430
+ return counts;
431
+ }
432
+
433
+ /** The names the line assigns. */
434
+ static assignedNames(opts: { commands: ISimpleCommand[] }): Set<string> {
435
+ return new Set(ShellFolders.assignmentCounts(opts).keys());
436
+ }
437
+
438
+ /**
439
+ * The variables a line cannot be trusted to have kept: assigned more than once, or named anywhere else in the line
440
+ * (`for NAME`, `read NAME`, `printf -v NAME`, a nameref, `eval`).
441
+ */
442
+ private static reboundOf(opts: { commands: ISimpleCommand[] }): Set<string> {
443
+ const counts = ShellFolders.assignmentCounts({ commands: opts.commands });
444
+
445
+ // `export NAME` marks the variable for the children of the shell and changes nothing of its value.
446
+ const texts = opts.commands.flatMap((command) => [
447
+ ...(command.words[0] === 'export'
448
+ ? command.words
449
+ .filter((word) => word.includes('='))
450
+ .map((word) => word.slice(word.indexOf('=') + 1))
451
+ : command.words),
452
+ ...command.assignments.map((assignment) => assignment.slice(assignment.indexOf('=') + 1)),
453
+ ]);
454
+
455
+ return new Set(
456
+ [...counts.entries()]
457
+ .filter(
458
+ ([name, count]) =>
459
+ count > 1 ||
460
+ !/^[A-Za-z_]\w*$/.test(name) ||
461
+ texts.some((text) =>
462
+ new RegExp(`\\b${name}\\b`).test(
463
+ text.replaceAll(`\${${name}}`, '').replaceAll(`$${name}`, ''),
464
+ ),
465
+ ),
466
+ )
467
+ .map(([name]) => name),
468
+ );
469
+ }
470
+
471
+ /**
472
+ * The folder each of `commands` runs in, in their order. A `cd`, `pushd` or `popd` moves the commands after
473
+ * it in its own scope; a subshell starts where its parent is and gives nothing back. A command line a word
474
+ * carries (`$(...)`, `sh -c`) starts where the command that carries it started; without that command in
475
+ * `commands`, where its parent is when the parent never moves, else in a folder that is not known. A `cd` in
476
+ * a pipeline is not known either.
477
+ */
478
+ static foldersOf(opts: {
479
+ commands: ISimpleCommand[];
480
+ cwd: string;
481
+ pwd: string | undefined;
482
+ /** False when the folder the line starts in is itself not known. */
483
+ isKnown?: boolean;
484
+ home: string;
485
+ env: TEnvironment;
486
+ }): IShellFolder[] {
487
+ const states = new Map<string, IFolderState>();
488
+ const piped = new Set(opts.commands.flatMap((command) => command.input?.pipedFrom ?? []));
489
+ const rebound = ShellFolders.reboundOf({ commands: opts.commands });
490
+ const assigned = ShellFolders.assignedNames({ commands: opts.commands });
491
+ const isLoopFollowed = !opts.commands.some((command) =>
492
+ REBINDING_PROGRAMS.has(
493
+ ShellParser.basenameOf({ word: ShellParser.programOf({ command }).name }),
494
+ ),
495
+ );
496
+ const loops: IOpenLoop[] = [];
497
+ const links: string[] = [];
498
+ // A command line a word carries (`sh -c`, `$(...)`) is listed after the commands of the line, so its links are not seen in order.
499
+ let hasUnknownLink = opts.commands.some(
500
+ (command) =>
501
+ (command.scope ?? '').includes('>') &&
502
+ (LinkMakers.of({
503
+ name: ShellParser.basenameOf({ word: ShellParser.programOf({ command }).name }),
504
+ args: ShellParser.programOf({ command }).args,
505
+ })?.names.length ?? 0) > 0,
506
+ );
507
+ const loopNames = ShellFolders.loopNamesOf({ commands: opts.commands });
508
+ // `cd x` looks for `x` in each folder of CDPATH first: set in the environment of the hook or named anywhere on the line
509
+ // (a prefix assignment, `export`, `declare`), it may put a plain relative name in another folder.
510
+ const hasCdpath =
511
+ (opts.env.CDPATH ?? '') !== '' ||
512
+ opts.commands.some((command) =>
513
+ [...command.words, ...command.assignments].some((word) => word.includes('CDPATH')),
514
+ );
515
+ // The folder each command started in, for the command lines its words carry.
516
+ const started = new Map<ISimpleCommand, IShellFolder>();
517
+ const stateOf = (scope: string, carrier: ISimpleCommand | undefined): IFolderState => {
518
+ const known = states.get(scope);
519
+
520
+ if (known !== undefined) {
521
+ return known;
522
+ }
523
+
524
+ const cut = Math.max(scope.lastIndexOf('/'), scope.lastIndexOf('>'));
525
+ const parent = cut === -1 ? undefined : stateOf(scope.slice(0, cut), undefined);
526
+ const isNested = cut !== -1 && scope[cut] === '>';
527
+ const from = isNested && carrier !== undefined ? started.get(carrier) : undefined;
528
+ const state: IFolderState =
529
+ parent === undefined
530
+ ? {
531
+ base: resolve(opts.cwd),
532
+ pwd: opts.pwd,
533
+ isKnown: opts.isKnown ?? true,
534
+ vars: {},
535
+ stack: [],
536
+ hasMoved: false,
537
+ }
538
+ : {
539
+ base: from?.base ?? parent.base,
540
+ pwd: from === undefined ? parent.pwd : from.pwd,
541
+ isKnown: from?.isKnown ?? (parent.isKnown && !(isNested && parent.hasMoved)),
542
+ vars: isNested ? {} : { ...parent.vars },
543
+ stack: [...parent.stack],
544
+ hasMoved: false,
545
+ };
546
+
547
+ states.set(scope, state);
548
+
549
+ return state;
550
+ };
551
+
552
+ return opts.commands.map((command) => {
553
+ const state = stateOf(command.scope ?? '', command.carrier);
554
+ const isNested = (command.scope ?? '').includes('>');
555
+ const words = commandWordsOf({ words: command.words });
556
+ const folder: IShellFolder = {
557
+ base: state.base,
558
+ pwd: state.pwd,
559
+ isKnown: state.isKnown,
560
+ vars: { ...state.vars },
561
+ // A command line a word carries (`sh -c`, `$(...)`) is another shell: it does not see the loop variables.
562
+ loops: isNested
563
+ ? {}
564
+ : Object.fromEntries(
565
+ loops.flatMap((loop) =>
566
+ loop.bound === undefined ? [] : [[loop.bound.name, loop.bound.values]],
567
+ ),
568
+ ),
569
+ links: [...links],
570
+ hasUnknownLink,
571
+ };
572
+
573
+ started.set(command, folder);
574
+
575
+ // A symbolic link the line makes is a name later words may go through: the system follows it when they run.
576
+ const made = ShellParser.programOf({ command });
577
+ const maker = LinkMakers.of({
578
+ name: ShellParser.basenameOf({ word: made.name }),
579
+ args: made.args,
580
+ });
581
+
582
+ const carried = LinkMakers.carriedTo({
583
+ name: ShellParser.basenameOf({ word: made.name }),
584
+ args: made.args,
585
+ });
586
+
587
+ for (const name of [...(maker?.names ?? []), ...carried]) {
588
+ // A name that holds a loop variable stands for each of its values.
589
+ for (const vars of loopCombinations({ word: name, loops: folder.loops })) {
590
+ const expanded = ShellFolders.expandPath({
591
+ word: name,
592
+ home: opts.home,
593
+ env: { ...opts.env, ...state.vars, ...vars },
594
+ cwd: state.pwd,
595
+ });
596
+
597
+ if (expanded === undefined) {
598
+ hasUnknownLink = true;
599
+ } else {
600
+ const lexical = isAbsolute(expanded) ? expanded : resolve(state.base, expanded);
601
+
602
+ // The walk of a path is physical, through the links already on disk: the name is kept both ways.
603
+ links.push(lexical, ShellFolders.physicalOf({ path: lexical }));
604
+ }
605
+ }
606
+ }
607
+
608
+ // A program that runs another one with the words it is given may run `ln` or `cp` where this check does not read it.
609
+ if (
610
+ command.words.some((word) => RUNNERS_OF_COMMANDS.has(ShellParser.basenameOf({ word }))) &&
611
+ command.words.some((word) => ['ln', 'cp'].includes(ShellParser.basenameOf({ word })))
612
+ ) {
613
+ hasUnknownLink = true;
614
+ }
615
+
616
+ if (!isNested) {
617
+ if (words[0] === 'done') {
618
+ loops.pop();
619
+ } else if (words[0] !== undefined && LOOP_STARTS.has(words[0])) {
620
+ const name = words[1] ?? '';
621
+ const values = words.slice(3);
622
+ const isBound =
623
+ words[0] === 'for' &&
624
+ isLoopFollowed &&
625
+ loopNames.get(name) === 1 &&
626
+ !assigned.has(name) &&
627
+ words[2] === 'in' &&
628
+ values.length > 0 &&
629
+ values.length <= MAX_LOOP_VALUES &&
630
+ values.every((value) => PLAIN_VALUE.test(value)) &&
631
+ !values.some((value) => command.literalDollars?.includes(value));
632
+
633
+ loops.push(isBound ? { bound: { name, values } } : {});
634
+ }
635
+ }
636
+
637
+ // A command that is only assignments sets them in its own shell, unless it is a stage of a pipeline. `export NAME=value`
638
+ // sets them the same way.
639
+ const isExport = command.words[0] === 'export';
640
+
641
+ if (
642
+ (command.words.length === 0 || isExport) &&
643
+ !piped.has(command) &&
644
+ command.input?.pipedFrom === undefined
645
+ ) {
646
+ for (const assignment of isExport
647
+ ? command.words.filter((word) => word.includes('='))
648
+ : command.assignments) {
649
+ const at = assignment.indexOf('=');
650
+ const name = assignment.slice(0, at);
651
+ const value = literalOf({ value: assignment.slice(at + 1), vars: state.vars });
652
+
653
+ if (
654
+ at > 0 &&
655
+ !rebound.has(name) &&
656
+ value !== undefined &&
657
+ !command.literalDollars?.includes(assignment)
658
+ ) {
659
+ state.vars[name] = value;
660
+ }
661
+ }
662
+ }
663
+ const program = ShellParser.programOf({ command });
664
+ const name = ShellParser.basenameOf({ word: program.name });
665
+
666
+ if (!ShellFolders.MOVING_COMMANDS.has(name)) {
667
+ return folder;
668
+ }
669
+
670
+ state.hasMoved = true;
671
+
672
+ if (piped.has(command) || command.input?.pipedFrom !== undefined) {
673
+ state.isKnown = false;
674
+
675
+ return folder;
676
+ }
677
+
678
+ // The variables the line set earlier win over the environment in a folder word, as in any other word.
679
+ ShellFolders.move({
680
+ ...opts,
681
+ env: { ...opts.env, ...state.vars },
682
+ state,
683
+ name,
684
+ args: program.args,
685
+ literalDollars: command.literalDollars ?? [],
686
+ hasCdpath,
687
+ links: folder.links,
688
+ });
689
+
690
+ return folder;
691
+ });
692
+ }
693
+
694
+ /** One `cd`, `pushd` or `popd` applied to `state`. */
695
+ private static move(opts: {
696
+ state: IFolderState;
697
+ name: string;
698
+ args: string[];
699
+ /** Words of the command that hold a quoted or escaped `$`. */
700
+ literalDollars: string[];
701
+ /** CDPATH is set, in the environment or on the line. */
702
+ hasCdpath: boolean;
703
+ /** The symbolic links the line made before this `cd`. */
704
+ links: string[];
705
+ home: string;
706
+ env: TEnvironment;
707
+ }): void {
708
+ const { state } = opts;
709
+ const words = opts.args.filter((word) => !/^-[LPe@]+$/.test(word) && word !== '--');
710
+
711
+ if (opts.name === 'popd') {
712
+ const saved = words.length === 0 ? state.stack.pop() : undefined;
713
+
714
+ Object.assign(state, saved ?? { pwd: undefined, isKnown: false });
715
+
716
+ return;
717
+ }
718
+
719
+ const [destination] = words;
720
+ const target = destination ?? (opts.name === 'cd' && opts.home !== '' ? '~' : undefined);
721
+ // `cd -` and `pushd +N` name a folder from the shell's own history.
722
+ const expanded =
723
+ target === undefined || /^[-+]/.test(target) || opts.literalDollars.includes(target)
724
+ ? undefined
725
+ : ShellFolders.expandPath({ word: target, home: opts.home, env: opts.env, cwd: state.pwd });
726
+
727
+ if (opts.name === 'pushd') {
728
+ state.stack.push({ base: state.base, pwd: state.pwd, isKnown: state.isKnown });
729
+ }
730
+
731
+ // A relative name that does not start with `./` or `../` (and is not `.` or `..`) is searched in the folders of CDPATH first, so it may land in another folder.
732
+ const isSearched =
733
+ expanded !== undefined &&
734
+ opts.hasCdpath &&
735
+ !isAbsolute(expanded) &&
736
+ !/^\.{1,2}(?:\/|$)/.test(expanded);
737
+
738
+ // A `cd` through a link the line just made lands where the link points, which the folder tree on disk does not show yet.
739
+ const isLinked =
740
+ expanded !== undefined &&
741
+ ShellFolders.passesThrough({
742
+ path: expanded,
743
+ base: state.base,
744
+ links: opts.links,
745
+ isLastCounted: true,
746
+ }) !== undefined;
747
+
748
+ // A `cd` the guard cannot work out leaves the shell's folder unknown.
749
+ if (expanded === undefined || isSearched || isLinked) {
750
+ state.pwd = undefined;
751
+ state.isKnown = false;
752
+
753
+ return;
754
+ }
755
+
756
+ state.base = resolve(state.base, expanded);
757
+ state.pwd = state.base;
758
+ state.isKnown ||= isAbsolute(expanded);
759
+ }
760
+ }