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
@@ -0,0 +1,81 @@
1
+ // `build decline` (REQ-2.6 step 8): a should-have the implementer declines becomes one tracker issue
2
+ // (C-2) and one line in the pull request body's "Should-haves declined". A finding ID names one
3
+ // finding for the whole slice, so a second decline finds the issue already filed, open or closed, and
4
+ // opens no other; a closed one is never reopened. The body never lists a URL twice.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { getSection, setSection } from '../prbody.js';
8
+ import { readSlice } from '../state/index.js';
9
+ import { parseVerdict } from '../verdict.js';
10
+ import { BuildError, findWorktree } from './worktree.js';
11
+
12
+ const SECTION = 'Should-haves declined';
13
+ // GitHub's issue title limit.
14
+ export const TITLE_MAX = 256;
15
+
16
+ const MENTION = /(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\/[A-Za-z0-9_.-]+)?)/g;
17
+
18
+ // Every `@name` outside a code span wrapped in backticks, so text an agent wrote never notifies a
19
+ // real user. An address like a@b.com is left alone.
20
+ export function quoteMentions(text) {
21
+ return String(text)
22
+ .split(/(`[^`]*`)/)
23
+ .map((part, i) => (i % 2 === 1 ? part : part.replace(MENTION, '$1`@$2`')))
24
+ .join('');
25
+ }
26
+
27
+ // `<prefix><what>`, with `what` cut so the whole is at most TITLE_MAX characters and ends with "…".
28
+ // A cut never leaves a code span open, which would let a mention it wrapped out again.
29
+ export function issueTitle(prefix, what) {
30
+ const chars = Array.from(what);
31
+ const room = TITLE_MAX - Array.from(prefix).length;
32
+ if (chars.length <= room) return `${prefix}${what}`;
33
+ let kept = chars.slice(0, Math.max(room - 1, 0)).join('');
34
+ if ((kept.match(/`/g) ?? []).length % 2 === 1) kept = kept.slice(0, kept.lastIndexOf('`'));
35
+ return `${prefix}${kept}…`;
36
+ }
37
+
38
+ // The verdict of the highest round the state records, or null when none is recorded.
39
+ function latestVerdict(state) {
40
+ return (state.verdicts ?? []).reduce((best, v) => (best === null || v.round > best.round ? v : best), null);
41
+ }
42
+
43
+ function issueBody(f, v) {
44
+ const q = quoteMentions;
45
+ return [`What is wrong: ${q(f.wrong)}`, `Why it matters: ${q(f.why)}`, `How verified: ${q(f.verified)}`, '', `Verdict: ${v.path} at ${v.headSha}`, ''].join('\n');
46
+ }
47
+
48
+ // The section's text with `url` added: in place of `none`, else on a line of its own.
49
+ function withUrl(current, url) {
50
+ const t = (current ?? '').trim();
51
+ if (t === '' || /^none\.?$/i.test(t)) return url;
52
+ return `${t}\n${url}`;
53
+ }
54
+
55
+ // -> {url, created, state}: state is the filed issue's, `open` or `closed`; a new issue is open.
56
+ export function declineFinding(root, cfg, host, tracker, id, finding, { worktree } = {}) {
57
+ const wt = findWorktree(root, id, { worktree }).path;
58
+ const state = readSlice(wt, cfg, id);
59
+ const v = latestVerdict(state);
60
+ if (v === null) throw new BuildError(`${id} has no recorded verdict`, 2);
61
+ let text;
62
+ try {
63
+ text = fs.readFileSync(path.resolve(wt, v.path), 'utf8');
64
+ } catch (e) {
65
+ throw new BuildError(`cannot read the verdict ${v.path}: ${e.code ?? e.message}`);
66
+ }
67
+ const f = parseVerdict(text, v.path).findings.find((x) => x.id === finding && x.kind === 'should-have');
68
+ if (!f) throw new BuildError(`${finding} is not a should-have of round ${v.round}`, 2);
69
+ const number = state.pr?.number;
70
+ if (!Number.isInteger(number)) throw new BuildError(`${id} has no pull request to list the declined should-have on`);
71
+
72
+ const filed = tracker.find(id, finding);
73
+ const issue = filed ?? tracker.open({ title: issueTitle(`[${id}] ${finding}: `, quoteMentions(f.wrong)), body: issueBody(f, v), slice: id });
74
+
75
+ const body = host.getPullRequest(number).body;
76
+ const current = getSection(body, SECTION);
77
+ if (!(current ?? '').split(/\s+/).includes(issue.url)) {
78
+ host.updatePullRequestBody(number, setSection(body, SECTION, withUrl(current, issue.url)));
79
+ }
80
+ return { url: issue.url, created: filed === null, state: filed?.state ?? 'open' };
81
+ }
@@ -0,0 +1,155 @@
1
+ // `build finish` (REQ-2.6 step 9, REQ-1.8): a slice whose latest verdict on its head is clean waits
2
+ // for CI on the head the git host holds; on success its pull request's "Proof" takes the run link,
3
+ // the pull request is marked ready and `ci-green` is recorded on that head. The live head may be a
4
+ // later one that adds only the kit's bookkeeping (D-35): the verdict and in-review commits `build
5
+ // verdict` pushed. A head with any other change is a fix push `build pr` has not recorded, and is
6
+ // refused before anything changes. After `ci-green` it records `ready` when the ready label's own
7
+ // decision passes: the function the CI job calls, with `review.independent` read from the default
8
+ // branch as that job reads it.
9
+ import { headSha, pushBranch, resolveCommit } from '../git.js';
10
+ import { sleep as sleepMs } from '../lock.js';
11
+ import { PrBodyError, getSection, prBodyProblems, setSection } from '../prbody.js';
12
+ import { readSlice } from '../state/index.js';
13
+ import { headCovers } from '../state/covers.js';
14
+ import { INDEPENDENT_MISSING, verdictsOnHead } from '../state/transitions.js';
15
+ import { decideReady, withBaseReviewMode } from '../ready-label.js';
16
+ import { recordState } from './record.js';
17
+ import { assertNotBehind } from './sync.js';
18
+ import { committedVerdict } from './verdict.js';
19
+ import { BuildError, findWorktree } from './worktree.js';
20
+
21
+ const PROOF = 'Proof';
22
+ const short = (sha) => sha.slice(0, 7);
23
+ const push = (wt, cfg) => pushBranch(wt, { protectedBranches: cfg.protectedBranches, defaultBranch: cfg.defaultBranch });
24
+
25
+ // "Proof" with its CI part naming the run: `CI: pending` (what `build pr` writes) replaced, else the
26
+ // CI part it already holds (a re-run, a hand edit), else one added. The run is taken literally: the
27
+ // replacement is a function, so a `$&` in it is never expanded.
28
+ export function proofWithCi(proof, run) {
29
+ const text = (proof ?? '').trim();
30
+ const part = () => `CI: ${run}`;
31
+ if (/CI: pending/.test(text)) return text.replace(/CI: pending/, part);
32
+ if (/CI: \S+/.test(text)) return text.replace(/CI: \S+/, part);
33
+ return text === '' ? part() : `${text} · ${part()}`;
34
+ }
35
+
36
+ // Writes "Proof" with the run, judged under `cfg` first: only problems the new text adds refuse it.
37
+ function setProof(cfg, host, number, ci) {
38
+ const pr = host.getPullRequest(number);
39
+ const body = pr.body ?? '';
40
+ const run = ci.url ?? `passed on ${short(ci.sha)}`;
41
+ const text = proofWithCi(getSection(body, PROOF), run);
42
+ if (getSection(body, PROOF) === text) return;
43
+ let next;
44
+ try {
45
+ next = setSection(body, PROOF, text);
46
+ } catch (e) {
47
+ if (e instanceof PrBodyError) throw new BuildError(`cannot set "${PROOF}" on pull request #${number}: ${e.message}`);
48
+ throw e;
49
+ }
50
+ const before = new Set(prBodyProblems(pr.title ?? '', body, cfg));
51
+ const added = prBodyProblems(pr.title ?? '', next, cfg).filter((p) => !before.has(p));
52
+ if (added.length > 0) throw new BuildError(`cannot set "${PROOF}" on pull request #${number}: ${added.join('; ')}`);
53
+ host.updatePullRequestBody(number, next);
54
+ }
55
+
56
+ // ciStatus(sha) until it is success or failure, or `wait` seconds are spent, sleeping `interval`
57
+ // seconds (the last nap cut to what is left) between asks.
58
+ function pollCi(host, sha, { wait, interval, sleep }) {
59
+ let waited = 0;
60
+ for (;;) {
61
+ const status = host.ciStatus(sha);
62
+ if (status.status === 'success' || status.status === 'failure' || waited >= wait) return status;
63
+ const nap = Math.min(interval, wait - waited);
64
+ sleep(nap);
65
+ waited += nap;
66
+ }
67
+ }
68
+
69
+ function assertTimes(wait, interval) {
70
+ if (!(Number.isFinite(wait) && wait >= 0)) throw new BuildError('--wait must be a number of seconds, 0 or more', 2);
71
+ if (!(Number.isFinite(interval) && interval > 0)) throw new BuildError('the poll interval must be a number of seconds above 0', 2);
72
+ }
73
+
74
+ // Seconds one `build finish` waits for CI by default: a Claude Code Bash call stops at 120 s, so the
75
+ // procedure runs it again on "CI still running" rather than waiting longer in one call.
76
+ export const FINISH_WAIT = 90;
77
+
78
+ // -> {ci: {status, sha, url}, ready, reason, number}. Every refusal is a BuildError; CI that
79
+ // failed, is still running or never ran is code 1 and records nothing.
80
+ export function finish(root, cfg, host, id, { worktree, wait = FINISH_WAIT, interval = 15, sleep = (s) => sleepMs(s * 1000) } = {}) {
81
+ assertTimes(wait, interval);
82
+ const held = findWorktree(root, id, { worktree });
83
+ const wt = held.path;
84
+ const current = readSlice(wt, cfg, id);
85
+ const number = current.pr?.number;
86
+ // Behind origin first, before the head guards below: commits another worktree pushed are synced.
87
+ assertNotBehind(wt, held.branch, id);
88
+
89
+ // A slice at ci-green skips the CI wait and goes to the ready decision, citing the run recorded
90
+ // with ci-green; one at ready finishes a run that stopped before the pull request or the push. It
91
+ // pushes only bookkeeping on top of the reviewed, green head.
92
+ if ((current.state === 'ci-green' || current.state === 'ready') && current.ci?.sha && Number.isInteger(number)) {
93
+ const local = headSha(wt);
94
+ if (!headCovers(wt, current.pr.headSha, local) || !headCovers(wt, current.ci.sha, local)) {
95
+ throw new BuildError(`${id} has commits since build pr; run slicekit build pr ${id} first`);
96
+ }
97
+ const ci = { status: 'success', sha: current.ci.sha, url: current.ci.url ?? null };
98
+ setProof(cfg, host, number, ci);
99
+ return { ci, ...readyStep(wt, cfg, host, id, current, ci.sha) };
100
+ }
101
+ if (current.state !== 'in-review') throw new BuildError(`${id} is ${current.state}; build finish runs from in-review`);
102
+ if (!Number.isInteger(number)) throw new BuildError(`${id} has no recorded pull request`);
103
+ const recorded = current.pr.headSha;
104
+
105
+ const latest = verdictsOnHead(current, recorded, wt).at(-1);
106
+ if (!latest) throw new BuildError(`${id} has no verdict on its head; finish needs a clean verdict`);
107
+ // The committed verdict decides, not the count the state file holds: either can be edited by hand.
108
+ const found = committedVerdict(wt, latest.path).findings.filter((f) => f.kind === 'blocker').length;
109
+ if (found !== latest.blockers) {
110
+ throw new BuildError(`the state says round ${latest.round} has ${latest.blockers} blockers but ${latest.path} holds ${found}`);
111
+ }
112
+ if (latest.blockers !== 0) throw new BuildError(`${id} has open blockers; finish needs a clean verdict`);
113
+
114
+ const pr = host.getPullRequest(number);
115
+ const live = pr.headSha;
116
+ if (typeof live !== 'string' || live === '') throw new BuildError(`pull request #${number} reports no head sha`);
117
+ const pull = `${id}'s pull request head ${short(live)} is not in the worktree; run slicekit build sync ${id}`;
118
+ if (resolveCommit(wt, live) === null) throw new BuildError(pull);
119
+ if (!headCovers(wt, recorded, live)) throw new BuildError(`a fix push is not recorded; run slicekit build pr ${id}`);
120
+ const local = headSha(wt);
121
+ if (!headCovers(wt, recorded, local)) throw new BuildError(`${id} has commits since build pr; run slicekit build pr ${id} first`);
122
+ if (!headCovers(wt, live, local)) throw new BuildError(pull);
123
+
124
+ const status = pollCi(host, live, { wait, interval, sleep });
125
+ if (status.status === 'failure') throw new BuildError(`CI failed on ${short(live)}${status.url ? `: ${status.url}` : ''}`);
126
+ if (status.status === 'unknown') throw new BuildError(`no CI run found for ${short(live)}; check that the workflow ran`);
127
+ if (status.status !== 'success') throw new BuildError(`CI still running on ${short(live)}; run slicekit build finish ${id} again`);
128
+
129
+ const ci = { status: 'success', sha: live, url: status.url ?? null };
130
+ setProof(cfg, host, number, ci);
131
+ const green = recordState(wt, cfg, id, 'ci-green', { ci: { status: 'success', sha: live, ...(ci.url ? { url: ci.url } : {}) } });
132
+ return { ci, ...readyStep(wt, cfg, host, id, green, live) };
133
+ }
134
+
135
+ // The step after ci-green, `head` being the green CI sha: `ready` is recorded when the ready label's
136
+ // decision passes. The pull request is marked ready only here, on green CI, so a failed or running CI
137
+ // leaves a draft, as in-review says. It is marked when the decision passes, or when no independent
138
+ // verdict is on the head yet so the independent reviewer is asked to review a ready pull request.
139
+ // After an independent verdict with blockers sent the slice back to in-review and the pull request to
140
+ // draft (D-39), it is ready again only once CI is green and the decision passes; a clean one leaves
141
+ // the pull request ready. Then the bookkeeping is
142
+ // pushed. At `ready` the decision is made again: one that fails records nothing and marks nothing.
143
+ // `review.independent` is the default branch's on origin (withBaseReviewMode), as the label job
144
+ // reads it, never the pull request's own. -> {ready, reason, number}.
145
+ function readyStep(wt, cfg, host, id, state, head) {
146
+ const number = state.pr.number;
147
+ const gate = withBaseReviewMode(wt, cfg, cfg.defaultBranch);
148
+ let current = state;
149
+ const decision = decideReady(current, gate, { headSha: head, number, root: wt });
150
+ if (decision.ready && current.state !== 'ready') current = recordState(wt, gate, id, 'ready', {});
151
+ const awaited = state.state !== 'ready' && decision.reason === INDEPENDENT_MISSING;
152
+ if ((decision.ready || awaited) && host.getPullRequest(number).draft !== false) host.markReady(number);
153
+ push(wt, cfg);
154
+ return { ready: decision.ready, reason: decision.reason, number };
155
+ }
@@ -0,0 +1,158 @@
1
+ // Which slice `build next` takes (REQ-2.6, D-38): a `todo` slice whose earlier phases, and earlier
2
+ // Order steps of its own phase, are all merged or released, and which no worktree, local branch or
3
+ // branch on origin already holds.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { readText } from '../fs.js';
7
+ import { GitError, assertRef, currentBranch, git, hasRemote } from '../git.js';
8
+ import { sliceFromBranch } from '../ids.js';
9
+ import { kitPaths } from '../paths.js';
10
+ import { findSliceFiles, parseOrder, parsePhaseFile, parseSliceFile } from '../slicefile.js';
11
+ import { readSlice } from '../state/index.js';
12
+ import { BuildError, listWorktrees, samePath } from './worktree.js';
13
+
14
+ const DONE = ['merged', 'released'];
15
+
16
+ // The phase's Order steps, each a list of groups: the phase file's `**Order:**` line, else each
17
+ // group its own step in name order. A group the line leaves out runs after the steps it names.
18
+ function steps(phaseDir, phaseId, groups) {
19
+ const own = `${phaseId}.md`;
20
+ const candidates = fs
21
+ .readdirSync(phaseDir)
22
+ .filter((f) => f.endsWith('.md') && !/^S-\d+/.test(f))
23
+ .sort((a, b) => (a === own ? -1 : b === own ? 1 : a.localeCompare(b)));
24
+ let order = null;
25
+ for (const f of candidates) {
26
+ const text = readText(path.join(phaseDir, f));
27
+ if (parsePhaseFile(text)?.id === phaseId) {
28
+ order = parseOrder(text);
29
+ break;
30
+ }
31
+ }
32
+ const out = order ?? [];
33
+ const named = new Set(out.flat());
34
+ for (const g of [...new Set(groups)].sort()) if (!named.has(g)) out.push([g]);
35
+ return out;
36
+ }
37
+
38
+ // Every slice in phase and slice order: { id, phase, group, file, state, step }.
39
+ function slices(root, cfg) {
40
+ const files = findSliceFiles(root, cfg).map((f) => ({ ...f, slice: parseSliceFile(readText(f.path), f.path) }));
41
+ const byPhase = new Map();
42
+ for (const f of files) {
43
+ if (!byPhase.has(f.phaseId)) byPhase.set(f.phaseId, { dir: f.phaseDir, groups: [] });
44
+ byPhase.get(f.phaseId).groups.push(f.slice.group);
45
+ }
46
+ const stepsOf = new Map([...byPhase].map(([id, p]) => [id, steps(p.dir, id, p.groups)]));
47
+ return files.map((f) => ({
48
+ id: f.slice.id,
49
+ phase: f.phaseId,
50
+ phaseN: Number(f.phaseId.slice(1)),
51
+ group: f.slice.group,
52
+ file: f.path,
53
+ state: readSlice(root, cfg, f.slice.id).state,
54
+ step: stepsOf.get(f.phaseId).findIndex((s) => s.includes(f.slice.group)),
55
+ }));
56
+ }
57
+
58
+ // Slice ID → { phase, step, state }, in phase and slice order: the phase it belongs to, the index of
59
+ // its Order step there (each group its own step without an Order line) and its state. Read from the
60
+ // checkout `root`.
61
+ export function sliceSteps(root, cfg) {
62
+ return new Map(slices(root, cfg).map((s) => [s.id, { phase: s.phase, step: s.step, state: s.state }]));
63
+ }
64
+
65
+ // The first slice `s` waits on: of an earlier phase, then of an earlier step of its own; or null.
66
+ function blocker(s, all) {
67
+ return (
68
+ all.find((o) => o.phaseN < s.phaseN && !DONE.includes(o.state)) ??
69
+ all.find((o) => o.phase === s.phase && o.step < s.step && !DONE.includes(o.state)) ??
70
+ null
71
+ );
72
+ }
73
+
74
+ // Slice ID → where it is held: a worktree path, a local branch, or `origin/<branch>`, as the refs
75
+ // stand now (runnable fetches first).
76
+ export function heldSlices(root) {
77
+ const held = new Map();
78
+ for (const w of listWorktrees(root)) {
79
+ const id = w.branch && sliceFromBranch(w.branch);
80
+ if (id && !held.has(id)) held.set(id, w.path);
81
+ }
82
+ const refs = git(root, ['for-each-ref', '--format=%(refname)', 'refs/heads/slice/', 'refs/remotes/origin/slice/']);
83
+ for (const ref of refs === '' ? [] : refs.split('\n')) {
84
+ const local = ref.startsWith('refs/heads/');
85
+ const branch = ref.slice(local ? 'refs/heads/'.length : 'refs/remotes/origin/'.length);
86
+ const id = sliceFromBranch(branch);
87
+ if (id && !held.has(id)) held.set(id, local ? branch : `origin/${branch}`);
88
+ }
89
+ return held;
90
+ }
91
+
92
+ const resolves = (root, ref) => {
93
+ try {
94
+ git(root, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
95
+ return true;
96
+ } catch (e) {
97
+ if (e instanceof GitError) return false;
98
+ throw e;
99
+ }
100
+ };
101
+
102
+ // States are read from the checkout the command runs in, so it must be the main checkout, on the
103
+ // default branch, and, with an origin, exactly where origin's default branch is after a fetch: a
104
+ // stale main would offer a slice that is merged, or claimed and gone, on origin. The state and plan
105
+ // files must be committed, so what is read is what HEAD holds.
106
+ export function prepare(root, cfg) {
107
+ const base = assertRef(cfg.defaultBranch);
108
+ const top = git(root, ['rev-parse', '--show-toplevel']);
109
+ const branch = currentBranch(root);
110
+ if (!samePath(top, listWorktrees(root)[0].path) || branch !== base) {
111
+ throw new BuildError(
112
+ `build next and build start read slice states from the checkout they run in; run them in the main checkout on ${base} (this one is on ${branch ?? 'a detached HEAD'})`,
113
+ );
114
+ }
115
+ const paths = kitPaths(root, cfg);
116
+ const rel = (abs) => path.relative(root, abs).split(path.sep).join('/') || '.';
117
+ if (git(root, ['--literal-pathspecs', 'status', '--porcelain', '--', rel(paths.state), rel(paths.phases)]) !== '') {
118
+ throw new BuildError('uncommitted changes to slice states or plan files; commit or stash them first');
119
+ }
120
+ if (!hasRemote(root, 'origin')) return;
121
+ // --prune: a slice branch deleted on origin no longer holds its slice.
122
+ git(root, ['fetch', '-q', '--prune', 'origin']);
123
+ const remote = `refs/remotes/origin/${base}`;
124
+ if (!resolves(root, remote)) throw new BuildError(`${base} has commits origin does not; push or reset first`);
125
+ const [ahead, behind] = git(root, ['rev-list', '--left-right', '--count', `HEAD...${remote}`]).split(/\s+/).map(Number);
126
+ if (behind > 0) throw new BuildError(`${base} is behind origin; pull first`);
127
+ if (ahead > 0) throw new BuildError(`${base} has commits origin does not; push or reset first`);
128
+ }
129
+
130
+ // `prepared`: the caller (startSlice) has already run prepare, so origin is not fetched twice.
131
+ export function runnable(root, cfg, { prepared = false } = {}) {
132
+ if (!prepared) prepare(root, cfg);
133
+ const all = slices(root, cfg);
134
+ const held = heldSlices(root);
135
+ return all
136
+ .filter((s) => s.state === 'todo' && !held.has(s.id) && blocker(s, all) === null)
137
+ .map(({ id, phase, group, file }) => ({ id, phase, group, file }));
138
+ }
139
+
140
+ const line = (s, b) => `${s.id} waits on ${b.id} (${b.state})`;
141
+
142
+ export function waiting(root, cfg) {
143
+ const all = slices(root, cfg);
144
+ const out = [];
145
+ for (const s of all) {
146
+ const b = s.state === 'todo' ? blocker(s, all) : null;
147
+ if (b) out.push(line(s, b));
148
+ }
149
+ return out;
150
+ }
151
+
152
+ // The waiting line of one slice, or null when nothing earlier holds it back.
153
+ export function waitingOn(root, cfg, id) {
154
+ const all = slices(root, cfg);
155
+ const s = all.find((o) => o.id === id);
156
+ const b = s && s.state === 'todo' ? blocker(s, all) : null;
157
+ return b ? line(s, b) : null;
158
+ }
@@ -0,0 +1,173 @@
1
+ // The overlap stop (D-06): two slices of one Order step run side by side because the plan said their
2
+ // changes do not overlap. `build pr` asks, before it pushes, whether this branch changes a path a
3
+ // branch of another slice of the same step already changes on origin; a path both change is a plan
4
+ // defect, not a merge conflict to resolve in the branch.
5
+ //
6
+ // What counts as both changing a path:
7
+ // - the same path, compared without regard to case: on a case-insensitive checkout `a.js` and `A.js`
8
+ // are one file, and a false alarm is a defect a person settles while a miss is silent;
9
+ // - a directory one branch deletes outright and a path the other changes or adds inside it.
10
+ // Renames count as a delete and an add (`--no-renames`). Shared roots (coverage's `isSharedRoot`)
11
+ // and the kit's bookkeeping never count.
12
+ import { execFileSync } from 'node:child_process';
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { GitError, assertRef, git, hasRemote } from '../git.js';
17
+ import { parseSliceAddr, sliceFromBranch } from '../ids.js';
18
+ import { isSharedRoot } from '../check/rules/coverage.js';
19
+ import { kitPaths } from '../paths.js';
20
+ import { SliceFileError } from '../slicefile.js';
21
+ import { bookkeepingTest } from '../state/covers.js';
22
+ import { sliceSteps } from './order.js';
23
+ import { reviewBranch } from './worktree.js';
24
+
25
+ const posix = (p) => p.split(path.sep).join('/');
26
+ const fold = (p) => p.toLowerCase();
27
+
28
+ const resolves = (wt, ref) => {
29
+ try {
30
+ git(wt, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]);
31
+ return true;
32
+ } catch (e) {
33
+ if (e instanceof GitError) return false;
34
+ throw e;
35
+ }
36
+ };
37
+
38
+ const nul = (out) => out.split('\0').filter((f) => f !== '');
39
+
40
+ // What `ref` changes since it left `base` (their merge base): `paths`, folded path → its spelling,
41
+ // and `gone`, each directory it deletes outright (shortest first), as {key, spelling}.
42
+ function changesOf(wt, base, ref) {
43
+ const from = git(wt, ['merge-base', base, ref]);
44
+ const fields = nul(git(wt, ['diff', '-z', '--name-status', '--no-renames', from, ref, '--']));
45
+ const paths = new Map();
46
+ const deleted = [];
47
+ for (let i = 0; i + 1 < fields.length; i += 2) {
48
+ paths.set(fold(fields[i + 1]), fields[i + 1]);
49
+ if (fields[i] === 'D') deleted.push(fields[i + 1]);
50
+ }
51
+ const gone = new Map();
52
+ if (deleted.length > 0) {
53
+ const kept = new Set(nul(git(wt, ['ls-tree', '-r', '-d', '-z', '--name-only', ref])).map(fold));
54
+ for (const f of deleted) {
55
+ const parts = f.split('/');
56
+ for (let k = 1; k < parts.length; k++) {
57
+ const dir = parts.slice(0, k).join('/');
58
+ if (!kept.has(fold(dir)) && !gone.has(fold(dir))) gone.set(fold(dir), dir);
59
+ }
60
+ }
61
+ }
62
+ const dirs = [...gone].map(([key, spelling]) => ({ key, spelling })).sort((a, b) => a.key.length - b.key.length);
63
+ return { paths, gone: dirs };
64
+ }
65
+
66
+ // The slice and phase files as `ref` holds them, written into a scratch directory, then `fn` on it.
67
+ // null when they cannot be read or do not parse.
68
+ function withPlanAt(wt, cfg, ref, fn) {
69
+ const phasesRel = posix(path.relative(wt, kitPaths(wt, cfg).phases));
70
+ let tmp;
71
+ try {
72
+ const files = nul(git(wt, ['ls-tree', '-r', '-z', '--name-only', ref, '--', phasesRel])).filter((f) => f.endsWith('.md'));
73
+ if (files.length === 0) return null;
74
+ // One process for every file: `cat-file --batch` answers `<sha> blob <size>\n<bytes>\n` per name.
75
+ const out = execFileSync('git', ['cat-file', '--batch'], { cwd: wt, input: files.map((f) => `${ref}:${f}\n`).join(''), maxBuffer: 256 * 1024 * 1024 });
76
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'slicekit-plan-'));
77
+ let at = 0;
78
+ for (const f of files) {
79
+ const eol = out.indexOf(0x0a, at);
80
+ const header = out.subarray(at, eol).toString('utf8').split(' ');
81
+ if (header[1] !== 'blob') return null;
82
+ const size = Number(header[2]);
83
+ const target = path.join(tmp, ...f.split('/'));
84
+ fs.mkdirSync(path.dirname(target), { recursive: true });
85
+ fs.writeFileSync(target, out.subarray(eol + 1, eol + 1 + size));
86
+ at = eol + 1 + size + 1;
87
+ }
88
+ return fn(tmp);
89
+ } catch (e) {
90
+ if (e instanceof GitError || e instanceof SliceFileError || e.status !== undefined) return null;
91
+ throw e;
92
+ } finally {
93
+ if (tmp) fs.rmSync(tmp, { recursive: true, force: true });
94
+ }
95
+ }
96
+
97
+ // The other slices of `id`'s phase and Order step in either plan: the worktree's, and origin's
98
+ // default branch's. The branch under judgement can edit its own plan (move its slice to another
99
+ // group), so its plan alone cannot clear it; origin's alone would miss a step the branch adds.
100
+ function matesOf(wt, cfg, id, base) {
101
+ const plans = [];
102
+ try {
103
+ plans.push(sliceSteps(wt, cfg));
104
+ } catch (e) {
105
+ // A plan file that does not parse is `slicekit check`'s to report, later in `build pr` and still
106
+ // before any push; origin's plan still judges.
107
+ if (!(e instanceof SliceFileError)) throw e;
108
+ }
109
+ const atBase = withPlanAt(wt, cfg, base, (dir) => sliceSteps(dir, cfg));
110
+ if (atBase) plans.push(atBase);
111
+ const mates = new Set();
112
+ for (const steps of plans) {
113
+ const mine = steps.get(id);
114
+ if (!mine || mine.step < 0) continue;
115
+ for (const [other, s] of steps) if (other !== id && s.phase === mine.phase && s.step === mine.step) mates.add(other);
116
+ }
117
+ return mates;
118
+ }
119
+
120
+ // -> [{other, path, otherPath}], sorted: for each other slice of `id`'s phase and Order step (its
121
+ // group, without an Order line) that has a branch on origin, each path both that branch and HEAD
122
+ // change since their merge base with origin's default branch (see the top of this file), less shared
123
+ // roots and the kit's bookkeeping. `path` is this branch's spelling, `otherPath` the other's. A
124
+ // slice's review branch is never one of its branches here, and `id`'s own branches are skipped.
125
+ // Without an origin, or without the default branch on it, there is nothing to compare: [].
126
+ export function overlapWith(wt, cfg, id) {
127
+ if (!hasRemote(wt, 'origin')) return [];
128
+ git(wt, ['fetch', '-q', '--prune', 'origin']);
129
+ const base = `refs/remotes/origin/${assertRef(cfg.defaultBranch)}`;
130
+ if (!resolves(wt, base)) return [];
131
+ const mates = matesOf(wt, cfg, id, base);
132
+ if (mates.size === 0) return [];
133
+
134
+ const refs = git(wt, ['for-each-ref', '--format=%(refname)', 'refs/remotes/origin/slice/']);
135
+ const others = [];
136
+ for (const ref of refs === '' ? [] : refs.split('\n')) {
137
+ const branch = ref.slice('refs/remotes/origin/'.length);
138
+ const other = sliceFromBranch(branch);
139
+ if (!other || !mates.has(other) || branch === reviewBranch(parseSliceAddr(other))) continue;
140
+ others.push({ other, ref });
141
+ }
142
+ if (others.length === 0) return [];
143
+
144
+ // The runbook as coverage resolves it, so `docsRoot: "./docs"` names the same file.
145
+ const runbook = posix(path.relative(wt, kitPaths(wt, cfg).runbook));
146
+ const kept = bookkeepingTest(wt);
147
+ const counts = (f) => !isSharedRoot(f, runbook) && !kept(f);
148
+ const ours = changesOf(wt, base, 'HEAD');
149
+ const out = new Map();
150
+ const add = (other, p, otherPath) => {
151
+ const key = `${other}\0${fold(p)}`;
152
+ if (counts(p) && counts(otherPath) && !out.has(key)) out.set(key, { other, path: p, otherPath });
153
+ };
154
+ // The shortest directory of `gone` holding `key`, or null.
155
+ const under = (gone, key) => gone.find((d) => key.startsWith(`${d.key}/`)) ?? null;
156
+ for (const { other, ref } of others) {
157
+ const theirs = changesOf(wt, base, ref);
158
+ for (const [key, spelling] of ours.paths) {
159
+ if (theirs.paths.has(key)) add(other, spelling, theirs.paths.get(key));
160
+ const dir = under(theirs.gone, key);
161
+ if (dir) add(other, dir.spelling, dir.spelling);
162
+ }
163
+ for (const [key] of theirs.paths) {
164
+ const dir = under(ours.gone, key);
165
+ if (dir) add(other, dir.spelling, dir.spelling);
166
+ }
167
+ }
168
+ return [...out.values()].sort((a, b) => a.other.localeCompare(b.other) || a.path.localeCompare(b.path));
169
+ }
170
+
171
+ // The refusal line; the other branch's spelling is given when it differs from this branch's.
172
+ export const planDefectLine = (id, { other, path: p, otherPath }) =>
173
+ `plan defect: ${id} and ${other} both change ${p}${otherPath && otherPath !== p ? ` (as ${otherPath} in ${other})` : ''}; the plan said they do not overlap`;
@@ -0,0 +1,50 @@
1
+ // `build parallel P<n>` (REQ-2.6, D-38): every runnable slice of the phase's next Order step started
2
+ // side by side, each in its own worktree. Each start goes through startSlice, so each is claimed on
3
+ // origin exactly as `build start` claims it; one start that fails does not take back the others.
4
+ import path from 'node:path';
5
+ import { GitError } from '../git.js';
6
+ import { heldSlices, prepare, runnable, sliceSteps, waiting } from './order.js';
7
+ import { BuildError, startSlice } from './worktree.js';
8
+
9
+ const DONE = ['merged', 'released'];
10
+
11
+ // -> [{id, worktree, branch}] for each slice started, [{id, error}] for each that was not, and [{id,
12
+ // error, held: true}] for each of the step another clone holds, in
13
+ // slice order. The step is the first Order step of `phase` holding a runnable slice. A phase with
14
+ // none is refused with a line for each of its slices that waits on another and for each already
15
+ // started, here or by another clone, saying where.
16
+ export function startParallel(root, cfg, phase, { onWarning } = {}) {
17
+ prepare(root, cfg);
18
+ const steps = sliceSteps(root, cfg);
19
+ if (![...steps.values()].some((s) => s.phase === phase)) throw new BuildError(`unknown phase ${phase}`, 2);
20
+ const ready = runnable(root, cfg, { prepared: true }).filter((s) => s.phase === phase);
21
+ if (ready.length === 0) {
22
+ const lines = waiting(root, cfg).filter((l) => l.startsWith(`${phase}/`));
23
+ const held = heldSlices(root);
24
+ for (const [id, s] of steps) {
25
+ if (s.phase !== phase || DONE.includes(s.state) || !held.has(id)) continue;
26
+ const where = held.get(id);
27
+ lines.push(`${id} started in ${where.startsWith('origin/') ? where : path.resolve(where).split(path.sep).join('/')}`);
28
+ }
29
+ throw new BuildError([`no slice of ${phase} is ready to build`, ...lines].join('\n'));
30
+ }
31
+ const first = Math.min(...ready.map((s) => steps.get(s.id).step));
32
+ const out = [];
33
+ // A slice of the step another clone holds is named, `held`, so the caller does not count it as a
34
+ // start that failed: it was never this clone's to start.
35
+ const held = heldSlices(root);
36
+ for (const [id, s] of steps) {
37
+ const where = held.get(id);
38
+ if (s.phase === phase && s.step === first && s.state === 'todo' && where?.startsWith('origin/')) out.push({ id, error: `held in ${where}`, held: true });
39
+ }
40
+ for (const s of ready.filter((r) => steps.get(r.id).step === first)) {
41
+ try {
42
+ const { worktree, branch } = startSlice(root, cfg, s.id, onWarning ? { onWarning } : {});
43
+ out.push({ id: s.id, worktree, branch });
44
+ } catch (e) {
45
+ if (!(e instanceof BuildError || e instanceof GitError)) throw e;
46
+ out.push({ id: s.id, error: e.message });
47
+ }
48
+ }
49
+ return out.sort((a, b) => a.id.localeCompare(b.id, 'en', { numeric: true }));
50
+ }