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/verdict.js ADDED
@@ -0,0 +1,203 @@
1
+ // The reviewer's verdict file (REQ-2.11): parsed into a record, and checked for the shape problems
2
+ // that make a hook refuse the reviewer. The head SHA is not read from the file: the state layer
3
+ // stamps a verdict with the pull request head it holds when the verdict is recorded (REQ-1.8).
4
+ import { lines, prose, headings } from './markdown.js';
5
+
6
+ const VERDICT = /^Verdict: (BLOCK|CHANGES|APPROVE)\s*$/;
7
+ const ANY_VERDICT = /^\s*Verdict:/;
8
+ // The state layer's `--independent` flag decides independence (REQ-2.8), not this field alone.
9
+ const INDEPENDENT = /^\s*Independent:\s*yes\s*$/i;
10
+ const KINDS = { B: 'blocker', H: 'should-have' };
11
+ const ID_FORM = /^([BH])-([1-9]\d*)$/;
12
+ const ITEM = /^\s*(?:[-*+]|\d+[.)])\s+(.*\S)\s*$/;
13
+ const FENCE = /^\s*(```|~~~)/;
14
+ const NOT_VERIFIED = new Set(['', '-', 'n/a', 'none', 'tbd']);
15
+ const COLUMNS = { file: 'file:line', wrong: 'what is wrong', why: 'why it matters', verified: 'how verified' };
16
+ const NAMED = { wrong: 'What is wrong', why: 'Why it matters' };
17
+
18
+ // A row split on pipes that are neither escaped (`\|`, read as `|`) nor inside a code span. An
19
+ // unclosed backtick opens no code span. Returns null for a line with no separating pipe.
20
+ function split(line, codeSpans = true) {
21
+ const s = line.trim();
22
+ const parts = [];
23
+ let cell = '';
24
+ let inCode = false;
25
+ let endsOnPipe = false;
26
+ for (let i = 0; i < s.length; i++) {
27
+ const ch = s[i];
28
+ endsOnPipe = false;
29
+ if (ch === '\\' && s[i + 1] === '|') {
30
+ cell += '|';
31
+ i++;
32
+ } else if (ch === '`' && codeSpans) {
33
+ inCode = !inCode;
34
+ cell += ch;
35
+ } else if (ch === '|' && !inCode) {
36
+ parts.push(cell);
37
+ cell = '';
38
+ endsOnPipe = true;
39
+ } else {
40
+ cell += ch;
41
+ }
42
+ }
43
+ if (inCode) return split(line, false);
44
+ parts.push(cell);
45
+ if (parts.length < 2) return null;
46
+ if (s.startsWith('|')) parts.shift();
47
+ if (endsOnPipe) parts.pop();
48
+ return parts.map((c) => c.trim());
49
+ }
50
+
51
+ const isDivider = (cells) => cells !== null && cells.length > 0 && cells.every((c) => /^:?-+:?$/.test(c));
52
+
53
+ function fileLine(cell) {
54
+ const s = cell === '-' ? '' : cell;
55
+ if (s === '') return { file: null, line: null, lineEnd: null };
56
+ const m = /^(.*\S):(\d+)(?:-(\d+))?$/.exec(s);
57
+ if (!m) return { file: s, line: null, lineEnd: null };
58
+ return { file: m[1], line: Number(m[2]), lineEnd: m[3] === undefined ? null : Number(m[3]) };
59
+ }
60
+
61
+ // Every table whose header's first cell is `ID`, in document order. A fence line ends a table and
62
+ // nothing inside a fence is read. Columns are found by name, so an extra or reordered one still reads.
63
+ function findingsTables(all) {
64
+ const fenced = [];
65
+ let inFence = false;
66
+ for (const l of all) {
67
+ if (FENCE.test(l)) {
68
+ inFence = !inFence;
69
+ fenced.push(true);
70
+ } else {
71
+ fenced.push(inFence);
72
+ }
73
+ }
74
+ const out = [];
75
+ for (let i = 0; i < all.length - 1; i++) {
76
+ if (fenced[i] || fenced[i + 1]) continue;
77
+ const header = split(all[i]);
78
+ if (!header || !isDivider(split(all[i + 1]))) continue;
79
+ const names = header.map((c) => c.toLowerCase());
80
+ const at = Object.fromEntries(Object.entries(COLUMNS).map(([k, name]) => [k, names.indexOf(name)]));
81
+ const rows = [];
82
+ let j = i + 2;
83
+ for (; j < all.length && !fenced[j]; j++) {
84
+ const row = split(all[j]);
85
+ if (!row) break;
86
+ rows.push(row);
87
+ }
88
+ if (names[0] === 'id') out.push({ width: header.length, at, rows });
89
+ i = j - 1;
90
+ }
91
+ return out;
92
+ }
93
+
94
+ function finding(row, t) {
95
+ const get = (k) => (t.at[k] === -1 ? '' : (row[t.at[k]] ?? ''));
96
+ const id = row[0];
97
+ const m = ID_FORM.exec(id);
98
+ const verified = get('verified');
99
+ return {
100
+ id,
101
+ kind: m ? KINDS[m[1]] : null,
102
+ ...fileLine(get('file')),
103
+ wrong: get('wrong'),
104
+ why: get('why'),
105
+ verified: NOT_VERIFIED.has(verified.toLowerCase()) ? '' : verified,
106
+ };
107
+ }
108
+
109
+ const sectionTitle = (text) => text.trim().replace(/:\s*$/, '').toLowerCase();
110
+
111
+ // The list items under a heading of level 2 or deeper with this title, up to the next heading of
112
+ // the same or a higher level, or a "Not checked" heading; null when there is no such heading.
113
+ function section(text, title) {
114
+ const hs = headings(text);
115
+ const h = hs.find((x) => x.level >= 2 && sectionTitle(x.text) === title);
116
+ if (!h) return null;
117
+ const end = hs.find((x) => x.line > h.line && (x.level <= h.level || sectionTitle(x.text) === 'not checked'));
118
+ const items = [];
119
+ for (const [line, n] of prose(text)) {
120
+ if (n <= h.line) continue;
121
+ if (end && n >= end.line) break;
122
+ const m = ITEM.exec(line);
123
+ if (m) items.push(m[1]);
124
+ }
125
+ return items;
126
+ }
127
+
128
+ const unreadable = (path) => ({
129
+ path,
130
+ verdict: null,
131
+ verdictLines: 0,
132
+ columns: [],
133
+ widths: [],
134
+ findings: [],
135
+ checklists: [],
136
+ notChecked: [],
137
+ hasNotChecked: false,
138
+ independent: false,
139
+ unreadable: true,
140
+ });
141
+
142
+ // Never throws: a Buffer is read as UTF-8, any other non-string gives a record whose only problem
143
+ // is "no verdict line".
144
+ export function parseVerdict(input, path) {
145
+ const text = Buffer.isBuffer(input) ? input.toString('utf8') : input;
146
+ if (typeof text !== 'string') return unreadable(path);
147
+ const all = lines(text);
148
+ const first = all.find((l) => l.trim() !== '');
149
+ const m = first === undefined ? null : VERDICT.exec(first);
150
+ const tables = findingsTables(all);
151
+ const columns = [];
152
+ for (const t of tables) {
153
+ for (const k of ['wrong', 'why']) if (t.at[k] === -1 && !columns.includes(NAMED[k])) columns.push(NAMED[k]);
154
+ }
155
+ const notChecked = section(text, 'not checked');
156
+ const proseLines = [...prose(text)].map(([l]) => l);
157
+ return {
158
+ path,
159
+ verdict: m ? m[1] : null,
160
+ verdictLines: proseLines.filter((l) => ANY_VERDICT.test(l)).length,
161
+ columns,
162
+ // Cells in each finding's row against its header, in finding order.
163
+ widths: tables.flatMap((t) => t.rows.map((r) => ({ cells: r.length, header: t.width }))),
164
+ findings: tables.flatMap((t) => t.rows.map((r) => finding(r, t))),
165
+ checklists: section(text, 'checklists run') ?? [],
166
+ notChecked: notChecked ?? [],
167
+ hasNotChecked: notChecked !== null,
168
+ independent: proseLines.some((l) => INDEPENDENT.test(l)),
169
+ };
170
+ }
171
+
172
+ // Every shape problem, in a stable order: the verdict line, the findings tables' columns, each
173
+ // finding in document order, the verdict against its findings, then the two lists. An empty array
174
+ // means the file is well formed.
175
+ export function verdictProblems(v) {
176
+ if (v.unreadable) return ['no verdict line'];
177
+ const out = [];
178
+ if (!v.verdict) out.push('no verdict line');
179
+ if (v.verdictLines > 1) out.push('more than one verdict line');
180
+ for (const c of v.columns) out.push(`findings table has no "${c}" column`);
181
+ const seen = new Set();
182
+ v.findings.forEach((f, i) => {
183
+ const name = f.id === '' ? '(no id)' : f.id;
184
+ if (!f.kind) out.push(`finding ${name} has an unknown id form`);
185
+ else if (seen.has(f.id)) out.push(`finding ${name} is listed twice`);
186
+ seen.add(f.id);
187
+ const w = v.widths[i];
188
+ if (w && w.cells > w.header) out.push(`finding ${name} has ${w.cells} cells, the header has ${w.header}`);
189
+ for (const k of ['wrong', 'why']) {
190
+ if (!v.columns.includes(NAMED[k]) && (f[k] === '' || f[k] === '-')) out.push(`finding ${name} has no "${NAMED[k]}"`);
191
+ }
192
+ if (f.verified.trim() === '') out.push(`finding ${name} has no "how verified"`);
193
+ });
194
+ const ids = (kind) => [...new Set(v.findings.filter((f) => f.kind === kind).map((f) => f.id))];
195
+ const blockers = ids('blocker');
196
+ if (v.verdict === 'BLOCK' && blockers.length === 0) out.push('verdict BLOCK with no open blocker');
197
+ if (v.verdict === 'APPROVE' && blockers.length > 0) out.push(`verdict APPROVE with open blocker ${blockers.join(', ')}`);
198
+ if (v.verdict === 'CHANGES' && blockers.length > 0) out.push(`verdict CHANGES with open blocker ${blockers.join(', ')}; use BLOCK`);
199
+ if (v.verdict === 'CHANGES' && ids('should-have').length === 0) out.push('verdict CHANGES with no should-have');
200
+ if (v.checklists.length === 0) out.push('no checklists listed');
201
+ if (!v.hasNotChecked) out.push('no "Not checked" section');
202
+ return out;
203
+ }
package/src/which.js ADDED
@@ -0,0 +1,37 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ // A file a shell could run: a regular file, executable on POSIX (win32 has no mode bit).
5
+ export function runnable(file) {
6
+ try {
7
+ if (!fs.statSync(file).isFile()) return false;
8
+ if (process.platform !== 'win32') fs.accessSync(file, fs.constants.X_OK);
9
+ return true;
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+
15
+ const envGet = (env, name) => {
16
+ const key = Object.keys(env).find((k) => k.toUpperCase() === name);
17
+ return key ? env[key] : undefined;
18
+ };
19
+
20
+ // Suffixes tried after a name: PATHEXT (default .COM;.EXE;.BAT;.CMD) plus the bare name on win32, none elsewhere.
21
+ export function extensions(env) {
22
+ if (process.platform !== 'win32') return [''];
23
+ return [...(envGet(env, 'PATHEXT') ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean), ''];
24
+ }
25
+
26
+ // The first runnable file for `name` in `extraDirs`, then every directory on env's PATH, with
27
+ // PATHEXT applied on win32 (and the bare name accepted). Returns its path or null. Never executes.
28
+ export function which(name, env, extraDirs = []) {
29
+ const dirs = [...extraDirs, ...(envGet(env, 'PATH') ?? '').split(path.delimiter).filter(Boolean)];
30
+ for (const dir of dirs) {
31
+ for (const ext of extensions(env)) {
32
+ const file = path.join(dir, `${name}${ext}`);
33
+ if (runnable(file)) return file;
34
+ }
35
+ }
36
+ return null;
37
+ }
@@ -0,0 +1,177 @@
1
+ // The GitHub Actions workflow init writes (REQ-3.11): a gate, a job per declared team command, a job
2
+ // per observability step (D-20), the ready label and the post-merge state sync (D-12). The YAML is
3
+ // generated as text; every free-text value goes through yamlScalar so a quote, colon or hash in a
4
+ // team's command cannot change the document's structure.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { DEFAULT_TIMEOUT_MINUTES, GITHUB_EXPRESSION, LINE_SEPARATOR } from './config.js';
9
+ import { readText } from './fs.js';
10
+ import { kitPaths } from './paths.js';
11
+ import { substitute } from './render/entry.js';
12
+
13
+ export const WORKFLOW_TEMPLATE = fileURLToPath(new URL('../templates/workflow/slicekit.yml', import.meta.url));
14
+ export const PINS_PATH = fileURLToPath(new URL('../templates/workflow/pins.json', import.meta.url));
15
+ // Where the workflow lands in a repository, relative to its root.
16
+ export const WORKFLOW_PATH = '.github/workflows/slicekit.yml';
17
+ export const WORKFLOW_DRIFT = `${WORKFLOW_PATH} differs from the generator; run slicekit workflow --write to regenerate it`;
18
+
19
+ const ACTIONS = { checkout: 'actions/checkout', setupNode: 'actions/setup-node', uploadArtifact: 'actions/upload-artifact' };
20
+ const COMMAND_ORDER = ['test', 'lint', 'build', 'e2e'];
21
+ const MATRIX_OS = ['ubuntu-latest', 'windows-latest', 'macos-latest'];
22
+ const SHA = /^[0-9a-f]{40}$/;
23
+ const TAG = /^v\d+\.\d+\.\d+$/;
24
+ const BLOCK_KEYS = ['gateExtraSteps', 'commandJobs', 'observabilityJobs'];
25
+ // Filled as written: values the kit computes or validates to a safe shape.
26
+ const VALUE_KEYS = [
27
+ 'defaultBranchItem', 'readyNeeds', 'syncPaths', 'timeoutMinutes',
28
+ ...Object.keys(ACTIONS).flatMap((k) => [`${k}Sha`, `${k}Tag`]),
29
+ ];
30
+ // The team's own text: a mapping value holding one is filled, then quoted as a whole.
31
+ const FREE_TEXT_KEYS = ['cli', 'defaultBranch'];
32
+
33
+ // REQ-5.3 for the kit's own repository: fails naming each non-empty field that installs a package
34
+ // with the kit (devDependencies are allowed) and its entries. `bundleDependencies: true` bundles all.
35
+ const DEPENDENCY_FIELDS = ['dependencies', 'optionalDependencies', 'bundleDependencies', 'bundledDependencies', 'peerDependencies'];
36
+ const NO_DEPENDENCIES = [
37
+ ' - name: No runtime dependencies (REQ-5.3)',
38
+ ' run: |',
39
+ ` node -e "const p = require('./package.json'); const bad = [${DEPENDENCY_FIELDS.map((f) => `'${f}'`).join(', ')}].flatMap((f) => { const v = p[f]; const n = v === true ? ['true'] : Array.isArray(v) ? v : Object.keys(v || {}); return n.length ? [f + ': ' + n.join(', ')] : []; }); if (bad.length) { console.error('package.json has runtime dependencies: ' + bad.join('; ')); process.exit(1) }"`,
40
+ ];
41
+
42
+ export function loadPins() {
43
+ return JSON.parse(fs.readFileSync(PINS_PATH, 'utf8'));
44
+ }
45
+
46
+ const RESERVED = /^(true|false|yes|no|on|off|null|~|y|n)$/i;
47
+
48
+ // One YAML scalar for value at a mapping key indented by indent spaces: plain when that is safe, a `|`
49
+ // block when it spans lines, otherwise single-quoted (a ' inside is doubled). A carriage return is a
50
+ // line break; the separators YAML also breaks on (U+0085, U+2028, U+2029) are refused.
51
+ export function yamlScalar(value, indent = 0) {
52
+ if (LINE_SEPARATOR.test(value)) throw new Error('yaml: value contains a line separator YAML cannot carry');
53
+ value = value.replace(/\r\n?/g, '\n');
54
+ if (value.includes('\n')) {
55
+ const lines = value.replace(/\n+$/, '').split('\n');
56
+ const pad = ' '.repeat(indent + 2);
57
+ // YAML takes the indentation from the first non-empty line, so a leading space there needs the indicator.
58
+ const first = lines.find((l) => l !== '') ?? '';
59
+ const indicator = first.startsWith(' ') ? '|2' : '|';
60
+ return [indicator, ...lines.map((l) => (l === '' ? '' : pad + l))].join('\n');
61
+ }
62
+ const unsafe =
63
+ value === '' ||
64
+ /[:#{}*\t]/.test(value) ||
65
+ value !== value.trim() ||
66
+ /^[-?,[\]&!|>'"%@`]/.test(value) ||
67
+ RESERVED.test(value) ||
68
+ /^[-+]?\.(inf|nan)$/i.test(value) ||
69
+ /^[-+]?\.?\d/.test(value);
70
+ return unsafe ? `'${value.replace(/'/g, "''")}'` : value;
71
+ }
72
+
73
+ function checkPins(pins) {
74
+ const vars = {};
75
+ for (const [key, action] of Object.entries(ACTIONS)) {
76
+ const pin = pins?.[action];
77
+ if (!pin || !SHA.test(pin.sha) || !TAG.test(pin.tag)) throw new Error(`pins: ${action} needs a 40-hex sha and a vX.Y.Z tag`);
78
+ vars[`${key}Sha`] = pin.sha;
79
+ vars[`${key}Tag`] = pin.tag;
80
+ }
81
+ return vars;
82
+ }
83
+
84
+ // Checkout (no token kept), Node 22 and npm ci (only when a lockfile exists): the head of every generated job.
85
+ function setupSteps(v) {
86
+ return [
87
+ ` - uses: actions/checkout@${v.checkoutSha} # ${v.checkoutTag}`,
88
+ ' with:',
89
+ ' persist-credentials: false',
90
+ ` - uses: actions/setup-node@${v.setupNodeSha} # ${v.setupNodeTag}`,
91
+ ' with:',
92
+ ' node-version: 22',
93
+ ' - name: Install',
94
+ " if: hashFiles('package-lock.json') != ''",
95
+ ' run: npm ci',
96
+ ];
97
+ }
98
+
99
+ function runStep(name, run, env) {
100
+ const lines = [` - name: ${yamlScalar(name, 8)}`];
101
+ const vars = Object.entries(env ?? {});
102
+ if (vars.length > 0) {
103
+ lines.push(' env:');
104
+ for (const [k, val] of vars) lines.push(` ${k}: ${yamlScalar(val, 10)}`);
105
+ }
106
+ lines.push(` run: ${yamlScalar(run, 8)}`);
107
+ return lines;
108
+ }
109
+
110
+ function commandJob(name, command, v, matrix, timeout) {
111
+ const head = matrix
112
+ ? [' strategy:', ' fail-fast: false', ' matrix:', ` os: [${MATRIX_OS.join(', ')}]`, ' runs-on: ${{ matrix.os }}']
113
+ : [' runs-on: ubuntu-latest'];
114
+ return ['', ` cmd-${name}:`, ...head, ` timeout-minutes: ${timeout}`, ' steps:', ...setupSteps(v), ...runStep(name, command)];
115
+ }
116
+
117
+ function observabilityJob(n, step, v, timeout) {
118
+ return ['', ` obs-${n}:`, ` name: ${yamlScalar(step.name, 4)}`, ' runs-on: ubuntu-latest', ` timeout-minutes: ${timeout}`, ' steps:', ...setupSteps(v), ...runStep(step.name, step.run, step.env)];
119
+ }
120
+
121
+ // One pass over the value, so text inside cli is never itself read as a placeholder.
122
+ function fillFreeText(line, vars) {
123
+ if (!FREE_TEXT_KEYS.some((k) => line.includes(`{{${k}}}`))) return line;
124
+ const m = /^(\s*(?:- )?[A-Za-z_-]+: )(.*)$/.exec(line);
125
+ if (!m) throw new Error(`workflow template: a free-text placeholder outside a mapping value: ${line}`);
126
+ return m[1] + yamlScalar(substitute(m[2], vars, FREE_TEXT_KEYS));
127
+ }
128
+
129
+ // What the sync commit may stage: BUILD.md and the state directory, as repository-relative paths.
130
+ function syncPaths(cfg) {
131
+ // Neither path depends on docsRoot; the default only keeps a partial config renderable.
132
+ const p = kitPaths('.', { docsRoot: 'docs', ...cfg });
133
+ return [p.build, p.state].map((f) => path.relative('.', f).split(path.sep).join('/')).join(' ');
134
+ }
135
+
136
+ export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileSync(WORKFLOW_TEMPLATE, 'utf8') } = {}) {
137
+ if (/[\r\n]/.test(cfg.cli)) throw new Error('cli: must be one line to render the workflow');
138
+ const v = checkPins(pins);
139
+ const matrix = cfg.ci?.matrix === true;
140
+ const timeout = cfg.ci?.timeoutMinutes ?? DEFAULT_TIMEOUT_MINUTES;
141
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 360) throw new Error('ci.timeoutMinutes: must be an integer from 1 to 360');
142
+ const commands = COMMAND_ORDER.filter((name) => typeof cfg.commands[name] === 'string' && cfg.commands[name].trim() !== '');
143
+ const steps = cfg.ci?.observabilitySteps ?? [];
144
+ const texts = [cfg.cli, ...commands.map((c) => cfg.commands[c]), ...steps.map((s) => s.run)];
145
+ if (texts.some((t) => GITHUB_EXPRESSION.test(t))) throw new Error('workflow: a command contains a GitHub expression; pass values through env:');
146
+ const blocks = {
147
+ gateExtraSteps: matrix ? NO_DEPENDENCIES : [],
148
+ commandJobs: commands.flatMap((name) => commandJob(name, cfg.commands[name], v, matrix && name === 'test', timeout)),
149
+ observabilityJobs: steps.flatMap((step, i) => observabilityJob(i + 1, step, v, timeout)),
150
+ };
151
+ const vars = {
152
+ ...v,
153
+ defaultBranchItem: yamlScalar(cfg.defaultBranch),
154
+ readyNeeds: ['gate', ...commands.map((c) => `cmd-${c}`), ...steps.map((_s, i) => `obs-${i + 1}`)].join(', '),
155
+ syncPaths: syncPaths(cfg),
156
+ timeoutMinutes: String(timeout),
157
+ };
158
+ const free = { cli: cfg.cli, defaultBranch: cfg.defaultBranch };
159
+ const out = [];
160
+ for (const line of template.replace(/\r\n/g, '\n').split('\n')) {
161
+ const block = /^\{\{([A-Za-z]+)\}\}$/.exec(line);
162
+ if (block && BLOCK_KEYS.includes(block[1])) {
163
+ out.push(...blocks[block[1]]);
164
+ continue;
165
+ }
166
+ out.push(fillFreeText(substitute(line, vars, VALUE_KEYS), free));
167
+ }
168
+ return out.join('\n');
169
+ }
170
+
171
+ // The rendered workflow and the repository's copy of it (null when absent), line endings normalised.
172
+ export function workflowState(root, cfg, pins = loadPins()) {
173
+ const expected = renderWorkflow(cfg, pins);
174
+ const file = path.join(root, WORKFLOW_PATH);
175
+ const current = fs.existsSync(file) ? readText(file) : null;
176
+ return { file, expected, current };
177
+ }
@@ -0,0 +1,68 @@
1
+ // Where a slice's worktrees are and how to know them: the build worktree `build start` makes and the
2
+ // review worktree `review start` makes (D-39). Pure path and branch rules plus git's own worktree
3
+ // list, shared by the build steps and the state transitions, so the rule that an independent verdict
4
+ // is recorded only in the review worktree holds whichever command records it.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { GitError, git } from './git.js';
8
+ import { parseSliceAddr } from './ids.js';
9
+
10
+ export const pad = (n) => String(n).padStart(2, '0');
11
+ export const branchPrefix = (addr) => `slice/P${addr.phase}-S-${pad(addr.slice)}`;
12
+ export const worktreeDir = (root, addr) => path.join(root, '.worktrees', `P${addr.phase}-S-${pad(addr.slice)}`);
13
+ // The review worktree `review start` makes, at a fixed path on a fixed branch: an independent verdict
14
+ // is recorded only there (D-39), so no build branch may take that name.
15
+ export const REVIEW_DESCR = 'review';
16
+ export const reviewBranch = (addr) => `${branchPrefix(addr)}-${REVIEW_DESCR}`;
17
+ export const reviewWorktreeDir = (root, addr) => path.join(root, '.worktrees', `review-P${addr.phase}-S-${pad(addr.slice)}`);
18
+
19
+ // One spelling of a path, so `C:/x` from git and `C:\x` from path.resolve compare equal.
20
+ export function samePath(a, b) {
21
+ const norm = (p) => {
22
+ let abs = path.resolve(p);
23
+ try {
24
+ abs = fs.realpathSync.native(abs);
25
+ } catch {
26
+ // A path that is gone is compared as written.
27
+ }
28
+ return process.platform === 'win32' ? abs.toLowerCase() : abs;
29
+ };
30
+ return norm(a) === norm(b);
31
+ }
32
+
33
+ // Every worktree of the repository as { path, branch }, the main one first; branch is null when
34
+ // HEAD is detached.
35
+ export function listWorktrees(root) {
36
+ const out = [];
37
+ let cur = null;
38
+ for (const line of git(root, ['worktree', 'list', '--porcelain']).split('\n')) {
39
+ if (line.startsWith('worktree ')) {
40
+ cur = { path: path.resolve(line.slice('worktree '.length)), branch: null };
41
+ out.push(cur);
42
+ } else if (cur && line.startsWith('branch refs/heads/')) {
43
+ cur.branch = line.slice('branch refs/heads/'.length);
44
+ }
45
+ }
46
+ return out;
47
+ }
48
+
49
+ // Whether `dir` is the review worktree of slice `id`: at review start's path under the main
50
+ // checkout (real paths compared, so a junction to it counts), on the review branch, and not the
51
+ // slice's build worktree. False outside a repository, or for a directory that is no worktree.
52
+ export function isReviewWorktreeAt(dir, id) {
53
+ const addr = parseSliceAddr(id);
54
+ if (!addr) return false;
55
+ let all;
56
+ let top;
57
+ try {
58
+ top = git(dir, ['rev-parse', '--show-toplevel']);
59
+ all = listWorktrees(dir);
60
+ } catch (e) {
61
+ if (e instanceof GitError) return false;
62
+ throw e;
63
+ }
64
+ const main = all[0]?.path;
65
+ const me = all.find((w) => samePath(w.path, top));
66
+ if (!main || !me) return false;
67
+ return me.branch === reviewBranch(addr) && samePath(me.path, reviewWorktreeDir(main, addr)) && !samePath(me.path, worktreeDir(main, addr));
68
+ }
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: auditor
3
+ description: Compares claims with evidence and writes a gaps file or audit report with a citation on both sides.
4
+ tools: Read, Grep, Glob, Write, Bash
5
+ model: inherit
6
+ ---
7
+ Brief: run `{{cli}} instructions auditor` and follow it. You never run a git command that commits, pushes or moves a branch; report and the command commits. End every reply with "Skipped:" and "Not checked:" lines.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: designer
3
+ description: Gives a verdict on a screen against the team's design rules; writes no code.
4
+ tools: Read, Grep, Glob, Write, Bash
5
+ model: inherit
6
+ ---
7
+ Brief: run `{{cli}} instructions designer` and follow it. You never run a git command that commits, pushes or moves a branch; report and the command commits. End every reply with "Skipped:" and "Not checked:" lines.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: developer
3
+ description: Writes the slice's tests, then the code that passes them, in the worktree.
4
+ tools: Read, Grep, Glob, Edit, Write, Bash
5
+ model: inherit
6
+ ---
7
+ Brief: run `{{cli}} instructions developer` and follow it. You never run a git command that commits, pushes or moves a branch; report and the command commits. End every reply with "Skipped:" and "Not checked:" lines.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: fixer
3
+ description: Changes code to answer named review findings and nothing else.
4
+ tools: Read, Grep, Glob, Edit, Write, Bash
5
+ model: inherit
6
+ ---
7
+ Brief: run `{{cli}} instructions fixer` and follow it. You never run a git command that commits, pushes or moves a branch; report and the command commits. End every reply with "Skipped:" and "Not checked:" lines.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: ops
3
+ description: Reads the runbook and history for a symptom and writes a proposed-actions report; changes nothing.
4
+ tools: Read, Grep, Glob, Write, Bash
5
+ model: inherit
6
+ ---
7
+ Brief: run `{{cli}} instructions ops` and follow it. You never run a git command that commits, pushes or moves a branch; report and the command commits. End every reply with "Skipped:" and "Not checked:" lines.
@@ -0,0 +1,7 @@
1
+ ---
2
+ name: reviewer
3
+ description: Reviews a slice and writes a verdict file; writes no code.
4
+ tools: Read, Grep, Glob, Write, Bash
5
+ model: inherit
6
+ ---
7
+ Brief: run `{{cli}} instructions reviewer` and follow it. You never run a git command that commits, pushes or moves a branch; report and the command commits. End every reply with "Skipped:" and "Not checked:" lines.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Check the spec and runbook claims against the code, tests and CI history.
3
+ argument-hint: "[area]"
4
+ ---
5
+ Run `{{cli}} instructions --command audit $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
6
+
7
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Build one slice through tests, code and review to a pull request ready for a human to merge.
3
+ argument-hint: "[P<n>/S-<nn>] [--parallel P<n>]"
4
+ ---
5
+ Run `{{cli}} instructions --command build $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
6
+
7
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,6 @@
1
+ ---
2
+ description: Audit the merged spec against intake and decisions, then close each gap with the human.
3
+ ---
4
+ Run `{{cli}} instructions --command gaps $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
5
+
6
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Snapshot a requirement document and interview the human, writing one decision row per answer.
3
+ argument-hint: "<file or URL>"
4
+ ---
5
+ Run `{{cli}} instructions --command intake $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
6
+
7
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Triage a symptom against the runbook and history, returning proposed actions.
3
+ argument-hint: "<symptom>"
4
+ ---
5
+ Run `{{cli}} instructions --command ops $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
6
+
7
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,6 @@
1
+ ---
2
+ description: Write the phases, slice files and BUILD.md, then open the plan pull request.
3
+ ---
4
+ Run `{{cli}} instructions --command plan $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
5
+
6
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Write the release record for a phase whose slices are all merged, and set each slice released.
3
+ argument-hint: "P<n>"
4
+ ---
5
+ Run `{{cli}} instructions --command release $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
6
+
7
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: Run an independent review of a pull request and fix the findings it raises.
3
+ argument-hint: "<PR>"
4
+ ---
5
+ Run `{{cli}} instructions --command review $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
6
+
7
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,6 @@
1
+ ---
2
+ description: Write the spec files from the intake snapshots and decisions, then open the spec pull request.
3
+ ---
4
+ Run `{{cli}} instructions --command specify $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
5
+
6
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.
@@ -0,0 +1,7 @@
1
+ ---
2
+ description: "Run a slicekit command: intake, specify, gaps, plan, build, review, release, ops or audit. /slicekit <command> [args]"
3
+ argument-hint: "<command> [args]"
4
+ ---
5
+ Run `{{cli}} instructions --command $ARGUMENTS` and follow the procedure it prints. The procedure is the only source of this command's rules.
6
+
7
+ Writing rules: `.claude/skills/slicekit-writing/SKILL.md`.