slicekit 0.0.0-stage → 0.1.1

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 +253 -2
  3. package/bin/slicekit.js +4 -0
  4. package/package.json +23 -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 +276 -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 +59 -0
  154. package/templates/githooks/pre-merge-commit +59 -0
  155. package/templates/githooks/prepare-commit-msg +74 -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
@@ -0,0 +1,103 @@
1
+ // The shape a subagent's final output must have, per role (REQ-3.5, REQ-2.11, REQ-2.12). subagent-stop
2
+ // blocks once on any problem named here. An empty array means the output is well formed.
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 { prose } from '../markdown.js';
8
+ import { parseVerdict, verdictProblems } from '../verdict.js';
9
+
10
+ export const ROLES = new Set(['developer', 'reviewer', 'fixer', 'auditor', 'ops', 'designer']);
11
+ export const REVIEW_WINDOW_MS = 30 * 60 * 1000;
12
+ export const NO_OUTPUT = 'no output to check';
13
+ export const NO_VERDICT = 'no verdict file in .slicekit/reviews/ from this run';
14
+
15
+ // Agents format replies: a checked label may follow a list marker (`- `, `4. `, `2) `) and open with
16
+ // bold or a backtick (`**Skipped:** x`, `` `ran: npm test → exit 0` ``). Fenced lines never count.
17
+ const LEAD = /^\s*(?:(?:[-*+]|\d+[.)])\s+)?(?:\*\*|`)?/.source;
18
+ const SKIPPED = new RegExp(`${LEAD}Skipped:`, 'm');
19
+ const NOT_CHECKED = new RegExp(`${LEAD}Not checked:`, 'm');
20
+ // Agents type ASCII: `->` stands for `→`. pre-compact reads the last such line from the transcript.
21
+ export const RAN = new RegExp(`${LEAD}ran:(?:\\*\\*)? .+ (?:→|->) exit \\d+`, 'm');
22
+ const FINDING_ID = /\b[BH]-[1-9]\d*\b/;
23
+
24
+ const VERDICT_NAME = /^(P\d+-S-\d+)[a-z]?-r\d+\.md$/;
25
+
26
+ // The slice the branch at root names, as a verdict file names it (`P1-S-07`); null when there is none.
27
+ function currentSlice(root) {
28
+ let branch;
29
+ try {
30
+ branch = currentBranch(root);
31
+ } catch (e) {
32
+ if (e instanceof GitError) return null;
33
+ throw e;
34
+ }
35
+ const id = branch ? sliceFromBranch(branch) : null;
36
+ return id ? id.replace('/', '-') : null;
37
+ }
38
+
39
+ // The newest regular file in <root>/.slicekit/reviews/ named like a verdict (`P<n>-S-<nn>-r<k>.md`) of
40
+ // the current slice, modified within the window, or null. With no current slice any verdict name counts.
41
+ function newestReview(root, now) {
42
+ const dir = path.join(root, '.slicekit', 'reviews');
43
+ let names;
44
+ try {
45
+ names = fs.readdirSync(dir);
46
+ } catch {
47
+ return null;
48
+ }
49
+ const slice = currentSlice(root);
50
+ let best = null;
51
+ for (const name of names) {
52
+ const m = VERDICT_NAME.exec(name);
53
+ if (!m || (slice !== null && m[1] !== slice)) continue;
54
+ let st;
55
+ try {
56
+ st = fs.statSync(path.join(dir, name));
57
+ } catch {
58
+ continue;
59
+ }
60
+ if (!st.isFile() || now - st.mtimeMs > REVIEW_WINDOW_MS) continue;
61
+ if (!best || st.mtimeMs > best.mtimeMs) best = { name, mtimeMs: st.mtimeMs };
62
+ }
63
+ return best && { file: path.join(dir, best.name), shown: `.slicekit/reviews/${best.name}` };
64
+ }
65
+
66
+ function reviewerProblems(root, now) {
67
+ const review = newestReview(root, now);
68
+ if (!review) return [NO_VERDICT];
69
+ let text;
70
+ try {
71
+ text = fs.readFileSync(review.file);
72
+ } catch (e) {
73
+ return [`verdict file ${review.shown} unreadable: ${e.code ?? e.message}`];
74
+ }
75
+ return verdictProblems(parseVerdict(text, review.shown)).map((p) => `verdict file ${review.shown}: ${p}`);
76
+ }
77
+
78
+ // -> string[]. `role` is one of ROLES; any other role has no shape and gives [].
79
+ export function shapeProblems(role, text, { root, now = Date.now() } = {}) {
80
+ if (!ROLES.has(role)) return [];
81
+ if (typeof text !== 'string' || text.trim() === '') return [NO_OUTPUT];
82
+ // Lines inside fenced code blocks are quoted material, not the agent's own report.
83
+ const own = [...prose(text)].map(([l]) => l).join('\n');
84
+ return reportProblems(role, own, root, now);
85
+ }
86
+
87
+ function reportProblems(role, text, root, now) {
88
+ const out = [];
89
+ if (!SKIPPED.test(text)) out.push('no "Skipped:" line');
90
+ if (!NOT_CHECKED.test(text)) out.push('no "Not checked:" line');
91
+ if (role === 'developer' && !RAN.test(text)) out.push('no "ran: <command> → exit <code>" line');
92
+ if (role === 'fixer' && !FINDING_ID.test(text)) out.push('no finding id (B-<n> or H-<n>) named');
93
+ if (role === 'reviewer') out.push(...reviewerProblems(root, now));
94
+ return out;
95
+ }
96
+
97
+ // Claude Code's `agent_type` mapped onto a kit role: the name after any `plugin:` prefix, any case;
98
+ // anything else is `other`.
99
+ export function roleOf(agentType) {
100
+ if (typeof agentType !== 'string') return 'other';
101
+ const name = agentType.trim().toLowerCase().split(':').pop();
102
+ return ROLES.has(name) ? name : 'other';
103
+ }
@@ -0,0 +1,37 @@
1
+ // stop (REQ-3.7): when the main session tries to stop, run the gate (`slicekit check`) and block the
2
+ // stop with the first ten failing finding lines when it is red. Fails closed through io.js.
3
+ //
4
+ // Claude Code's Stop carries session_id, transcript_path, cwd and stop_hook_active. A block makes
5
+ // Claude continue with the reason as its next instruction. stop_hook_active is true when Claude is
6
+ // already continuing because of a stop hook: the hook then allows, so the main session gets one push
7
+ // to fix the gate and, if it stops again still red, the human sees it. It never loops.
8
+ //
9
+ // The finding lines are check()'s own (`<rule> <file>:<line> <message>`, what `slicekit check`
10
+ // prints), less the summary line and the findings held at their baseline, which do not fail the gate.
11
+ // The reason keeps "\n" between lines: io.js passes a handler's reason through untouched and collapses
12
+ // newlines only in its own failure messages.
13
+ import { allow, block } from './io.js';
14
+ import { check } from '../check/index.js';
15
+
16
+ export const MAX_LINES = 10;
17
+
18
+ export async function handle(input, { root, env = process.env, runCheck = check }) {
19
+ if (input?.stop_hook_active === true) return allow();
20
+ let result;
21
+ try {
22
+ result = runCheck(root, { ci: false, env });
23
+ } catch (e) {
24
+ return block(`slicekit check could not run: ${e?.message ?? e}`);
25
+ }
26
+ if (result.exitCode === 0) return allow();
27
+ // check() pushes one line per finding, in order, then its summary line.
28
+ const lines = result.findings.map((f, i) => (f.baseline ? null : result.lines[i])).filter((l) => l !== null);
29
+ const shown = lines.slice(0, MAX_LINES);
30
+ const more = lines.length - shown.length;
31
+ return block([
32
+ 'slicekit check failed:',
33
+ ...shown,
34
+ ...(more > 0 ? [`…and ${more} more`] : []),
35
+ 'Fix them; do not raise a baseline.',
36
+ ].join('\n'));
37
+ }
@@ -0,0 +1,88 @@
1
+ // The subagent marker (REQ-2.1, REQ-3.4): the session's started-agents record, one sanitised agent_id
2
+ // per line. SubagentStart adds the agent (once: it fires on spawn and again on resume), SubagentStop
3
+ // drops it. pre-bash does not read it (it keys on the tool call's agent_id, S-07); subagent-stop acts
4
+ // only for an agent recorded here.
5
+ //
6
+ // Inside a git repository the files live in `<git-common-dir>/slicekit/`: every worktree of the
7
+ // repository shares the common directory, so an agent recorded from the main checkout is found from a
8
+ // linked worktree and the other way round. Outside a repository they live in `<root>/.slicekit/`, with
9
+ // a leading dot.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { GitError, git } from '../git.js';
13
+ import { real } from './paths.js';
14
+
15
+ const MAX_ID = 200;
16
+ const RETRY = { repo: 'retry-', local: '.retry-' };
17
+ const AGENTS = { repo: 'agents-', local: '.agents-' };
18
+
19
+ // -> {dir, kind}: where the files for root live, and whether that is the git common directory.
20
+ function markerHome(root) {
21
+ try {
22
+ const common = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
23
+ return { dir: path.join(real(path.resolve(common)), 'slicekit'), kind: 'repo' };
24
+ } catch (e) {
25
+ if (!(e instanceof GitError)) throw e;
26
+ return { dir: path.join(root, '.slicekit'), kind: 'local' };
27
+ }
28
+ }
29
+
30
+ const usable = (id) => typeof id === 'string' && id !== '' && id.length <= MAX_ID;
31
+
32
+ // Ids are mapped to [A-Za-z0-9_-] so a file can never land outside the marker directory.
33
+ const safe = (id) => id.replace(/[^A-Za-z0-9_-]/g, '_');
34
+ function check(id, what) {
35
+ if (!usable(id)) throw new Error(`subagent marker: ${what} must be a non-empty string of at most 200 characters`);
36
+ }
37
+
38
+ // subagent-stop's retry state for one agent of a session, next to the started-agents record:
39
+ // `retry-<session>-<agent>` in the git common directory, `.retry-<session>-<agent>` under .slicekit
40
+ // outside a repository.
41
+ export function retryPath(root, sessionId, agentId) {
42
+ check(sessionId, 'session id');
43
+ check(agentId, 'agent id');
44
+ const { dir, kind } = markerHome(root);
45
+ return path.join(dir, `${RETRY[kind]}${safe(sessionId)}-${safe(agentId)}`);
46
+ }
47
+
48
+ export const usableId = usable;
49
+
50
+ // The agents subagent-start recorded for a session: `agents-<session>` in the git common directory,
51
+ // `.agents-<session>` under .slicekit outside a repository. subagent-stop acts only for an agent
52
+ // recorded here: Claude Code also sends SubagentStop for its own internal agents, which never had a
53
+ // SubagentStart.
54
+ export function agentsPath(root, sessionId) {
55
+ check(sessionId, 'session id');
56
+ const { dir, kind } = markerHome(root);
57
+ return path.join(dir, `${AGENTS[kind]}${safe(sessionId)}`);
58
+ }
59
+
60
+ function readAgents(file) {
61
+ try {
62
+ return fs.readFileSync(file, 'utf8').split(/\r?\n/).filter((l) => l !== '');
63
+ } catch (e) {
64
+ if (e.code === 'ENOENT') return [];
65
+ throw e;
66
+ }
67
+ }
68
+
69
+ // Once per agent id: SubagentStart fires again when an agent resumes, and that adds nothing.
70
+ export function addAgent(root, sessionId, agentId) {
71
+ check(agentId, 'agent id');
72
+ const file = agentsPath(root, sessionId);
73
+ const ids = readAgents(file);
74
+ if (ids.includes(safe(agentId))) return;
75
+ fs.mkdirSync(path.dirname(file), { recursive: true });
76
+ fs.writeFileSync(file, `${[...ids, safe(agentId)].join('\n')}\n`);
77
+ }
78
+
79
+ export function hasAgent(root, sessionId, agentId) {
80
+ return usable(agentId) && readAgents(agentsPath(root, sessionId)).includes(safe(agentId));
81
+ }
82
+
83
+ export function removeAgent(root, sessionId, agentId) {
84
+ const file = agentsPath(root, sessionId);
85
+ const ids = readAgents(file).filter((id) => id !== safe(agentId));
86
+ if (ids.length === 0) fs.rmSync(file, { force: true });
87
+ else fs.writeFileSync(file, `${ids.join('\n')}\n`);
88
+ }
@@ -0,0 +1,100 @@
1
+ // subagent-start (REQ-3.4): records the agent in the session's started-agents record (once per agent:
2
+ // SubagentStart fires on spawn and again on resume), which subagent-stop checks, and injects its role
3
+ // brief in its short form, then the writing rules (once, though `slicekit instructions --summary` gives
4
+ // a text holding them) and
5
+ // the no-git rule. Fails open through io.js. pre-bash keeps git out of the subagent by the agent_id
6
+ // Claude Code puts on every tool call made inside it, not by the record.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { context } from './io.js';
11
+ import { toPosix } from './paths.js';
12
+ import { roleOf } from './shapes.js';
13
+ import { addAgent, usableId } from './subagent-marker.js';
14
+
15
+ export { roleOf };
16
+ export const BRIEF_MAX = 8000;
17
+ export const NO_GIT = 'You never run a git command that commits, pushes or moves a branch; report and the command commits.';
18
+ const SKILL = path.join('.claude', 'skills', 'slicekit-writing', 'SKILL.md');
19
+ const KIT_SKILL = fileURLToPath(new URL('../../templates/claude-code/skills/slicekit-writing/SKILL.md', import.meta.url));
20
+
21
+ const stripFrontMatter = (text) => text.replace(/^?---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/, '');
22
+
23
+ // A file as the brief names it: relative to root when inside it, else absolute; forward slashes.
24
+ function shown(root, file) {
25
+ const rel = path.relative(path.resolve(root), file);
26
+ return toPosix(rel === '' || rel.startsWith('..') || path.isAbsolute(rel) ? file : rel);
27
+ }
28
+
29
+ // -> {text, file}: the writing rules as rendered in the project, else the kit's template; text '' when
30
+ // neither reads.
31
+ function writingRules(root) {
32
+ for (const file of [path.join(root, SKILL), KIT_SKILL]) {
33
+ try {
34
+ return { text: stripFrontMatter(fs.readFileSync(file, 'utf8')).replace(/\r\n/g, '\n').trim(), file: shown(root, file) };
35
+ } catch {
36
+ // try the next one
37
+ }
38
+ }
39
+ return { text: '', file: null };
40
+ }
41
+
42
+ // `slicekit instructions <role> --summary` when that command exists (S-09) and succeeds, else the P1
43
+ // placeholder. The summary is the role template, the writing rules, the slice's ids and the command
44
+ // that prints the full brief. -> {text, fromKit}: fromKit when the text came from the command, whose
45
+ // summary carries the writing rules under `## Writing rules`.
46
+ async function roleBrief(role, root, env, commands) {
47
+ const placeholder = { text: `Brief: role ${role}.`, fromKit: false };
48
+ const cmd = Object.hasOwn(commands, 'instructions') ? commands.instructions : undefined;
49
+ if (!cmd) return placeholder;
50
+ let out = '';
51
+ try {
52
+ const code = await cmd.run([role, '--summary'], { cwd: root, env, stdout: (s) => { out += s; }, stderr: () => {}, stdin: async () => '' });
53
+ return code === 0 && out.trim() !== '' ? { text: out.trim(), fromKit: true } : placeholder;
54
+ } catch {
55
+ return placeholder;
56
+ }
57
+ }
58
+
59
+ async function cliCommands() {
60
+ return (await import('../cli/index.js')).COMMANDS;
61
+ }
62
+
63
+ // A brief from `slicekit instructions` without its `## Writing rules` section: the hook appends the
64
+ // rules itself, at the end, so they appear once and survive a cut.
65
+ function withoutRules(text) {
66
+ const out = [];
67
+ let inFence = false;
68
+ let skipping = false;
69
+ for (const l of text.split('\n')) {
70
+ if (/^\s*(```|~~~)/.test(l)) inFence = !inFence;
71
+ else if (!inFence && /^## /.test(l)) skipping = /^## Writing rules\s*$/.test(l);
72
+ if (!skipping) out.push(l);
73
+ }
74
+ return out.join('\n').trim();
75
+ }
76
+
77
+ // The brief, the rules and the no-git sentence in at most BRIEF_MAX characters, the rules and the
78
+ // sentence always last and whole. A brief that does not fit is cut from its end and followed by a
79
+ // line naming where the full text is. Only when the rules alone do not fit are they cut too.
80
+ function assemble(brief, rules, role, cli) {
81
+ const tail = `\n\n${NO_GIT}`;
82
+ const end = rules.text === '' ? tail : `\n\n${rules.text}${tail}`;
83
+ if (brief.length + end.length <= BRIEF_MAX) return brief + end;
84
+ const note = `\n(brief truncated; full text in ${cli} instructions ${role})`;
85
+ const room = BRIEF_MAX - end.length - note.length;
86
+ if (room >= 200) return brief.slice(0, room) + note + end;
87
+ const body = [brief, rules.text].filter((s) => s !== '').join('\n\n');
88
+ const where = brief.length + tail.length + 200 > BRIEF_MAX || !rules.file ? `${cli} instructions ${role}` : rules.file;
89
+ const cut = `\n(brief truncated; full text in ${where})`;
90
+ return body.slice(0, BRIEF_MAX - tail.length - cut.length) + cut + tail;
91
+ }
92
+
93
+ export async function handle(input, { root, cfg, env = process.env, commands }) {
94
+ // Only an agent that can be named at its stop is recorded: the stop hook acts for recorded agents.
95
+ if (usableId(input?.session_id) && usableId(input?.agent_id)) addAgent(root, input.session_id, input.agent_id);
96
+ const role = roleOf(input?.agent_type);
97
+ const brief = await roleBrief(role, root, env, commands ?? await cliCommands());
98
+ const text = brief.fromKit ? withoutRules(brief.text) : brief.text;
99
+ return context('SubagentStart', assemble(text, writingRules(root), role, cfg?.cli || 'slicekit'));
100
+ }
@@ -0,0 +1,106 @@
1
+ // subagent-stop (REQ-3.5, REQ-2.11, REQ-2.12): drops the agent from the session's started-agents record
2
+ // and blocks the subagent once when its final output lacks its role's shape (shapes.js). Fails closed
3
+ // through io.js.
4
+ //
5
+ // Claude Code's SubagentStop carries agent_id, agent_type, agent_transcript_path, last_assistant_message
6
+ // and stop_hook_active. After a block the subagent keeps running and its next stop arrives with
7
+ // stop_hook_active: true. SubagentStop also fires for Claude Code's internal agents, which never had a
8
+ // SubagentStart: the hook acts only for an agent_id subagent-start recorded, and answers {} otherwise.
9
+ //
10
+ // Retry state, per session and agent, sits next to that record (subagent-marker.js retryPath). It is read
11
+ // first:
12
+ // "stopped" -> the stop after the "stopping:" block: allow, delete, do not leave again
13
+ // "1" + problems -> leave, write "stopped", block "stopping: ..." (whatever stop_hook_active says)
14
+ // "1" + no problems -> allow, leave, delete
15
+ // no file + stop_hook_active -> allow, leave (another hook blocked this stop; the kit does not block twice)
16
+ // no file + problems -> write "1", block "output shape: ..." (the subagent goes on; still recorded)
17
+ // no problems or unknown role -> allow, leave, delete
18
+ // "Leave" drops the agent from the started-agents record, so a later stop for the same agent is ignored.
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { allow, block } from './io.js';
22
+ import { fromGitBash, transcriptTail } from './paths.js';
23
+ import { roleOf, shapeProblems, ROLES } from './shapes.js';
24
+ import { hasAgent, removeAgent, retryPath, usableId } from './subagent-marker.js';
25
+
26
+ export const TRANSCRIPT_TAIL = 256 * 1024;
27
+ const STOPPED = 'stopped';
28
+
29
+ function textOf(content) {
30
+ if (typeof content === 'string') return content;
31
+ if (!Array.isArray(content)) return '';
32
+ return content.filter((p) => p?.type === 'text' && typeof p.text === 'string').map((p) => p.text).join('\n');
33
+ }
34
+
35
+ // The last assistant text in the transcript's last TRANSCRIPT_TAIL bytes; '' when there is none.
36
+ export function lastAssistantText(file) {
37
+ const lines = transcriptTail(file, TRANSCRIPT_TAIL) ?? [];
38
+ for (let i = lines.length - 1; i >= 0; i--) {
39
+ let entry;
40
+ try {
41
+ entry = JSON.parse(lines[i]);
42
+ } catch {
43
+ continue;
44
+ }
45
+ if (entry?.message?.role !== 'assistant') continue;
46
+ const text = textOf(entry.message.content);
47
+ if (text.trim() !== '') return text;
48
+ }
49
+ return '';
50
+ }
51
+
52
+ // The subagent's final text: last_assistant_message, else its own transcript. transcript_path is the
53
+ // main session's transcript and is never read.
54
+ function outputOf(input) {
55
+ if (typeof input.last_assistant_message === 'string' && input.last_assistant_message.trim() !== '') {
56
+ return input.last_assistant_message;
57
+ }
58
+ const p = input.agent_transcript_path;
59
+ if (typeof p !== 'string' || p === '') return '';
60
+ return lastAssistantText(path.resolve(fromGitBash(p.replace(/\\/g, '/'))));
61
+ }
62
+
63
+ function readRetry(file) {
64
+ try {
65
+ return fs.readFileSync(file, 'utf8').trim();
66
+ } catch (e) {
67
+ if (e.code === 'ENOENT') return null;
68
+ throw e;
69
+ }
70
+ }
71
+
72
+ export async function handle(input, { root }) {
73
+ const session = input?.session_id;
74
+ const agent = input?.agent_id;
75
+ // Without both ids this cannot be an agent subagent-start recorded.
76
+ if (!usableId(session) || !usableId(agent)) return allow();
77
+ const retry = retryPath(root, session, agent);
78
+ const state = readRetry(retry);
79
+ if (state === STOPPED) {
80
+ fs.rmSync(retry, { force: true });
81
+ return allow();
82
+ }
83
+ if (!hasAgent(root, session, agent)) return allow();
84
+ const quit = () => removeAgent(root, session, agent);
85
+ const finish = () => {
86
+ fs.rmSync(retry, { force: true });
87
+ quit();
88
+ return allow();
89
+ };
90
+
91
+ const role = roleOf(input.agent_type);
92
+ if (!ROLES.has(role)) return finish();
93
+ if (state === null && input.stop_hook_active === true) return finish();
94
+ const problems = shapeProblems(role, outputOf(input), { root });
95
+ if (problems.length === 0) return finish();
96
+
97
+ const list = problems.join('; ');
98
+ if (state === null) {
99
+ fs.mkdirSync(path.dirname(retry), { recursive: true });
100
+ fs.writeFileSync(retry, '1\n');
101
+ return block(`output shape: ${list}. Add the missing parts and finish.`);
102
+ }
103
+ quit();
104
+ fs.writeFileSync(retry, `${STOPPED}\n`);
105
+ return block(`stopping: shape still wrong after retry: ${list}. End your report with the line: stopping: ${list}`);
106
+ }
package/src/ids.js ADDED
@@ -0,0 +1,43 @@
1
+ export const ID = {
2
+ req: 'REQ-\\d+\\.\\d+',
3
+ decision: 'D-\\d+',
4
+ gap: 'G-\\d+',
5
+ contract: 'C-\\d+',
6
+ phase: 'P\\d+',
7
+ slice: 'S-\\d{2}',
8
+ sliceAddr: 'P\\d+\\/S-\\d{2}',
9
+ };
10
+
11
+ // A fresh RegExp each call, so callers never share a stateful global regex.
12
+ export function re(name, flags = '') {
13
+ return new RegExp(ID[name], flags);
14
+ }
15
+
16
+ export function parseSliceAddr(addr) {
17
+ const m = /^P(\d+)\/S-(\d{2})$/.exec(addr);
18
+ return m ? { phase: Number(m[1]), slice: Number(m[2]), id: addr } : null;
19
+ }
20
+
21
+ export function sliceFromBranch(branch) {
22
+ const m = /^slice\/P(\d+)-S-(\d{2})(?:-|$)/.exec(branch);
23
+ return m ? `P${m[1]}/S-${m[2]}` : null;
24
+ }
25
+
26
+ export function stateFileName(addr) {
27
+ return `${addr.replace('/', '-')}.json`;
28
+ }
29
+
30
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
31
+ const verdictStem = (addr) => stateFileName(addr).replace(/\.json$/, '');
32
+
33
+ // A slice's verdict file name, `P<n>-S-<nn>[i]-r<k>.md`: `i` marks an independent review.
34
+ export function verdictFileName(addr, round, { independent = false } = {}) {
35
+ return `${verdictStem(addr)}${independent ? 'i' : ''}-r${round}.md`;
36
+ }
37
+
38
+ // The verdict file names of a slice: group 1 is the `i` (or ''), group 2 the round. With
39
+ // `independent` given, only names of that kind match; left out, both do.
40
+ export function verdictFilePattern(addr, { independent } = {}) {
41
+ const i = independent === undefined ? 'i?' : independent ? 'i' : '';
42
+ return new RegExp(`^${escapeRe(verdictStem(addr))}(${i})-r([1-9]\\d*)\\.md$`);
43
+ }