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
package/src/init.js ADDED
@@ -0,0 +1,276 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { CONFIG_PATH, ConfigError, defaultConfig, loadConfig, validateConfig } from './config.js';
5
+ import { exists, listFiles, readText, writeText } from './fs.js';
6
+ import { currentBranch, git, GitError, hasCommits, isRepo } from './git.js';
7
+ import { GITHOOKS, HOOKS_PATH, hooksPathValue, isInstalledHooksPath } from './githooks.js';
8
+ import { probeCli } from './hook-cli.js';
9
+ import { kitPaths } from './paths.js';
10
+ import { kitVersion, renderAll } from './render/index.js';
11
+ import { readSettings } from './render/settings.js';
12
+ import { WORKFLOW_DRIFT, WORKFLOW_PATH, workflowState } from './workflow.js';
13
+
14
+ const TEMPLATES_DIR = fileURLToPath(new URL('../templates/docs/', import.meta.url));
15
+ const GITHOOKS_DIR = fileURLToPath(new URL('../templates/githooks/', import.meta.url));
16
+ // Each ignore rule init owns, with every spelling of it that already counts as present. Missing rules
17
+ // are appended at the end, so the journal un-ignores come after any `*.log` rule and win (later rules
18
+ // win in git): journal files are committed, their locks are not.
19
+ const IGNORE_RULES = [
20
+ { rule: '.slicekit/graph/', forms: new Set(['.slicekit/graph/', '/.slicekit/graph/', '.slicekit/graph', '/.slicekit/graph']) },
21
+ { rule: '.slicekit/.subagent-*', forms: new Set(['.slicekit/.subagent-*', '/.slicekit/.subagent-*']) },
22
+ { rule: '!.slicekit/journal/', forms: new Set(['!.slicekit/journal/', '!/.slicekit/journal/']) },
23
+ { rule: '!.slicekit/journal/*.log', forms: new Set(['!.slicekit/journal/*.log', '!/.slicekit/journal/*.log']) },
24
+ { rule: '.slicekit/journal/*.lock', forms: new Set(['.slicekit/journal/*.lock', '/.slicekit/journal/*.lock']) },
25
+ // Slice worktrees (REQ-2.6 step 1) live under the root and are never part of the checkout.
26
+ { rule: '.worktrees/', forms: new Set(['.worktrees/', '/.worktrees/', '.worktrees', '/.worktrees']) },
27
+ ];
28
+ // Hooks checked out with CRLF break sh (REQ-3.9).
29
+ // Intake snapshots (S-10) are stored byte for byte, so git must not convert their line endings. The
30
+ // pattern comes from kitPaths as S-10 builds it, so `./docs` and `docs` write the same line.
31
+ function attributeRules(root, cfg) {
32
+ const intakeDir = path.relative(root, kitPaths(root, cfg).intake).split(path.sep).join('/');
33
+ const intake = `${intakeDir}/** -text`;
34
+ return [
35
+ { rule: '.githooks/* text eol=lf', forms: new Set(['.githooks/* text eol=lf', '/.githooks/* text eol=lf']) },
36
+ { rule: intake, forms: new Set([intake, `/${intake}`]) },
37
+ ];
38
+ }
39
+ const NOT_A_REPO = 'not a git repository';
40
+ const UNBORN_PROTECTED = 'commit this scaffold with ALLOW_PROTECTED_COMMIT=1 git commit …, or start on a slice branch';
41
+
42
+ // Each template file maps to a kitPaths destination; nothing else names a destination.
43
+ const TEMPLATE_DEST = {
44
+ 'BUILD.md': (p) => p.build,
45
+ 'decisions.md': (p) => p.decisions,
46
+ 'platform.md': (p) => p.platform,
47
+ 'observability.md': (p) => p.observability,
48
+ 'runbook.md': (p) => p.runbook,
49
+ 'spec/00-overview.md': (p) => path.join(p.spec, '00-overview.md'),
50
+ 'spec/gaps.md': (p) => p.gaps,
51
+ 'spec/stack.md': (p) => p.stack,
52
+ 'intake/.keep': (p) => path.join(p.intake, '.keep'),
53
+ 'spec/contracts/.keep': (p) => path.join(p.contracts, '.keep'),
54
+ 'phases/.keep': (p) => path.join(p.phases, '.keep'),
55
+ 'releases/.keep': (p) => path.join(p.releases, '.keep'),
56
+ };
57
+
58
+ function render(text, vars) {
59
+ return text.replace(/\{\{(name|docsRoot|date)\}\}/g, (_, key) => vars[key]);
60
+ }
61
+
62
+ function plan(cfg, paths) {
63
+ const vars = { name: cfg.name, docsRoot: cfg.docsRoot, date: new Date().toISOString().slice(0, 10) };
64
+ const files = new Map();
65
+ for (const rel of listFiles(TEMPLATES_DIR)) {
66
+ const dest = TEMPLATE_DEST[rel];
67
+ if (!dest) throw new Error(`init: template ${rel} has no destination in kitPaths`);
68
+ files.set(dest(paths), render(readText(path.join(TEMPLATES_DIR, rel)), vars));
69
+ }
70
+ files.set(paths.config, `${JSON.stringify(cfg, null, 2)}\n`);
71
+ files.set(path.join(paths.baselines, 'references.json'), '{}\n');
72
+ files.set(path.join(paths.baselines, 'style.json'), '{}\n');
73
+ files.set(path.join(paths.state, '.keep'), '');
74
+ files.set(path.join(paths.githooks, '.keep'), '');
75
+ return files;
76
+ }
77
+
78
+ // Each rule is added once, when no accepted spelling of it is already a line of the file (spacing
79
+ // inside a line does not matter). Appended lines take the file's own line ending.
80
+ function ensureLines(file, rules) {
81
+ if (!exists(file)) {
82
+ writeText(file, rules.map(({ rule }) => `${rule}\n`).join(''));
83
+ return 'created';
84
+ }
85
+ const raw = fs.readFileSync(file, 'utf8');
86
+ const squash = (line) => line.trim().replace(/\s+/g, ' ');
87
+ const present = new Set(raw.split(/\r?\n/).map(squash));
88
+ const missing = rules.filter(({ forms }) => ![...forms].some((f) => present.has(squash(f))));
89
+ if (missing.length === 0) return 'skipped';
90
+ const eol = raw.includes('\r\n') ? '\r\n' : '\n';
91
+ const sep = raw === '' || raw.endsWith('\n') ? '' : eol;
92
+ fs.appendFileSync(file, `${sep}${missing.map(({ rule }) => `${rule}${eol}`).join('')}`);
93
+ return 'updated';
94
+ }
95
+
96
+ // The slicekit git hooks (REQ-3.9), LF and executable. One that exists with other content is the
97
+ // team's own hook: it is never overwritten, and the warning names it. Returns the files it created.
98
+ function installHooks(paths, rel, lists, warnings) {
99
+ const created = [];
100
+ for (const name of GITHOOKS) {
101
+ const abs = path.join(paths.githooks, name);
102
+ const content = readText(path.join(GITHOOKS_DIR, name));
103
+ if (!exists(abs)) {
104
+ writeText(abs, content);
105
+ fs.chmodSync(abs, 0o755);
106
+ lists.created.push(rel(abs));
107
+ created.push(rel(abs));
108
+ continue;
109
+ }
110
+ lists.skipped.push(rel(abs));
111
+ if (readText(abs) !== content) warnings.push(`${rel(abs)} differs from the slicekit hook; left as is`);
112
+ }
113
+ return created;
114
+ }
115
+
116
+ // A new file is staged 100644 on win32, where there is no mode bit; staging the hooks init created
117
+ // with +x makes the team's first commit record them executable. In an empty repository this creates
118
+ // the index; it is never a commit (D-19).
119
+ function stageHooks(root, files, warnings) {
120
+ if (files.length === 0) return;
121
+ try {
122
+ git(root, ['add', '--chmod=+x', '--', ...files]);
123
+ } catch (e) {
124
+ if (!(e instanceof GitError)) throw e;
125
+ warnings.push(`could not stage ${files.join(', ')} as executable: ${e.stderr}`);
126
+ }
127
+ }
128
+
129
+ // The pre-commit hook init just installed refuses the first commit of a repository whose HEAD is
130
+ // unborn on a protected branch: the line that says how to make it, or null.
131
+ function firstCommitHint(root, cfg) {
132
+ if (hasCommits(root)) return null;
133
+ let branch;
134
+ try {
135
+ branch = currentBranch(root);
136
+ } catch (e) {
137
+ if (e instanceof GitError) return null;
138
+ throw e;
139
+ }
140
+ return branch !== null && cfg.protectedBranches.includes(branch) ? UNBORN_PROTECTED : null;
141
+ }
142
+
143
+ // Points core.hooksPath at .githooks, unless it already names something else: that is left alone
144
+ // and reported. Hooks in .git/hooks stop running once the path is set, so they are named first.
145
+ function setHooksPath(root, warnings) {
146
+ const current = hooksPathValue(root);
147
+ if (isInstalledHooksPath(root, current)) return;
148
+ if (current !== null) {
149
+ warnings.push(`core.hooksPath is ${current}; left as is, so the slicekit git hooks in ${HOOKS_PATH}/ do not run`);
150
+ return;
151
+ }
152
+ const dir = path.join(git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir']), 'hooks');
153
+ const live = exists(dir)
154
+ ? fs
155
+ .readdirSync(dir, { withFileTypes: true })
156
+ .filter((e) => e.isFile() && !e.name.endsWith('.sample'))
157
+ .map((e) => `.git/hooks/${e.name}`)
158
+ .sort()
159
+ : [];
160
+ if (live.length > 0) {
161
+ warnings.push(`${live.join(', ')} stop running once core.hooksPath is set to ${HOOKS_PATH}; move them into ${HOOKS_PATH}/ to keep them`);
162
+ }
163
+ git(root, ['config', 'core.hooksPath', HOOKS_PATH]);
164
+ }
165
+
166
+ // An existing config.json is the truth: a flag may repeat its shape, docsRoot or cli, never change them.
167
+ // A new config takes cli from --cli, else from the probe (D-30); the probe's warning comes back with it.
168
+ // One exception: a config with no cli key at all (an example project ships one, so that it names no
169
+ // one's install) takes cli from --cli, else from the probe, and is written back with it.
170
+ function resolveConfig(root, { name, shape, docsRoot, commands, cli, env }) {
171
+ const file = path.join(root, CONFIG_PATH);
172
+ if (exists(file)) {
173
+ const raw = configWithoutCli(file);
174
+ let probed = null;
175
+ if (raw) {
176
+ probed = cli === undefined ? probeCli(root, { env }) : { cli, warning: null };
177
+ raw.cli = probed.cli;
178
+ }
179
+ const cfg = raw ?? loadConfig(root);
180
+ for (const [field, value] of [['shape', shape], ['docsRoot', docsRoot], ['cli', cli]]) {
181
+ if (value !== undefined && value !== cfg[field]) {
182
+ throw new ConfigError([`config.json already sets ${field} = ${cfg[field]}; remove the flag or edit the config`]);
183
+ }
184
+ }
185
+ if (!raw) return { cfg, cliWarning: null, cliFilled: false };
186
+ const errors = validateConfig(raw);
187
+ if (errors.length > 0) throw new ConfigError(errors);
188
+ writeText(file, `${JSON.stringify(raw, null, 2)}\n`);
189
+ return { cfg: loadConfig(root), cliWarning: probed.warning, cliFilled: true };
190
+ }
191
+ const probed = cli === undefined ? probeCli(root, { env }) : { cli, warning: null };
192
+ const cfg = defaultConfig({
193
+ name,
194
+ shape,
195
+ docsRoot: docsRoot ?? 'docs',
196
+ commands,
197
+ cli: probed.cli,
198
+ });
199
+ const errors = validateConfig(cfg);
200
+ if (errors.length > 0) throw new ConfigError(errors);
201
+ return { cfg, cliWarning: probed.warning, cliFilled: false };
202
+ }
203
+
204
+ // The parsed config when it is a JSON object with no cli key; null otherwise (loadConfig then reads,
205
+ // and reports, the file as it is).
206
+ function configWithoutCli(file) {
207
+ let raw;
208
+ try {
209
+ raw = JSON.parse(readText(file).replace(/^/, ''));
210
+ } catch {
211
+ return null;
212
+ }
213
+ return raw !== null && typeof raw === 'object' && !Array.isArray(raw) && !Object.hasOwn(raw, 'cli') ? raw : null;
214
+ }
215
+
216
+ // M4: a cli with no path separator that is not `node <file>` is looked up on PATH, and a CI runner
217
+ // has no global slicekit, so the workflow init writes could not run it.
218
+ export function bareCliWarning(cli) {
219
+ if (/[\\/]/.test(cli) || /^node\s/.test(cli)) return null;
220
+ return `cli is "${cli}", a bare command, and CI has no global install, so ${WORKFLOW_PATH} cannot run it; set cli in .slicekit/config.json to a repository path or add an install step`;
221
+ }
222
+
223
+ export function init(root, { name, shape, docsRoot, commands = {}, cli, env = process.env }) {
224
+ const { cfg, cliWarning, cliFilled } = resolveConfig(root, { name, shape, docsRoot, commands, cli, env });
225
+ readSettings(root); // a corrupt .claude/settings.json stops init before anything is written
226
+
227
+ const paths = kitPaths(root, cfg);
228
+ const rel = (abs) => path.relative(root, abs).split(path.sep).join('/');
229
+ const lists = { created: [], updated: cliFilled ? [rel(paths.config)] : [], skipped: [] };
230
+ for (const [abs, content] of plan(cfg, paths)) {
231
+ if (cliFilled && abs === paths.config) continue;
232
+ if (exists(abs)) {
233
+ lists.skipped.push(rel(abs));
234
+ } else {
235
+ writeText(abs, content);
236
+ lists.created.push(rel(abs));
237
+ }
238
+ }
239
+ lists[ensureLines(paths.gitignore, IGNORE_RULES)].push(rel(paths.gitignore));
240
+ const attributes = path.join(root, '.gitattributes');
241
+ lists[ensureLines(attributes, attributeRules(root, cfg))].push(rel(attributes));
242
+
243
+ const repo = isRepo(root);
244
+ const warnings = repo ? [] : [NOT_A_REPO];
245
+ if (cliWarning) warnings.push(cliWarning);
246
+ const hooks = installHooks(paths, rel, lists, warnings);
247
+ if (repo) {
248
+ stageHooks(root, hooks, warnings);
249
+ setHooksPath(root, warnings);
250
+ }
251
+ // The CI workflow (REQ-3.11): written when absent; an existing one is the team's and stays as is.
252
+ const workflow = workflowState(root, cfg);
253
+ if (workflow.current === null) {
254
+ writeText(workflow.file, workflow.expected);
255
+ lists.created.push(WORKFLOW_PATH);
256
+ const bare = bareCliWarning(cfg.cli);
257
+ if (bare) warnings.push(bare);
258
+ } else {
259
+ lists.skipped.push(WORKFLOW_PATH);
260
+ if (workflow.current !== workflow.expected) warnings.push(`${WORKFLOW_DRIFT}; left as is`);
261
+ }
262
+ for (const { dest, action, warning } of renderAll(root, cfg, { version: kitVersion() })) {
263
+ lists[action === 'unchanged' || action === 'skipped' ? 'skipped' : action].push(dest);
264
+ if (warning) warnings.push(warning);
265
+ }
266
+
267
+ return {
268
+ created: lists.created.sort(),
269
+ updated: lists.updated.sort(),
270
+ skipped: lists.skipped.sort(),
271
+ warnings,
272
+ cli: cfg.cli,
273
+ cliWarned: cliWarning !== null,
274
+ next: repo ? firstCommitHint(root, cfg) : null,
275
+ };
276
+ }
@@ -0,0 +1,235 @@
1
+ // The one home of every agent brief and every command procedure (REQ-2.12). A brief is the role's
2
+ // template followed by everything the agent needs inlined: the writing rules, the REQ blocks and
3
+ // decision rows the slice names, the slice file's summary, the team's commands, and last the slice's
4
+ // tasks. A procedure is a command's template with its arguments filled in.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { readDecisions } from './decisions.js';
9
+ import { exists, readText } from './fs.js';
10
+ import { GitError, currentBranch, isRepo } from './git.js';
11
+ import { ROLES } from './hooks/shapes.js';
12
+ import { parseSliceAddr, sliceFromBranch } from './ids.js';
13
+ import { frontMatter, headings, lines } from './markdown.js';
14
+ import { kitPaths } from './paths.js';
15
+ import { findSliceFiles } from './slicefile.js';
16
+ import { reqBlocks } from './stage.js';
17
+
18
+ export const PROCEDURES = ['intake', 'specify', 'gaps', 'plan', 'build', 'review', 'release', 'ops', 'audit'];
19
+ export const TEMPLATES = fileURLToPath(new URL('../templates/instructions', import.meta.url));
20
+
21
+ const KIT_SKILL = fileURLToPath(new URL('../templates/claude-code/skills/slicekit-writing/SKILL.md', import.meta.url));
22
+ const SKILL = path.join('.claude', 'skills', 'slicekit-writing', 'SKILL.md');
23
+ const TEAM_COMMANDS = ['test', 'lint', 'build', 'e2e'];
24
+ const SUMMARY_SECTIONS = ['Done when', 'Evaluation set', 'Expected changes'];
25
+
26
+ // code 1: refused (a template the kit does not ship yet); code 2: usage or an unknown name.
27
+ export class InstructionsError extends Error {
28
+ constructor(code, message) {
29
+ super(message);
30
+ this.name = 'InstructionsError';
31
+ this.code = code;
32
+ }
33
+ }
34
+
35
+ const posix = (p) => p.split(path.sep).join('/');
36
+ const fill = (text, values) => text.replace(/\{\{(cli|args)\}\}/g, (m, k) => (k in values ? values[k] : m));
37
+ const asList = (v) => (Array.isArray(v) ? v : v === undefined || v === null || v === '' ? [] : [String(v)]);
38
+
39
+ // The slice a brief is for: `arg` when it is a slice address, else the one the current branch names;
40
+ // null outside a repository or off a slice branch.
41
+ export function briefSlice(root, arg) {
42
+ if (arg !== undefined && arg !== null) {
43
+ if (!parseSliceAddr(arg)) throw new InstructionsError(2, `not a slice address: ${arg}`);
44
+ return arg;
45
+ }
46
+ if (!isRepo(root)) return null;
47
+ try {
48
+ const branch = currentBranch(root);
49
+ return branch ? sliceFromBranch(branch) : null;
50
+ } catch (e) {
51
+ if (e instanceof GitError) return null;
52
+ throw e;
53
+ }
54
+ }
55
+
56
+ // Every heading outside a fenced block `by` levels lower (at most level 6), so inlined text sits under
57
+ // the brief's own `##` sections. Every other line is kept as it is.
58
+ export function demote(text, by = 1) {
59
+ let inFence = false;
60
+ return text
61
+ .split('\n')
62
+ .map((l) => {
63
+ if (/^\s*(```|~~~)/.test(l)) {
64
+ inFence = !inFence;
65
+ return l;
66
+ }
67
+ if (inFence) return l;
68
+ const m = /^(#{1,6})(\s.*)$/.exec(l);
69
+ return m ? '#'.repeat(Math.min(6, m[1].length + by)) + m[2] : l;
70
+ })
71
+ .join('\n');
72
+ }
73
+
74
+ // The slice file whose front matter names `id`, as {data, body}; null when none does.
75
+ function sliceFile(root, cfg, id) {
76
+ for (const f of findSliceFiles(root, cfg)) {
77
+ const { data, body } = frontMatter(readText(f.path));
78
+ if (String(data.slice ?? '') === id) return { data, body };
79
+ }
80
+ return null;
81
+ }
82
+
83
+ // The level-2 sections of a slice file's body: lower-case title -> {title, text after the heading}.
84
+ function sliceSections(body) {
85
+ const all = lines(body);
86
+ const hs = headings(body).filter((h) => h.level === 2);
87
+ return new Map(
88
+ hs.map((h, i) => {
89
+ const end = i + 1 < hs.length ? hs[i + 1].line - 1 : all.length;
90
+ return [h.text.toLowerCase(), { title: h.text, text: all.slice(h.line, end).join('\n').trim() }];
91
+ }),
92
+ );
93
+ }
94
+
95
+ // The front matter as a list, then Done when, Evaluation set and Expected changes, their headings one
96
+ // level lower. The Tasks section goes last in the brief, on its own.
97
+ function sliceSummary(slice) {
98
+ const parts = [Object.entries(slice.data).map(([k, v]) => `- ${k}: ${Array.isArray(v) ? v.join(', ') : v}`).join('\n')];
99
+ const sections = sliceSections(slice.body);
100
+ for (const title of SUMMARY_SECTIONS) {
101
+ const sec = sections.get(title.toLowerCase());
102
+ if (sec) parts.push(demote(`## ${sec.title}\n\n${sec.text}`.trim()));
103
+ }
104
+ return parts.filter((p) => p !== '').join('\n\n');
105
+ }
106
+
107
+ function requirements(root, cfg, ids) {
108
+ if (ids.length === 0) return 'The slice names no requirement.';
109
+ const blocks = reqBlocks(root, cfg);
110
+ const specDir = `${posix(cfg.docsRoot).replace(/\/$/, '')}/spec/`;
111
+ return ids
112
+ .map((id) => {
113
+ const b = blocks.find((x) => x.id === id);
114
+ if (!b) return `${id}: not found under ${specDir}`;
115
+ const heading = lines(readText(path.join(root, b.file)))[b.line - 1];
116
+ return demote(`${heading}\n${b.block}`.trimEnd());
117
+ })
118
+ .join('\n\n');
119
+ }
120
+
121
+ function decisions(root, cfg, ids) {
122
+ if (ids.length === 0) return 'The slice names no decision.';
123
+ const file = kitPaths(root, cfg).decisions;
124
+ const rows = exists(file) ? readDecisions(readText(file)).rows : [];
125
+ return ids
126
+ .map((id) => {
127
+ const m = /^D-(\d+)$/.exec(id);
128
+ const row = m ? rows.find((r) => r.n === Number(m[1])) : undefined;
129
+ if (!row) return `- ${id}: not found in decisions.md`;
130
+ const answer = row.table === 'settled' ? row.answer : `open; recommendation: ${row.recommendation || 'none'}`;
131
+ return `- ${row.id} (${row.type}): ${row.question} → ${answer}`;
132
+ })
133
+ .join('\n');
134
+ }
135
+
136
+ const stripFrontMatter = (text) => text.replace(/^?---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/, '');
137
+
138
+ // The project's rendered writing rules, else the kit's, without front matter or the leading level-1
139
+ // title (`# Writing rules` in the kit's), the other headings one level lower.
140
+ function writingRules(root) {
141
+ for (const file of [path.join(root, SKILL), KIT_SKILL]) {
142
+ let text;
143
+ try {
144
+ text = fs.readFileSync(file, 'utf8');
145
+ } catch {
146
+ continue;
147
+ }
148
+ return demote(stripFrontMatter(text).replace(/\r\n/g, '\n').replace(/^\s*# [^\n]*(?:\n|$)/, '').trim());
149
+ }
150
+ return '';
151
+ }
152
+
153
+ function template(file, what) {
154
+ try {
155
+ return fs.readFileSync(file, 'utf8').replace(/\r\n/g, '\n');
156
+ } catch (e) {
157
+ if (e.code === 'ENOENT') throw new InstructionsError(1, what);
158
+ throw e;
159
+ }
160
+ }
161
+
162
+ // Refuses a role that is not one of the six, and the designer outside a fullstack project.
163
+ export function checkRole(cfg, role) {
164
+ if (!ROLES.has(role)) throw new InstructionsError(2, `unknown role '${role}'; one of ${[...ROLES].join(', ')}`);
165
+ if (role === 'designer' && cfg.shape !== 'fullstack') throw new InstructionsError(2, `designer is not installed for shape ${cfg.shape}`);
166
+ }
167
+
168
+ // The slice file of `sliceId` (null: none) and the role's template with `{{cli}}` filled in, after
169
+ // the role and the slice are checked.
170
+ function briefHead(root, cfg, role, sliceId, templatesDir, fromBranch) {
171
+ checkRole(cfg, role);
172
+ const slice = sliceId ? sliceFile(root, cfg, sliceId) : null;
173
+ if (sliceId && !slice && !fromBranch) throw new InstructionsError(2, `unknown slice ${sliceId}`);
174
+ const file = path.join(templatesDir, 'agents', `${role}.md`);
175
+ const head = fill(template(file, `the ${role} brief is not built in this version: ${posix(file)} is missing`), { cli: cfg.cli });
176
+ return { slice, head };
177
+ }
178
+
179
+ // The whole brief of `role` for `sliceId` (null: no active slice). The essentials come first and the
180
+ // slice's Tasks section last, so a reader that cuts the text from its end loses the least. With
181
+ // `worktree` it names where the agent works, so the brief is the agent's whole prompt (REQ-2.6 step 2).
182
+ // `fromBranch`: the id came from the branch, so a missing slice file is no active slice, not an error.
183
+ export function renderBrief(root, cfg, role, sliceId, { templatesDir = TEMPLATES, worktree, fromBranch = false } = {}) {
184
+ const { slice, head } = briefHead(root, cfg, role, sliceId, templatesDir, fromBranch);
185
+ const none = sliceId && !slice ? `No active slice. (branch names ${sliceId}, which has no slice file)` : 'No active slice.';
186
+ const parts = [head.trim(), `## Writing rules\n\n${writingRules(root)}`.trim()];
187
+ parts.push(`## Requirements\n\n${slice ? requirements(root, cfg, asList(slice.data.requirements)) : none}`);
188
+ parts.push(`## Decisions\n\n${slice ? decisions(root, cfg, asList(slice.data.decisions)) : none}`);
189
+ parts.push(slice ? `## Slice ${sliceId}\n\n${sliceSummary(slice)}` : `## Slice\n\n${none}`);
190
+ parts.push(`## Team commands\n\n${TEAM_COMMANDS.map((k) => `- ${k}: ${cfg.commands?.[k] || 'not declared'}`).join('\n')}`);
191
+ // The reviewer's verdict goes in the session root, where `build verdict` and the stop hook read it.
192
+ const verdictFile = role === 'reviewer' ? ' The one exception is the verdict file: write it at the absolute path the command gives you, in the session root.' : '';
193
+ if (worktree) parts.push(`## Where\n\nWork only under ${posix(path.resolve(root, worktree))}; use absolute paths.${verdictFile}`);
194
+ const tasks = slice ? sliceSections(slice.body).get('tasks') : undefined;
195
+ if (tasks) parts.push(`## Tasks\n\n${demote(tasks.text)}`.trim());
196
+ return parts.join('\n\n');
197
+ }
198
+
199
+ // The cap on a summary with the kit's writing rules, and on each of its two id lines: the hook that
200
+ // injects a summary has 8000 characters for it, its own copy of the rules and the no-git sentence.
201
+ export const SUMMARY_MAX = 6000;
202
+ const ID_LINE_MAX = 600;
203
+
204
+ // `<label>: a, b, c`, or as many ids as fit in ID_LINE_MAX followed by `, and <n> more`.
205
+ function idLine(label, ids) {
206
+ const full = `${label}: ${ids.length > 0 ? ids.join(', ') : 'none'}`;
207
+ if (full.length <= ID_LINE_MAX) return full;
208
+ const kept = [];
209
+ for (const id of ids) {
210
+ const next = `${label}: ${[...kept, id].join(', ')}, and ${ids.length - kept.length - 1} more`;
211
+ if (next.length > ID_LINE_MAX) break;
212
+ kept.push(id);
213
+ }
214
+ return `${label}: ${kept.join(', ')}, and ${ids.length - kept.length} more`;
215
+ }
216
+
217
+ // The short form of a brief, for the SubagentStart hook: the role template, the writing rules, the
218
+ // slice's REQ and D ids, and last the command that prints the full brief. The build procedure gives
219
+ // the developer the full brief in its prompt; every other agent reads it with that command.
220
+ export function renderSummary(root, cfg, role, sliceId, { templatesDir = TEMPLATES, fromBranch = false } = {}) {
221
+ const { slice, head } = briefHead(root, cfg, role, sliceId, templatesDir, fromBranch);
222
+ const ids = slice
223
+ ? [idLine('Requirements', asList(slice.data.requirements)), idLine('Decisions', asList(slice.data.decisions))]
224
+ : [sliceId ? `No active slice. (branch names ${sliceId}, which has no slice file)` : 'No active slice.'];
225
+ const full = `Full brief: ${cfg.cli} instructions ${role}${slice ? ` ${sliceId}` : ''}`;
226
+ const heading = `## Slice${slice ? ` ${sliceId}` : ''}`;
227
+ return [head.trim(), `## Writing rules\n\n${writingRules(root)}`.trim(), `${heading}\n\n${[...ids, full].join('\n')}`].join('\n\n');
228
+ }
229
+
230
+ // The procedure of `/slicekit <name>` with `{{cli}}` and `{{args}}` filled in.
231
+ export function renderProcedure(root, cfg, name, args, { templatesDir = TEMPLATES } = {}) {
232
+ if (!PROCEDURES.includes(name)) throw new InstructionsError(2, `unknown command '${name}'`);
233
+ const text = template(path.join(templatesDir, 'commands', `${name}.md`), `the /slicekit ${name} command is not built in this version`);
234
+ return fill(text, { cli: cfg.cli, args: args.length > 0 ? args.join(' ') : '(none)' });
235
+ }