slicekit 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +253 -2
  3. package/bin/slicekit.js +4 -0
  4. package/package.json +23 -4
  5. package/src/adapters/githost/errors.js +17 -0
  6. package/src/adapters/githost/fixture.js +136 -0
  7. package/src/adapters/githost/gh-json.js +99 -0
  8. package/src/adapters/githost/github.js +127 -0
  9. package/src/adapters/githost/index.js +12 -0
  10. package/src/adapters/tracker/errors.js +53 -0
  11. package/src/adapters/tracker/fixture.js +71 -0
  12. package/src/adapters/tracker/github-issues.js +65 -0
  13. package/src/adapters/tracker/index.js +14 -0
  14. package/src/baseline.js +109 -0
  15. package/src/build/commit.js +201 -0
  16. package/src/build/decline.js +81 -0
  17. package/src/build/finish.js +155 -0
  18. package/src/build/order.js +158 -0
  19. package/src/build/overlap.js +173 -0
  20. package/src/build/parallel.js +50 -0
  21. package/src/build/pr.js +263 -0
  22. package/src/build/record.js +28 -0
  23. package/src/build/red.js +207 -0
  24. package/src/build/review.js +123 -0
  25. package/src/build/sync.js +47 -0
  26. package/src/build/verdict.js +410 -0
  27. package/src/build/worktree.js +169 -0
  28. package/src/check/ci-event.js +52 -0
  29. package/src/check/context.js +129 -0
  30. package/src/check/index.js +140 -0
  31. package/src/check/rules/.gitkeep +0 -0
  32. package/src/check/rules/ci-body.js +22 -0
  33. package/src/check/rules/ci-title.js +43 -0
  34. package/src/check/rules/citations.js +224 -0
  35. package/src/check/rules/commands.js +146 -0
  36. package/src/check/rules/coverage.js +248 -0
  37. package/src/check/rules/hooks.js +58 -0
  38. package/src/check/rules/journal.js +17 -0
  39. package/src/check/rules/layout.js +56 -0
  40. package/src/check/rules/managed.js +31 -0
  41. package/src/check/rules/queue.js +106 -0
  42. package/src/check/rules/references.js +249 -0
  43. package/src/check/rules/style.js +177 -0
  44. package/src/check/rules/trailer.js +67 -0
  45. package/src/cli/baseline.js +66 -0
  46. package/src/cli/branch.js +86 -0
  47. package/src/cli/build.js +239 -0
  48. package/src/cli/check.js +40 -0
  49. package/src/cli/decide.js +59 -0
  50. package/src/cli/gaps.js +73 -0
  51. package/src/cli/hook.js +28 -0
  52. package/src/cli/index.js +83 -0
  53. package/src/cli/init.js +96 -0
  54. package/src/cli/instructions.js +63 -0
  55. package/src/cli/intake.js +107 -0
  56. package/src/cli/journal.js +82 -0
  57. package/src/cli/plan.js +29 -0
  58. package/src/cli/pr.js +83 -0
  59. package/src/cli/process.js +59 -0
  60. package/src/cli/ready-label.js +119 -0
  61. package/src/cli/review.js +64 -0
  62. package/src/cli/spec.js +31 -0
  63. package/src/cli/stage.js +37 -0
  64. package/src/cli/state.js +106 -0
  65. package/src/cli/status.js +108 -0
  66. package/src/cli/update.js +62 -0
  67. package/src/cli/workflow.js +48 -0
  68. package/src/config.js +203 -0
  69. package/src/decisions.js +289 -0
  70. package/src/evidence.js +27 -0
  71. package/src/fs.js +38 -0
  72. package/src/gaps.js +271 -0
  73. package/src/git.js +209 -0
  74. package/src/githooks.js +37 -0
  75. package/src/hook-cli.js +63 -0
  76. package/src/hooks/io.js +205 -0
  77. package/src/hooks/paths.js +82 -0
  78. package/src/hooks/pre-bash.js +715 -0
  79. package/src/hooks/pre-compact.js +139 -0
  80. package/src/hooks/pre-edit.js +170 -0
  81. package/src/hooks/session-end.js +118 -0
  82. package/src/hooks/session-start.js +209 -0
  83. package/src/hooks/shapes.js +103 -0
  84. package/src/hooks/stop.js +37 -0
  85. package/src/hooks/subagent-marker.js +88 -0
  86. package/src/hooks/subagent-start.js +100 -0
  87. package/src/hooks/subagent-stop.js +106 -0
  88. package/src/ids.js +43 -0
  89. package/src/init.js +276 -0
  90. package/src/instructions.js +235 -0
  91. package/src/intake.js +409 -0
  92. package/src/journal.js +326 -0
  93. package/src/lock.js +35 -0
  94. package/src/markdown.js +155 -0
  95. package/src/paths.js +33 -0
  96. package/src/plan.js +25 -0
  97. package/src/pr.js +73 -0
  98. package/src/prbody.js +266 -0
  99. package/src/ready-label.js +107 -0
  100. package/src/redact.js +33 -0
  101. package/src/render/compare.js +23 -0
  102. package/src/render/entry.js +101 -0
  103. package/src/render/index.js +27 -0
  104. package/src/render/managed.js +128 -0
  105. package/src/render/manifest.js +24 -0
  106. package/src/render/settings.js +76 -0
  107. package/src/render/update.js +151 -0
  108. package/src/slicefile.js +173 -0
  109. package/src/spec-verify.js +58 -0
  110. package/src/stage.js +325 -0
  111. package/src/state/build.js +156 -0
  112. package/src/state/covers.js +58 -0
  113. package/src/state/index.js +191 -0
  114. package/src/state/sync.js +64 -0
  115. package/src/state/transitions.js +282 -0
  116. package/src/verdict.js +203 -0
  117. package/src/which.js +37 -0
  118. package/src/workflow.js +177 -0
  119. package/src/worktrees.js +68 -0
  120. package/templates/claude-code/agents/auditor.md +7 -0
  121. package/templates/claude-code/agents/designer.md +7 -0
  122. package/templates/claude-code/agents/developer.md +7 -0
  123. package/templates/claude-code/agents/fixer.md +7 -0
  124. package/templates/claude-code/agents/ops.md +7 -0
  125. package/templates/claude-code/agents/reviewer.md +7 -0
  126. package/templates/claude-code/commands/slicekit-audit.md +7 -0
  127. package/templates/claude-code/commands/slicekit-build.md +7 -0
  128. package/templates/claude-code/commands/slicekit-gaps.md +6 -0
  129. package/templates/claude-code/commands/slicekit-intake.md +7 -0
  130. package/templates/claude-code/commands/slicekit-ops.md +7 -0
  131. package/templates/claude-code/commands/slicekit-plan.md +6 -0
  132. package/templates/claude-code/commands/slicekit-release.md +7 -0
  133. package/templates/claude-code/commands/slicekit-review.md +7 -0
  134. package/templates/claude-code/commands/slicekit-specify.md +6 -0
  135. package/templates/claude-code/commands/slicekit.md +7 -0
  136. package/templates/claude-code/hooks.json +90 -0
  137. package/templates/claude-code/manifest.json +171 -0
  138. package/templates/claude-code/skills/slicekit-ids/SKILL.md +16 -0
  139. package/templates/claude-code/skills/slicekit-loop/SKILL.md +23 -0
  140. package/templates/claude-code/skills/slicekit-writing/SKILL.md +24 -0
  141. package/templates/docs/BUILD.md +5 -0
  142. package/templates/docs/decisions.md +15 -0
  143. package/templates/docs/intake/.keep +0 -0
  144. package/templates/docs/observability.md +25 -0
  145. package/templates/docs/phases/.keep +0 -0
  146. package/templates/docs/platform.md +25 -0
  147. package/templates/docs/releases/.keep +0 -0
  148. package/templates/docs/runbook.md +21 -0
  149. package/templates/docs/spec/00-overview.md +8 -0
  150. package/templates/docs/spec/contracts/.keep +0 -0
  151. package/templates/docs/spec/gaps.md +6 -0
  152. package/templates/docs/spec/stack.md +3 -0
  153. package/templates/githooks/pre-commit +59 -0
  154. package/templates/githooks/pre-merge-commit +59 -0
  155. package/templates/githooks/prepare-commit-msg +74 -0
  156. package/templates/instructions/agents/auditor.md +33 -0
  157. package/templates/instructions/agents/designer.md +21 -0
  158. package/templates/instructions/agents/developer.md +49 -0
  159. package/templates/instructions/agents/fixer.md +41 -0
  160. package/templates/instructions/agents/ops.md +21 -0
  161. package/templates/instructions/agents/reviewer.md +63 -0
  162. package/templates/instructions/commands/build.md +234 -0
  163. package/templates/instructions/commands/gaps.md +65 -0
  164. package/templates/instructions/commands/intake.md +90 -0
  165. package/templates/instructions/commands/plan.md +60 -0
  166. package/templates/instructions/commands/review.md +117 -0
  167. package/templates/instructions/commands/specify.md +49 -0
  168. package/templates/style.json +11 -0
  169. package/templates/workflow/pins.json +6 -0
  170. package/templates/workflow/slicekit.yml +110 -0
@@ -0,0 +1,249 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseSliceAddr, stateFileName } from '../../ids.js';
4
+ import { blankCodeSpans, frontMatter, headings, isPathLike, prose, refs, toSlashes } from '../../markdown.js';
5
+ import { findSliceFiles } from '../../slicefile.js';
6
+ import { readSlice } from '../../state/index.js';
7
+ import { MARKER as BUILD_MARKER } from '../../state/build.js';
8
+ import { intakeStatus } from '../context.js';
9
+
10
+ export const id = 'references';
11
+ export const blocking = true;
12
+ export const ratchet = true;
13
+
14
+ const EXAMPLE = '<!-- slicekit:example -->';
15
+ const DONE = new Set(['merged', 'released']);
16
+
17
+ // Which `ctx.ids` set an id belongs to, by its prefix.
18
+ const KIND = [
19
+ [/^REQ-/, 'req'],
20
+ [/^P\d+\/S-/, 'slice'],
21
+ [/^D-/, 'decision'],
22
+ [/^G-/, 'gap'],
23
+ [/^C-/, 'contract'],
24
+ ];
25
+
26
+ const decode = (s) => {
27
+ try {
28
+ return decodeURIComponent(s);
29
+ } catch {
30
+ return s;
31
+ }
32
+ };
33
+
34
+ // GitHub's heading anchor: lower-case, punctuation other than `-` and `_` dropped, each space a
35
+ // `-`; a repeated heading gains `-1`, `-2`.
36
+ export function slug(text) {
37
+ return text.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
38
+ }
39
+
40
+ function slugs(text) {
41
+ const seen = new Map();
42
+ const out = new Set();
43
+ for (const h of headings(text)) {
44
+ const base = slug(h.text);
45
+ const n = seen.get(base) ?? 0;
46
+ seen.set(base, n + 1);
47
+ out.add(n === 0 ? base : `${base}-${n}`);
48
+ }
49
+ return out;
50
+ }
51
+
52
+ // A slice's state: `todo` when it has no state file (planned or not), `problem` set when its state
53
+ // file exists but does not parse.
54
+ function sliceState(ctx, sliceId) {
55
+ try {
56
+ return { state: readSlice(ctx.root, ctx.cfg, sliceId).state };
57
+ } catch {
58
+ // readSlice throws for a present file only when it is not valid JSON; an absent one with no
59
+ // matching slice is `todo`.
60
+ const file = path.join(ctx.paths.state, stateFileName(sliceId));
61
+ if (fs.existsSync(file)) return { state: null, problem: `state file ${toSlashes(path.relative(ctx.root, file))} is not valid JSON` };
62
+ return { state: 'todo' };
63
+ }
64
+ }
65
+
66
+ // The slices a line's pending markers name, read outside code spans so a quoted marker does not
67
+ // count.
68
+ const PENDING = /<!--\s*slicekit:pending\s+(P(\d+)\/S-\d{2})\s*-->/g;
69
+ const pendingOn = (line) => [...blankCodeSpans(line).matchAll(PENDING)].map((m) => ({ id: m[1], phase: `P${m[2]}` }));
70
+
71
+ // The lines of an unmerged slice file whose code-span paths are promises: a `**Files:**` line, and
72
+ // every line under `## Expected changes` up to the next heading of level 1 or 2. Null for any
73
+ // other doc, and for a slice that is merged or released (its promises are due). A state file that
74
+ // exists but does not parse is reported through `broken` and defers nothing: an unknown state must
75
+ // not read as `todo`.
76
+ function promiseLines(ctx, doc, sliceIds, broken) {
77
+ const sliceId = sliceIds.get(doc.rel);
78
+ if (!sliceId) return null;
79
+ const { state, problem } = sliceState(ctx, sliceId);
80
+ if (problem) {
81
+ broken(problem);
82
+ return null;
83
+ }
84
+ if (DONE.has(state)) return null;
85
+ const out = new Set();
86
+ doc.lines.forEach((l, i) => {
87
+ if (l.includes('**Files:**')) out.add(i + 1);
88
+ });
89
+ const hs = headings(doc.text);
90
+ for (const [i, h] of hs.entries()) {
91
+ if (h.level !== 2 || h.text.trim().toLowerCase() !== 'expected changes') continue;
92
+ const next = hs.slice(i + 1).find((x) => x.level <= 2);
93
+ const end = next ? next.line : doc.lines.length + 1;
94
+ for (let n = h.line + 1; n < end; n++) out.add(n);
95
+ }
96
+ return out;
97
+ }
98
+
99
+ // Each slice file's address, keyed by its doc `rel`.
100
+ function sliceAddresses(ctx) {
101
+ const out = new Map();
102
+ let files = [];
103
+ try {
104
+ files = findSliceFiles(ctx.root, ctx.cfg);
105
+ } catch {
106
+ return out;
107
+ }
108
+ const byRel = new Map(ctx.docs.map((d) => [d.rel, d]));
109
+ for (const f of files) {
110
+ const rel = toSlashes(path.relative(ctx.root, f.path));
111
+ const doc = byRel.get(rel);
112
+ let addr = null;
113
+ try {
114
+ addr = doc ? parseSliceAddr(String(frontMatter(doc.text).data.slice ?? '')) : null;
115
+ } catch {
116
+ addr = null;
117
+ }
118
+ if (addr) out.set(rel, addr.id);
119
+ }
120
+ return out;
121
+ }
122
+
123
+ export function run(ctx) {
124
+ const findings = [];
125
+ const slugCache = new Map();
126
+ const dirCache = new Map();
127
+ const docByPath = new Map(ctx.docs.map((d) => [path.resolve(d.path), d]));
128
+ const sliceIds = sliceAddresses(ctx);
129
+ const root = path.resolve(ctx.root);
130
+
131
+ const namesIn = (dir) => {
132
+ if (!dirCache.has(dir)) {
133
+ let names;
134
+ try {
135
+ names = new Set(fs.readdirSync(dir));
136
+ } catch {
137
+ names = new Set();
138
+ }
139
+ dirCache.set(dir, names);
140
+ }
141
+ return dirCache.get(dir);
142
+ };
143
+
144
+ // True when abs exists with exactly this spelling below the root, so a case-insensitive disk
145
+ // gives the answer a case-sensitive one does. Outside the root only existence is checked.
146
+ const existsExact = (abs) => {
147
+ if (!fs.existsSync(abs)) return false;
148
+ const rel = path.relative(root, abs);
149
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return true;
150
+ let dir = root;
151
+ for (const seg of rel.split(path.sep)) {
152
+ if (!namesIn(dir).has(seg)) return false;
153
+ dir = path.join(dir, seg);
154
+ }
155
+ return true;
156
+ };
157
+
158
+ // The absolute path a target names. A link resolves as a reader's click does: against the doc's
159
+ // directory, or the root when it starts with `/`. A backticked path names a repo path, so it is
160
+ // also tried against the root. A trailing separator must name a directory. Null when none fits.
161
+ const resolve = (doc, target, via) => {
162
+ const rel = toSlashes(decode(target));
163
+ const wantDir = rel.endsWith('/');
164
+ const here = path.resolve(path.dirname(doc.path), rel);
165
+ const tries = rel.startsWith('/')
166
+ ? [path.join(root, rel)]
167
+ : via === 'code'
168
+ ? [here, path.resolve(root, rel)]
169
+ : [here];
170
+ return tries.find((p) => existsExact(p) && (!wantDir || fs.statSync(p).isDirectory())) ?? null;
171
+ };
172
+
173
+ const slugsOf = (abs) => {
174
+ if (!slugCache.has(abs)) {
175
+ const text = docByPath.get(abs)?.text ?? fs.readFileSync(abs, 'utf8');
176
+ slugCache.set(abs, slugs(text));
177
+ }
178
+ return slugCache.get(abs);
179
+ };
180
+
181
+ const stateCache = new Map();
182
+ const buildFile = path.resolve(ctx.paths.build);
183
+ for (const doc of ctx.docs) {
184
+ const intake = intakeStatus(ctx, doc);
185
+ if (intake === 'frozen') continue;
186
+ // BUILD.md's generated region is a view of the slice files, which are checked themselves: its
187
+ // paths are skipped there (a marker in a slice file must not be needed twice), its ids are not.
188
+ // Without the marker the whole file is generated, as `generatedRegion` reads it.
189
+ let viewEnd = 0;
190
+ if (path.resolve(doc.path) === buildFile) {
191
+ const i = doc.lines.findIndex((l) => l.trim() === BUILD_MARKER);
192
+ viewEnd = i === -1 ? doc.lines.length : i + 1;
193
+ }
194
+ const seen = new Set();
195
+ const mine = [];
196
+ const add = (line, message) => {
197
+ const key = `${line} ${message}`;
198
+ if (seen.has(key)) return;
199
+ seen.add(key);
200
+ mine.push({ rule: id, file: doc.rel, line, message, bucket: doc.rel });
201
+ };
202
+ // An intake file earns its exemption through its sidecar; without a valid one it is checked
203
+ // like any doc and is itself a finding (REQ-1.2).
204
+ if (intake === 'unpinned') add(0, 'intake file has no valid sidecar');
205
+ const promises = promiseLines(ctx, doc, sliceIds, (message) => add(0, message));
206
+
207
+ // A pending marker defers its line's paths while the slice it names is not merged or
208
+ // released; once it is, the paths are checked and the marker is stale. Its own address is not
209
+ // an unknown id when it names a phase not yet planned; in a planned phase it must be a slice.
210
+ const deferred = new Set();
211
+ const ownIds = new Map();
212
+ for (const [line, n] of prose(doc.text)) {
213
+ for (const p of pendingOn(line)) {
214
+ if (!ctx.ids.phase.has(p.phase)) ownIds.set(n, new Set([...(ownIds.get(n) ?? []), p.id]));
215
+ if (!stateCache.has(p.id)) stateCache.set(p.id, sliceState(ctx, p.id));
216
+ const { state, problem } = stateCache.get(p.id);
217
+ if (problem) add(n, problem);
218
+ else if (DONE.has(state)) add(n, `stale pending marker for ${p.id}; the slice is done, remove it`);
219
+ else deferred.add(n);
220
+ }
221
+ }
222
+
223
+ for (const ref of refs(doc.text)) {
224
+ // A marker quoted in a code span is text about the marker, not a marker.
225
+ if (blankCodeSpans(doc.lines[ref.line - 1] ?? '').includes(EXAMPLE)) continue;
226
+ if (ref.kind === 'path') {
227
+ if (ref.line <= viewEnd || deferred.has(ref.line)) continue;
228
+ if (ref.via === 'code' && promises?.has(ref.line)) continue;
229
+ if (isPathLike(ref.value) && !resolve(doc, ref.value, ref.via)) add(ref.line, `missing file ${ref.value}`);
230
+ } else if (ref.kind === 'anchor') {
231
+ if (!/\.md$/i.test(ref.file)) continue;
232
+ const abs = resolve(doc, ref.file, 'link');
233
+ if (!abs || !fs.statSync(abs).isFile()) continue;
234
+ if (!slugsOf(path.resolve(abs)).has(decode(ref.value).toLowerCase())) {
235
+ add(ref.line, `missing anchor #${ref.value} in ${ref.file}`);
236
+ }
237
+ } else if (ref.kind === 'id') {
238
+ if (ownIds.get(ref.line)?.has(ref.value)) continue;
239
+ const kind = KIND.find(([re]) => re.test(ref.value))?.[1];
240
+ if (kind && !ctx.ids[kind]?.has(ref.value)) add(ref.line, `unknown id ${ref.value}`);
241
+ }
242
+ }
243
+ // In line order; a stable sort keeps a line's findings in the order they were found.
244
+ findings.push(...mine.sort((a, b) => a.line - b.line));
245
+ }
246
+ return findings;
247
+ }
248
+
249
+ export default { id, blocking, ratchet, run };
@@ -0,0 +1,177 @@
1
+ import { seedBanned } from '../../config.js';
2
+ import { blankCodeSpans, prose } from '../../markdown.js';
3
+ import { intakeStatus } from '../context.js';
4
+
5
+ export const id = 'style';
6
+ export const blocking = true;
7
+ export const ratchet = true;
8
+
9
+ // A doc section that starts with this marker defines the filler list: it is not matched, and it
10
+ // must keep the seed list.
11
+ export const CATALOGUE = '<!-- slicekit:style-catalogue -->';
12
+ // A line carrying this marker quotes an example; it is not matched (as in `references`).
13
+ const EXAMPLE = '<!-- slicekit:example -->';
14
+
15
+ // Files that define the list without being docs. They are never in ctx.docs; named here so the
16
+ // exemption REQ-3.10 grants them stays explicit if the doc set ever widens.
17
+ const CONFIG = '.slicekit/config.json';
18
+ const EXEMPT = new Set([CONFIG, 'templates/style.json']);
19
+
20
+ const HEADING = /^(#{1,6})\s/;
21
+ const LINK_TARGET = /\]\(([^)]*)\)/g;
22
+ const URL = /[a-z][a-z0-9+.-]*:\/\/[^\s<>)\]]+/gi;
23
+
24
+ const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
25
+ const blank = (m) => ' '.repeat(m.length);
26
+
27
+ // One spelling per phrase: trimmed, single-spaced, a curly apostrophe made straight.
28
+ const normal = (p) => p.replace(/’/g, "'").trim().replace(/\s+/g, ' ');
29
+
30
+ // Config phrases with duplicates (by lower-cased normal form) and blanks removed, first spelling kept.
31
+ function phrases(list) {
32
+ const seen = new Map();
33
+ for (const raw of list) {
34
+ const p = normal(raw);
35
+ if (p !== '' && !seen.has(p.toLowerCase())) seen.set(p.toLowerCase(), p);
36
+ }
37
+ return [...seen.values()];
38
+ }
39
+
40
+ // A phrase as whole words, case-insensitive: bounded by non-letters, any whitespace (a line break
41
+ // included) between its words, and a straight apostrophe also matching a curly one. Inflections are
42
+ // not derived, so `leverage` does not match `leverages`; a team lists each form it bans.
43
+ function matcher(phrase) {
44
+ const body = phrase
45
+ .split(' ')
46
+ .map((w) => escape(w).replace(/'/g, "['’]"))
47
+ .join('\\s+');
48
+ return new RegExp(`(?<!\\p{L})${body}(?!\\p{L})`, 'giu');
49
+ }
50
+
51
+ // What a line says as writing: code spans, link targets and bare URLs blanked, columns unchanged.
52
+ const writing = (line) => blankCodeSpans(line).replace(LINK_TARGET, (m, t) => `](${blank(t)})`).replace(URL, blank);
53
+
54
+ // Catalogue sections: each starts at a marker written as prose (not quoted in code) and runs to the
55
+ // next heading of a level at or above the heading the marker sits under (to the end with none).
56
+ function sections(prosed) {
57
+ const out = [];
58
+ let parent = 0;
59
+ for (const [i, [line]] of prosed.entries()) {
60
+ const h = HEADING.exec(line);
61
+ if (h) parent = h[1].length;
62
+ if (!blankCodeSpans(line).includes(CATALOGUE)) continue;
63
+ let end = prosed.length;
64
+ for (let j = i + 1; j < prosed.length; j++) {
65
+ const hj = HEADING.exec(prosed[j][0]);
66
+ if (hj && parent > 0 && hj[1].length <= parent) {
67
+ end = j;
68
+ break;
69
+ }
70
+ }
71
+ out.push({ start: i, end, line: prosed[i][1] });
72
+ }
73
+ return out;
74
+ }
75
+
76
+ // Runs of consecutive prose lines to match as one text: a blank line, a fence, a heading (its own
77
+ // run), an example line or a catalogue line ends one, so a phrase is found across a hard wrap but
78
+ // never across a paragraph break.
79
+ function runs(prosed, skip) {
80
+ const out = [];
81
+ let cur = null;
82
+ const close = () => {
83
+ if (cur) out.push(cur);
84
+ cur = null;
85
+ };
86
+ for (const [i, [line, n]] of prosed.entries()) {
87
+ // A marker quoted in a code span is text about the marker, not a marker.
88
+ if (skip.has(i) || line.trim() === '' || blankCodeSpans(line).includes(EXAMPLE)) {
89
+ close();
90
+ continue;
91
+ }
92
+ const heading = HEADING.test(line);
93
+ if (heading || (cur && n !== cur.lines.at(-1) + 1)) close();
94
+ cur ??= { text: '', starts: [], lines: [] };
95
+ if (cur.lines.length > 0) cur.text += '\n';
96
+ cur.starts.push(cur.text.length);
97
+ cur.lines.push(n);
98
+ cur.text += writing(line);
99
+ if (heading) close();
100
+ }
101
+ close();
102
+ return out;
103
+ }
104
+
105
+ // The findings for docs, given the team's list and the kit's seed list. Exported for the
106
+ // empty-seed test, which cannot empty the real template.
107
+ export function findStyle(docs, banned, seed) {
108
+ const findings = [];
109
+ const seeds = phrases(seed);
110
+ if (seeds.length === 0) {
111
+ // A seed list emptied by accident would make every catalogue pass with nothing in it.
112
+ findings.push({ file: 'templates/style.json', line: 0, message: 'catalogue seed list is empty', bucket: 'catalogue' });
113
+ }
114
+ const configured = phrases(banned);
115
+ // The configured list must keep every seed phrase (REQ-3.10): an emptied list would make this
116
+ // rule match nothing. Its bucket is a catalogue bucket, which `baseline update --adopt` refuses.
117
+ const have = new Set(configured.map((p) => p.toLowerCase()));
118
+ for (const p of seeds) {
119
+ if (!have.has(p.toLowerCase())) {
120
+ findings.push({ file: CONFIG, line: 0, message: `catalogue missing "${p}"`, bucket: `catalogue:${CONFIG}` });
121
+ }
122
+ }
123
+ const patterns = configured.map((p) => [p, matcher(p)]);
124
+
125
+ for (const doc of docs) {
126
+ if (EXEMPT.has(doc.rel)) continue;
127
+ const prosed = [...prose(doc.text)];
128
+ const skip = new Set();
129
+ for (const s of sections(prosed)) {
130
+ for (let i = s.start; i < s.end; i++) skip.add(i);
131
+ // A catalogue finding's bucket is `catalogue:<rel>`, which no baseline carries, so the
132
+ // ratchet fails it on the first one. Only the seed list is required: a team phrase lives in
133
+ // config alone.
134
+ const text = normal(prosed.slice(s.start, s.end).map(([l]) => l).join(' ')).toLowerCase();
135
+ for (const p of seeds) {
136
+ if (!text.includes(p.toLowerCase())) {
137
+ findings.push({ file: doc.rel, line: s.line, message: `catalogue missing "${p}"`, bucket: `catalogue:${doc.rel}` });
138
+ }
139
+ }
140
+ }
141
+ for (const run of runs(prosed, skip)) {
142
+ const hits = [];
143
+ for (const [phrase, re] of patterns) {
144
+ for (const m of run.text.matchAll(re)) {
145
+ let k = run.starts.length - 1;
146
+ while (run.starts[k] > m.index) k--;
147
+ hits.push({ file: doc.rel, line: run.lines[k], message: `banned phrase "${phrase}"`, bucket: doc.rel });
148
+ }
149
+ }
150
+ findings.push(...hits.sort((a, b) => a.line - b.line));
151
+ }
152
+ }
153
+ return findings;
154
+ }
155
+
156
+ // The configured phrases found in one markdown text (a pull request body), in list order, each once.
157
+ // Matched as the doc rule matches: whole words, any case, across a hard wrap, never inside a fenced
158
+ // block, a code span, a link target or a URL.
159
+ export function bannedPhrasesIn(text, banned) {
160
+ const texts = runs([...prose(text)], new Set()).map((r) => r.text);
161
+ return phrases(banned).filter((p) => {
162
+ const re = matcher(p);
163
+ return texts.some((t) => {
164
+ re.lastIndex = 0;
165
+ return re.test(t);
166
+ });
167
+ });
168
+ }
169
+
170
+ export function run(ctx) {
171
+ // A pinned intake file is frozen (REQ-1.2): a quoted phrase there is the author's words, never
172
+ // rewritten. An unpinned one is matched like any doc.
173
+ const docs = ctx.docs.filter((d) => intakeStatus(ctx, d) !== 'frozen');
174
+ return findStyle(docs, ctx.cfg.style?.banned ?? [], seedBanned());
175
+ }
176
+
177
+ export default { id, blocking, ratchet, run };
@@ -0,0 +1,67 @@
1
+ // trailer (01 REQ-1.9, 03 REQ-3.7): on a slice branch every commit the branch adds carries
2
+ // `Slice: P<n>/S-<nn>` naming the branch's slice. The commits judged are HEAD's first-parent line,
3
+ // excluding everything reachable from `<defaultBranch>` and `origin/<defaultBranch>` (whichever
4
+ // exist; neither: every commit). First-parent only, so a stacked slice merged into this branch is
5
+ // judged on its own branch, not here. A merge commit is exempt: git writes its message. git itself
6
+ // reads the trailers (`%(trailers)`), so what counts as a trailer block, a folded value or a key's
7
+ // case is git's rule, not a parser of ours. No branch, a branch that is not a slice branch, or no
8
+ // commits at all: nothing to judge.
9
+ //
10
+ // Under --ci on a pull request, actions/checkout leaves a detached merge commit whose first parent is
11
+ // the base: the branch is GITHUB_HEAD_REF and the tip judged is the pull request's head, from the
12
+ // event's head sha (or the merge commit's second parent when the event has none).
13
+ import { assertRef, git, GitError, resolveCommit } from '../../git.js';
14
+ import { readCiEvent } from '../ci-event.js';
15
+ import { sliceFromBranch } from '../../ids.js';
16
+
17
+ export const id = 'trailer';
18
+ export const blocking = true;
19
+ export const ratchet = false;
20
+
21
+ const FORMAT = '--format=%H%x1f%P%x1f%(trailers:key=Slice,valueonly,unfold,separator=%x1d)%x1e';
22
+
23
+ const refExists = (root, ref) => {
24
+ try {
25
+ git(root, ['rev-parse', '--verify', '--quiet', ref]);
26
+ return true;
27
+ } catch (e) {
28
+ if (e instanceof GitError) return false;
29
+ throw e;
30
+ }
31
+ };
32
+
33
+ // The pull request's branch and head under --ci, or null outside a pull_request run.
34
+ function pullRequestTip(ctx) {
35
+ const ref = ctx.env?.GITHUB_HEAD_REF;
36
+ if (!ctx.ci || typeof ref !== 'string' || ref === '') return null;
37
+ const headSha = readCiEvent(ctx.env)?.headSha;
38
+ const tip = (headSha && /^[0-9a-f]{7,40}$/.test(headSha) && resolveCommit(ctx.root, headSha)) || resolveCommit(ctx.root, 'HEAD^2') || 'HEAD';
39
+ return { branch: ref, tip };
40
+ }
41
+
42
+ export function run(ctx) {
43
+ const { root, cfg } = ctx;
44
+ if (!ctx.git?.isRepo || !ctx.git.hasCommits) return [];
45
+ const pr = pullRequestTip(ctx);
46
+ const branch = pr?.branch ?? ctx.git.branch;
47
+ const tip = pr?.tip ?? 'HEAD';
48
+ if (!branch) return [];
49
+ const slice = sliceFromBranch(branch);
50
+ if (!slice) return [];
51
+
52
+ const def = assertRef(cfg.defaultBranch ?? 'main');
53
+ const exclude = [`refs/heads/${def}`, `refs/remotes/origin/${def}`].filter((ref) => refExists(root, ref)).map((ref) => `^${ref}`);
54
+ const log = git(root, ['log', '--first-parent', FORMAT, '--end-of-options', tip, ...exclude, '--']);
55
+ const out = [];
56
+ for (const rec of log.split('\x1e')) {
57
+ const [sha, parents = '', slices = ''] = rec.replace(/^\n/, '').split('\x1f');
58
+ if (!sha || parents.trim().split(/\s+/).length > 1) continue;
59
+ const named = slices.split('\x1d').map((s) => s.trim()).filter(Boolean);
60
+ const sha7 = sha.slice(0, 7);
61
+ if (named.length === 0) out.push({ file: branch, line: 0, message: `commit ${sha7} has no Slice trailer` });
62
+ else if (!named.includes(slice)) out.push({ file: branch, line: 0, message: `commit ${sha7} names ${named[0]}, branch is ${slice}` });
63
+ }
64
+ return out;
65
+ }
66
+
67
+ export default { id, blocking, ratchet, run };
@@ -0,0 +1,66 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { ConfigError } from '../config.js';
3
+ import { readBaselinesWithProblems, updateBaselines } from '../baseline.js';
4
+ import { check } from '../check/index.js';
5
+
6
+ const USAGE = 'baseline <update [--adopt]|show> [--json]';
7
+
8
+ // `update` ratchets the baselines down to today's counts and refuses to raise any (REQ-3.7): exit 1
9
+ // when something was refused or a baseline file is damaged. `update --adopt` is the one exception,
10
+ // a first adoption from a developer machine, and is refused in CI. `show` prints the baselines as
11
+ // JSON and any problems on stderr. Exit 2 on bad usage. `io.rules` is a test seam; production
12
+ // leaves it unset and `check` loads the rule files.
13
+ async function run(args, io) {
14
+ let values;
15
+ let positionals;
16
+ try {
17
+ ({ values, positionals } = parseArgs({
18
+ args,
19
+ options: { json: { type: 'boolean' }, adopt: { type: 'boolean' } },
20
+ allowPositionals: true,
21
+ }));
22
+ } catch (e) {
23
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
24
+ return 2;
25
+ }
26
+ const [sub, ...extra] = positionals;
27
+ if ((sub !== 'update' && sub !== 'show') || extra.length > 0 || (values.adopt && sub !== 'update')) {
28
+ io.stderr(`usage: slicekit ${USAGE}\n`);
29
+ return 2;
30
+ }
31
+ const env = io.env ?? process.env;
32
+ if (sub === 'show') {
33
+ const { baselines, problems } = readBaselinesWithProblems(io.cwd);
34
+ for (const p of problems) io.stderr(`baseline ${p.file}: ${p.problem}\n`);
35
+ io.stdout(`${JSON.stringify(baselines, null, 2)}\n`);
36
+ return 0;
37
+ }
38
+ if (values.adopt && env.CI) {
39
+ io.stderr('slicekit: --adopt is not allowed in CI; adopt a baseline from a developer machine and commit it\n');
40
+ return 2;
41
+ }
42
+ let result;
43
+ try {
44
+ result = check(io.cwd, { env, ...(io.rules ? { rules: io.rules } : {}) });
45
+ } catch (e) {
46
+ if (!(e instanceof ConfigError)) throw e;
47
+ io.stderr(`slicekit: ${e.message}\n`);
48
+ return 2;
49
+ }
50
+ const before = readBaselinesWithProblems(io.cwd).problems;
51
+ const { written, refused, adopted, rewrote } = updateBaselines(io.cwd, result.ratchetCounts, { adopt: Boolean(values.adopt) });
52
+ const rewroteFiles = new Set(rewrote.map((r) => r.file));
53
+ const remaining = before.filter((p) => !rewroteFiles.has(p.file));
54
+ if (values.json) {
55
+ io.stdout(`${JSON.stringify({ written, refused, adopted, rewrote, problems: remaining }, null, 2)}\n`);
56
+ } else {
57
+ for (const r of rewrote) io.stdout(`rewrote ${r.file} (was: ${r.problem})\n`);
58
+ for (const p of remaining) io.stdout(`baseline ${p.file}: ${p.problem}\n`);
59
+ for (const w of written) io.stdout(`baseline ${w.rule} ${w.bucket}: ${w.from} → ${w.to}\n`);
60
+ for (const a of adopted) io.stdout(`adopted ${a.rule} ${a.bucket}: ${a.from} → ${a.to}\n`);
61
+ for (const r of refused) io.stdout(`refused ${r.rule} ${r.bucket}: ${r.from} → ${r.to} (${r.reason ?? 'a baseline may only go down'})\n`);
62
+ }
63
+ return refused.length > 0 || remaining.length > 0 ? 1 : 0;
64
+ }
65
+
66
+ export const baselineCommand = { run, usage: USAGE };
@@ -0,0 +1,86 @@
1
+ // `slicekit branch <spec|gaps|plan> <slug>` (REQ-2.3..REQ-2.5): puts the session on the work branch
2
+ // of a document pull request, cut from the default branch as origin has it. The command owns git
3
+ // (D-19). A change to a tracked file (staged or not) is refused, so no edit is carried across;
4
+ // untracked files go along as git carries them, so a source dropped in for intake survives.
5
+ import { ConfigError, loadConfig } from '../config.js';
6
+ import { GitError, assertRef, currentBranch, git, hasRemote, switchBranch } from '../git.js';
7
+
8
+ const KINDS = ['spec', 'gaps', 'plan'];
9
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,59}$/;
10
+ const USAGE = 'branch <spec|gaps|plan> <slug>';
11
+
12
+ const resolves = (root, ref) => {
13
+ try {
14
+ git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
15
+ return true;
16
+ } catch (e) {
17
+ if (e instanceof GitError) return false;
18
+ throw e;
19
+ }
20
+ };
21
+
22
+ async function run(args, io) {
23
+ const [kind, slug, ...rest] = args;
24
+ if (!KINDS.includes(kind) || slug === undefined || rest.length > 0) {
25
+ io.stderr(`usage: slicekit ${USAGE}\n`);
26
+ return 2;
27
+ }
28
+ if (!SLUG.test(slug)) {
29
+ io.stderr(`slicekit: slug '${slug}' must be lowercase letters, digits and dashes, at most 60, not starting with a dash\n`);
30
+ return 2;
31
+ }
32
+ const root = io.cwd;
33
+ const target = `${kind}/${slug}`;
34
+ try {
35
+ const cfg = loadConfig(root);
36
+ const base = assertRef(cfg.defaultBranch);
37
+ if (currentBranch(root) === target) {
38
+ io.stdout(`${target}\n`);
39
+ return 0;
40
+ }
41
+ if (git(root, ['status', '--porcelain', '--untracked-files=no']) !== '') {
42
+ io.stderr('slicekit: commit or stash your changes first\n');
43
+ return 1;
44
+ }
45
+ // The full ref: a tag named like the default branch must not be what the branch is cut from.
46
+ let from = `refs/heads/${base}`;
47
+ if (hasRemote(root, 'origin')) {
48
+ try {
49
+ git(root, ['fetch', '-q', 'origin', base]);
50
+ if (resolves(root, `refs/remotes/origin/${base}`)) from = `refs/remotes/origin/${base}`;
51
+ // The work branch too, so one pushed from another clone is found; origin not having it is
52
+ // the usual case for a new branch, not an error.
53
+ try {
54
+ git(root, ['fetch', '-q', 'origin', `+refs/heads/${target}:refs/remotes/origin/${target}`]);
55
+ } catch (e) {
56
+ if (!(e instanceof GitError)) throw e;
57
+ }
58
+ } catch (e) {
59
+ if (!(e instanceof GitError)) throw e;
60
+ const lines = e.stderr.split('\n');
61
+ const reason = lines.find((l) => /^(fatal|error):/.test(l)) ?? (lines[0] || 'unknown reason');
62
+ io.stderr(`slicekit: could not fetch origin (${reason}); branching from local ${base}\n`);
63
+ }
64
+ }
65
+ // A work branch someone already pushed is taken up where it stands, tracking origin's copy;
66
+ // only a new one is cut from the default branch.
67
+ const remote = `refs/remotes/origin/${target}`;
68
+ if (resolves(root, `refs/heads/${target}`)) switchBranch(root, target);
69
+ else if (resolves(root, remote)) switchBranch(root, target, { create: true, from: remote, track: true });
70
+ else switchBranch(root, target, { create: true, from });
71
+ io.stdout(`${target}\n`);
72
+ return 0;
73
+ } catch (e) {
74
+ if (e instanceof ConfigError) {
75
+ io.stderr(`slicekit: ${e.message}\n`);
76
+ return 2;
77
+ }
78
+ if (e instanceof GitError) {
79
+ io.stderr(`slicekit: ${e.message}\n`);
80
+ return 1;
81
+ }
82
+ throw e;
83
+ }
84
+ }
85
+
86
+ export const branchCommand = { run, usage: USAGE, subcommands: KINDS };