slicekit 0.0.1 → 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 +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 +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/prbody.js ADDED
@@ -0,0 +1,266 @@
1
+ // The pull request body (02 REQ-2.10): one home for what the body must hold, read by the ci-body
2
+ // rule and by `slicekit pr open`, and the renderer and editors every command writes it through.
3
+ // A section is `**<name>:**` at the start of a line (indent allowed); its text is what follows the
4
+ // colon on that line, or the next non-blank line when that is not itself a required section or a
5
+ // heading. Anything inside a fenced code block (CommonMark fences) or an HTML comment is never a
6
+ // section or a heading, and a comment is never section text. A `[spec] ` / `[plan] ` title needs
7
+ // only the first three sections and no slice heading; a title with no slice id leaves the heading to
8
+ // ci-title. The configured filler list (style.banned) is matched over the body, one finding per
9
+ // phrase (REQ-3.10).
10
+ import { ID } from './ids.js';
11
+ import { EXEMPT_TITLE } from './check/ci-event.js';
12
+ import { titleSlice } from './check/rules/ci-title.js';
13
+ import { bannedPhrasesIn } from './check/rules/style.js';
14
+
15
+ export class PrBodyError extends Error {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = 'PrBodyError';
19
+ }
20
+ }
21
+
22
+ export const REQUIRED_SECTIONS = Object.freeze([
23
+ 'Done when',
24
+ 'Proof',
25
+ 'Decisions',
26
+ 'Runbook',
27
+ 'Infra / migration',
28
+ 'Try it',
29
+ 'Reviewer blocked',
30
+ 'Should-haves declined',
31
+ 'Skipped / not checked',
32
+ ]);
33
+ export const EXEMPT_SECTIONS = Object.freeze(REQUIRED_SECTIONS.slice(0, 3));
34
+
35
+ const SECTION = /^\s*\*\*([^*\n]+?):\*\*(.*)$/;
36
+ const HEADING = new RegExp(`^## \\[(${ID.sliceAddr})\\] \\S`);
37
+ const ANY_HEADING = /^ {0,3}#{1,6}(\s|$)/;
38
+ // A CommonMark fence: up to three spaces, then three or more backticks or tildes.
39
+ const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;
40
+ const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})\s*$/;
41
+
42
+ // Each line as `{text, fenced}`. A fenced line (fence lines included) keeps its text and is never a
43
+ // section or a heading. Outside a fence, text inside `<!-- ... -->` (across lines too) is removed,
44
+ // so a line that is only a comment reads as blank. A leading byte order mark is dropped. Lines break
45
+ // at CRLF, CR or LF, the same breaks `segments` keeps.
46
+ function scan(body) {
47
+ let fence = null;
48
+ let comment = false;
49
+ const out = [];
50
+ for (const raw of body.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n').split('\n')) {
51
+ if (fence !== null) {
52
+ const m = FENCE_CLOSE.exec(raw);
53
+ if (m && m[1][0] === fence[0] && m[1].length >= fence.length) fence = null;
54
+ out.push({ text: raw, fenced: true });
55
+ continue;
56
+ }
57
+ if (!comment) {
58
+ const m = FENCE_OPEN.exec(raw);
59
+ if (m) {
60
+ fence = m[1];
61
+ out.push({ text: raw, fenced: true });
62
+ continue;
63
+ }
64
+ }
65
+ let text = '';
66
+ let rest = raw;
67
+ while (rest !== '') {
68
+ if (comment) {
69
+ const end = rest.indexOf('-->');
70
+ if (end === -1) rest = '';
71
+ else {
72
+ comment = false;
73
+ rest = rest.slice(end + 3);
74
+ }
75
+ } else {
76
+ const start = rest.indexOf('<!--');
77
+ if (start === -1) {
78
+ text += rest;
79
+ rest = '';
80
+ } else {
81
+ comment = true;
82
+ text += rest.slice(0, start);
83
+ rest = rest.slice(start + 4);
84
+ }
85
+ }
86
+ }
87
+ out.push({ text, fenced: false });
88
+ }
89
+ return out;
90
+ }
91
+
92
+ const sectionName = (line) => {
93
+ const m = !line.fenced && SECTION.exec(line.text);
94
+ return m ? m[1].trim() : null;
95
+ };
96
+
97
+ // Whether a line ends the text of a section that has none on its own line.
98
+ const ends = (line, required) => {
99
+ if (line.fenced) return false;
100
+ if (ANY_HEADING.test(line.text)) return true;
101
+ const name = sectionName(line);
102
+ return name !== null && required.includes(name);
103
+ };
104
+
105
+ // REQ-2.10's messages for a title and body, exactly as ci-body reports them.
106
+ export function prBodyProblems(title, body, cfg) {
107
+ const exempt = EXEMPT_TITLE.test(title);
108
+ const required = exempt ? EXEMPT_SECTIONS : REQUIRED_SECTIONS;
109
+ const lines = scan(body ?? '');
110
+ const out = [];
111
+
112
+ const slice = exempt ? null : titleSlice(title);
113
+ if (slice && !lines.some((l) => !l.fenced && HEADING.exec(l.text)?.[1] === slice)) {
114
+ out.push(`pull request body heading does not name ${slice}`);
115
+ }
116
+
117
+ // Every section line outside a fence, with whether text follows it.
118
+ const found = [];
119
+ lines.forEach((l, i) => {
120
+ const m = !l.fenced && SECTION.exec(l.text);
121
+ if (!m) return;
122
+ let filled = m[2].trim() !== '';
123
+ if (!filled) {
124
+ const next = lines.slice(i + 1).find((n) => n.text.trim() !== '');
125
+ filled = next !== undefined && !ends(next, required);
126
+ }
127
+ found.push({ name: m[1].trim(), filled });
128
+ });
129
+
130
+ const seen = new Set();
131
+ let furthest = -1;
132
+ for (const s of found) {
133
+ const rank = required.indexOf(s.name);
134
+ if (rank === -1) continue;
135
+ if (seen.has(s.name)) {
136
+ out.push(`pull request body has "${s.name}" twice`);
137
+ continue;
138
+ }
139
+ seen.add(s.name);
140
+ if (rank < furthest) out.push(`pull request body has "${s.name}" out of order`);
141
+ furthest = Math.max(furthest, rank);
142
+ if (!s.filled) out.push(`pull request body has an empty "${s.name}"`);
143
+ }
144
+ for (const name of required) if (!seen.has(name)) out.push(`pull request body is missing "${name}"`);
145
+ for (const p of bannedPhrasesIn(body ?? '', cfg?.style?.banned ?? [])) out.push(`pull request body uses banned phrase "${p}"`);
146
+ return out;
147
+ }
148
+
149
+ const blank = (text) => typeof text !== 'string' || text.trim() === '';
150
+
151
+ function assertSection(name, text) {
152
+ if (!REQUIRED_SECTIONS.includes(name)) throw new PrBodyError(`unknown section "${name}"`);
153
+ if (blank(text)) throw new PrBodyError(`section "${name}" is empty`);
154
+ }
155
+
156
+ const SLICE_ADDR = new RegExp(`^${ID.sliceAddr}$`);
157
+
158
+ // A section's line, and its continuation lines when the text has more than one. A text that opens
159
+ // with a fence starts on the line after the marker, since a fence only opens at the start of a line.
160
+ function sectionLines(name, text) {
161
+ const t = text.trim();
162
+ return FENCE_OPEN.test(t.split(/\r\n|\r|\n/)[0]) ? `**${name}:**\n${t}` : `**${name}:** ${t}`;
163
+ }
164
+
165
+ // A body with every section in order: `## [<slice>] <name>` first, or, with `slice: null` (a
166
+ // `[spec]` or `[plan]` pull request), no heading and only the first three sections. The result is
167
+ // judged as ci-body would judge it; a value that would make it fail (an unclosed fence or comment,
168
+ // a line that reads as another section) is refused naming the problem.
169
+ export function renderPrBody({ slice, name, sections }) {
170
+ if (slice !== null && (typeof slice !== 'string' || !SLICE_ADDR.test(slice))) {
171
+ throw new PrBodyError(`slice must be null or P<n>/S-<nn>, got ${JSON.stringify(slice)}`);
172
+ }
173
+ if (slice !== null && (typeof name !== 'string' || name.trim() === '')) {
174
+ throw new PrBodyError(`a slice body needs the slice's name, got ${JSON.stringify(name)}`);
175
+ }
176
+ const names = slice === null ? EXEMPT_SECTIONS : REQUIRED_SECTIONS;
177
+ const out = slice === null ? [] : [`## [${slice}] ${name}`];
178
+ for (const n of names) {
179
+ const text = sections?.[n];
180
+ assertSection(n, text);
181
+ out.push(sectionLines(n, text));
182
+ }
183
+ const body = `${out.join('\n')}\n`;
184
+ const problems = prBodyProblems(slice === null ? '[spec] body' : `[${slice}] ${name}`, body, {});
185
+ if (problems.length > 0) throw new PrBodyError(`the body would fail the CI body rule: ${problems.join('; ')}`);
186
+ return body;
187
+ }
188
+
189
+ // The body as lines with the break that follows each, so an edit keeps every other byte.
190
+ function segments(body) {
191
+ const parts = body.split(/(\r\n|\r|\n)/);
192
+ const out = [];
193
+ for (let i = 0; i < parts.length; i += 2) out.push({ raw: parts[i], sep: parts[i + 1] ?? '' });
194
+ return out;
195
+ }
196
+
197
+ // The section's line range [start, end) and its text, or null when the body has no such section.
198
+ // Its text is the rest of its line and the lines that follow up to a blank line outside a fence, a
199
+ // heading or another required section; when its own line has no text, blank lines before the text
200
+ // are skipped.
201
+ function locate(lines, name) {
202
+ const start = lines.findIndex((l) => sectionName(l) === name);
203
+ if (start === -1) return null;
204
+ const first = SECTION.exec(lines[start].text)[2].trim();
205
+ const text = first === '' ? [] : [first];
206
+ let end = start + 1;
207
+ if (first === '') {
208
+ let k = end;
209
+ while (k < lines.length && lines[k].text.trim() === '') k++;
210
+ if (k < lines.length && !ends(lines[k], REQUIRED_SECTIONS)) end = k;
211
+ }
212
+ // A fenced block is one piece of text, blank lines inside it included.
213
+ while (end < lines.length && (lines[end].fenced || (lines[end].text.trim() !== '' && !ends(lines[end], REQUIRED_SECTIONS)))) {
214
+ text.push(lines[end].text);
215
+ end++;
216
+ }
217
+ return { start, end, text: text.join('\n').trim() };
218
+ }
219
+
220
+ // The text of a section, or null when the body does not have it.
221
+ export function getSection(body, name) {
222
+ return locate(scan(body), name)?.text ?? null;
223
+ }
224
+
225
+ // Writes `**<name>:** <text>` in place of the section and its text, keeping every other byte. An
226
+ // absent section goes before the next required section the body has, else at the end. An edit that
227
+ // gives the body a problem it did not have (judged under the slice its heading names) is refused.
228
+ export function setSection(body, name, text) {
229
+ assertSection(name, text);
230
+ const out = writeSection(body, name, text);
231
+ const slice = scan(body).map((l) => !l.fenced && HEADING.exec(l.text)?.[1]).find(Boolean);
232
+ const title = slice ? `[${slice}] body` : 'body';
233
+ const before = prBodyProblems(title, body, {});
234
+ const added = prBodyProblems(title, out, {}).filter((p) => !before.includes(p));
235
+ if (added.length > 0) throw new PrBodyError(`the section would break the body: ${added.join('; ')}`);
236
+ return out;
237
+ }
238
+
239
+ function writeSection(body, name, text) {
240
+ const segs = segments(body);
241
+ const lines = scan(body);
242
+ const at = locate(lines, name);
243
+ const eol = segs.find((s) => s.sep !== '')?.sep ?? '\n';
244
+ const fresh = sectionLines(name, text).split(/\r\n|\r|\n/);
245
+ const bom = body.startsWith('\uFEFF') ? '\uFEFF' : '';
246
+ const join = (list) => list.map((s) => s.raw + s.sep).join('');
247
+ if (at) {
248
+ const sep = segs[at.end - 1].sep;
249
+ const keepBom = at.start === 0 ? bom : '';
250
+ const replaced = fresh.map((raw, i) => ({ raw: (i === 0 ? keepBom : '') + raw, sep: i === fresh.length - 1 ? sep : eol }));
251
+ return join([...segs.slice(0, at.start), ...replaced, ...segs.slice(at.end)]);
252
+ }
253
+ const later = REQUIRED_SECTIONS.slice(REQUIRED_SECTIONS.indexOf(name) + 1);
254
+ const before = lines.findIndex((l) => later.includes(sectionName(l)));
255
+ const inserted = fresh.map((raw) => ({ raw, sep: eol }));
256
+ if (before !== -1) {
257
+ if (before === 0 && bom) {
258
+ inserted[0].raw = bom + inserted[0].raw;
259
+ segs[0] = { ...segs[0], raw: segs[0].raw.slice(1) };
260
+ }
261
+ return join([...segs.slice(0, before), ...inserted, ...segs.slice(before)]);
262
+ }
263
+ if (body === '') return fresh.join(eol);
264
+ const tail = body.endsWith('\n') || body.endsWith('\r');
265
+ return tail ? `${body}${fresh.join(eol)}${eol}` : `${body}${eol}${fresh.join(eol)}`;
266
+ }
@@ -0,0 +1,107 @@
1
+ // The `ready` label decision (03 REQ-3.11, 02 REQ-2.8). Only verdicts that hold on the pull
2
+ // request's current head count (given on it, or on an earlier head followed only by bookkeeping
3
+ // commits, D-35): the latest of them must have no open blockers, and unless the config makes
4
+ // independent review optional, the latest independent one must have none either. The label is
5
+ // information; the merge button stays the human's.
6
+ import path from 'node:path';
7
+ import { GitError, assertRef, git } from './git.js';
8
+ import { verdictFilePattern } from './ids.js';
9
+ import { independentProblem, verdictsOnHead } from './state/transitions.js';
10
+ import { parseVerdict } from './verdict.js';
11
+
12
+ export const READY_LABEL = 'ready';
13
+ // What the label looks like when the CLI has to create it (I2): GitHub green, and who set it.
14
+ export const READY_LABEL_COLOR = '0e8a16';
15
+ export const READY_LABEL_DESCRIPTION = 'slicekit: reviewed and green';
16
+
17
+ // The states in which a pull request is open and under review.
18
+ const REVIEW_STATES = ['draft-pr', 'in-review', 'changes-requested', 'ci-green', 'ready'];
19
+
20
+ // The config file as git names it, whatever the platform's separator.
21
+ const CONFIG_GIT_PATH = '.slicekit/config.json';
22
+
23
+ // `review.independent` as `branch` holds it on origin, after a fetch: a pull request cannot switch
24
+ // off its own independent-review gate by editing the config on its branch or in a working tree.
25
+ // Anything that cannot be read (no origin, no such branch, no config, bad JSON) is `required`.
26
+ export function baseReviewMode(root, branch) {
27
+ try {
28
+ assertRef(branch);
29
+ } catch {
30
+ return 'required';
31
+ }
32
+ try {
33
+ git(root, ['fetch', '-q', 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`]);
34
+ } catch (e) {
35
+ if (!(e instanceof GitError)) throw e;
36
+ // Offline, or a CI checkout without credentials: judge on the last fetch.
37
+ }
38
+ try {
39
+ const cfg = JSON.parse(git(root, ['show', `refs/remotes/origin/${branch}:${CONFIG_GIT_PATH}`]));
40
+ return cfg?.review?.independent === 'optional' ? 'optional' : 'required';
41
+ } catch {
42
+ return 'required';
43
+ }
44
+ }
45
+
46
+ // `cfg` with `review.independent` taken from `branch` on origin (baseReviewMode).
47
+ export const withBaseReviewMode = (root, cfg, branch) => ({ ...cfg, review: { ...(cfg.review ?? {}), independent: baseReviewMode(root, branch) } });
48
+
49
+ // What a recorded verdict says against the file the commit that added it holds: the blocker count,
50
+ // the independent flag against the file's `i-r<k>` name and its own Independent line, and the round.
51
+ // A hand edit of the state file is caught here. -> null, or the reason.
52
+ export function verdictMismatch(root, id, v) {
53
+ const bad = (what) => `state does not match ${v.path}: ${what}`;
54
+ let text;
55
+ try {
56
+ const sha = git(root, ['--literal-pathspecs', 'log', '-1', '--format=%H', '--diff-filter=A', '--', v.path]);
57
+ if (sha === '') return bad('the file is not committed');
58
+ text = git(root, ['show', `${sha}:${v.path}`]);
59
+ } catch (e) {
60
+ if (e instanceof GitError) return bad('the file cannot be read');
61
+ throw e;
62
+ }
63
+ const file = parseVerdict(text, v.path);
64
+ const blockers = file.findings.filter((f) => f.kind === 'blocker').length;
65
+ if (blockers !== v.blockers) return bad(`the state records ${v.blockers} blockers, the file holds ${blockers}`);
66
+ const name = verdictFilePattern(id).exec(path.posix.basename(String(v.path)));
67
+ if (!name) return bad(`it is not a verdict file name of ${id}`);
68
+ const named = name[1] === 'i';
69
+ if (Boolean(v.independent) !== named) return bad(`the state records it as ${v.independent ? '' : 'not '}independent`);
70
+ if (file.independent && !v.independent) return bad('the file says Independent: yes');
71
+ if (Number(name[2]) !== v.round) return bad(`the state records round ${v.round}`);
72
+ return null;
73
+ }
74
+
75
+ // `headSha` is the live head from the CI event; without it, the head the state recorded. `number`
76
+ // is the event's pull request, which must be the one the state recorded. `root` is the repository
77
+ // to look for bookkeeping-only commits in, and to check the latest verdict and the latest
78
+ // independent verdict against their committed files; without it only the exact head counts and
79
+ // nothing is checked. `cfg.review.independent` is taken as given: callers pass the default
80
+ // branch's (withBaseReviewMode).
81
+ export function decideReady(state, cfg, opts = {}) {
82
+ if (!REVIEW_STATES.includes(state.state)) return { ready: false, reason: `the slice is ${state.state}, not under review` };
83
+ if ('number' in opts && state.pr?.number !== opts.number) {
84
+ return { ready: false, reason: `the state records pull request #${state.pr?.number ?? 'none'}, not #${opts.number ?? 'none'}` };
85
+ }
86
+ const verdicts = verdictsOnHead(state, opts.headSha ?? state.pr?.headSha, opts.root);
87
+ if (verdicts.length === 0) return { ready: false, reason: 'no review verdict on the current head' };
88
+ const latest = verdicts[verdicts.length - 1];
89
+ if (opts.root !== undefined) {
90
+ if (typeof state.slice !== 'string') return { ready: false, reason: 'the state names no slice' };
91
+ const ind = verdicts.filter((v) => v.independent).at(-1);
92
+ for (const v of ind && ind !== latest ? [latest, ind] : [latest]) {
93
+ const problem = verdictMismatch(opts.root, state.slice, v);
94
+ if (problem) return { ready: false, reason: problem };
95
+ }
96
+ }
97
+ if (latest.blockers !== 0) {
98
+ const n = latest.blockers;
99
+ return { ready: false, reason: `the latest verdict on the current head has ${n} open blocker${n === 1 ? '' : 's'}` };
100
+ }
101
+ // A config without a review section is held to the default: independent review required.
102
+ if (cfg.review?.independent !== 'optional') {
103
+ const problem = independentProblem(verdicts);
104
+ if (problem) return { ready: false, reason: problem };
105
+ }
106
+ return { ready: true, reason: 'the latest verdict on the current head has no open blockers' };
107
+ }
package/src/redact.js ADDED
@@ -0,0 +1,33 @@
1
+ // Masks secrets in a line of text with ***, so a command line can be stored in a committed file (the
2
+ // pre-compact handoff; later the journal). It masks known shapes only and is not a guarantee: a
3
+ // secret in an unknown shape passes through. Apply it before any cut, so a secret straddling the cut
4
+ // is masked whole.
5
+ const MASK = '***';
6
+
7
+ const RULES = [
8
+ // URL credentials: ://user:pass@ -> ://***@
9
+ [/:\/\/[^\s/@:]+:[^\s/@]+@/g, `://${MASK}@`],
10
+ // Token shapes.
11
+ [/\bgh[pousr]_[A-Za-z0-9]{20,}/g, MASK],
12
+ [/\bgithub_pat_[A-Za-z0-9_]{20,}/g, MASK],
13
+ [/\bsk-[A-Za-z0-9_-]{16,}/g, MASK],
14
+ [/\bAKIA[0-9A-Z]{16}\b/g, MASK],
15
+ [/\bxox[abpr]-[A-Za-z0-9-]+/g, MASK],
16
+ [/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, MASK],
17
+ // Authorization schemes.
18
+ [/\b(Bearer|Basic)\s+[^\s'"]+/gi, `$1 ${MASK}`],
19
+ // key=value.
20
+ [/\b(token|password|passwd|secret|api[_-]?key)=[^\s&'"]+/gi, `$1=${MASK}`],
21
+ // --flag=value and --flag value.
22
+ [/(--(?:password|token|secret))(=|\s+)[^\s'"]+/gi, `$1$2${MASK}`],
23
+ // -p<value> / -p <value> for the MySQL clients only (psql -p and mysql -P are ports). Case-sensitive.
24
+ [/(\b(?:mysql|mysqldump|mariadb)\b[^;&|\n]*?\s-p)(\s+[^\s'"]+|[^\s'"]+)/g,
25
+ (_m, head, value) => `${head}${/^\s/.test(value) ? `${value.match(/^\s+/)[0]}${MASK}` : MASK}`],
26
+ ];
27
+
28
+ export function redact(text) {
29
+ if (typeof text !== 'string') return '';
30
+ let out = text;
31
+ for (const [re, by] of RULES) out = out.replace(re, by);
32
+ return out;
33
+ }
@@ -0,0 +1,23 @@
1
+ import { extractManaged } from './managed.js';
2
+
3
+ // html and hash files keep the team's own text around the managed block, so only the block counts.
4
+ // frontmatter and json files are managed whole.
5
+ const BLOCK_STYLES = new Set(['html', 'hash']);
6
+
7
+ export function managedPart(text, style) {
8
+ if (!BLOCK_STYLES.has(style)) return text;
9
+ return extractManaged(text, style)?.block ?? null;
10
+ }
11
+
12
+ // 'missing' no file, 'unmanaged' a file with no slicekit marker, 'drifted' differs from what slicekit
13
+ // wrote (the reference copy, or with none the fresh render: an unprovable edit is kept, never overwritten),
14
+ // 'same' otherwise. With neither a reference nor a fresh render there is nothing to judge by: 'same'.
15
+ export function compareManaged({ current, reference, fresh, style }) {
16
+ if (current === null || current === undefined) return 'missing';
17
+ if (!extractManaged(current, style)) return 'unmanaged';
18
+ const basis = reference ?? fresh;
19
+ if (basis === null || basis === undefined) return 'same';
20
+ const was = managedPart(basis, style);
21
+ if (was === null) return 'same';
22
+ return managedPart(current, style) === was ? 'same' : 'drifted';
23
+ }
@@ -0,0 +1,101 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { exists, readText } from '../fs.js';
5
+ import { compareManaged } from './compare.js';
6
+ import { markerStyle, replaceManaged, wrapManaged } from './managed.js';
7
+ import { readSettings } from './settings.js';
8
+
9
+ export const TEMPLATES = fileURLToPath(new URL('../../templates/claude-code/', import.meta.url));
10
+ export const SETTINGS = '.claude/settings.json';
11
+ export const RENDERED = '.slicekit/rendered';
12
+ const VERSION_RE = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
13
+
14
+ const TEMPLATE_KEYS = ['version', 'name', 'docsRoot', 'cli'];
15
+
16
+ // {{key}} for each key in keys; any other {{…}} (and GitHub's ${{ … }}) is left as written.
17
+ export function substitute(text, vars, keys = TEMPLATE_KEYS) {
18
+ return text.replace(/\{\{([A-Za-z]+)\}\}/g, (whole, key) => (keys.includes(key) ? vars[key] : whole));
19
+ }
20
+
21
+ export const varsFor = (cfg, version) => ({ version, name: cfg.name, docsRoot: cfg.docsRoot, cli: cfg.cli });
22
+
23
+ // hooks.json parsed first, then {{…}} filled inside each string, so a quote or backslash in a value
24
+ // (a Windows path in cli) stays a string and never breaks the JSON.
25
+ export function loadHooks(templates, vars) {
26
+ const fill = (v) =>
27
+ typeof v === 'string'
28
+ ? substitute(v, vars)
29
+ : Array.isArray(v)
30
+ ? v.map(fill)
31
+ : v && typeof v === 'object'
32
+ ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, fill(x)]))
33
+ : v;
34
+ return fill(JSON.parse(readText(path.join(templates, 'hooks.json'))));
35
+ }
36
+
37
+ // Semver precedence: major.minor.patch numerically; a prerelease sorts before its release; prerelease
38
+ // identifiers compare numerically when numeric, numeric before alphanumeric, a shorter set first.
39
+ export function compareVersions(a, b) {
40
+ const split = (v) => {
41
+ const cut = v.indexOf('-');
42
+ const core = cut === -1 ? v : v.slice(0, cut);
43
+ return { core: core.split('.').map(Number), pre: cut === -1 ? null : v.slice(cut + 1).split('.') };
44
+ };
45
+ const x = split(a);
46
+ const y = split(b);
47
+ for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] - y.core[i];
48
+ if (x.pre === null || y.pre === null) return (x.pre === null) - (y.pre === null);
49
+ const num = /^\d+$/;
50
+ for (let i = 0; i < Math.max(x.pre.length, y.pre.length); i++) {
51
+ const p = x.pre[i];
52
+ const q = y.pre[i];
53
+ if (p === undefined) return -1;
54
+ if (q === undefined) return 1;
55
+ if (p === q) continue;
56
+ if (num.test(p) && num.test(q)) return Number(p) - Number(q);
57
+ if (num.test(p)) return -1;
58
+ if (num.test(q)) return 1;
59
+ return p < q ? -1 : 1;
60
+ }
61
+ return 0;
62
+ }
63
+
64
+ // The version whose reference copies slicekit holds: the one settings.json records if its directory
65
+ // exists, else the newest directory by semver. It becomes a path segment, so only version-shaped names count.
66
+ export function installedVersion(renderedRoot, settings) {
67
+ if (!exists(renderedRoot)) return null;
68
+ const recorded = settings?._slicekit?.version;
69
+ if (typeof recorded === 'string' && VERSION_RE.test(recorded) && exists(path.join(renderedRoot, recorded))) return recorded;
70
+ const dirs = fs
71
+ .readdirSync(renderedRoot)
72
+ .filter((d) => VERSION_RE.test(d))
73
+ .sort(compareVersions);
74
+ return dirs.length > 0 ? dirs[dirs.length - 1] : null;
75
+ }
76
+
77
+ // The copy of dest that slicekit wrote last, or null when there is none.
78
+ export function loadReference(root, dest) {
79
+ const renderedRoot = path.join(root, RENDERED);
80
+ const installed = installedVersion(renderedRoot, readSettings(root));
81
+ const refFile = installed === null ? null : path.join(renderedRoot, installed, dest);
82
+ return refFile !== null && exists(refFile) ? readText(refFile) : null;
83
+ }
84
+
85
+ // The one place a manifest entry is rendered and judged; planUpdate and renderAll both come through here.
86
+ // next: the whole file as it would be written (null for an unmanaged file, which is never written).
87
+ export function renderEntry(root, cfg, { src, dest }, { version, templates = TEMPLATES }) {
88
+ const rendered = substitute(readText(path.join(templates, src)), varsFor(cfg, version));
89
+ const style = markerStyle(dest, rendered);
90
+ const fresh = wrapManaged(rendered, { version, style });
91
+ const file = path.join(root, dest);
92
+ const current = exists(file) ? readText(file) : null;
93
+ const reference = loadReference(root, dest);
94
+ const verdict = compareManaged({ current, reference, fresh, style });
95
+ let next = null;
96
+ if (verdict === 'missing') next = fresh;
97
+ else if (verdict !== 'unmanaged') {
98
+ next = style === 'json' || style === 'frontmatter' ? fresh : replaceManaged(current, fresh.split('\n').slice(1, -2).join('\n'), { version, style });
99
+ }
100
+ return { dest, style, fresh, current, reference, verdict, next };
101
+ }
@@ -0,0 +1,27 @@
1
+ import fs from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { entriesForShape } from './manifest.js';
4
+ import { TEMPLATES } from './entry.js';
5
+ import { applyUpdate, planUpdate } from './update.js';
6
+
7
+ export { installedVersion, loadReference, substitute, TEMPLATES, SETTINGS, RENDERED } from './entry.js';
8
+
9
+ const PACKAGE_JSON = fileURLToPath(new URL('../../package.json', import.meta.url));
10
+
11
+ export function kitVersion() {
12
+ return JSON.parse(fs.readFileSync(PACKAGE_JSON, 'utf8')).version;
13
+ }
14
+
15
+ // Plan, then apply with the rules slicekit update uses: a missing or changed file is written, a drifted
16
+ // one only with force. opts.entries and opts.templates render from another manifest; a template root
17
+ // without hooks.json renders files only (opts.settings: true forces the settings merge).
18
+ export function renderAll(root, cfg, { version, force = false, entries = entriesForShape(cfg.shape), templates = TEMPLATES, settings }) {
19
+ const plan = planUpdate(root, cfg, { version, entries, templates, settings });
20
+ const { written, skipped } = applyUpdate(root, cfg, plan, { version, force });
21
+ return plan.map(({ dest, status }) => {
22
+ const skip = skipped.find((s) => s.dest === dest);
23
+ if (skip) return { dest, action: 'skipped', warning: skip.warning };
24
+ if (!written.includes(dest)) return { dest, action: 'unchanged' };
25
+ return { dest, action: status === 'missing' ? 'created' : 'updated' };
26
+ });
27
+ }