slicekit 0.0.1 → 0.1.2

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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +252 -3
  3. package/bin/slicekit.js +4 -0
  4. package/package.json +21 -4
  5. package/src/adapters/githost/errors.js +17 -0
  6. package/src/adapters/githost/fixture.js +136 -0
  7. package/src/adapters/githost/gh-json.js +99 -0
  8. package/src/adapters/githost/github.js +127 -0
  9. package/src/adapters/githost/index.js +12 -0
  10. package/src/adapters/tracker/errors.js +53 -0
  11. package/src/adapters/tracker/fixture.js +71 -0
  12. package/src/adapters/tracker/github-issues.js +65 -0
  13. package/src/adapters/tracker/index.js +14 -0
  14. package/src/baseline.js +109 -0
  15. package/src/build/commit.js +201 -0
  16. package/src/build/decline.js +81 -0
  17. package/src/build/finish.js +155 -0
  18. package/src/build/order.js +158 -0
  19. package/src/build/overlap.js +173 -0
  20. package/src/build/parallel.js +50 -0
  21. package/src/build/pr.js +263 -0
  22. package/src/build/record.js +28 -0
  23. package/src/build/red.js +207 -0
  24. package/src/build/review.js +123 -0
  25. package/src/build/sync.js +47 -0
  26. package/src/build/verdict.js +410 -0
  27. package/src/build/worktree.js +169 -0
  28. package/src/check/ci-event.js +52 -0
  29. package/src/check/context.js +129 -0
  30. package/src/check/index.js +140 -0
  31. package/src/check/rules/.gitkeep +0 -0
  32. package/src/check/rules/ci-body.js +22 -0
  33. package/src/check/rules/ci-title.js +43 -0
  34. package/src/check/rules/citations.js +224 -0
  35. package/src/check/rules/commands.js +146 -0
  36. package/src/check/rules/coverage.js +248 -0
  37. package/src/check/rules/hooks.js +58 -0
  38. package/src/check/rules/journal.js +17 -0
  39. package/src/check/rules/layout.js +56 -0
  40. package/src/check/rules/managed.js +31 -0
  41. package/src/check/rules/queue.js +106 -0
  42. package/src/check/rules/references.js +249 -0
  43. package/src/check/rules/style.js +177 -0
  44. package/src/check/rules/trailer.js +67 -0
  45. package/src/cli/baseline.js +66 -0
  46. package/src/cli/branch.js +86 -0
  47. package/src/cli/build.js +239 -0
  48. package/src/cli/check.js +40 -0
  49. package/src/cli/decide.js +59 -0
  50. package/src/cli/gaps.js +73 -0
  51. package/src/cli/hook.js +28 -0
  52. package/src/cli/index.js +83 -0
  53. package/src/cli/init.js +96 -0
  54. package/src/cli/instructions.js +63 -0
  55. package/src/cli/intake.js +107 -0
  56. package/src/cli/journal.js +82 -0
  57. package/src/cli/plan.js +29 -0
  58. package/src/cli/pr.js +83 -0
  59. package/src/cli/process.js +59 -0
  60. package/src/cli/ready-label.js +119 -0
  61. package/src/cli/review.js +64 -0
  62. package/src/cli/spec.js +31 -0
  63. package/src/cli/stage.js +37 -0
  64. package/src/cli/state.js +106 -0
  65. package/src/cli/status.js +108 -0
  66. package/src/cli/update.js +62 -0
  67. package/src/cli/workflow.js +48 -0
  68. package/src/config.js +203 -0
  69. package/src/decisions.js +289 -0
  70. package/src/evidence.js +27 -0
  71. package/src/fs.js +38 -0
  72. package/src/gaps.js +271 -0
  73. package/src/git.js +209 -0
  74. package/src/githooks.js +37 -0
  75. package/src/hook-cli.js +63 -0
  76. package/src/hooks/io.js +205 -0
  77. package/src/hooks/paths.js +82 -0
  78. package/src/hooks/pre-bash.js +715 -0
  79. package/src/hooks/pre-compact.js +139 -0
  80. package/src/hooks/pre-edit.js +170 -0
  81. package/src/hooks/session-end.js +118 -0
  82. package/src/hooks/session-start.js +209 -0
  83. package/src/hooks/shapes.js +103 -0
  84. package/src/hooks/stop.js +37 -0
  85. package/src/hooks/subagent-marker.js +88 -0
  86. package/src/hooks/subagent-start.js +100 -0
  87. package/src/hooks/subagent-stop.js +106 -0
  88. package/src/ids.js +43 -0
  89. package/src/init.js +281 -0
  90. package/src/instructions.js +235 -0
  91. package/src/intake.js +409 -0
  92. package/src/journal.js +326 -0
  93. package/src/lock.js +35 -0
  94. package/src/markdown.js +155 -0
  95. package/src/paths.js +33 -0
  96. package/src/plan.js +25 -0
  97. package/src/pr.js +73 -0
  98. package/src/prbody.js +266 -0
  99. package/src/ready-label.js +107 -0
  100. package/src/redact.js +33 -0
  101. package/src/render/compare.js +23 -0
  102. package/src/render/entry.js +101 -0
  103. package/src/render/index.js +27 -0
  104. package/src/render/managed.js +128 -0
  105. package/src/render/manifest.js +24 -0
  106. package/src/render/settings.js +76 -0
  107. package/src/render/update.js +151 -0
  108. package/src/slicefile.js +173 -0
  109. package/src/spec-verify.js +58 -0
  110. package/src/stage.js +325 -0
  111. package/src/state/build.js +156 -0
  112. package/src/state/covers.js +58 -0
  113. package/src/state/index.js +191 -0
  114. package/src/state/sync.js +64 -0
  115. package/src/state/transitions.js +282 -0
  116. package/src/verdict.js +203 -0
  117. package/src/which.js +37 -0
  118. package/src/workflow.js +177 -0
  119. package/src/worktrees.js +68 -0
  120. package/templates/claude-code/agents/auditor.md +7 -0
  121. package/templates/claude-code/agents/designer.md +7 -0
  122. package/templates/claude-code/agents/developer.md +7 -0
  123. package/templates/claude-code/agents/fixer.md +7 -0
  124. package/templates/claude-code/agents/ops.md +7 -0
  125. package/templates/claude-code/agents/reviewer.md +7 -0
  126. package/templates/claude-code/commands/slicekit-audit.md +7 -0
  127. package/templates/claude-code/commands/slicekit-build.md +7 -0
  128. package/templates/claude-code/commands/slicekit-gaps.md +6 -0
  129. package/templates/claude-code/commands/slicekit-intake.md +7 -0
  130. package/templates/claude-code/commands/slicekit-ops.md +7 -0
  131. package/templates/claude-code/commands/slicekit-plan.md +6 -0
  132. package/templates/claude-code/commands/slicekit-release.md +7 -0
  133. package/templates/claude-code/commands/slicekit-review.md +7 -0
  134. package/templates/claude-code/commands/slicekit-specify.md +6 -0
  135. package/templates/claude-code/commands/slicekit.md +7 -0
  136. package/templates/claude-code/hooks.json +90 -0
  137. package/templates/claude-code/manifest.json +171 -0
  138. package/templates/claude-code/skills/slicekit-ids/SKILL.md +16 -0
  139. package/templates/claude-code/skills/slicekit-loop/SKILL.md +23 -0
  140. package/templates/claude-code/skills/slicekit-writing/SKILL.md +24 -0
  141. package/templates/docs/BUILD.md +5 -0
  142. package/templates/docs/decisions.md +15 -0
  143. package/templates/docs/intake/.keep +0 -0
  144. package/templates/docs/observability.md +25 -0
  145. package/templates/docs/phases/.keep +0 -0
  146. package/templates/docs/platform.md +25 -0
  147. package/templates/docs/releases/.keep +0 -0
  148. package/templates/docs/runbook.md +21 -0
  149. package/templates/docs/spec/00-overview.md +8 -0
  150. package/templates/docs/spec/contracts/.keep +0 -0
  151. package/templates/docs/spec/gaps.md +6 -0
  152. package/templates/docs/spec/stack.md +3 -0
  153. package/templates/githooks/pre-commit +79 -0
  154. package/templates/githooks/pre-merge-commit +79 -0
  155. package/templates/githooks/prepare-commit-msg +110 -0
  156. package/templates/instructions/agents/auditor.md +33 -0
  157. package/templates/instructions/agents/designer.md +21 -0
  158. package/templates/instructions/agents/developer.md +49 -0
  159. package/templates/instructions/agents/fixer.md +41 -0
  160. package/templates/instructions/agents/ops.md +21 -0
  161. package/templates/instructions/agents/reviewer.md +63 -0
  162. package/templates/instructions/commands/build.md +234 -0
  163. package/templates/instructions/commands/gaps.md +65 -0
  164. package/templates/instructions/commands/intake.md +90 -0
  165. package/templates/instructions/commands/plan.md +60 -0
  166. package/templates/instructions/commands/review.md +117 -0
  167. package/templates/instructions/commands/specify.md +49 -0
  168. package/templates/style.json +11 -0
  169. package/templates/workflow/pins.json +6 -0
  170. package/templates/workflow/slicekit.yml +110 -0
package/src/git.js ADDED
@@ -0,0 +1,209 @@
1
+ import { execFileSync } from 'node:child_process';
2
+
3
+ export class GitError extends Error {
4
+ constructor(args, stderr) {
5
+ super(`git ${args.join(' ')} failed: ${stderr}`);
6
+ this.name = 'GitError';
7
+ this.args = args;
8
+ this.stderr = stderr;
9
+ }
10
+ }
11
+
12
+ export function git(root, args) {
13
+ try {
14
+ return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
15
+ } catch (e) {
16
+ throw new GitError(args, String(e.stderr ?? e.message).trim());
17
+ }
18
+ }
19
+
20
+ function succeeds(root, args) {
21
+ try {
22
+ git(root, args);
23
+ return true;
24
+ } catch (e) {
25
+ if (e instanceof GitError) return false;
26
+ throw e;
27
+ }
28
+ }
29
+
30
+ export const isRepo = (root) => succeeds(root, ['rev-parse', '--git-dir']);
31
+ export const hasCommits = (root) => succeeds(root, ['rev-parse', '--verify', 'HEAD']);
32
+ // HEAD's branch, or null when HEAD is detached. It reads the full ref and strips `refs/heads/`:
33
+ // `--short` gives `heads/main` when a tag `main` exists, which would slip past a protected check.
34
+ export function currentBranch(root) {
35
+ let ref;
36
+ try {
37
+ ref = git(root, ['symbolic-ref', '-q', 'HEAD']);
38
+ } catch (e) {
39
+ // -q: a detached HEAD exits 1 with nothing on stderr; anything else is a real failure.
40
+ if (e instanceof GitError && e.stderr === '') return null;
41
+ throw e;
42
+ }
43
+ return ref.startsWith('refs/heads/') ? ref.slice('refs/heads/'.length) : null;
44
+ }
45
+
46
+ export const headSha = (root) => git(root, ['rev-parse', 'HEAD']);
47
+
48
+ // Whether `sha` names a commit object in the repository at root.
49
+ export function commitExists(root, sha) {
50
+ assertRef(sha);
51
+ return succeeds(root, ['cat-file', '-e', `${sha}^{commit}`]);
52
+ }
53
+
54
+ // The full 40-hex SHA of the commit `sha` names, or null when the repository cannot resolve it
55
+ // (unknown, ambiguous, or not a commit).
56
+ export function resolveCommit(root, sha) {
57
+ assertRef(sha);
58
+ try {
59
+ return git(root, ['rev-parse', '--verify', '--quiet', `${sha}^{commit}`]);
60
+ } catch (e) {
61
+ if (e instanceof GitError) return null;
62
+ throw e;
63
+ }
64
+ }
65
+
66
+ // A ref from user input or config: never an option, never a range, never two words.
67
+ export function assertRef(name) {
68
+ if (typeof name !== 'string' || name === '' || name.startsWith('-') || /\s/.test(name) || name.includes('..')) {
69
+ throw new GitError(['assertRef', String(name)], `refusing ref '${name}': empty, option-shaped, spaced or a range`);
70
+ }
71
+ return name;
72
+ }
73
+
74
+ export function changedFiles(root, base) {
75
+ assertRef(base);
76
+ const out = git(root, ['diff', '--name-only', '--end-of-options', `${base}...HEAD`, '--']);
77
+ return out === '' ? [] : out.split('\n');
78
+ }
79
+
80
+ // git's rule: trailers are the lines of the last paragraph, and only when every line is one.
81
+ export function parseTrailers(body) {
82
+ const paragraphs = body.replace(/\r\n/g, '\n').trim().split(/\n\n+/);
83
+ const last = paragraphs[paragraphs.length - 1].split('\n');
84
+ const trailers = {};
85
+ for (const line of last) {
86
+ const m = /^([A-Za-z][A-Za-z0-9-]*):\s*(.+)$/.exec(line);
87
+ if (!m) return {};
88
+ trailers[m[1]] = m[2].trim();
89
+ }
90
+ return trailers;
91
+ }
92
+
93
+ export function commitsOnBranch(root, base) {
94
+ const range = base == null ? 'HEAD' : `${assertRef(base)}..HEAD`;
95
+ const out = git(root, ['log', '--format=%H%x1f%s%x1f%b%x1e', '--end-of-options', range, '--']);
96
+ return out
97
+ .split('\x1e')
98
+ .map((rec) => rec.replace(/^\n/, ''))
99
+ .filter((rec) => rec.trim() !== '')
100
+ .map((rec) => {
101
+ const [sha, subject, body = ''] = rec.split('\x1f');
102
+ return { sha, subject, body: body.trim(), trailers: parseTrailers(body) };
103
+ });
104
+ }
105
+
106
+ // The commands own git (D-19): these are the helpers they do it through. Each throws GitError.
107
+
108
+ // `git config user.name`, or null when it is unset or empty.
109
+ export function gitUser(root) {
110
+ try {
111
+ return git(root, ['config', 'user.name']) || null;
112
+ } catch (e) {
113
+ if (e instanceof GitError) return null;
114
+ throw e;
115
+ }
116
+ }
117
+
118
+ // No staged, unstaged or untracked change (ignored files do not count).
119
+ export const isClean = (root) => git(root, ['status', '--porcelain']) === '';
120
+
121
+ export const hasRemote = (root, name = 'origin') => git(root, ['remote']).split('\n').includes(name);
122
+
123
+ // Switches to `name`; with `create`, makes it from `from` (default HEAD) without an upstream, so a
124
+ // branch cut from origin/main never pushes to main. `track` sets `from` as the upstream instead:
125
+ // only for origin's copy of the same work branch. Without `create`, it never guesses a branch from
126
+ // a remote one.
127
+ export function switchBranch(root, name, { create = false, from, track = false } = {}) {
128
+ assertRef(name);
129
+ if (from !== undefined) assertRef(from);
130
+ const upstream = track ? '--track' : '--no-track';
131
+ if (create) git(root, ['switch', '-q', upstream, '-c', name, ...(from === undefined ? [] : [from])]);
132
+ else git(root, ['switch', '-q', '--no-guess', name]);
133
+ }
134
+
135
+ // Stages `paths` (additions, changes and deletions) and commits only them. Null when none of them
136
+ // has a change to commit; otherwise the new commit's SHA.
137
+ export function commitPaths(root, paths, message) {
138
+ if (!Array.isArray(paths) || paths.length === 0) throw new GitError(['commit'], 'no paths to commit');
139
+ // --literal-pathspecs: a path is a path, never a glob or a magic pathspec such as `:/`.
140
+ git(root, ['--literal-pathspecs', 'add', '-A', '--', ...paths]);
141
+ if (succeeds(root, ['--literal-pathspecs', 'diff', '--cached', '--quiet', '--', ...paths])) return null;
142
+ git(root, ['--literal-pathspecs', 'commit', '-q', '-m', message, '--', ...paths]);
143
+ return headSha(root);
144
+ }
145
+
146
+ // The current branch's upstream as { remote, branch }, or null when it has none.
147
+ function upstreamOf(root, branch) {
148
+ const get = (key) => {
149
+ try {
150
+ return git(root, ['config', '--get', `branch.${branch}.${key}`]);
151
+ } catch (e) {
152
+ if (e instanceof GitError) return '';
153
+ throw e;
154
+ }
155
+ };
156
+ const remote = get('remote');
157
+ const merge = get('merge');
158
+ if (remote === '' || !merge.startsWith('refs/heads/')) return null;
159
+ return { remote, branch: merge.slice('refs/heads/'.length) };
160
+ }
161
+
162
+ function branchOrThrow(root, what) {
163
+ const branch = currentBranch(root);
164
+ if (branch === null) throw new GitError([what], 'HEAD is detached; work on a branch');
165
+ return branch;
166
+ }
167
+
168
+ // Where pushBranch would push, as { branch, target, tracked }, without sending anything: a caller
169
+ // that commits first asks this, so a refused target is refused before the commit too.
170
+ export function pushTarget(root) {
171
+ const branch = branchOrThrow(root, 'push');
172
+ const up = upstreamOf(root, branch);
173
+ const tracked = up !== null && up.remote === 'origin';
174
+ const target = tracked ? up.branch : branch;
175
+ assertRef(target);
176
+ return { branch, target, tracked };
177
+ }
178
+
179
+ // Pushes HEAD to origin, always by explicit refspec `HEAD:refs/heads/<target>`: the target is the
180
+ // upstream branch on origin when there is one (a plain push refuses when the names differ under
181
+ // push.default=simple), else the current branch, and then `-u` sets the upstream. An explicit
182
+ // refspec also keeps a `remote.origin.push` mapping from redirecting the push. Refuses a target in
183
+ // `protectedBranches` or equal to `defaultBranch` before anything is sent. Both are required, from the
184
+ // config: a default here would quietly guard the wrong branch in a repository that names it otherwise.
185
+ export function pushBranch(root, opts) {
186
+ const { protectedBranches, defaultBranch } = opts ?? {};
187
+ if (!Array.isArray(protectedBranches) || typeof defaultBranch !== 'string' || defaultBranch === '') {
188
+ throw new TypeError('pushBranch needs {protectedBranches, defaultBranch} from the config');
189
+ }
190
+ const { branch, target, tracked } = pushTarget(root);
191
+ if (protectedBranches.includes(target) || target === defaultBranch) {
192
+ throw new GitError(['push'], `refusing to push to ${target}: it is protected; push from a work branch`);
193
+ }
194
+ const remoteRef = `refs/heads/${target}`;
195
+ git(root, ['push', '-q', ...(tracked ? [] : ['-u']), 'origin', `HEAD:${remoteRef}`]);
196
+ return { branch, remoteRef };
197
+ }
198
+
199
+ // The number of commits on the upstream that HEAD lacks, after fetching its remote; 0 without an
200
+ // upstream, or when the upstream branch is gone from the remote.
201
+ export function behindUpstream(root) {
202
+ const branch = currentBranch(root);
203
+ const up = branch === null ? null : upstreamOf(root, branch);
204
+ if (up === null) return 0;
205
+ // --prune drops the remote-tracking ref of a branch deleted on the remote, so it reads as gone.
206
+ git(root, ['fetch', '--prune', '-q', up.remote]);
207
+ if (!succeeds(root, ['rev-parse', '--verify', '--quiet', '@{u}'])) return 0;
208
+ return Number(git(root, ['rev-list', '--count', 'HEAD..@{u}']));
209
+ }
@@ -0,0 +1,37 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { git, GitError } from './git.js';
4
+
5
+ // The slicekit git hooks (REQ-3.9) and the hooks path that runs them; init and the hooks rule share
6
+ // these, so they never disagree about what "installed" means.
7
+ export const HOOKS_PATH = '.githooks';
8
+ export const GITHOOKS = ['pre-commit', 'pre-merge-commit', 'prepare-commit-msg'];
9
+
10
+ // The configured core.hooksPath, or null when it is unset.
11
+ export function hooksPathValue(root) {
12
+ try {
13
+ return git(root, ['config', '--get', 'core.hooksPath']);
14
+ } catch (e) {
15
+ if (e instanceof GitError) return null;
16
+ throw e;
17
+ }
18
+ }
19
+
20
+ // Whether `value` names <root>/.githooks: git resolves a relative path against the worktree root, a
21
+ // trailing slash is ignored, on win32 the comparison ignores case, and when both paths exist their
22
+ // real paths are compared, so a junction or symlink to .githooks counts.
23
+ export function isInstalledHooksPath(root, value) {
24
+ if (typeof value !== 'string' || value.trim() === '') return false;
25
+ const resolved = [value, HOOKS_PATH].map((p) => path.resolve(root, p));
26
+ let real;
27
+ try {
28
+ real = resolved.map((p) => fs.realpathSync.native(p));
29
+ } catch {
30
+ real = resolved;
31
+ }
32
+ const norm = (abs) => {
33
+ const trimmed = abs.replace(/[\\/]+$/, '');
34
+ return process.platform === 'win32' ? trimmed.toLowerCase() : trimmed;
35
+ };
36
+ return norm(real[0]) === norm(real[1]);
37
+ }
@@ -0,0 +1,63 @@
1
+ import { execSync } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { which } from './which.js';
5
+
6
+ const LOCAL = 'node_modules/slicekit/bin/slicekit.js';
7
+ const CHECK_TIMEOUT_MS = 10_000;
8
+
9
+ // True when `name` resolves on env's PATH (with PATHEXT on Windows).
10
+ export function onPath(name, env) {
11
+ return which(name, env) !== null;
12
+ }
13
+
14
+ // The install advice of D-30: the kit is on npm from 0.1.1 (D-41).
15
+ export const NOT_INSTALLED =
16
+ 'slicekit is not installed locally or on PATH; hooks will fail until it is (npm i -D slicekit, or set cli in .slicekit/config.json)';
17
+
18
+ // The command the hooks call, D-30: a local install, else slicekit on PATH, else the PATH form with
19
+ // NOT_INSTALLED. Never a registry fetch: a hook that installs would run whatever the registry serves
20
+ // under the name on every call, so a missing kit is reported, never fetched (D-30).
21
+ export function probeCli(root, { env = process.env } = {}) {
22
+ if (fs.existsSync(path.join(root, LOCAL))) return { cli: `node ${LOCAL}`, warning: null };
23
+ if (onPath('slicekit', env)) return { cli: 'slicekit', warning: null };
24
+ return { cli: 'slicekit', warning: NOT_INSTALLED };
25
+ }
26
+
27
+ // Runs `<cli> --version` once. null when it prints `version`; otherwise the warning to show.
28
+ // Through a shell, as Claude Code runs a hook command: a quoted path stays one argument, and the
29
+ // npm .cmd shims on Windows cannot be spawned without one.
30
+ export function checkCli(cli, { version, cwd, platform = process.platform }) {
31
+ let out;
32
+ try {
33
+ out = execSync(`${cli} --version`, {
34
+ cwd,
35
+ encoding: 'utf8',
36
+ stdio: ['ignore', 'pipe', 'pipe'],
37
+ timeout: CHECK_TIMEOUT_MS,
38
+ windowsHide: true,
39
+ });
40
+ } catch {
41
+ out = null;
42
+ }
43
+ if (out !== null && out.trim() === version) return null;
44
+ const base = `hook command "${cli}" did not answer; hooks will report errors on every tool call until .slicekit/config.json cli is fixed`;
45
+ const causes = cliCauses(cli, platform);
46
+ return causes.length === 0 ? base : `${base}. Likely cause: ${causes.join('; ')}`;
47
+ }
48
+
49
+ // What a command that did not answer most likely got wrong, as far as its text shows: an unquoted
50
+ // path with spaces, which the shell splits into several arguments; and on Windows a Git Bash path
51
+ // such as /c/... or /tmp/..., which Node there cannot read.
52
+ export function cliCauses(cli, platform = process.platform) {
53
+ const causes = [];
54
+ const words = cli.trim().split(/\s+/);
55
+ const quoted = /["']/.test(cli);
56
+ if (!quoted && words.length > 2 && words.slice(1).some((w) => /[/\\]/.test(w))) {
57
+ causes.push('a path with spaces is split by the shell; quote a path that has spaces, as --cli "node \\"<path>\\""');
58
+ }
59
+ if (platform === 'win32' && words.some((w) => /^["']?\/[^/]/.test(w))) {
60
+ causes.push('on Windows, Node cannot read a Git Bash path such as /c/...; use C:/..., which pwd -W prints');
61
+ }
62
+ return causes;
63
+ }
@@ -0,0 +1,205 @@
1
+ // The hook protocol (C-3): every hook reads one JSON object on stdin and answers one JSON decision.
2
+ // Each hook module lives at src/hooks/<name>.js and exports handle(input, {root, cfg, env, git}).
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { CONFIG_PATH, loadConfig } from '../config.js';
7
+ import { git as runGit } from '../git.js';
8
+ import { existingAncestor, fromGitBash } from './paths.js';
9
+
10
+ // C-3's table: these eight names are the full set.
11
+ export const HOOK_NAMES = new Set([
12
+ 'session-start', 'pre-bash', 'pre-edit', 'subagent-start', 'subagent-stop', 'pre-compact', 'stop', 'session-end',
13
+ ]);
14
+ // REQ-3.1, 3.4, 3.6, 3.8 fail open; every other hook fails closed (REQ-3.2, 3.3, 3.5, 3.7).
15
+ export const FAIL_OPEN = new Set(['session-start', 'subagent-start', 'pre-compact', 'session-end']);
16
+ // A fail-closed PreToolUse hook denies; a fail-closed stop hook blocks.
17
+ const DENIES = new Set(['pre-bash', 'pre-edit']);
18
+
19
+ export class HookInputError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'HookInputError';
23
+ }
24
+ }
25
+
26
+ export function readHookInput(stdin) {
27
+ const text = String(stdin ?? '').trim();
28
+ if (text === '') throw new HookInputError('could not read hook input: stdin was empty');
29
+ let input;
30
+ try {
31
+ input = JSON.parse(text);
32
+ } catch {
33
+ throw new HookInputError('could not read hook input: stdin is not valid JSON');
34
+ }
35
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {
36
+ throw new HookInputError('could not read hook input: stdin is not a JSON object');
37
+ }
38
+ return input;
39
+ }
40
+
41
+ export const allow = () => ({});
42
+ export const deny = (reason) => ({
43
+ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason },
44
+ });
45
+ export const context = (event, text) => ({ hookSpecificOutput: { hookEventName: event, additionalContext: text } });
46
+ export const block = (reason) => ({ decision: 'block', reason });
47
+
48
+ // The nearest directory at or above dir holding .slicekit/config.json, or null.
49
+ function configAbove(dir) {
50
+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {
51
+ if (fs.existsSync(path.join(d, CONFIG_PATH))) return d;
52
+ if (path.dirname(d) === d) return null;
53
+ }
54
+ }
55
+
56
+ // The directory holding .slicekit/config.json, walking up from cwd; process.cwd() when there is none.
57
+ export function findRoot(cwd) {
58
+ return (typeof cwd === 'string' && cwd !== '' ? configAbove(cwd) : null) ?? process.cwd();
59
+ }
60
+
61
+ const PATH_KEYS = ['file_path', 'notebook_path'];
62
+
63
+ // Whether the hook call belongs to a slicekit project: a config above the cwd (process.cwd() when the
64
+ // input has none) or, for pre-edit, above any path the tool names. Outside one, every hook answers {}.
65
+ const slashed = (p) => fromGitBash(p.replace(/\\/g, '/'));
66
+ function inProject(name, input) {
67
+ const cwd = typeof input.cwd === 'string' && input.cwd !== '' ? path.resolve(slashed(input.cwd)) : process.cwd();
68
+ if (configAbove(cwd)) return true;
69
+ if (name !== 'pre-edit') return false;
70
+ return PATH_KEYS.some((k) => {
71
+ const p = input.tool_input?.[k];
72
+ if (typeof p !== 'string' || p === '') return false;
73
+ return configAbove(existingAncestor(path.resolve(cwd, slashed(p)))) !== null;
74
+ });
75
+ }
76
+
77
+
78
+ // null when the hook's module does not exist yet.
79
+ async function loadModule(name) {
80
+ const file = fileURLToPath(new URL(`./${name}.js`, import.meta.url));
81
+ if (!fs.existsSync(file)) return null;
82
+ return import(pathToFileURL(file).href);
83
+ }
84
+
85
+ const REASON_MAX = 300;
86
+ // One line, at most 300 characters: a reason is read in the agent's transcript, not a log.
87
+ export function oneLine(text) {
88
+ return String(text).replace(/\s+/g, ' ').trim().slice(0, REASON_MAX);
89
+ }
90
+
91
+ function refuse(name, reason) {
92
+ return DENIES.has(name) ? deny(oneLine(reason)) : block(oneLine(reason));
93
+ }
94
+
95
+ // The serialised answer for a hook that failed: the refusal for a fail-closed name, {} for a fail-open one.
96
+ export function failureOutput(name, message) {
97
+ if (FAIL_OPEN.has(name) || !HOOK_NAMES.has(name)) return '{}';
98
+ return JSON.stringify(refuse(name, `slicekit hook ${name} failed: ${message}`));
99
+ }
100
+
101
+ const DEFAULT_DEADLINE = 8000;
102
+ const DEADLINE_MARGIN = 2000;
103
+ let renderedHooks;
104
+ function templateHooks() {
105
+ if (renderedHooks === undefined) {
106
+ try {
107
+ const file = fileURLToPath(new URL('../../templates/claude-code/hooks.json', import.meta.url));
108
+ renderedHooks = JSON.parse(fs.readFileSync(file, 'utf8'));
109
+ } catch {
110
+ renderedHooks = {};
111
+ }
112
+ }
113
+ return renderedHooks;
114
+ }
115
+
116
+ // The handler's deadline: the timeout the renderer writes for this hook into .claude/settings.json
117
+ // (from templates/claude-code/hooks.json) minus 2 s, so the kit answers before the agent tool gives up.
118
+ export function hookDeadline(name, hooks = templateHooks()) {
119
+ const suffix = ` hook ${name}`;
120
+ for (const groups of Object.values(hooks ?? {})) {
121
+ for (const group of Array.isArray(groups) ? groups : []) {
122
+ for (const h of Array.isArray(group?.hooks) ? group.hooks : []) {
123
+ if (typeof h?.command !== 'string' || !h.command.endsWith(suffix)) continue;
124
+ if (typeof h.timeout === 'number' && h.timeout * 1000 > DEADLINE_MARGIN) return h.timeout * 1000 - DEADLINE_MARGIN;
125
+ return DEFAULT_DEADLINE;
126
+ }
127
+ }
128
+ }
129
+ return DEFAULT_DEADLINE;
130
+ }
131
+
132
+ class HookTimeout extends Error {}
133
+
134
+ // The timer is unref'd so it never holds the process open on its own.
135
+ function withDeadline(promise, ms) {
136
+ let timer;
137
+ const timeout = new Promise((_, reject) => {
138
+ timer = setTimeout(() => reject(new HookTimeout(`timed out after ${ms} ms`)), ms);
139
+ timer.unref?.();
140
+ });
141
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
142
+ }
143
+
144
+ const kindOf = (v) => (v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v);
145
+ const PERMISSION = new Set(['allow', 'deny', 'ask']);
146
+
147
+ // null when the result is a decision this hook may give; otherwise why not.
148
+ function shapeError(name, result) {
149
+ const kind = kindOf(result);
150
+ if (kind !== 'object') return `handler returned ${kind}`;
151
+ if (FAIL_OPEN.has(name) || Object.keys(result).length === 0) return null;
152
+ if (DENIES.has(name)) {
153
+ return PERMISSION.has(result.hookSpecificOutput?.permissionDecision)
154
+ ? null : 'handler returned a result with no permissionDecision';
155
+ }
156
+ return result.decision === 'block' && typeof result.reason === 'string'
157
+ ? null : 'handler returned a result that is neither {} nor a block with a reason';
158
+ }
159
+
160
+ // -> {stdout: string (one JSON object; '' for an unknown name), code: number, stderr: string}.
161
+ // `load` and `deadline` are injectable for tests.
162
+ export async function runHook(name, { stdin, root, env = process.env, load = loadModule, deadline } = {}) {
163
+ if (!HOOK_NAMES.has(name)) return { stdout: '', code: 2, stderr: `unknown hook ${name}\n` };
164
+ const open = FAIL_OPEN.has(name);
165
+ const fail = (message) => (open
166
+ ? { stdout: '{}', code: 0, stderr: `slicekit hook ${name} failed: ${oneLine(message)}\n` }
167
+ : { stdout: failureOutput(name, message), code: 0, stderr: '' });
168
+
169
+ let input;
170
+ try {
171
+ input = readHookInput(stdin);
172
+ } catch (err) {
173
+ if (open) return { stdout: '{}', code: 0, stderr: `slicekit hook ${name}: ${err.message}\n` };
174
+ return { stdout: JSON.stringify(refuse(name, err.message)), code: 0, stderr: '' };
175
+ }
176
+
177
+ try {
178
+ const mod = await load(name);
179
+ // Not built yet: answer {} even for a fail-closed name once its input parsed, so installing the
180
+ // kit never blocks a team before the guard exists. The guard takes over when its module lands.
181
+ if (!mod) return { stdout: '{}', code: 0, stderr: '' };
182
+ // Not a slicekit project: the kit has nothing to guard. A config that exists but is invalid is
183
+ // still loaded below, and fails closed.
184
+ if (root === undefined && !inProject(name, input)) return { stdout: '{}', code: 0, stderr: '' };
185
+ const hookRoot = root ?? findRoot(input.cwd);
186
+ const cfg = loadConfig(hookRoot);
187
+ const git = (args) => runGit(hookRoot, args);
188
+ const ms = deadline ?? hookDeadline(name);
189
+ const result = await withDeadline(Promise.resolve().then(() => mod.handle(input, { root: hookRoot, cfg, env, git })), ms);
190
+ // Serialised here so a circular or BigInt result is a failure of this hook, not of the CLI; the
191
+ // shape check runs on what is written (a Date, a Map or a toJSON can make the two disagree).
192
+ const raw = kindOf(result);
193
+ if (raw !== 'object') return fail(`handler returned ${raw}`);
194
+ // Only a plain object: a Map serialises to {} and would read as an answer it never gave.
195
+ const proto = Object.getPrototypeOf(result);
196
+ if (proto !== Object.prototype && proto !== null) return fail(`handler returned a ${proto?.constructor?.name ?? 'non-plain object'}`);
197
+ const text = JSON.stringify(result);
198
+ if (typeof text !== 'string') return fail('handler result did not serialise');
199
+ const problem = shapeError(name, JSON.parse(text));
200
+ if (problem) return fail(problem);
201
+ return { stdout: text, code: 0, stderr: '' };
202
+ } catch (err) {
203
+ return fail(err?.message ?? String(err));
204
+ }
205
+ }
@@ -0,0 +1,82 @@
1
+ // Path and slice helpers the hooks share: pre-bash, pre-edit and session-start read paths and the
2
+ // active slice the same way.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { GitError, currentBranch } from '../git.js';
6
+ import { sliceFromBranch } from '../ids.js';
7
+ import { readSlice } from '../state/index.js';
8
+
9
+ export const toPosix = (p) => p.split(path.sep).join('/');
10
+
11
+ // The lines of a transcript's last `bytes` bytes, oldest first, without the cut first line when the
12
+ // read starts mid-file; null when file is not a regular file or cannot be read.
13
+ export function transcriptTail(file, bytes) {
14
+ let fd;
15
+ try {
16
+ fd = fs.openSync(file, 'r');
17
+ const st = fs.fstatSync(fd);
18
+ if (!st.isFile()) return null;
19
+ const start = Math.max(0, st.size - bytes);
20
+ const buf = Buffer.alloc(st.size - start);
21
+ fs.readSync(fd, buf, 0, buf.length, start);
22
+ const lines = buf.toString('utf8').split('\n');
23
+ if (start > 0) lines.shift();
24
+ return lines;
25
+ } catch {
26
+ return null;
27
+ } finally {
28
+ if (fd !== undefined) fs.closeSync(fd);
29
+ }
30
+ }
31
+
32
+ // Git Bash's `/c/...` spelling of a Windows path as `C:/...`; unchanged off win32.
33
+ export function fromGitBash(p) {
34
+ if (process.platform !== 'win32') return p;
35
+ const m = /^\/([A-Za-z])(\/.*)?$/.exec(p);
36
+ return m ? `${m[1].toUpperCase()}:/${(m[2] ?? '').slice(1)}` : p;
37
+ }
38
+
39
+ // The deepest existing ancestor of abs (abs itself when it exists).
40
+ export function existingAncestor(abs) {
41
+ let dir = abs;
42
+ while (!fs.existsSync(dir)) {
43
+ const parent = path.dirname(dir);
44
+ if (parent === dir) break;
45
+ dir = parent;
46
+ }
47
+ return dir;
48
+ }
49
+
50
+ // p with its deepest existing ancestor replaced by that ancestor's real path and the missing segments
51
+ // re-appended, so 8.3 short names and links resolve.
52
+ export function real(p) {
53
+ const existing = existingAncestor(p);
54
+ let resolved = existing;
55
+ try {
56
+ resolved = fs.realpathSync.native(existing);
57
+ } catch {
58
+ // keep the path as given
59
+ }
60
+ const rest = path.relative(existing, p);
61
+ return rest === '' ? resolved : path.join(resolved, rest);
62
+ }
63
+
64
+ // The slice the branch at root names: {id, state}, or {id, error} when its state file cannot be read,
65
+ // or null when the branch is not a slice branch, has no state file, or root is not a repository.
66
+ export function activeSlice(root, cfg) {
67
+ let branch;
68
+ try {
69
+ branch = currentBranch(root);
70
+ } catch (e) {
71
+ if (e instanceof GitError) return null;
72
+ throw e;
73
+ }
74
+ const id = branch ? sliceFromBranch(branch) : null;
75
+ if (!id) return null;
76
+ try {
77
+ return { id, state: readSlice(root, cfg, id) };
78
+ } catch (e) {
79
+ if (/^unknown slice /.test(e?.message ?? '')) return null;
80
+ return { id, error: e?.message ?? String(e) };
81
+ }
82
+ }