@venizia/vulcan 0.4.5 → 0.4.7

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 (54) hide show
  1. package/LICENSE.md +1 -1
  2. package/README.md +13 -0
  3. package/base/checks/wiki-anchors.ts +8 -0
  4. package/base/checks/wiki-source-links.ts +8 -0
  5. package/base/hooks/guard-git.ts +9 -2
  6. package/base/hooks/guard-writes.ts +4 -0
  7. package/base/hooks/session-start.ts +14 -4
  8. package/base/make/vulcan.mk +12 -1
  9. package/base/references/delegation-brief.md +5 -4
  10. package/base/rules.md +2 -2
  11. package/base/skills/docs-writing/SKILL.md +1 -1
  12. package/base/skills/docs-writing/references/agent-documents.md +1 -1
  13. package/base/skills/knowledge-sync/SKILL.md +1 -1
  14. package/base/skills/plan-a-change/SKILL.md +2 -2
  15. package/base/skills/plan-a-change/evals/evals.json +6 -0
  16. package/base/skills/plan-a-change/references/spec-card.md +1 -0
  17. package/base/skills/report-back/SKILL.md +1 -1
  18. package/base/skills/retro/SKILL.md +1 -1
  19. package/base/skills/review-a-change/SKILL.md +1 -1
  20. package/base/skills/ship/SKILL.md +1 -1
  21. package/base/skills/visualize-work/SKILL.md +33 -11
  22. package/base/skills/visualize-work/references/spec.md +77 -12
  23. package/package.json +4 -4
  24. package/src/config/schema.ts +58 -4
  25. package/src/doctor/checks.ts +29 -1
  26. package/src/doctor/runner.ts +2 -0
  27. package/src/hooks/command-view.ts +24 -0
  28. package/src/hooks/common/constants.ts +10 -0
  29. package/src/hooks/guard-git.ts +78 -2
  30. package/src/hooks/guard-outside.ts +20 -3
  31. package/src/hooks/guard-writes.ts +17 -6
  32. package/src/hooks/index.ts +2 -0
  33. package/src/hooks/project-guards.ts +123 -0
  34. package/src/hooks/project-tmp.ts +36 -0
  35. package/src/hooks/session-digest.ts +5 -0
  36. package/src/manifest/render.ts +38 -0
  37. package/src/sync/claude-launch.ts +48 -0
  38. package/src/sync/index.ts +1 -0
  39. package/src/sync/local-choice.ts +2 -0
  40. package/src/visualize/assets.ts +195 -54
  41. package/src/visualize/charts.ts +235 -0
  42. package/src/visualize/constants.ts +106 -1
  43. package/src/visualize/diagrams.ts +224 -0
  44. package/src/visualize/icons.ts +28 -0
  45. package/src/visualize/layout.ts +58 -8
  46. package/src/visualize/page.ts +152 -146
  47. package/src/visualize/schema.ts +246 -0
  48. package/src/visualize/sections.ts +370 -0
  49. package/src/visualize/validate.ts +100 -7
  50. package/src/wiki/anchors.ts +118 -0
  51. package/src/wiki/command.ts +110 -0
  52. package/src/wiki/constants.ts +30 -0
  53. package/src/wiki/index.ts +4 -0
  54. package/src/wiki/source-links.ts +186 -0
@@ -11,6 +11,41 @@ const HOOK_EVENT = z.string().refine((value) => HookEvents.isValid(value), {
11
11
  message: `one of: ${[...HookEvents.SCHEME_SET].join(', ')}`,
12
12
  });
13
13
 
14
+ /** An ed25519 public key as `atlas index keygen` prints it: the base64 of its 32 raw bytes, nothing else. */
15
+ const INDEX_PUBLIC_KEY = z.string().refine(
16
+ (value) => {
17
+ const raw = Buffer.from(value, 'base64');
18
+
19
+ return raw.length === 32 && raw.toString('base64') === value;
20
+ },
21
+ { message: 'the public key `atlas index keygen` prints: the base64 of 32 bytes' },
22
+ );
23
+
24
+ const compiles = (value: string): boolean => {
25
+ try {
26
+ return new RegExp(value) instanceof RegExp;
27
+ } catch {
28
+ return false;
29
+ }
30
+ };
31
+
32
+ /** A command the project says is a database write (V-W-02) or a deploy (V-W-03): guard-writes asks when its pattern matches. */
33
+ const GUARD_COMMAND = z.strictObject({
34
+ rule: z.enum(['V-W-02', 'V-W-03']),
35
+ what: z.string().min(1).max(120),
36
+ pattern: z
37
+ .string()
38
+ .min(1)
39
+ .max(500)
40
+ .refine(compiles, { message: 'a regular expression (JavaScript syntax)' }),
41
+ ignoreCase: z.boolean().optional(),
42
+ });
43
+
44
+ /** A branch a plain `git push` asks about: a name, with `*` for any run of characters. */
45
+ const PUSH_TARGET = z
46
+ .string()
47
+ .regex(/^[A-Za-z0-9._/*-]+$/, { message: 'a branch name, with * for any run of characters' });
48
+
14
49
  /** A layout folder: 1 to 4 plain segments, never climbing, never absolute (the validator `guard-package` shares). */
15
50
  const LAYOUT_FOLDER = z.string().superRefine((value, context) => {
16
51
  const problem = layoutFolderProblem({ folder: value });
@@ -253,6 +288,14 @@ export const VULCAN_CONFIG_SCHEMA = z.strictObject({
253
288
  .default([]),
254
289
  /** Tags neither read nor checked (globs) - an old layout's tags. */
255
290
  ignoreTags: z.array(z.string()).optional(),
291
+ /**
292
+ * The prebuilt atlas index this repository publishes: the public keys (any one may have signed a
293
+ * pair) that a project reading this one as a source checks the signature against. Rotation is a
294
+ * new list; a pair signed by a key no longer listed is not used.
295
+ */
296
+ index: z.strictObject({ keys: z.array(INDEX_PUBLIC_KEY).default([]) }).optional(),
297
+ /** `false`: atlas never downloads a prebuilt index for a source this project reads; the default is to. */
298
+ prebuilt: z.boolean().optional(),
256
299
  })
257
300
  .default({
258
301
  tagPattern: '<dir>-v<version>',
@@ -295,16 +338,27 @@ export const VULCAN_CONFIG_SCHEMA = z.strictObject({
295
338
  * runtime dir for locks, git config, the agent tool's memory) with stores a tool in this project
296
339
  * manages itself: absolute globs, `~` and `$NAME` allowed. `writes.trustedScripts` lists the project's own
297
340
  * CLIs (repo-relative `.ts` paths, no globs) whose body guard-writes does not read for mutating calls
298
- * while git tracks them and they equal HEAD; the command line is still checked.
341
+ * while git tracks them and they equal HEAD; the command line is still checked. `writes.commands` adds the
342
+ * project's own deploy and migrate commands to what guard-writes asks about (a pattern, matched inside
343
+ * compound commands too), and `git.askPush` lists the branches a plain `git push` asks about; `vulcan sync`
344
+ * writes both to the manifest, where the hooks read them.
299
345
  */
300
346
  guard: z
301
347
  .strictObject({
302
348
  toolOwnedPaths: z.array(z.string().min(1)).default([]),
303
349
  writes: z
304
- .strictObject({ trustedScripts: z.array(TRUSTED_SCRIPT).default([]) })
305
- .default({ trustedScripts: [] }),
350
+ .strictObject({
351
+ trustedScripts: z.array(TRUSTED_SCRIPT).default([]),
352
+ commands: z.array(GUARD_COMMAND).default([]),
353
+ })
354
+ .default({ trustedScripts: [], commands: [] }),
355
+ git: z.strictObject({ askPush: z.array(PUSH_TARGET).default([]) }).default({ askPush: [] }),
306
356
  })
307
- .default({ toolOwnedPaths: [], writes: { trustedScripts: [] } }),
357
+ .default({
358
+ toolOwnedPaths: [],
359
+ writes: { trustedScripts: [], commands: [] },
360
+ git: { askPush: [] },
361
+ }),
308
362
  });
309
363
 
310
364
  export type VulcanConfig = z.input<typeof VULCAN_CONFIG_SCHEMA>;
@@ -840,7 +840,7 @@ export const checkDockerignore = (opts: ICheckContext): IViolation[] => {
840
840
  const FMT_SECTION_ADVICE =
841
841
  'add a [fmt] section (printWidth = 100, singleQuote = true, arrowParens = "always", flavor = "oxfmt"): without it bun fmt formats with Bun\'s defaults, not the shared style';
842
842
  const FMT_FLAVOR_ADVICE =
843
- 'without it bun fmt formats like Prettier when oxfmt is not a dependency, and the output changes';
843
+ 'without it bun fmt uses its default style when oxfmt is not a dependency, and the output changes';
844
844
  const OXFMT_LOADED_ADVICE =
845
845
  'bun fmt loads it and it overrides the [fmt] section of bunfig.toml - delete it, or move its settings to [fmt]';
846
846
 
@@ -1205,6 +1205,34 @@ export const checkStaleTrustedScripts = (opts: ICheckContext): IViolation[] =>
1205
1205
  : [];
1206
1206
  });
1207
1207
 
1208
+ /**
1209
+ * The commands and push targets the project adds to guard-writes and guard-git, one note each: so the
1210
+ * guards' reach beyond their own list is visible where a person looks, with the rule and the pattern.
1211
+ */
1212
+ export const checkGuardPatterns = (opts: ICheckContext): IViolation[] => {
1213
+ const { commands } = opts.config.guard.writes;
1214
+ const { askPush } = opts.config.guard.git;
1215
+
1216
+ return [
1217
+ ...commands.map((command) =>
1218
+ createViolation({
1219
+ check: DoctorChecks.GUARDS,
1220
+ file: opts.configFile,
1221
+ message: `guard.writes.commands: ${command.rule} '${command.what}' asks when a command matches /${command.pattern}/${command.ignoreCase === true ? 'i' : ''}`,
1222
+ }),
1223
+ ),
1224
+ ...(askPush.length === 0
1225
+ ? []
1226
+ : [
1227
+ createViolation({
1228
+ check: DoctorChecks.GUARDS,
1229
+ file: opts.configFile,
1230
+ message: `guard.git.askPush: a plain git push asks for ${askPush.join(', ')}`,
1231
+ }),
1232
+ ]),
1233
+ ];
1234
+ };
1235
+
1208
1236
  export const checkLocalSize = (opts: ICheckContext): IViolation[] => {
1209
1237
  const entries = scanLocal({ root: opts.root });
1210
1238
  const total = entries.reduce((sum, entry) => sum + entry.bytes, 0);
@@ -22,6 +22,7 @@ import {
22
22
  checkTrustedScripts,
23
23
  checkHooks,
24
24
  checkLayout,
25
+ checkGuardPatterns,
25
26
  checkLocalWorkspace,
26
27
  checkMake,
27
28
  checkOutsideWorktrees,
@@ -97,6 +98,7 @@ export const runDoctorNotes = async (opts: {
97
98
  ...checkAppScripts(context),
98
99
  ...checkAtlasBlock(context),
99
100
  ...checkLocalSize(context),
101
+ ...checkGuardPatterns(context),
100
102
  ...checkReplyShape(context),
101
103
  ...checkOwnerReplySwitch({ env: opts.env ?? process.env }),
102
104
  ...checkTrustedScripts(context),
@@ -30,6 +30,15 @@ const READ_ONLY_PROGRAMS = new Set([
30
30
  /** Programs whose arguments are messages and titles for the write guards (a commit message, an issue body). */
31
31
  const MESSAGE_PROGRAMS = new Set(['git', 'gh']);
32
32
 
33
+ /**
34
+ * The `gh` subcommands whose arguments are a request and not a message: the project's own patterns match them
35
+ * (`gh api -X PUT .../rulesets`, `gh secret set`). The arguments of every other `gh` subcommand stay data.
36
+ */
37
+ const GH_REQUESTS = new Set(['api', 'secret', 'variable']);
38
+
39
+ /** The `gh` options that take the repository as their value: that value is not the subcommand. */
40
+ const GH_REPOSITORY_FLAGS = new Set(['-R', '--repo']);
41
+
33
42
  /** `find` runs a command only with these; without them it only lists. */
34
43
  const FIND_RUNS = new Set(['-exec', '-execdir', '-ok', '-okdir', '-delete']);
35
44
 
@@ -54,6 +63,17 @@ const HEREDOC_READERS = new Set([
54
63
  const PIPED_INTO_RUNNER =
55
64
  /\|\s*(?:sudo\s+)?(?:sh|bash|zsh|dash|psql|mysql|mongosh|sqlite3|python3?|node|bun|ssh)\b/;
56
65
 
66
+ /** Whether a `gh` command is a request: its subcommand (the first word that is not an option or an option's value) is one of `GH_REQUESTS`. */
67
+ const isGhRequest = (opts: { command: ISimpleCommand }): boolean => {
68
+ const { args } = programOf({ command: opts.command });
69
+ const subcommand = args.find(
70
+ (word, index) =>
71
+ !word.startsWith('-') && !(index > 0 && GH_REPOSITORY_FLAGS.has(args[index - 1] ?? '')),
72
+ );
73
+
74
+ return subcommand !== undefined && GH_REQUESTS.has(subcommand);
75
+ };
76
+
57
77
  /**
58
78
  * Whether the arguments of a command are data. `withMessages` adds `git` and `gh` (their arguments are
59
79
  * messages to the write guards, but a `git` remote is a host to the remote-host guard).
@@ -65,6 +85,10 @@ export const isDataOnly = (opts: { command: ISimpleCommand; withMessages: boolea
65
85
  return !opts.command.words.some((word) => FIND_RUNS.has(word));
66
86
  }
67
87
 
88
+ if (name === 'gh' && isGhRequest({ command: opts.command })) {
89
+ return false;
90
+ }
91
+
68
92
  return READ_ONLY_PROGRAMS.has(name) || (opts.withMessages && MESSAGE_PROGRAMS.has(name));
69
93
  };
70
94
 
@@ -56,8 +56,18 @@ export class HookConstants {
56
56
  static readonly QUERY_TIMEOUT_MS = 5000;
57
57
  /** The `git` and `gh` queries one command line may make; past it the guard asks instead of querying on. */
58
58
  static readonly MAX_QUERIES = 4;
59
+ /**
60
+ * A blanket stage (`git add -A`, `git commit -a`) asks past this many changed paths. A formatter run once put 152
61
+ * unintended files into one commit; on this repository's develop the median commit touches 7 files and 2.2% touch more than 50.
62
+ */
63
+ static readonly BLANKET_STAGE_PATHS = 50;
59
64
  /** Branches no agent deletes or force-pushes (V-W-06). */
60
65
  static readonly PROTECTED_BRANCHES = new Set(['develop', 'main']);
66
+ /**
67
+ * Where a session's temporary files go, from the project root: `ProjectLayout.LOCAL_DIRECTORY` and `tmp`.
68
+ * Spelt out here because the blocking hooks import nothing that reads the package (a test holds the two equal).
69
+ */
70
+ static readonly PROJECT_TMP = '.agents/local/tmp';
61
71
  /** Set to `off` to switch the guards off for a session; the hooks then pass every call. */
62
72
  static readonly KILL_SWITCH_ENV = 'VULCAN_GUARDS';
63
73
  static readonly KILL_SWITCH_OFF = 'off';
@@ -3,6 +3,7 @@ import { basenameOf, parseShellChecked, programOf } from './shell.ts';
3
3
  import type { ISimpleCommand } from './shell.ts';
4
4
  import { GuardDecisions, HookConstants } from './common/index.ts';
5
5
  import type { IGitHit, IGitRunner } from './common/index.ts';
6
+ import { matchesBranch } from './project-guards.ts';
6
7
 
7
8
  /** `git` and `gh` read-only queries the guard makes; `undefined` when the tool is missing, slow or fails. */
8
9
  export const runQuery: IGitRunner = (opts) => {
@@ -57,6 +58,7 @@ const inspectPush = (opts: {
57
58
  rest: string[];
58
59
  cwd: string | undefined;
59
60
  run: IGitRunner;
61
+ askPush: string[];
60
62
  }): IGitHit[] => {
61
63
  const flags = opts.rest.filter((word) => word.startsWith('-') && word !== '-');
62
64
  const positional = opts.rest.filter((word) => !word.startsWith('-'));
@@ -97,6 +99,21 @@ const inspectPush = (opts: {
97
99
  }
98
100
  }
99
101
 
102
+ // A target the project lists asks even for a plain push; a hit already made says the push needs a human.
103
+ if (hits.length === 0 && !deleting) {
104
+ for (const name of targets) {
105
+ const branch = name.replace(/^\+/, '').replace(/^refs\/heads\//, '');
106
+
107
+ if (matchesBranch({ name: branch, patterns: opts.askPush })) {
108
+ hits.push({
109
+ decision: GuardDecisions.ASK,
110
+ rule: 'V-W-06',
111
+ message: `pushing to '${branch}', a target this project lists in guard.git.askPush`,
112
+ });
113
+ }
114
+ }
115
+ }
116
+
100
117
  if (flags.includes('--mirror')) {
101
118
  hits.push({
102
119
  decision: GuardDecisions.ASK,
@@ -116,6 +133,58 @@ const inspectPush = (opts: {
116
133
  return hits;
117
134
  };
118
135
 
136
+ /**
137
+ * `git add -A`, `--all`, `.`, `-u` and `git commit -a` stage every change, a formatter's or a generator's included. Past
138
+ * `HookConstants.BLANKET_STAGE_PATHS` changed paths the guard asks, so the files are named. A stage of named paths, `-p` and a
139
+ * status that cannot be read pass: the guard asks, it does not deny, and it is not a sandbox.
140
+ */
141
+ const inspectStage = (opts: {
142
+ sub: string;
143
+ rest: string[];
144
+ cwd: string | undefined;
145
+ run: IGitRunner;
146
+ }): IGitHit[] => {
147
+ const flags = opts.rest.filter((word) => word.startsWith('-') && word !== '--');
148
+ const paths = opts.rest.filter((word) => !word.startsWith('-'));
149
+ const everything =
150
+ opts.sub === 'add' &&
151
+ (flags.some((flag) => flag === '--all' || /^-[a-zA-Z]*A[a-zA-Z]*$/.test(flag)) ||
152
+ paths.includes('.')) &&
153
+ paths.every((path) => path === '.');
154
+ const tracked =
155
+ (opts.sub === 'add' && flags.some((flag) => flag === '-u' || flag === '--update')) ||
156
+ (opts.sub === 'commit' &&
157
+ flags.some((flag) => flag === '--all' || /^-[a-zA-Z]*a[a-zA-Z]*$/.test(flag)));
158
+
159
+ if (!everything && !tracked) {
160
+ return [];
161
+ }
162
+
163
+ // One line per file: the default status prints a new folder as one line, which would undercount what `git add -A` takes.
164
+ const status = opts.run({
165
+ program: 'git',
166
+ args: ['status', '--porcelain', '--untracked-files=all'],
167
+ cwd: opts.cwd,
168
+ });
169
+
170
+ if (status === undefined) {
171
+ return [];
172
+ }
173
+
174
+ const lines = status.split('\n').filter((line) => line.length > 0);
175
+ const count = (everything ? lines : lines.filter((line) => !line.startsWith('??'))).length;
176
+
177
+ return count > HookConstants.BLANKET_STAGE_PATHS
178
+ ? [
179
+ {
180
+ decision: GuardDecisions.ASK,
181
+ rule: 'V-W-06',
182
+ message: `this stages ${count} changed paths at once (more than ${HookConstants.BLANKET_STAGE_PATHS}), a formatter's or a generator's included; name the files you mean`,
183
+ },
184
+ ]
185
+ : [];
186
+ };
187
+
119
188
  const inspectBranch = (opts: {
120
189
  rest: string[];
121
190
  cwd: string | undefined;
@@ -229,6 +298,7 @@ const inspectOne = (opts: {
229
298
  command: ISimpleCommand;
230
299
  cwd: string | undefined;
231
300
  run: IGitRunner;
301
+ askPush: string[];
232
302
  }): IGitHit[] => {
233
303
  const program = programOf({ command: opts.command });
234
304
  const name = basenameOf({ word: program.name });
@@ -245,13 +315,17 @@ const inspectOne = (opts: {
245
315
  const cwd = call.dir ?? opts.cwd;
246
316
 
247
317
  if (call.sub === 'push') {
248
- return inspectPush({ rest: call.rest, cwd, run: opts.run });
318
+ return inspectPush({ rest: call.rest, cwd, run: opts.run, askPush: opts.askPush });
249
319
  }
250
320
 
251
321
  if (call.sub === 'branch') {
252
322
  return inspectBranch({ rest: call.rest, cwd, run: opts.run });
253
323
  }
254
324
 
325
+ if (call.sub === 'add' || call.sub === 'commit') {
326
+ return inspectStage({ sub: call.sub, rest: call.rest, cwd, run: opts.run });
327
+ }
328
+
255
329
  if (call.sub === 'update-ref' && call.rest.some((word) => word === '-d' || word === '--delete')) {
256
330
  const refs = call.rest.filter((word) => !word.startsWith('-'));
257
331
 
@@ -282,6 +356,8 @@ export const inspectGit = (opts: {
282
356
  command: string;
283
357
  cwd: string | undefined;
284
358
  run?: IGitRunner;
359
+ /** Branches (names, `*` allowed) a plain `git push` asks about: `guard.git.askPush`. */
360
+ askPush?: string[];
285
361
  }): IGitHit[] => {
286
362
  const parsed = parseShellChecked({ command: opts.command });
287
363
  const run = opts.run ?? runQuery;
@@ -301,7 +377,7 @@ export const inspectGit = (opts: {
301
377
  return run(call);
302
378
  };
303
379
  const hits = parsed.commands.flatMap((command) =>
304
- inspectOne({ command, cwd: opts.cwd, run: limited }),
380
+ inspectOne({ command, cwd: opts.cwd, run: limited, askPush: opts.askPush ?? [] }),
305
381
  );
306
382
 
307
383
  // Part of the line was not read: never an allow.
@@ -4,6 +4,7 @@ import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
4
  import { basenameOf, parseShellChecked, programOf } from './shell.ts';
5
5
  import type { ISimpleCommand } from './shell.ts';
6
6
  import { HookConstants } from './common/index.ts';
7
+ import { projectTmpOf } from './project-tmp.ts';
7
8
  import type { IManifestHookInput, IOutsideHit } from './common/index.ts';
8
9
 
9
10
  const FILE_TOOLS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
@@ -238,7 +239,7 @@ const gitTargets = (opts: { rest: string[]; base: string; dir: string | undefine
238
239
  };
239
240
 
240
241
  /** The words a simple command would create or write, with a name for what writes them. */
241
- const targetsOf = (opts: { command: ISimpleCommand; base: string }): ITarget[] => {
242
+ const targetsOf = (opts: { command: ISimpleCommand; base: string; tmp: string }): ITarget[] => {
242
243
  const program = programOf({ command: opts.command });
243
244
  const name = basenameOf({ word: program.name });
244
245
  const { args } = program;
@@ -314,7 +315,7 @@ const targetsOf = (opts: { command: ISimpleCommand; base: string }): ITarget[] =
314
315
  if (directory !== undefined) {
315
316
  add(directory, 'mktemp creates a temporary file');
316
317
  } else if (inTmpdir || template === undefined) {
317
- add(tmpdir(), 'mktemp creates a file in the system temp directory');
318
+ add(opts.tmp, 'mktemp creates a file in the system temp directory');
318
319
  } else {
319
320
  add(template, 'mktemp creates a temporary file');
320
321
  }
@@ -327,6 +328,21 @@ const targetsOf = (opts: { command: ISimpleCommand; base: string }): ITarget[] =
327
328
  return targets;
328
329
  };
329
330
 
331
+ /**
332
+ * The folder a bare `mktemp` uses in the command: the `TMPDIR` this hook runs with (Claude Code started
333
+ * with the launch file or the variables), else the project's own folder when Claude Code's session-start
334
+ * hook exports it (`CLAUDE_PROJECT_DIR` is set only by Claude Code), else the system temp directory.
335
+ */
336
+ const commandTmpdirOf = (opts: { env: TEnvironment; projectRoot: string }): string => {
337
+ if (opts.env.TMPDIR !== undefined && opts.env.TMPDIR !== '') {
338
+ return opts.env.TMPDIR;
339
+ }
340
+
341
+ return opts.env.CLAUDE_PROJECT_DIR === undefined
342
+ ? tmpdir()
343
+ : projectTmpOf({ root: opts.projectRoot });
344
+ };
345
+
330
346
  /**
331
347
  * Every file, worktree, clone or temp file `input` would create outside the project. Files a package
332
348
  * manager, a runtime or the agent tool manage themselves are allowed (`toolOwnedPaths`, extending the
@@ -350,6 +366,7 @@ export const inspectOutside = (opts: {
350
366
  env,
351
367
  });
352
368
  const start = opts.input.cwd ?? opts.projectRoot;
369
+ const tmp = commandTmpdirOf({ env, projectRoot: opts.projectRoot });
353
370
  const targets: ITarget[] = [];
354
371
 
355
372
  if (FILE_TOOLS.has(opts.input.tool) && opts.input.filePath !== undefined) {
@@ -381,7 +398,7 @@ export const inspectOutside = (opts: {
381
398
  continue;
382
399
  }
383
400
 
384
- targets.push(...targetsOf({ command, base }));
401
+ targets.push(...targetsOf({ command, base, tmp }));
385
402
  }
386
403
  }
387
404
 
@@ -5,6 +5,7 @@ import { TrustStates } from './common/index.ts';
5
5
  import type { IHookCommand, IWriteCheck, IWriteHit } from './common/index.ts';
6
6
  import { commandTextsOf } from './command-view.ts';
7
7
  import { forHost } from './decision.ts';
8
+ import type { IProjectCommandCheck } from './project-guards.ts';
8
9
  import { listedScriptOf, trustOf } from './trusted-scripts.ts';
9
10
 
10
11
  const MUTATING_VERB = '(?:POST|PUT|PATCH|DELETE)';
@@ -87,16 +88,26 @@ export const inspectCommand = (opts: {
87
88
  command: string;
88
89
  cwd: string;
89
90
  trust?: { root: string; scripts: string[] };
91
+ /** The project's own commands (`guard.writes.commands`), checked beside the fixed list. */
92
+ extra?: IProjectCommandCheck[];
90
93
  }): IWriteHit[] => {
91
94
  // The patterns run on what the command runs, not on its text: a heredoc written to a file, the pattern
92
95
  // of an `rg` and a commit message are data.
93
96
  const texts = commandTextsOf({ command: opts.command, withMessages: true });
94
- const hits: IWriteHit[] = COMMAND_CHECKS.filter((check) =>
95
- texts.some((text) => check.pattern.test(text)),
96
- ).map((check) => ({
97
- rule: check.rule,
98
- message: check.what,
99
- }));
97
+ const checks: IWriteCheck[] = [
98
+ ...COMMAND_CHECKS,
99
+ ...(opts.extra ?? []).map((check) => ({
100
+ rule: check.rule,
101
+ what: `${check.what} (this project's pattern)`,
102
+ pattern: check.pattern,
103
+ })),
104
+ ];
105
+ const hits: IWriteHit[] = checks
106
+ .filter((check) => texts.some((text) => check.pattern.test(text)))
107
+ .map((check) => ({
108
+ rule: check.rule,
109
+ message: check.what,
110
+ }));
100
111
 
101
112
  for (const target of extractScriptTargets({ command: texts.join('\n') })) {
102
113
  const source = readScript({ target, cwd: opts.cwd });
@@ -10,6 +10,8 @@ export * from './trusted-scripts.ts';
10
10
  export * from './session-digest.ts';
11
11
  export * from './subagent-card.ts';
12
12
  export * from './owner-reply.ts';
13
+ export * from './project-tmp.ts';
14
+ export * from './project-guards.ts';
13
15
  export * from './remote-hosts.ts';
14
16
  export * from './codex-patch.ts';
15
17
  export * from './shell.ts';
@@ -0,0 +1,123 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ /** A command the project says is a database write or a deploy: guard-writes asks on a match. */
5
+ export interface IProjectCommandCheck {
6
+ rule: 'V-W-02' | 'V-W-03';
7
+ what: string;
8
+ pattern: RegExp;
9
+ }
10
+
11
+ /** What the project adds to the guards: the manifest's `guard` block, compiled. */
12
+ export interface IGuardPolicy {
13
+ commands: IProjectCommandCheck[];
14
+ askPush: string[];
15
+ }
16
+
17
+ /** Spelt out: the blocking hooks import nothing that reads the package (a test holds it equal to the manifest's name). */
18
+ export const GUARD_MANIFEST_FILE = '.agents/vulcan.manifest.json';
19
+
20
+ const isRecord = (opts: { value: unknown }): opts is { value: Record<string, unknown> } =>
21
+ typeof opts.value === 'object' && opts.value !== null && !Array.isArray(opts.value);
22
+
23
+ const ruleOf = (opts: { value: unknown }): 'V-W-02' | 'V-W-03' | undefined =>
24
+ opts.value === 'V-W-02' || opts.value === 'V-W-03' ? opts.value : undefined;
25
+
26
+ const note = (opts: { message: string }): void => {
27
+ console.error(`vulcan: [guard] ${opts.message}`);
28
+ };
29
+
30
+ const commandOf = (opts: { value: unknown }): IProjectCommandCheck | undefined => {
31
+ const holder = { value: opts.value };
32
+
33
+ if (!isRecord(holder)) {
34
+ return undefined;
35
+ }
36
+
37
+ const rule = ruleOf({ value: holder.value['rule'] });
38
+ const what = holder.value['what'];
39
+ const source = holder.value['pattern'];
40
+
41
+ if (rule === undefined || typeof what !== 'string' || what === '' || typeof source !== 'string') {
42
+ note({
43
+ message: 'ignoring a guard.writes.commands entry that has no usable rule, what or pattern',
44
+ });
45
+
46
+ return undefined;
47
+ }
48
+
49
+ try {
50
+ return {
51
+ rule,
52
+ what,
53
+ pattern: new RegExp(source, holder.value['ignoreCase'] === true ? 'i' : ''),
54
+ };
55
+ } catch (error) {
56
+ note({
57
+ message: `ignoring the pattern '${source}' of guard.writes.commands (${error instanceof Error ? error.message : String(error)})`,
58
+ });
59
+
60
+ return undefined;
61
+ }
62
+ };
63
+
64
+ /**
65
+ * The commands and push targets a project lists, from the committed manifest (`vulcan sync` renders
66
+ * them from the config), so a hook reads them with no config loader and no zod. A project with no
67
+ * manifest, or none of the block, has none; an entry that cannot be used is skipped, said once on
68
+ * stderr, and the others stay.
69
+ */
70
+ export const readGuardPolicy = (opts: { root: string }): IGuardPolicy => {
71
+ const path = join(opts.root, GUARD_MANIFEST_FILE);
72
+ const empty: IGuardPolicy = { commands: [], askPush: [] };
73
+
74
+ if (!existsSync(path)) {
75
+ return empty;
76
+ }
77
+
78
+ let manifest: unknown;
79
+
80
+ try {
81
+ manifest = JSON.parse(readFileSync(path, 'utf8'));
82
+ } catch (error) {
83
+ note({
84
+ message: `the manifest could not be read, so the project's own patterns are off (${error instanceof Error ? error.message : String(error)})`,
85
+ });
86
+
87
+ return empty;
88
+ }
89
+
90
+ const top = { value: manifest };
91
+ const guard = isRecord(top) ? { value: top.value['guard'] } : { value: undefined };
92
+
93
+ if (!isRecord(guard)) {
94
+ return empty;
95
+ }
96
+
97
+ const writes = { value: guard.value['writes'] };
98
+ const git = { value: guard.value['git'] };
99
+ const listed = isRecord(writes) ? writes.value['commands'] : undefined;
100
+ const targets = isRecord(git) ? git.value['askPush'] : undefined;
101
+
102
+ return {
103
+ commands: (Array.isArray(listed) ? listed : []).flatMap((entry) => {
104
+ const check = commandOf({ value: entry });
105
+
106
+ return check === undefined ? [] : [check];
107
+ }),
108
+ askPush: (Array.isArray(targets) ? targets : []).filter(
109
+ (target): target is string => typeof target === 'string' && target !== '',
110
+ ),
111
+ };
112
+ };
113
+
114
+ /** Whether a branch name is one of the listed names; `*` stands for any run of characters, nothing else is special. */
115
+ export const matchesBranch = (opts: { name: string; patterns: string[] }): boolean =>
116
+ opts.patterns.some((pattern) =>
117
+ new RegExp(
118
+ `^${pattern
119
+ .split('*')
120
+ .map((part) => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&'))
121
+ .join('.*')}$`,
122
+ ).test(opts.name),
123
+ );
@@ -0,0 +1,36 @@
1
+ import { appendFileSync, mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { HookConstants } from './common/index.ts';
4
+
5
+ /** `<root>/.agents/local/tmp`: where a session's temporary files go, absolute. `vulcan clean` reads its age. */
6
+ export const projectTmpOf = (opts: { root: string }): string =>
7
+ join(opts.root, HookConstants.PROJECT_TMP);
8
+
9
+ /** A word for `sh`, whatever it holds: in single quotes, a quote itself closed, escaped and opened again. */
10
+ const shellQuote = (opts: { text: string }): string => `'${opts.text.replaceAll("'", "'\\''")}'`;
11
+
12
+ /**
13
+ * Makes every Bash command of a Claude Code session run with `TMPDIR` in the project. Claude Code hands a
14
+ * SessionStart hook a file (`CLAUDE_ENV_FILE`) and sources it before each Bash command, so one `export`
15
+ * there is enough: `mktemp`, bun, node and every script a command starts then use the project folder. It
16
+ * does not move Claude Code's own task-output files or an MCP server (those need the launch file), and
17
+ * `TMPDIR` in the project's settings `env` is not applied by Claude Code, which is why this is a hook.
18
+ * Returns whether it wrote; with no file (another agent, a run outside Claude Code) it does nothing. A
19
+ * path with a line break is refused: a line of shell must never be made from a folder name.
20
+ */
21
+ export const exportProjectTmp = (opts: { root: string; envFile: string | undefined }): boolean => {
22
+ if (opts.envFile === undefined || opts.envFile === '') {
23
+ return false;
24
+ }
25
+
26
+ const folder = projectTmpOf({ root: opts.root });
27
+
28
+ if (/[\r\n]/.test(folder)) {
29
+ return false;
30
+ }
31
+
32
+ mkdirSync(folder, { recursive: true });
33
+ appendFileSync(opts.envFile, `export TMPDIR=${shellQuote({ text: folder })}\n`);
34
+
35
+ return true;
36
+ };
@@ -11,6 +11,7 @@ import {
11
11
  resolveOwnerView,
12
12
  } from '../owner/index.ts';
13
13
  import { extractRuleRows, parseRuleIds, readSlots, RuleConstants } from '../rules/index.ts';
14
+ import { projectTmpOf } from './project-tmp.ts';
14
15
 
15
16
  /** A project row whose first cell lists IDs - `| V-W-02, V-W-03 |` - elaborates those base rules. */
16
17
  const ID_LIST_ROW =
@@ -96,6 +97,10 @@ export const buildSessionDigest = async (opts: {
96
97
  ...TABLE_HEADER,
97
98
  ...baseRows.filter((row) => row.startsWith(`| ${RuleConstants.BASE_NAMESPACE}W-`)),
98
99
  '',
100
+ '## Temporary files',
101
+ '',
102
+ `Scratch and temporary files go in \`${projectTmpOf({ root: opts.projectRoot })}\`, never /tmp (V-B-08). In Claude Code every Bash command already runs with \`TMPDIR\` set to it; in any other agent run \`export TMPDIR=${projectTmpOf({ root: opts.projectRoot })}\` first. Remove what you made when the task ends.`,
103
+ '',
99
104
  "## This project's slot choices",
100
105
  '',
101
106
  ...slotRows,