@descent-vtt/spec-harness 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +212 -0
  4. package/README.md +30 -15
  5. package/dist/briefs.d.ts +45 -0
  6. package/dist/briefs.js +73 -0
  7. package/dist/briefs.js.map +1 -1
  8. package/dist/cli.d.ts +1 -1
  9. package/dist/cli.js +211 -134
  10. package/dist/cli.js.map +1 -1
  11. package/dist/commands.js +7 -2
  12. package/dist/commands.js.map +1 -1
  13. package/dist/config.d.ts +13 -1
  14. package/dist/config.js +14 -3
  15. package/dist/config.js.map +1 -1
  16. package/dist/configure.d.ts +55 -1
  17. package/dist/configure.js +130 -22
  18. package/dist/configure.js.map +1 -1
  19. package/dist/fs.d.ts +78 -1
  20. package/dist/fs.js +289 -10
  21. package/dist/fs.js.map +1 -1
  22. package/dist/git.d.ts +50 -2
  23. package/dist/git.js +98 -8
  24. package/dist/git.js.map +1 -1
  25. package/dist/hooks.d.ts +45 -0
  26. package/dist/hooks.js +62 -3
  27. package/dist/hooks.js.map +1 -1
  28. package/dist/round.d.ts +8 -0
  29. package/dist/round.js +23 -8
  30. package/dist/round.js.map +1 -1
  31. package/dist/sandbox.js +4 -3
  32. package/dist/sandbox.js.map +1 -1
  33. package/dist/server.d.ts +25 -1
  34. package/dist/server.js +194 -27
  35. package/dist/server.js.map +1 -1
  36. package/dist/setup.js +40 -10
  37. package/dist/setup.js.map +1 -1
  38. package/dist/siblings.d.ts +24 -3
  39. package/dist/siblings.js +106 -14
  40. package/dist/siblings.js.map +1 -1
  41. package/dist/usage.d.ts +42 -7
  42. package/dist/usage.js +65 -6
  43. package/dist/usage.js.map +1 -1
  44. package/dist/workspace.d.ts +45 -3
  45. package/dist/workspace.js +133 -13
  46. package/dist/workspace.js.map +1 -1
  47. package/package.json +1 -1
package/dist/git.d.ts CHANGED
@@ -12,8 +12,39 @@ export interface Run {
12
12
  readonly stdout: string;
13
13
  readonly stderr: string;
14
14
  }
15
- /** Runs git and answers whatever it answered; a missing git is a code of -1. */
16
- export declare function git(args: readonly string[], cwd: string): Promise<Run>;
15
+ /**
16
+ * How long a process the harness asks a question of is given to answer:
17
+ * git's reads, spec-brief's list of the briefs. Claude Code gives the hook's
18
+ * entry 60 seconds, as init and the plugin write it, and cancels a hook that
19
+ * reaches them, which before a write lets the write go ahead (ADR-0002). A
20
+ * process that does not answer within this is stopped and its question
21
+ * answered as one that failed, which before a write holds it, well inside
22
+ * that minute; and the slowest such process measured, on a Windows
23
+ * workstation under load and on GitHub's runner, answered in a fraction of
24
+ * it.
25
+ */
26
+ export declare const ANSWER_MS = 20000;
27
+ /**
28
+ * How long a process that does a round's work is given: a diff of the
29
+ * round, a worktree added for a probe or taken away, a sibling's check of
30
+ * the repository. Its length is the repository's, and none runs before a
31
+ * write.
32
+ */
33
+ export declare const WORK_MS = 600000;
34
+ /**
35
+ * Whether a process ended because the harness stopped it at its time
36
+ * limit: Node kills it then and says so with `killed`. It kills one for
37
+ * output past `maxBuffer` as well, and names that by its code.
38
+ */
39
+ export declare function stoppedAtLimit(error: unknown): boolean;
40
+ /**
41
+ * Runs git and answers whatever it answered; a missing git is a code of -1.
42
+ * A git that does not answer within `limit` is stopped, and rejected as a
43
+ * `GitError` that says so: read as a failure, a question about the work
44
+ * tree or the branch would answer as a directory in none, or a head on no
45
+ * branch, under which the hook checks no write.
46
+ */
47
+ export declare function git(args: readonly string[], cwd: string, limit?: number): Promise<Run>;
17
48
  export declare class GitError extends Error {
18
49
  constructor(message: string);
19
50
  }
@@ -98,6 +129,23 @@ export declare function mergeBase(a: string, b: string, cwd: string): Promise<st
98
129
  export declare function parseNameStatus(output: string): FileChange[];
99
130
  /** The files changed from one revision to another, renames found. */
100
131
  export declare function changes(from: string, to: string, cwd: string): Promise<FileChange[]>;
132
+ /**
133
+ * The paths `git status --porcelain=v2 -z` names, each once, in the order
134
+ * git gives them: a rename or a copy by both its paths. A path with a space
135
+ * in it is the rest of its record, which `-z` prints as is.
136
+ */
137
+ export declare function parseStatus(output: string): string[];
138
+ /**
139
+ * Every path the work tree holds changed from HEAD: tracked files that
140
+ * differ in the index or in the work tree, unmerged ones, and each
141
+ * untracked file, those in an untracked directory one by one. One start of
142
+ * git, with no optional lock taken: a status that writes the index as it
143
+ * refreshes it holds a lock that can make another git running beside it
144
+ * fail, and the manual has a status run in the background take none
145
+ * (git-status(1), *Background Refresh*, and git(1), `--no-optional-locks`,
146
+ * as Git for Windows 2.55.0 has them, read 2026-10-19).
147
+ */
148
+ export declare function changedPaths(cwd: string): Promise<string[]>;
101
149
  /** The files a commit would change: what is staged. */
102
150
  export declare function stagedChanges(cwd: string): Promise<FileChange[]>;
103
151
  /** A file's content at a revision, or `null` when it does not exist there. */
package/dist/git.js CHANGED
@@ -7,12 +7,54 @@
7
7
  * become a command.
8
8
  */
9
9
  import { execFile } from 'node:child_process';
10
- /** Runs git and answers whatever it answered; a missing git is a code of -1. */
11
- export function git(args, cwd) {
12
- return new Promise((resolve) => {
10
+ /**
11
+ * How long a process the harness asks a question of is given to answer:
12
+ * git's reads, spec-brief's list of the briefs. Claude Code gives the hook's
13
+ * entry 60 seconds, as init and the plugin write it, and cancels a hook that
14
+ * reaches them, which before a write lets the write go ahead (ADR-0002). A
15
+ * process that does not answer within this is stopped and its question
16
+ * answered as one that failed, which before a write holds it, well inside
17
+ * that minute; and the slowest such process measured, on a Windows
18
+ * workstation under load and on GitHub's runner, answered in a fraction of
19
+ * it.
20
+ */
21
+ export const ANSWER_MS = 20_000;
22
+ /**
23
+ * How long a process that does a round's work is given: a diff of the
24
+ * round, a worktree added for a probe or taken away, a sibling's check of
25
+ * the repository. Its length is the repository's, and none runs before a
26
+ * write.
27
+ */
28
+ export const WORK_MS = 600_000;
29
+ /**
30
+ * Whether a process ended because the harness stopped it at its time
31
+ * limit: Node kills it then and says so with `killed`. It kills one for
32
+ * output past `maxBuffer` as well, and names that by its code.
33
+ */
34
+ export function stoppedAtLimit(error) {
35
+ const failure = error;
36
+ return failure !== null && failure.killed === true && failure.code !== 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER';
37
+ }
38
+ /** The git command a line of arguments runs, past the `-c` settings before it: every line the harness hands git names one. */
39
+ function subcommand(args) {
40
+ return args.find((arg, index) => !arg.startsWith('-') && args[index - 1] !== '-c');
41
+ }
42
+ /**
43
+ * Runs git and answers whatever it answered; a missing git is a code of -1.
44
+ * A git that does not answer within `limit` is stopped, and rejected as a
45
+ * `GitError` that says so: read as a failure, a question about the work
46
+ * tree or the branch would answer as a directory in none, or a head on no
47
+ * branch, under which the hook checks no write.
48
+ */
49
+ export function git(args, cwd, limit = ANSWER_MS) {
50
+ return new Promise((resolve, reject) => {
13
51
  // windowsHide only keeps a console window from flashing up on Windows,
14
52
  // and the sweep runs on Linux, where its mutant is equivalent.
15
- execFile('git', [...args], { cwd, maxBuffer: 256 * 1024 * 1024, encoding: 'utf8', windowsHide: true }, (error, stdout, stderr) => {
53
+ execFile('git', [...args], { cwd, maxBuffer: 256 * 1024 * 1024, encoding: 'utf8', windowsHide: true, timeout: limit }, (error, stdout, stderr) => {
54
+ if (stoppedAtLimit(error)) {
55
+ reject(new GitError(`git ${subcommand(args)} did not answer within ${limit / 1000} seconds, and was stopped`));
56
+ return;
57
+ }
16
58
  // Every caller tells 0 from any other code, never one failure from
17
59
  // another, so which code a failure gets is equivalent to its mutants.
18
60
  const code = error === null ? 0 : typeof error.code === 'number' ? error.code : -1;
@@ -164,14 +206,62 @@ export function parseNameStatus(output) {
164
206
  }
165
207
  /** The files changed from one revision to another, renames found. */
166
208
  export async function changes(from, to, cwd) {
167
- const run = await git(['diff', '--name-status', '-z', '--find-renames', '--no-color', from, to, '--'], cwd);
209
+ const run = await git(['diff', '--name-status', '-z', '--find-renames', '--no-color', from, to, '--'], cwd, WORK_MS);
168
210
  if (run.code !== 0)
169
211
  throw new GitError(`git diff ${from} ${to} failed: ${run.stderr.trim()}`);
170
212
  return parseNameStatus(run.stdout);
171
213
  }
214
+ /**
215
+ * How many words stand before the path in each kind of record of
216
+ * `git status --porcelain=v2`, as git-status(1) has them (Git for Windows
217
+ * 2.55.0, *Porcelain Format Version 2*, read 2026-10-19): an ordinary
218
+ * change, `1`, and seven; a rename or a copy, `2`, and eight, its path
219
+ * followed by the path it came from as a record of its own under `-z`; an
220
+ * unmerged path, `u`, and nine; an untracked or an ignored path, `?` or
221
+ * `!`, and none. A header, `#`, names no path.
222
+ */
223
+ const STATUS_FIELDS = { '1': 8, '2': 9, u: 10, '?': 1, '!': 1 };
224
+ /**
225
+ * The paths `git status --porcelain=v2 -z` names, each once, in the order
226
+ * git gives them: a rename or a copy by both its paths. A path with a space
227
+ * in it is the rest of its record, which `-z` prints as is.
228
+ */
229
+ export function parseStatus(output) {
230
+ const records = output.split('\0');
231
+ const paths = new Set();
232
+ for (let at = 0; at < records.length; at += 1) {
233
+ const record = records[at];
234
+ const fields = STATUS_FIELDS[record.charAt(0)];
235
+ if (fields === undefined)
236
+ continue;
237
+ paths.add(record.split(' ').slice(fields).join(' '));
238
+ if (record.startsWith('2')) {
239
+ at += 1;
240
+ paths.add(records[at] ?? '');
241
+ }
242
+ }
243
+ paths.delete('');
244
+ return [...paths];
245
+ }
246
+ /**
247
+ * Every path the work tree holds changed from HEAD: tracked files that
248
+ * differ in the index or in the work tree, unmerged ones, and each
249
+ * untracked file, those in an untracked directory one by one. One start of
250
+ * git, with no optional lock taken: a status that writes the index as it
251
+ * refreshes it holds a lock that can make another git running beside it
252
+ * fail, and the manual has a status run in the background take none
253
+ * (git-status(1), *Background Refresh*, and git(1), `--no-optional-locks`,
254
+ * as Git for Windows 2.55.0 has them, read 2026-10-19).
255
+ */
256
+ export async function changedPaths(cwd) {
257
+ const run = await git(['--no-optional-locks', 'status', '--porcelain=v2', '-z', '--untracked-files=all'], cwd);
258
+ if (run.code !== 0)
259
+ throw new GitError(`git status failed: ${run.stderr.trim()}`);
260
+ return parseStatus(run.stdout);
261
+ }
172
262
  /** The files a commit would change: what is staged. */
173
263
  export async function stagedChanges(cwd) {
174
- const run = await git(['diff', '--cached', '--name-status', '-z', '--find-renames', '--no-color', '--'], cwd);
264
+ const run = await git(['diff', '--cached', '--name-status', '-z', '--find-renames', '--no-color', '--'], cwd, WORK_MS);
175
265
  if (run.code !== 0)
176
266
  throw new GitError(`git diff --cached failed: ${run.stderr.trim()}`);
177
267
  return parseNameStatus(run.stdout);
@@ -215,7 +305,7 @@ export async function verifyCommit(sha, allowedSignersFile, cwd) {
215
305
  return run.code === 0 && principal !== undefined ? { good: true, principal, detail } : { good: false, principal: null, detail };
216
306
  }
217
307
  export async function addWorktree(path, rev, cwd) {
218
- const run = await git(['worktree', 'add', '--detach', '--force', path, rev], cwd);
308
+ const run = await git(['worktree', 'add', '--detach', '--force', path, rev], cwd, WORK_MS);
219
309
  if (run.code !== 0)
220
310
  throw new GitError(`git worktree add failed: ${run.stderr.trim()}`);
221
311
  }
@@ -232,6 +322,6 @@ export async function removeWorktree(path, cwd) {
232
322
  // The sandbox asks again when this answers false, and git, asked again
233
323
  // about a worktree it has forgotten, changes nothing: the mutant that
234
324
  // always answers false is equivalent.
235
- return (await git(['worktree', 'remove', '--force', path], cwd)).code === 0;
325
+ return (await git(['worktree', 'remove', '--force', path], cwd, WORK_MS)).code === 0;
236
326
  }
237
327
  //# sourceMappingURL=git.js.map
package/dist/git.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"git.js","sourceRoot":"","sources":["../src/git.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAU9C,gFAAgF;AAChF,MAAM,UAAU,GAAG,CAAC,IAAuB,EAAE,GAAW;IACtD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,uEAAuE;QACvE,+DAA+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,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["/**\n * The edge where the harness meets git.\n *\n * Reads, except for two things ADR-0003 allows and bounds: a temporary\n * worktree, added and always removed by the sandbox, and nothing else. Every\n * call is an argument vector, never a shell string, so a path or a ref cannot\n * become a command.\n */\n\nimport { execFile } from 'node:child_process';\n\nimport type { FileChange, LocalBranch } from './types.js';\n\nexport interface Run {\n readonly code: number;\n readonly stdout: string;\n readonly stderr: string;\n}\n\n/** Runs git and answers whatever it answered; a missing git is a code of -1. */\nexport function git(args: readonly string[], cwd: string): Promise<Run> {\n return new Promise((resolve) => {\n // windowsHide only keeps a console window from flashing up on Windows,\n // and the sweep runs on Linux, where its mutant is equivalent.\n execFile('git', [...args], { cwd, maxBuffer: 256 * 1024 * 1024, encoding: 'utf8', windowsHide: true }, (error, stdout, stderr) => {\n // Every caller tells 0 from any other code, never one failure from\n // another, so which code a failure gets is equivalent to its mutants.\n const code = error === null ? 0 : typeof (error as { code?: unknown }).code === 'number' ? (error as { code: number }).code : -1;\n resolve({ code, stdout, stderr });\n });\n });\n}\n\nasync function value(args: readonly string[], cwd: string): Promise<string | null> {\n const run = await git(args, cwd);\n return run.code === 0 ? run.stdout.trim() : null;\n}\n\nexport class GitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitError';\n }\n}\n\n/** The top of the work tree holding `cwd`, POSIX-separated, or `null` outside one. */\nexport async function workTreeRoot(cwd: string): Promise<string | null> {\n return value(['rev-parse', '--show-toplevel'], cwd);\n}\n\n/** The git directory every worktree of this repository shares. */\nexport async function commonDirectory(cwd: string): Promise<string | null> {\n return value(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n}\n\n/** A work tree as one start of git names it: its top, and the git directory its worktrees share. */\nexport interface WorkTree {\n readonly root: string;\n readonly commonDir: string;\n}\n\n/**\n * The top of the work tree holding `cwd` and the common directory, asked of\n * git in one start where {@link workTreeRoot} and {@link commonDirectory}\n * are two: `null` outside a work tree, and `'unread'` where the one answer\n * cannot be taken for the two, which are then to be asked for as they were.\n *\n * Measured with git 2.43 and 2.55, rev-parse answers the two in the order\n * they stand on its line, a line each, and prints nothing where the first\n * fails. Its manual says of that only that `--show-toplevel` reports an\n * error where there is no working tree (git-rev-parse(1), Options for\n * Files, as git 2.55.0 has it, read 2026-10-14), so nothing is read on\n * trust. Two lines that are each what `trim` would leave, from a git that\n * did not fail, are the two answers. Nothing printed, by a git that\n * failed, is the first question failing, the one {@link workTreeRoot}\n * asks: `cwd` is in no work tree. Anything else is not read: a path that\n * holds a line break is more lines than two, and so is what a git before\n * 2.31 would print, to which `--path-format=absolute` is a flag to hand\n * back (the same manual, Options for Filtering; the option is new in the\n * release notes of 2.31.0). No such git was measured.\n *\n * `--path-format` reaches only what follows it on the line (Options for\n * Files), so the top is printed as it is where it is asked for alone. The\n * common directory is asked for from `cwd` here, and from the top by\n * {@link commonDirectory}: the same directory only where `cwd` is the top.\n */\nexport async function workTree(cwd: string): Promise<WorkTree | 'unread' | null> {\n const run = await git(['rev-parse', '--show-toplevel', '--path-format=absolute', '--git-common-dir'], cwd);\n if (run.stdout === '') return run.code === 0 ? 'unread' : null;\n const lines = run.stdout.split('\\n');\n if (run.code !== 0 || lines.length !== 3 || lines[2] !== '') return 'unread';\n const root = lines[0]!;\n const commonDir = lines[1]!;\n if (root === '' || commonDir === '' || root.trim() !== root || commonDir.trim() !== commonDir) return 'unread';\n return { root, commonDir };\n}\n\n/**\n * Where git runs the hook `name` from, absolute: `core.hooksPath` read as git\n * reads it - relative to the work tree, absolute, or under `~` - and a linked\n * worktree's shared hooks. Where git cannot say, the first line of what it\n * said instead: under a `core.hooksPath` that names a file it refuses the\n * path as one that is not a directory (measured with git 2.47 and 2.55).\n */\nexport async function hookPath(name: string, cwd: string): Promise<{ readonly path: string } | { readonly refused: string }> {\n const run = await git(['rev-parse', '--path-format=absolute', '--git-path', `hooks/${name}`], cwd);\n if (run.code === 0) return { path: run.stdout.trim() };\n return { refused: run.stderr.split(/\\r?\\n/)[0]! };\n}\n\nconst HEADS = 'refs/heads/';\n\n/**\n * The checked-out branch's name, or `null` on a detached head: what HEAD\n * points at, with `refs/heads/` taken off and nothing else. `--short` gives\n * the shortest name git reads as that ref and no other, which is another\n * name where a tag, or a ref under `refs/`, has the branch's: measured with\n * git 2.55, on `claude/brief-042-x` beside the tag `claude/brief-042-x` it\n * answers `heads/claude/brief-042-x`, which no template reads, and the\n * brief went unnamed (ADR-0005). A HEAD that points outside `refs/heads/`,\n * as `git symbolic-ref HEAD refs/tags/x` leaves it, is named as git status\n * names it, the ref whole.\n */\nexport async function currentBranch(cwd: string): Promise<string | null> {\n const ref = await value(['symbolic-ref', '--quiet', 'HEAD'], cwd);\n return ref !== null && ref.startsWith(HEADS) ? ref.slice(HEADS.length) : ref;\n}\n\n/**\n * The remote's default branch as a local ref, such as `origin/main`, or\n * `null`. This is a ref the harness hands git and spec-brief as the base, so\n * it is the short name git reads as that ref and no other: beside a local\n * branch or a tag named `origin/main`, measured with git 2.55, it is\n * `remotes/origin/main`, where `origin/main` would be read as the branch or\n * the tag (gitrevisions(7), the order a ref name is read in).\n */\nexport async function remoteDefault(cwd: string): Promise<string | null> {\n return value(['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], cwd);\n}\n\n/**\n * Every local branch. The two are one name but where a tag, or a ref under\n * `refs/`, has the branch's: `main` beside the tag `main` is the ref\n * `heads/main`. A ref name holds no control character\n * (git-check-ref-format(1)), so a tab parts the two.\n */\nexport async function localBranches(cwd: string): Promise<LocalBranch[]> {\n const listed = await value(['for-each-ref', '--format=%(refname:lstrip=2)%09%(refname:short)', HEADS], cwd);\n // for-each-ref fails only where git itself does, outside a repository,\n // where init never runs: the null check is there for the type.\n if (listed === null || listed === '') return [];\n return listed.split('\\n').map((line) => {\n const parts = line.split('\\t');\n return { name: parts[0]!, ref: parts[1]! };\n });\n}\n\nexport async function revision(ref: string, cwd: string): Promise<string | null> {\n return value(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], cwd);\n}\n\nexport async function mergeBase(a: string, b: string, cwd: string): Promise<string | null> {\n return value(['merge-base', a, b], cwd);\n}\n\n/** Parses `git diff --name-status -z` output. */\nexport function parseNameStatus(output: string): FileChange[] {\n const fields = output.split('\\0');\n const out: FileChange[] = [];\n for (let i = 0; i < fields.length; ) {\n const code = fields[i] as string;\n if (code === '') {\n i += 1;\n continue;\n }\n const letter = code.charAt(0);\n const status = letter as FileChange['status'];\n if (status === 'R' || status === 'C') {\n out.push({ status, from: fields[i + 1] ?? '', path: fields[i + 2] ?? '' });\n i += 3;\n } else {\n out.push({ status, path: fields[i + 1] ?? '' });\n i += 2;\n }\n }\n return out;\n}\n\n/** The files changed from one revision to another, renames found. */\nexport async function changes(from: string, to: string, cwd: string): Promise<FileChange[]> {\n const run = await git(['diff', '--name-status', '-z', '--find-renames', '--no-color', from, to, '--'], cwd);\n if (run.code !== 0) throw new GitError(`git diff ${from} ${to} failed: ${run.stderr.trim()}`);\n return parseNameStatus(run.stdout);\n}\n\n/** The files a commit would change: what is staged. */\nexport async function stagedChanges(cwd: string): Promise<FileChange[]> {\n const run = await git(['diff', '--cached', '--name-status', '-z', '--find-renames', '--no-color', '--'], cwd);\n if (run.code !== 0) throw new GitError(`git diff --cached failed: ${run.stderr.trim()}`);\n return parseNameStatus(run.stdout);\n}\n\n/** A file's content at a revision, or `null` when it does not exist there. */\nexport async function show(ref: string, path: string, cwd: string): Promise<string | null> {\n const run = await git(['show', `${ref}:${path}`], cwd);\n return run.code === 0 ? run.stdout : null;\n}\n\n/** Whether a commit id from {@link blameLine} is the all-zero one of a line nobody committed. */\nexport function isUncommitted(sha: string): boolean {\n return /^0+$/.test(sha);\n}\n\n/**\n * The commit that last changed one line of a file, as of a revision, or of\n * the working tree when `ref` is `null` - where a line nobody committed yet\n * belongs to the all-zero commit.\n */\nexport async function blameLine(ref: string | null, path: string, line: number, cwd: string): Promise<string | null> {\n const run = await git(['blame', '--porcelain', '-L', `${line},${line}`, ...(ref === null ? [] : [ref]), '--', path], cwd);\n // A blame that fails prints nothing on stdout, which names no commit. Its\n // output opens with the commit, so the anchor is equivalent to its mutant.\n const sha = /^([0-9a-f]{40,64}) /.exec(run.stdout)?.[1];\n return sha ?? null;\n}\n\n/** A good signature names its allowed signer's principal; any other names none. */\nexport type Signature =\n | { readonly good: true; readonly principal: string; readonly detail: string }\n | { readonly good: false; readonly principal: null; readonly detail: string };\n\n/**\n * Whether a commit carries a good SSH signature by a principal in the given\n * allowed-signers file. The file is passed in, never read from the commit's\n * own tree: a round cannot vouch for itself (ADR-0006).\n */\nexport async function verifyCommit(sha: string, allowedSignersFile: string, cwd: string): Promise<Signature> {\n const run = await git(\n ['-c', `gpg.ssh.allowedSignersFile=${allowedSignersFile}`, '-c', 'gpg.format=ssh', 'verify-commit', '--raw', sha],\n cwd,\n );\n const text = `${run.stderr}\\n${run.stdout}`;\n const principal = /Good \"git\" signature for (\\S+)/.exec(text)?.[1];\n // git writes the check to stderr, so the trim changes the first line only\n // for output on stdout alone, which verify-commit does not print; and split\n // always answers a first part.\n const detail = text.trim().split('\\n')[0]!;\n // git exits 0 only for a signature by a listed principal, which it names:\n // either condition alone is equivalent to both, and both trust neither.\n return run.code === 0 && principal !== undefined ? { good: true, principal, detail } : { good: false, principal: null, detail };\n}\n\nexport async function addWorktree(path: string, rev: string, cwd: string): Promise<void> {\n const run = await git(['worktree', 'add', '--detach', '--force', path, rev], cwd);\n if (run.code !== 0) throw new GitError(`git worktree add failed: ${run.stderr.trim()}`);\n}\n\n/**\n * Has git remove the worktree at `path`, and no other, with its record of it,\n * and answers whether git did. Git deletes what it can of the worktree's\n * directory and forgets the worktree even when it cannot delete it all. It\n * refuses a worktree whose directory has lost its `.git` file, and removes\n * its record of one whose directory is gone, found by the path it was added\n * at: `git worktree prune` would also forget every other worktree git has\n * lost track of, the person's among them.\n */\nexport async function removeWorktree(path: string, cwd: string): Promise<boolean> {\n // The sandbox asks again when this answers false, and git, asked again\n // about a worktree it has forgotten, changes nothing: the mutant that\n // always answers false is equivalent.\n return (await git(['worktree', 'remove', '--force', path], cwd)).code === 0;\n}\n"]}
1
+ {"version":3,"file":"git.js","sourceRoot":"","sources":["../src/git.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAU9C;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC;AAEhC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IAC3C,MAAM,OAAO,GAAG,KAAoD,CAAC;IACrE,OAAO,OAAO,KAAK,IAAI,IAAI,OAAO,CAAC,MAAM,KAAK,IAAI,IAAI,OAAO,CAAC,IAAI,KAAK,mCAAmC,CAAC;AAC7G,CAAC;AAED,8HAA8H;AAC9H,SAAS,UAAU,CAAC,IAAuB;IACzC,OAAO,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,CAAE,CAAC;AACtF,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,GAAG,CAAC,IAAuB,EAAE,GAAW,EAAE,KAAK,GAAG,SAAS;IACzE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,uEAAuE;QACvE,+DAA+D;QAC/D,QAAQ,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,GAAG,IAAI,GAAG,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MA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CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,IAAY,EAAE,GAAW;IAC5D,uEAAuE;IACvE,sEAAsE;IACtE,sCAAsC;IACtC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,IAAI,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC;AACvF,CAAC","sourcesContent":["/**\n * The edge where the harness meets git.\n *\n * Reads, except for two things ADR-0003 allows and bounds: a temporary\n * worktree, added and always removed by the sandbox, and nothing else. Every\n * call is an argument vector, never a shell string, so a path or a ref cannot\n * become a command.\n */\n\nimport { execFile } from 'node:child_process';\n\nimport type { FileChange, LocalBranch } from './types.js';\n\nexport interface Run {\n readonly code: number;\n readonly stdout: string;\n readonly stderr: string;\n}\n\n/**\n * How long a process the harness asks a question of is given to answer:\n * git's reads, spec-brief's list of the briefs. Claude Code gives the hook's\n * entry 60 seconds, as init and the plugin write it, and cancels a hook that\n * reaches them, which before a write lets the write go ahead (ADR-0002). A\n * process that does not answer within this is stopped and its question\n * answered as one that failed, which before a write holds it, well inside\n * that minute; and the slowest such process measured, on a Windows\n * workstation under load and on GitHub's runner, answered in a fraction of\n * it.\n */\nexport const ANSWER_MS = 20_000;\n\n/**\n * How long a process that does a round's work is given: a diff of the\n * round, a worktree added for a probe or taken away, a sibling's check of\n * the repository. Its length is the repository's, and none runs before a\n * write.\n */\nexport const WORK_MS = 600_000;\n\n/**\n * Whether a process ended because the harness stopped it at its time\n * limit: Node kills it then and says so with `killed`. It kills one for\n * output past `maxBuffer` as well, and names that by its code.\n */\nexport function stoppedAtLimit(error: unknown): boolean {\n const failure = error as { killed?: unknown; code?: unknown } | null;\n return failure !== null && failure.killed === true && failure.code !== 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER';\n}\n\n/** The git command a line of arguments runs, past the `-c` settings before it: every line the harness hands git names one. */\nfunction subcommand(args: readonly string[]): string {\n return args.find((arg, index) => !arg.startsWith('-') && args[index - 1] !== '-c')!;\n}\n\n/**\n * Runs git and answers whatever it answered; a missing git is a code of -1.\n * A git that does not answer within `limit` is stopped, and rejected as a\n * `GitError` that says so: read as a failure, a question about the work\n * tree or the branch would answer as a directory in none, or a head on no\n * branch, under which the hook checks no write.\n */\nexport function git(args: readonly string[], cwd: string, limit = ANSWER_MS): Promise<Run> {\n return new Promise((resolve, reject) => {\n // windowsHide only keeps a console window from flashing up on Windows,\n // and the sweep runs on Linux, where its mutant is equivalent.\n execFile('git', [...args], { cwd, maxBuffer: 256 * 1024 * 1024, encoding: 'utf8', windowsHide: true, timeout: limit }, (error, stdout, stderr) => {\n if (stoppedAtLimit(error)) {\n reject(new GitError(`git ${subcommand(args)} did not answer within ${limit / 1000} seconds, and was stopped`));\n return;\n }\n // Every caller tells 0 from any other code, never one failure from\n // another, so which code a failure gets is equivalent to its mutants.\n const code = error === null ? 0 : typeof (error as { code?: unknown }).code === 'number' ? (error as { code: number }).code : -1;\n resolve({ code, stdout, stderr });\n });\n });\n}\n\nasync function value(args: readonly string[], cwd: string): Promise<string | null> {\n const run = await git(args, cwd);\n return run.code === 0 ? run.stdout.trim() : null;\n}\n\nexport class GitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'GitError';\n }\n}\n\n/** The top of the work tree holding `cwd`, POSIX-separated, or `null` outside one. */\nexport async function workTreeRoot(cwd: string): Promise<string | null> {\n return value(['rev-parse', '--show-toplevel'], cwd);\n}\n\n/** The git directory every worktree of this repository shares. */\nexport async function commonDirectory(cwd: string): Promise<string | null> {\n return value(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n}\n\n/** A work tree as one start of git names it: its top, and the git directory its worktrees share. */\nexport interface WorkTree {\n readonly root: string;\n readonly commonDir: string;\n}\n\n/**\n * The top of the work tree holding `cwd` and the common directory, asked of\n * git in one start where {@link workTreeRoot} and {@link commonDirectory}\n * are two: `null` outside a work tree, and `'unread'` where the one answer\n * cannot be taken for the two, which are then to be asked for as they were.\n *\n * Measured with git 2.43 and 2.55, rev-parse answers the two in the order\n * they stand on its line, a line each, and prints nothing where the first\n * fails. Its manual says of that only that `--show-toplevel` reports an\n * error where there is no working tree (git-rev-parse(1), Options for\n * Files, as git 2.55.0 has it, read 2026-10-14), so nothing is read on\n * trust. Two lines that are each what `trim` would leave, from a git that\n * did not fail, are the two answers. Nothing printed, by a git that\n * failed, is the first question failing, the one {@link workTreeRoot}\n * asks: `cwd` is in no work tree. Anything else is not read: a path that\n * holds a line break is more lines than two, and so is what a git before\n * 2.31 would print, to which `--path-format=absolute` is a flag to hand\n * back (the same manual, Options for Filtering; the option is new in the\n * release notes of 2.31.0). No such git was measured.\n *\n * `--path-format` reaches only what follows it on the line (Options for\n * Files), so the top is printed as it is where it is asked for alone. The\n * common directory is asked for from `cwd` here, and from the top by\n * {@link commonDirectory}: the same directory only where `cwd` is the top.\n */\nexport async function workTree(cwd: string): Promise<WorkTree | 'unread' | null> {\n const run = await git(['rev-parse', '--show-toplevel', '--path-format=absolute', '--git-common-dir'], cwd);\n if (run.stdout === '') return run.code === 0 ? 'unread' : null;\n const lines = run.stdout.split('\\n');\n if (run.code !== 0 || lines.length !== 3 || lines[2] !== '') return 'unread';\n const root = lines[0]!;\n const commonDir = lines[1]!;\n if (root === '' || commonDir === '' || root.trim() !== root || commonDir.trim() !== commonDir) return 'unread';\n return { root, commonDir };\n}\n\n/**\n * Where git runs the hook `name` from, absolute: `core.hooksPath` read as git\n * reads it - relative to the work tree, absolute, or under `~` - and a linked\n * worktree's shared hooks. Where git cannot say, the first line of what it\n * said instead: under a `core.hooksPath` that names a file it refuses the\n * path as one that is not a directory (measured with git 2.47 and 2.55).\n */\nexport async function hookPath(name: string, cwd: string): Promise<{ readonly path: string } | { readonly refused: string }> {\n const run = await git(['rev-parse', '--path-format=absolute', '--git-path', `hooks/${name}`], cwd);\n if (run.code === 0) return { path: run.stdout.trim() };\n return { refused: run.stderr.split(/\\r?\\n/)[0]! };\n}\n\nconst HEADS = 'refs/heads/';\n\n/**\n * The checked-out branch's name, or `null` on a detached head: what HEAD\n * points at, with `refs/heads/` taken off and nothing else. `--short` gives\n * the shortest name git reads as that ref and no other, which is another\n * name where a tag, or a ref under `refs/`, has the branch's: measured with\n * git 2.55, on `claude/brief-042-x` beside the tag `claude/brief-042-x` it\n * answers `heads/claude/brief-042-x`, which no template reads, and the\n * brief went unnamed (ADR-0005). A HEAD that points outside `refs/heads/`,\n * as `git symbolic-ref HEAD refs/tags/x` leaves it, is named as git status\n * names it, the ref whole.\n */\nexport async function currentBranch(cwd: string): Promise<string | null> {\n const ref = await value(['symbolic-ref', '--quiet', 'HEAD'], cwd);\n return ref !== null && ref.startsWith(HEADS) ? ref.slice(HEADS.length) : ref;\n}\n\n/**\n * The remote's default branch as a local ref, such as `origin/main`, or\n * `null`. This is a ref the harness hands git and spec-brief as the base, so\n * it is the short name git reads as that ref and no other: beside a local\n * branch or a tag named `origin/main`, measured with git 2.55, it is\n * `remotes/origin/main`, where `origin/main` would be read as the branch or\n * the tag (gitrevisions(7), the order a ref name is read in).\n */\nexport async function remoteDefault(cwd: string): Promise<string | null> {\n return value(['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], cwd);\n}\n\n/**\n * Every local branch. The two are one name but where a tag, or a ref under\n * `refs/`, has the branch's: `main` beside the tag `main` is the ref\n * `heads/main`. A ref name holds no control character\n * (git-check-ref-format(1)), so a tab parts the two.\n */\nexport async function localBranches(cwd: string): Promise<LocalBranch[]> {\n const listed = await value(['for-each-ref', '--format=%(refname:lstrip=2)%09%(refname:short)', HEADS], cwd);\n // for-each-ref fails only where git itself does, outside a repository,\n // where init never runs: the null check is there for the type.\n if (listed === null || listed === '') return [];\n return listed.split('\\n').map((line) => {\n const parts = line.split('\\t');\n return { name: parts[0]!, ref: parts[1]! };\n });\n}\n\nexport async function revision(ref: string, cwd: string): Promise<string | null> {\n return value(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], cwd);\n}\n\nexport async function mergeBase(a: string, b: string, cwd: string): Promise<string | null> {\n return value(['merge-base', a, b], cwd);\n}\n\n/** Parses `git diff --name-status -z` output. */\nexport function parseNameStatus(output: string): FileChange[] {\n const fields = output.split('\\0');\n const out: FileChange[] = [];\n for (let i = 0; i < fields.length; ) {\n const code = fields[i] as string;\n if (code === '') {\n i += 1;\n continue;\n }\n const letter = code.charAt(0);\n const status = letter as FileChange['status'];\n if (status === 'R' || status === 'C') {\n out.push({ status, from: fields[i + 1] ?? '', path: fields[i + 2] ?? '' });\n i += 3;\n } else {\n out.push({ status, path: fields[i + 1] ?? '' });\n i += 2;\n }\n }\n return out;\n}\n\n/** The files changed from one revision to another, renames found. */\nexport async function changes(from: string, to: string, cwd: string): Promise<FileChange[]> {\n const run = await git(['diff', '--name-status', '-z', '--find-renames', '--no-color', from, to, '--'], cwd, WORK_MS);\n if (run.code !== 0) throw new GitError(`git diff ${from} ${to} failed: ${run.stderr.trim()}`);\n return parseNameStatus(run.stdout);\n}\n\n/**\n * How many words stand before the path in each kind of record of\n * `git status --porcelain=v2`, as git-status(1) has them (Git for Windows\n * 2.55.0, *Porcelain Format Version 2*, read 2026-10-19): an ordinary\n * change, `1`, and seven; a rename or a copy, `2`, and eight, its path\n * followed by the path it came from as a record of its own under `-z`; an\n * unmerged path, `u`, and nine; an untracked or an ignored path, `?` or\n * `!`, and none. A header, `#`, names no path.\n */\nconst STATUS_FIELDS: Readonly<Record<string, number>> = { '1': 8, '2': 9, u: 10, '?': 1, '!': 1 };\n\n/**\n * The paths `git status --porcelain=v2 -z` names, each once, in the order\n * git gives them: a rename or a copy by both its paths. A path with a space\n * in it is the rest of its record, which `-z` prints as is.\n */\nexport function parseStatus(output: string): string[] {\n const records = output.split('\\0');\n const paths = new Set<string>();\n for (let at = 0; at < records.length; at += 1) {\n const record = records[at]!;\n const fields = STATUS_FIELDS[record.charAt(0)];\n if (fields === undefined) continue;\n paths.add(record.split(' ').slice(fields).join(' '));\n if (record.startsWith('2')) {\n at += 1;\n paths.add(records[at] ?? '');\n }\n }\n paths.delete('');\n return [...paths];\n}\n\n/**\n * Every path the work tree holds changed from HEAD: tracked files that\n * differ in the index or in the work tree, unmerged ones, and each\n * untracked file, those in an untracked directory one by one. One start of\n * git, with no optional lock taken: a status that writes the index as it\n * refreshes it holds a lock that can make another git running beside it\n * fail, and the manual has a status run in the background take none\n * (git-status(1), *Background Refresh*, and git(1), `--no-optional-locks`,\n * as Git for Windows 2.55.0 has them, read 2026-10-19).\n */\nexport async function changedPaths(cwd: string): Promise<string[]> {\n const run = await git(['--no-optional-locks', 'status', '--porcelain=v2', '-z', '--untracked-files=all'], cwd);\n if (run.code !== 0) throw new GitError(`git status failed: ${run.stderr.trim()}`);\n return parseStatus(run.stdout);\n}\n\n/** The files a commit would change: what is staged. */\nexport async function stagedChanges(cwd: string): Promise<FileChange[]> {\n const run = await git(['diff', '--cached', '--name-status', '-z', '--find-renames', '--no-color', '--'], cwd, WORK_MS);\n if (run.code !== 0) throw new GitError(`git diff --cached failed: ${run.stderr.trim()}`);\n return parseNameStatus(run.stdout);\n}\n\n/** A file's content at a revision, or `null` when it does not exist there. */\nexport async function show(ref: string, path: string, cwd: string): Promise<string | null> {\n const run = await git(['show', `${ref}:${path}`], cwd);\n return run.code === 0 ? run.stdout : null;\n}\n\n/** Whether a commit id from {@link blameLine} is the all-zero one of a line nobody committed. */\nexport function isUncommitted(sha: string): boolean {\n return /^0+$/.test(sha);\n}\n\n/**\n * The commit that last changed one line of a file, as of a revision, or of\n * the working tree when `ref` is `null` - where a line nobody committed yet\n * belongs to the all-zero commit.\n */\nexport async function blameLine(ref: string | null, path: string, line: number, cwd: string): Promise<string | null> {\n const run = await git(['blame', '--porcelain', '-L', `${line},${line}`, ...(ref === null ? [] : [ref]), '--', path], cwd);\n // A blame that fails prints nothing on stdout, which names no commit. Its\n // output opens with the commit, so the anchor is equivalent to its mutant.\n const sha = /^([0-9a-f]{40,64}) /.exec(run.stdout)?.[1];\n return sha ?? null;\n}\n\n/** A good signature names its allowed signer's principal; any other names none. */\nexport type Signature =\n | { readonly good: true; readonly principal: string; readonly detail: string }\n | { readonly good: false; readonly principal: null; readonly detail: string };\n\n/**\n * Whether a commit carries a good SSH signature by a principal in the given\n * allowed-signers file. The file is passed in, never read from the commit's\n * own tree: a round cannot vouch for itself (ADR-0006).\n */\nexport async function verifyCommit(sha: string, allowedSignersFile: string, cwd: string): Promise<Signature> {\n const run = await git(\n ['-c', `gpg.ssh.allowedSignersFile=${allowedSignersFile}`, '-c', 'gpg.format=ssh', 'verify-commit', '--raw', sha],\n cwd,\n );\n const text = `${run.stderr}\\n${run.stdout}`;\n const principal = /Good \"git\" signature for (\\S+)/.exec(text)?.[1];\n // git writes the check to stderr, so the trim changes the first line only\n // for output on stdout alone, which verify-commit does not print; and split\n // always answers a first part.\n const detail = text.trim().split('\\n')[0]!;\n // git exits 0 only for a signature by a listed principal, which it names:\n // either condition alone is equivalent to both, and both trust neither.\n return run.code === 0 && principal !== undefined ? { good: true, principal, detail } : { good: false, principal: null, detail };\n}\n\nexport async function addWorktree(path: string, rev: string, cwd: string): Promise<void> {\n const run = await git(['worktree', 'add', '--detach', '--force', path, rev], cwd, WORK_MS);\n if (run.code !== 0) throw new GitError(`git worktree add failed: ${run.stderr.trim()}`);\n}\n\n/**\n * Has git remove the worktree at `path`, and no other, with its record of it,\n * and answers whether git did. Git deletes what it can of the worktree's\n * directory and forgets the worktree even when it cannot delete it all. It\n * refuses a worktree whose directory has lost its `.git` file, and removes\n * its record of one whose directory is gone, found by the path it was added\n * at: `git worktree prune` would also forget every other worktree git has\n * lost track of, the person's among them.\n */\nexport async function removeWorktree(path: string, cwd: string): Promise<boolean> {\n // The sandbox asks again when this answers false, and git, asked again\n // about a worktree it has forgotten, changes nothing: the mutant that\n // always answers false is equivalent.\n return (await git(['worktree', 'remove', '--force', path], cwd, WORK_MS)).code === 0;\n}\n"]}
package/dist/hooks.d.ts CHANGED
@@ -50,6 +50,12 @@ export interface HookRequest {
50
50
  * write of the session will need (ADR-0005).
51
51
  */
52
52
  export declare const SESSION_START = "SessionStart";
53
+ /**
54
+ * The event Claude Code runs as its main agent finishes a turn, under which
55
+ * the hook reports what the work tree holds, where the configuration asks
56
+ * for it (ADR-0005). No tool is named.
57
+ */
58
+ export declare const TURN_END = "Stop";
53
59
  /** Reads a Claude Code hook's stdin, or says why it cannot. */
54
60
  export declare function parseClaudeHook(raw: string): HookRequest | {
55
61
  readonly error: string;
@@ -62,11 +68,44 @@ export declare function parseClaudeHook(raw: string): HookRequest | {
62
68
  * starting.
63
69
  */
64
70
  export declare function sessionResponse(problem: string | null): HookResponse;
71
+ /**
72
+ * The answer as a turn ends: the report, in one `systemMessage`, or
73
+ * nothing, where there is nothing to report. Always exit 0, and never a
74
+ * field that has Claude go on: `decision`, `additionalContext` and exit 2
75
+ * each continue the turn under Stop, and `continue: false` would stop one
76
+ * another hook continues. Claude Code shows a `systemMessage` to the person
77
+ * from an entry it waits on, and hands it to Claude on the next turn from
78
+ * one it runs in the background, as `init` writes it (ADR-0005, ADR-0012).
79
+ */
80
+ export declare function turnResponse(report: string | null): HookResponse;
65
81
  export interface HookResponse {
66
82
  /** What to print on stdout: JSON, or nothing. */
67
83
  readonly stdout: string;
68
84
  readonly exitCode: number;
69
85
  }
86
+ /**
87
+ * The answer before the one write a configuration that does not load lets
88
+ * through, a write to the configuration file itself: no decision, so that
89
+ * the person's own permission prompt stands as for any write the guard
90
+ * passes, and the line that says why every other write is held, for the
91
+ * person as `systemMessage` and for Claude as `additionalContext`, which
92
+ * Claude Code's hooks reference has a PreToolUse hook's answer carry
93
+ * (ADR-0005). Exit 0.
94
+ */
95
+ export declare function mendResponse(said: string): HookResponse;
96
+ /** The answer that says nothing and decides nothing: the write goes on as the person's own permissions have it. */
97
+ export declare const NONE: HookResponse;
98
+ /**
99
+ * The answer where the hook checks nothing and says so, a question it cannot
100
+ * read or a line of its own that turns the guard off: one line, as
101
+ * `systemMessage`, which Claude Code's hooks reference has shown to the
102
+ * person on every event the hook answers, and exit 0. It decides nothing,
103
+ * so the call goes on as it would without the hook. It was exit 1, which
104
+ * the reference counts as a hook that failed: under `onFailure: "block"`,
105
+ * which holds the call of a hook that cannot start, it held every write of
106
+ * a session for a line only a write can mend (ADR-0005).
107
+ */
108
+ export declare function warningResponse(said: string): HookResponse;
70
109
  /** What a warning after a write says: a decision's message and its next step. */
71
110
  export type Warning = Pick<Decision, 'message' | 'hint'>;
72
111
  /** The answer after a write: the warnings, as additional context for the model, or nothing. */
@@ -102,6 +141,12 @@ export interface CallRecord {
102
141
  readonly started: string;
103
142
  readonly env: readonly (string | null)[];
104
143
  }
144
+ /**
145
+ * The session a question is in, which spec-brief's answers are kept for,
146
+ * or `null` where it names none in the form Claude Code's ids have: such a
147
+ * question has every answer asked for afresh (ADR-0002).
148
+ */
149
+ export declare function sessionOf(request: HookRequest): string | null;
105
150
  /**
106
151
  * The call a question is about, or `null` where it does not say which
107
152
  * session and call it is, or says it in a form no file is named by.
package/dist/hooks.js CHANGED
@@ -42,6 +42,14 @@ function isObject(value) {
42
42
  * write of the session will need (ADR-0005).
43
43
  */
44
44
  export const SESSION_START = 'SessionStart';
45
+ /**
46
+ * The event Claude Code runs as its main agent finishes a turn, under which
47
+ * the hook reports what the work tree holds, where the configuration asks
48
+ * for it (ADR-0005). No tool is named.
49
+ */
50
+ export const TURN_END = 'Stop';
51
+ /** The events that name no tool, which the hook answers of the session and not of a write. */
52
+ const NO_TOOL = [SESSION_START, TURN_END];
45
53
  /** Reads a Claude Code hook's stdin, or says why it cannot. */
46
54
  export function parseClaudeHook(raw) {
47
55
  let value;
@@ -55,9 +63,9 @@ export function parseClaudeHook(raw) {
55
63
  return { error: 'the hook input is not a JSON object' };
56
64
  const event = value['hook_event_name'];
57
65
  const tool = value['tool_name'];
58
- if (typeof event !== 'string' || (typeof tool !== 'string' && event !== SESSION_START))
66
+ if (typeof event !== 'string' || (typeof tool !== 'string' && !NO_TOOL.includes(event)))
59
67
  return { error: 'the hook input names no event or tool' };
60
- // A session's start names no tool, and is read as naming none.
68
+ // A session's start and a turn's end name no tool, and are read as naming none.
61
69
  const named = typeof tool === 'string' ? tool : '';
62
70
  const input = isObject(value['tool_input']) ? value['tool_input'] : {};
63
71
  const paths = [];
@@ -87,7 +95,48 @@ export function sessionResponse(problem) {
87
95
  const said = `spec-harness: ${problem}`;
88
96
  return { stdout: `${JSON.stringify({ systemMessage: said, hookSpecificOutput: { hookEventName: SESSION_START, additionalContext: said } })}\n`, exitCode: 0 };
89
97
  }
90
- const NONE = { stdout: '', exitCode: 0 };
98
+ /**
99
+ * The answer as a turn ends: the report, in one `systemMessage`, or
100
+ * nothing, where there is nothing to report. Always exit 0, and never a
101
+ * field that has Claude go on: `decision`, `additionalContext` and exit 2
102
+ * each continue the turn under Stop, and `continue: false` would stop one
103
+ * another hook continues. Claude Code shows a `systemMessage` to the person
104
+ * from an entry it waits on, and hands it to Claude on the next turn from
105
+ * one it runs in the background, as `init` writes it (ADR-0005, ADR-0012).
106
+ */
107
+ export function turnResponse(report) {
108
+ if (report === null)
109
+ return NONE;
110
+ return { stdout: `${JSON.stringify({ systemMessage: report })}\n`, exitCode: 0 };
111
+ }
112
+ /**
113
+ * The answer before the one write a configuration that does not load lets
114
+ * through, a write to the configuration file itself: no decision, so that
115
+ * the person's own permission prompt stands as for any write the guard
116
+ * passes, and the line that says why every other write is held, for the
117
+ * person as `systemMessage` and for Claude as `additionalContext`, which
118
+ * Claude Code's hooks reference has a PreToolUse hook's answer carry
119
+ * (ADR-0005). Exit 0.
120
+ */
121
+ export function mendResponse(said) {
122
+ const line = `spec-harness: ${said}`;
123
+ return { stdout: `${JSON.stringify({ systemMessage: line, hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: line } })}\n`, exitCode: 0 };
124
+ }
125
+ /** The answer that says nothing and decides nothing: the write goes on as the person's own permissions have it. */
126
+ export const NONE = { stdout: '', exitCode: 0 };
127
+ /**
128
+ * The answer where the hook checks nothing and says so, a question it cannot
129
+ * read or a line of its own that turns the guard off: one line, as
130
+ * `systemMessage`, which Claude Code's hooks reference has shown to the
131
+ * person on every event the hook answers, and exit 0. It decides nothing,
132
+ * so the call goes on as it would without the hook. It was exit 1, which
133
+ * the reference counts as a hook that failed: under `onFailure: "block"`,
134
+ * which holds the call of a hook that cannot start, it held every write of
135
+ * a session for a line only a write can mend (ADR-0005).
136
+ */
137
+ export function warningResponse(said) {
138
+ return { stdout: `${JSON.stringify({ systemMessage: `spec-harness: ${said}` })}\n`, exitCode: 0 };
139
+ }
91
140
  function reasonOf(decisions) {
92
141
  return decisions.map((decision) => `spec-harness: ${decision.message}. Next: ${decision.hint}.`).join('\n');
93
142
  }
@@ -148,6 +197,16 @@ export const CALL_VARIABLES = [
148
197
  ];
149
198
  /** An id the hook names a file by: what Claude Code's ids are made of, and nothing a path could climb out by. */
150
199
  const ID = /^[\w-]{1,256}$/;
200
+ /**
201
+ * The session a question is in, which spec-brief's answers are kept for,
202
+ * or `null` where it names none in the form Claude Code's ids have: such a
203
+ * question has every answer asked for afresh (ADR-0002).
204
+ */
205
+ export function sessionOf(request) {
206
+ // The pattern reads null as "null", and what is answered is the session,
207
+ // null: the test of null is the compiler's, and its mutant equivalent.
208
+ return request.session !== null && ID.test(request.session) ? request.session : null;
209
+ }
151
210
  /**
152
211
  * The call a question is about, or `null` where it does not say which
153
212
  * session and call it is, or says it in a form no file is named by.
package/dist/hooks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAAsB,CAAC,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,cAAc,CAAC,CAAC;AAE/F;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,cAAc,GAAsB,CAAC,MAAM,EAAE,OAAO,E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E,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,QAAQ,EAAE,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACpG,CAAC","sourcesContent":["/**\n * The guard, spoken in the languages that ask it: an agent's pre- and\n * post-tool hooks, and git's pre-commit.\n *\n * Claude Code sends a hook one JSON object on stdin naming the tool and its\n * input. A file-editing tool names its file under `file_path`, `path` or\n * `notebook_path` depending on the tool and the release; all three are read,\n * because a guard that missed a renamed field would allow everything.\n *\n * What the answer may not do matters as much as what it does. Returning\n * `allow` from a pre-tool hook skips the person's own permission prompt, so\n * the guard never says `allow`: it says `deny`, or `ask`, or nothing. A\n * warning - a write outside the scope when the repository asked only to be\n * warned - is told to the model after the write, through the post-tool hook's\n * additional context, where it cannot unlock anything.\n */\n\nimport type { Decision } from './guard.js';\n\n/**\n * The tools whose input names a file they write, by every name a release of\n * Claude Code has had for one. The hook reads a path from each: a name more\n * costs nothing, and a Claude Code that still has the tool may send it.\n */\nexport const WRITING_TOOLS: readonly string[] = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'];\n\n/**\n * Those of them a Claude Code the harness runs under can call\n * (`CLAUDE_CODE_MINIMUM`, versions.ts). Its tools reference\n * (https://code.claude.com/docs/en/tools-reference, read 2026-10-12) has\n * `Edit`, `Write` and `NotebookEdit` in its table of tools, and no\n * `MultiEdit`, which its permissions page calls a legacy tool; and the tool\n * inputs each release declares hold a `MultiEdit` up to 1.0.128 and none\n * from 2.0.0 on (ADR-0005). So what doctor and init say of the writes a\n * line is started for names these alone: a tool nobody can call leaves no\n * write unchecked.\n */\nexport const CALLABLE_TOOLS: readonly string[] = ['Edit', 'Write', 'NotebookEdit'];\n\nconst PATH_FIELDS: readonly string[] = ['file_path', 'path', 'notebook_path'];\n\nexport interface HookRequest {\n readonly event: string;\n readonly tool: string;\n /** The session's working directory, when the hook says. */\n readonly cwd: string | null;\n /** Files the tool writes, as the tool named them - absolute, usually. */\n readonly paths: readonly string[];\n /** The session and the tool call the question is about, when it says: `session_id` and `tool_use_id`. */\n readonly session: string | null;\n readonly call: string | null;\n}\n\ntype Json = Record<string, unknown>;\n\nfunction isObject(value: unknown): value is Json {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * The event Claude Code runs as a session starts, resumes, is cleared or\n * compacted, or is forked: no tool is named, and the hook checks what every\n * write of the session will need (ADR-0005).\n */\nexport const SESSION_START = 'SessionStart';\n\n/** Reads a Claude Code hook's stdin, or says why it cannot. */\nexport function parseClaudeHook(raw: string): HookRequest | { readonly error: string } {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch {\n return { error: 'the hook input is not JSON' };\n }\n if (!isObject(value)) return { error: 'the hook input is not a JSON object' };\n const event = value['hook_event_name'];\n const tool = value['tool_name'];\n if (typeof event !== 'string' || (typeof tool !== 'string' && event !== SESSION_START)) return { error: 'the hook input names no event or tool' };\n // A session's start names no tool, and is read as naming none.\n const named = typeof tool === 'string' ? tool : '';\n const input = isObject(value['tool_input']) ? value['tool_input'] : {};\n const paths: string[] = [];\n if (WRITING_TOOLS.includes(named)) {\n for (const field of PATH_FIELDS) {\n const path = input[field];\n if (typeof path === 'string' && path !== '' && !paths.includes(path)) paths.push(path);\n }\n }\n const text = (field: string): string | null => {\n const found = value[field];\n return typeof found === 'string' ? found : null;\n };\n return { event, tool: named, cwd: text('cwd'), paths, session: text('session_id'), call: text('tool_use_id') };\n}\n\n/**\n * The answer as a session starts: what would hold every write of it, in\n * one line, for the person as `systemMessage` and for Claude as\n * `additionalContext`; or nothing, where all is well. Always exit 0: the\n * event cannot block, and a check that fails must not keep a session from\n * starting.\n */\nexport function sessionResponse(problem: string | null): HookResponse {\n if (problem === null) return NONE;\n const said = `spec-harness: ${problem}`;\n return { stdout: `${JSON.stringify({ systemMessage: said, hookSpecificOutput: { hookEventName: SESSION_START, additionalContext: said } })}\\n`, exitCode: 0 };\n}\n\nexport interface HookResponse {\n /** What to print on stdout: JSON, or nothing. */\n readonly stdout: string;\n readonly exitCode: number;\n}\n\nconst NONE: HookResponse = { stdout: '', exitCode: 0 };\n\nfunction reasonOf(decisions: readonly Warning[]): string {\n return decisions.map((decision) => `spec-harness: ${decision.message}. Next: ${decision.hint}.`).join('\\n');\n}\n\n/** What a warning after a write says: a decision's message and its next step. */\nexport type Warning = Pick<Decision, 'message' | 'hint'>;\n\n/** The answer after a write: the warnings, as additional context for the model, or nothing. */\nexport function afterResponse(warnings: readonly Warning[]): HookResponse {\n if (warnings.length === 0) return NONE;\n return {\n stdout: `${JSON.stringify({\n hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: reasonOf(warnings) },\n })}\\n`,\n exitCode: 0,\n };\n}\n\n/**\n * The answer to a Claude Code hook: a refusal or a question before a write,\n * a warning after one, or nothing.\n */\nexport function claudeResponse(event: string, decisions: readonly Decision[]): HookResponse {\n if (event === 'PreToolUse') {\n const denied = decisions.filter((decision) => decision.verdict === 'deny');\n const asked = decisions.filter((decision) => decision.verdict === 'ask');\n const decided = denied.length > 0 ? { verdict: 'deny', list: denied } : asked.length > 0 ? { verdict: 'ask', list: asked } : null;\n if (decided === null) return NONE;\n return {\n stdout: `${JSON.stringify({\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: decided.verdict,\n permissionDecisionReason: reasonOf(decided.list),\n },\n })}\\n`,\n exitCode: 0,\n };\n }\n if (event === 'PostToolUse') return afterResponse(warningsOf(decisions));\n return NONE;\n}\n\n/** The decisions a run after the write would say: those that warn, each by its message and next step. */\nexport function warningsOf(decisions: readonly Decision[]): Warning[] {\n return decisions.filter((decision) => decision.verdict === 'warn').map(({ message, hint }) => ({ message, hint }));\n}\n\n/**\n * What the hook reads besides its question and its line, as it decides: the\n * project Claude Code names, the brief the environment names, and the\n * branch a forge's CI names on a detached head (ADR-0004).\n */\nexport const CALL_VARIABLES: readonly string[] = [\n 'CLAUDE_PROJECT_DIR',\n 'SPEC_BRIEF',\n 'GITHUB_HEAD_REF',\n 'GITHUB_REF_TYPE',\n 'GITHUB_REF_NAME',\n 'CI_MERGE_REQUEST_SOURCE_BRANCH_NAME',\n 'CI_COMMIT_BRANCH',\n];\n\n/**\n * A tool call, as both of its hooks see it: the release, the session and\n * the call, the tool and its paths, the session's directory, what the\n * hook's line gives, the directory the hook was started in, and the\n * variables it reads (ADR-0002). What a run before the write keeps is\n * answered after it only to a run for which all of it is the same.\n */\nexport interface CallRecord {\n readonly release: string;\n readonly session: string;\n readonly call: string;\n readonly tool: string;\n readonly paths: readonly string[];\n readonly cwd: string | null;\n readonly line: readonly (string | null)[];\n readonly started: string;\n readonly env: readonly (string | null)[];\n}\n\n/** An id the hook names a file by: what Claude Code's ids are made of, and nothing a path could climb out by. */\nconst ID = /^[\\w-]{1,256}$/;\n\n/**\n * The call a question is about, or `null` where it does not say which\n * session and call it is, or says it in a form no file is named by.\n */\nexport function callRecord(\n request: HookRequest,\n line: Readonly<{ root: string | undefined; brief: string | undefined; base: string | undefined }>,\n started: string,\n env: Readonly<Record<string, string | undefined>>,\n release: string,\n): CallRecord | null {\n const { session, call } = request;\n if (session === null || call === null || !ID.test(session) || !ID.test(call)) return null;\n return {\n release,\n session,\n call,\n tool: request.tool,\n paths: request.paths,\n cwd: request.cwd,\n line: [line.root ?? null, line.brief ?? null, line.base ?? null],\n started,\n env: CALL_VARIABLES.map((name) => env[name] ?? null),\n };\n}\n\n/** The name of the file a call's decisions are kept under. */\nexport function callFile(record: CallRecord): string {\n return `${record.session}.${record.call}.json`;\n}\n\n/** What a run before the write keeps for the run after it: the call, and the warnings it decided. */\nexport function keptCall(record: CallRecord, warnings: readonly Warning[]): string {\n return `${JSON.stringify({ record, warnings })}\\n`;\n}\n\nfunction isWarning(value: unknown): value is Warning {\n return isObject(value) && typeof value['message'] === 'string' && typeof value['hint'] === 'string';\n}\n\n/**\n * The warnings kept for this call, or `null` where what was kept is not\n * JSON, is another call's, or holds anything but warnings: such a call is\n * decided as it was before anything was kept (ADR-0002).\n */\nexport function warningsKept(text: string, record: CallRecord): Warning[] | null {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n // Read as an empty object, a text that is not JSON holds no record\n // either: that mutant is equivalent.\n return null;\n }\n if (!isObject(value) || JSON.stringify(value['record']) !== JSON.stringify(record)) return null;\n const warnings = value['warnings'];\n return Array.isArray(warnings) && warnings.every(isWarning) ? warnings.map(({ message, hint }) => ({ message, hint })) : null;\n}\n\n/**\n * The answer to git's pre-commit hook: every file the commit would change\n * that the round may not, and exit 1 if any is refused. A warning prints and\n * lets the commit through; a question has no one to ask in git, so it refuses.\n */\nexport function gitResponse(decisions: readonly Decision[]): { readonly text: string; readonly exitCode: number } {\n const lines: string[] = [];\n let refused = 0;\n for (const decision of decisions) {\n if (decision.verdict === 'allow') continue;\n const blocking = decision.verdict === 'deny' || decision.verdict === 'ask';\n if (blocking) refused += 1;\n lines.push(`${blocking ? 'refused' : 'warning'} ${decision.message}`, ` ${decision.hint}`);\n }\n if (refused > 0) lines.push(`spec-harness: ${refused} file(s) this round may not change; the commit was stopped`);\n return { text: lines.length === 0 ? '' : `${lines.join('\\n')}\\n`, exitCode: refused > 0 ? 1 : 0 };\n}\n"]}
1
+ {"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAIH;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAAsB,CAAC,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,cAAc,CAAC,CAAC;AAE/F;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,cAAc,GAAsB,CAAC,MAAM,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC;AAEnF,MAAM,WAAW,GAAsB,CAAC,WAAW,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC;AAgB9E,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAA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AAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACpG,CAAC","sourcesContent":["/**\n * The guard, spoken in the languages that ask it: an agent's pre- and\n * post-tool hooks, and git's pre-commit.\n *\n * Claude Code sends a hook one JSON object on stdin naming the tool and its\n * input. A file-editing tool names its file under `file_path`, `path` or\n * `notebook_path` depending on the tool and the release; all three are read,\n * because a guard that missed a renamed field would allow everything.\n *\n * What the answer may not do matters as much as what it does. Returning\n * `allow` from a pre-tool hook skips the person's own permission prompt, so\n * the guard never says `allow`: it says `deny`, or `ask`, or nothing. A\n * warning - a write outside the scope when the repository asked only to be\n * warned - is told to the model after the write, through the post-tool hook's\n * additional context, where it cannot unlock anything.\n */\n\nimport type { Decision } from './guard.js';\n\n/**\n * The tools whose input names a file they write, by every name a release of\n * Claude Code has had for one. The hook reads a path from each: a name more\n * costs nothing, and a Claude Code that still has the tool may send it.\n */\nexport const WRITING_TOOLS: readonly string[] = ['Edit', 'Write', 'MultiEdit', 'NotebookEdit'];\n\n/**\n * Those of them a Claude Code the harness runs under can call\n * (`CLAUDE_CODE_MINIMUM`, versions.ts). Its tools reference\n * (https://code.claude.com/docs/en/tools-reference, read 2026-10-12) has\n * `Edit`, `Write` and `NotebookEdit` in its table of tools, and no\n * `MultiEdit`, which its permissions page calls a legacy tool; and the tool\n * inputs each release declares hold a `MultiEdit` up to 1.0.128 and none\n * from 2.0.0 on (ADR-0005). So what doctor and init say of the writes a\n * line is started for names these alone: a tool nobody can call leaves no\n * write unchecked.\n */\nexport const CALLABLE_TOOLS: readonly string[] = ['Edit', 'Write', 'NotebookEdit'];\n\nconst PATH_FIELDS: readonly string[] = ['file_path', 'path', 'notebook_path'];\n\nexport interface HookRequest {\n readonly event: string;\n readonly tool: string;\n /** The session's working directory, when the hook says. */\n readonly cwd: string | null;\n /** Files the tool writes, as the tool named them - absolute, usually. */\n readonly paths: readonly string[];\n /** The session and the tool call the question is about, when it says: `session_id` and `tool_use_id`. */\n readonly session: string | null;\n readonly call: string | null;\n}\n\ntype Json = Record<string, unknown>;\n\nfunction isObject(value: unknown): value is Json {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * The event Claude Code runs as a session starts, resumes, is cleared or\n * compacted, or is forked: no tool is named, and the hook checks what every\n * write of the session will need (ADR-0005).\n */\nexport const SESSION_START = 'SessionStart';\n\n/**\n * The event Claude Code runs as its main agent finishes a turn, under which\n * the hook reports what the work tree holds, where the configuration asks\n * for it (ADR-0005). No tool is named.\n */\nexport const TURN_END = 'Stop';\n\n/** The events that name no tool, which the hook answers of the session and not of a write. */\nconst NO_TOOL: readonly string[] = [SESSION_START, TURN_END];\n\n/** Reads a Claude Code hook's stdin, or says why it cannot. */\nexport function parseClaudeHook(raw: string): HookRequest | { readonly error: string } {\n let value: unknown;\n try {\n value = JSON.parse(raw);\n } catch {\n return { error: 'the hook input is not JSON' };\n }\n if (!isObject(value)) return { error: 'the hook input is not a JSON object' };\n const event = value['hook_event_name'];\n const tool = value['tool_name'];\n if (typeof event !== 'string' || (typeof tool !== 'string' && !NO_TOOL.includes(event))) return { error: 'the hook input names no event or tool' };\n // A session's start and a turn's end name no tool, and are read as naming none.\n const named = typeof tool === 'string' ? tool : '';\n const input = isObject(value['tool_input']) ? value['tool_input'] : {};\n const paths: string[] = [];\n if (WRITING_TOOLS.includes(named)) {\n for (const field of PATH_FIELDS) {\n const path = input[field];\n if (typeof path === 'string' && path !== '' && !paths.includes(path)) paths.push(path);\n }\n }\n const text = (field: string): string | null => {\n const found = value[field];\n return typeof found === 'string' ? found : null;\n };\n return { event, tool: named, cwd: text('cwd'), paths, session: text('session_id'), call: text('tool_use_id') };\n}\n\n/**\n * The answer as a session starts: what would hold every write of it, in\n * one line, for the person as `systemMessage` and for Claude as\n * `additionalContext`; or nothing, where all is well. Always exit 0: the\n * event cannot block, and a check that fails must not keep a session from\n * starting.\n */\nexport function sessionResponse(problem: string | null): HookResponse {\n if (problem === null) return NONE;\n const said = `spec-harness: ${problem}`;\n return { stdout: `${JSON.stringify({ systemMessage: said, hookSpecificOutput: { hookEventName: SESSION_START, additionalContext: said } })}\\n`, exitCode: 0 };\n}\n\n/**\n * The answer as a turn ends: the report, in one `systemMessage`, or\n * nothing, where there is nothing to report. Always exit 0, and never a\n * field that has Claude go on: `decision`, `additionalContext` and exit 2\n * each continue the turn under Stop, and `continue: false` would stop one\n * another hook continues. Claude Code shows a `systemMessage` to the person\n * from an entry it waits on, and hands it to Claude on the next turn from\n * one it runs in the background, as `init` writes it (ADR-0005, ADR-0012).\n */\nexport function turnResponse(report: string | null): HookResponse {\n if (report === null) return NONE;\n return { stdout: `${JSON.stringify({ systemMessage: report })}\\n`, exitCode: 0 };\n}\n\nexport interface HookResponse {\n /** What to print on stdout: JSON, or nothing. */\n readonly stdout: string;\n readonly exitCode: number;\n}\n\n/**\n * The answer before the one write a configuration that does not load lets\n * through, a write to the configuration file itself: no decision, so that\n * the person's own permission prompt stands as for any write the guard\n * passes, and the line that says why every other write is held, for the\n * person as `systemMessage` and for Claude as `additionalContext`, which\n * Claude Code's hooks reference has a PreToolUse hook's answer carry\n * (ADR-0005). Exit 0.\n */\nexport function mendResponse(said: string): HookResponse {\n const line = `spec-harness: ${said}`;\n return { stdout: `${JSON.stringify({ systemMessage: line, hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: line } })}\\n`, exitCode: 0 };\n}\n\n/** The answer that says nothing and decides nothing: the write goes on as the person's own permissions have it. */\nexport const NONE: HookResponse = { stdout: '', exitCode: 0 };\n\n/**\n * The answer where the hook checks nothing and says so, a question it cannot\n * read or a line of its own that turns the guard off: one line, as\n * `systemMessage`, which Claude Code's hooks reference has shown to the\n * person on every event the hook answers, and exit 0. It decides nothing,\n * so the call goes on as it would without the hook. It was exit 1, which\n * the reference counts as a hook that failed: under `onFailure: \"block\"`,\n * which holds the call of a hook that cannot start, it held every write of\n * a session for a line only a write can mend (ADR-0005).\n */\nexport function warningResponse(said: string): HookResponse {\n return { stdout: `${JSON.stringify({ systemMessage: `spec-harness: ${said}` })}\\n`, exitCode: 0 };\n}\n\nfunction reasonOf(decisions: readonly Warning[]): string {\n return decisions.map((decision) => `spec-harness: ${decision.message}. Next: ${decision.hint}.`).join('\\n');\n}\n\n/** What a warning after a write says: a decision's message and its next step. */\nexport type Warning = Pick<Decision, 'message' | 'hint'>;\n\n/** The answer after a write: the warnings, as additional context for the model, or nothing. */\nexport function afterResponse(warnings: readonly Warning[]): HookResponse {\n if (warnings.length === 0) return NONE;\n return {\n stdout: `${JSON.stringify({\n hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: reasonOf(warnings) },\n })}\\n`,\n exitCode: 0,\n };\n}\n\n/**\n * The answer to a Claude Code hook: a refusal or a question before a write,\n * a warning after one, or nothing.\n */\nexport function claudeResponse(event: string, decisions: readonly Decision[]): HookResponse {\n if (event === 'PreToolUse') {\n const denied = decisions.filter((decision) => decision.verdict === 'deny');\n const asked = decisions.filter((decision) => decision.verdict === 'ask');\n const decided = denied.length > 0 ? { verdict: 'deny', list: denied } : asked.length > 0 ? { verdict: 'ask', list: asked } : null;\n if (decided === null) return NONE;\n return {\n stdout: `${JSON.stringify({\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: decided.verdict,\n permissionDecisionReason: reasonOf(decided.list),\n },\n })}\\n`,\n exitCode: 0,\n };\n }\n if (event === 'PostToolUse') return afterResponse(warningsOf(decisions));\n return NONE;\n}\n\n/** The decisions a run after the write would say: those that warn, each by its message and next step. */\nexport function warningsOf(decisions: readonly Decision[]): Warning[] {\n return decisions.filter((decision) => decision.verdict === 'warn').map(({ message, hint }) => ({ message, hint }));\n}\n\n/**\n * What the hook reads besides its question and its line, as it decides: the\n * project Claude Code names, the brief the environment names, and the\n * branch a forge's CI names on a detached head (ADR-0004).\n */\nexport const CALL_VARIABLES: readonly string[] = [\n 'CLAUDE_PROJECT_DIR',\n 'SPEC_BRIEF',\n 'GITHUB_HEAD_REF',\n 'GITHUB_REF_TYPE',\n 'GITHUB_REF_NAME',\n 'CI_MERGE_REQUEST_SOURCE_BRANCH_NAME',\n 'CI_COMMIT_BRANCH',\n];\n\n/**\n * A tool call, as both of its hooks see it: the release, the session and\n * the call, the tool and its paths, the session's directory, what the\n * hook's line gives, the directory the hook was started in, and the\n * variables it reads (ADR-0002). What a run before the write keeps is\n * answered after it only to a run for which all of it is the same.\n */\nexport interface CallRecord {\n readonly release: string;\n readonly session: string;\n readonly call: string;\n readonly tool: string;\n readonly paths: readonly string[];\n readonly cwd: string | null;\n readonly line: readonly (string | null)[];\n readonly started: string;\n readonly env: readonly (string | null)[];\n}\n\n/** An id the hook names a file by: what Claude Code's ids are made of, and nothing a path could climb out by. */\nconst ID = /^[\\w-]{1,256}$/;\n\n/**\n * The session a question is in, which spec-brief's answers are kept for,\n * or `null` where it names none in the form Claude Code's ids have: such a\n * question has every answer asked for afresh (ADR-0002).\n */\nexport function sessionOf(request: HookRequest): string | null {\n // The pattern reads null as \"null\", and what is answered is the session,\n // null: the test of null is the compiler's, and its mutant equivalent.\n return request.session !== null && ID.test(request.session) ? request.session : null;\n}\n\n/**\n * The call a question is about, or `null` where it does not say which\n * session and call it is, or says it in a form no file is named by.\n */\nexport function callRecord(\n request: HookRequest,\n line: Readonly<{ root: string | undefined; brief: string | undefined; base: string | undefined }>,\n started: string,\n env: Readonly<Record<string, string | undefined>>,\n release: string,\n): CallRecord | null {\n const { session, call } = request;\n if (session === null || call === null || !ID.test(session) || !ID.test(call)) return null;\n return {\n release,\n session,\n call,\n tool: request.tool,\n paths: request.paths,\n cwd: request.cwd,\n line: [line.root ?? null, line.brief ?? null, line.base ?? null],\n started,\n env: CALL_VARIABLES.map((name) => env[name] ?? null),\n };\n}\n\n/** The name of the file a call's decisions are kept under. */\nexport function callFile(record: CallRecord): string {\n return `${record.session}.${record.call}.json`;\n}\n\n/** What a run before the write keeps for the run after it: the call, and the warnings it decided. */\nexport function keptCall(record: CallRecord, warnings: readonly Warning[]): string {\n return `${JSON.stringify({ record, warnings })}\\n`;\n}\n\nfunction isWarning(value: unknown): value is Warning {\n return isObject(value) && typeof value['message'] === 'string' && typeof value['hint'] === 'string';\n}\n\n/**\n * The warnings kept for this call, or `null` where what was kept is not\n * JSON, is another call's, or holds anything but warnings: such a call is\n * decided as it was before anything was kept (ADR-0002).\n */\nexport function warningsKept(text: string, record: CallRecord): Warning[] | null {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n // Read as an empty object, a text that is not JSON holds no record\n // either: that mutant is equivalent.\n return null;\n }\n if (!isObject(value) || JSON.stringify(value['record']) !== JSON.stringify(record)) return null;\n const warnings = value['warnings'];\n return Array.isArray(warnings) && warnings.every(isWarning) ? warnings.map(({ message, hint }) => ({ message, hint })) : null;\n}\n\n/**\n * The answer to git's pre-commit hook: every file the commit would change\n * that the round may not, and exit 1 if any is refused. A warning prints and\n * lets the commit through; a question has no one to ask in git, so it refuses.\n */\nexport function gitResponse(decisions: readonly Decision[]): { readonly text: string; readonly exitCode: number } {\n const lines: string[] = [];\n let refused = 0;\n for (const decision of decisions) {\n if (decision.verdict === 'allow') continue;\n const blocking = decision.verdict === 'deny' || decision.verdict === 'ask';\n if (blocking) refused += 1;\n lines.push(`${blocking ? 'refused' : 'warning'} ${decision.message}`, ` ${decision.hint}`);\n }\n if (refused > 0) lines.push(`spec-harness: ${refused} file(s) this round may not change; the commit was stopped`);\n return { text: lines.length === 0 ? '' : `${lines.join('\\n')}\\n`, exitCode: refused > 0 ? 1 : 0 };\n}\n"]}
package/dist/round.d.ts CHANGED
@@ -127,10 +127,18 @@ export declare function claudeCodeWiring(root: string, io: CliIO, pattern?: Patt
127
127
  * wrong with the name when no round can work under it. Every other command
128
128
  * stops there. A diagnosis says it, being what a person runs when the guard
129
129
  * holds a write they expected it to pass.
130
+ *
131
+ * `branch` is whether the name no round can work under is the branch's: a
132
+ * brief it names that spec-brief does not know, or has archived. The hook
133
+ * reads the same branch and holds every write under such a name, which is a
134
+ * setup that holds every write, as a hook's line naming such a brief is
135
+ * (ADR-0004). A name the flag gives is the question doctor was asked, and
136
+ * holds no write of anyone's.
130
137
  */
131
138
  export declare function diagnoseBrief(workspace: Workspace, options: Pick<Options, 'brief'>, env: CliIO['env']): Promise<{
132
139
  readonly id: string | null;
133
140
  readonly problem: string | null;
141
+ readonly branch: boolean;
134
142
  }>;
135
143
  export interface AuditResult {
136
144
  readonly brief: BriefRow;