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.
- package/LICENSE +21 -0
- package/README.md +253 -2
- package/bin/slicekit.js +4 -0
- package/package.json +23 -4
- package/src/adapters/githost/errors.js +17 -0
- package/src/adapters/githost/fixture.js +136 -0
- package/src/adapters/githost/gh-json.js +99 -0
- package/src/adapters/githost/github.js +127 -0
- package/src/adapters/githost/index.js +12 -0
- package/src/adapters/tracker/errors.js +53 -0
- package/src/adapters/tracker/fixture.js +71 -0
- package/src/adapters/tracker/github-issues.js +65 -0
- package/src/adapters/tracker/index.js +14 -0
- package/src/baseline.js +109 -0
- package/src/build/commit.js +201 -0
- package/src/build/decline.js +81 -0
- package/src/build/finish.js +155 -0
- package/src/build/order.js +158 -0
- package/src/build/overlap.js +173 -0
- package/src/build/parallel.js +50 -0
- package/src/build/pr.js +263 -0
- package/src/build/record.js +28 -0
- package/src/build/red.js +207 -0
- package/src/build/review.js +123 -0
- package/src/build/sync.js +47 -0
- package/src/build/verdict.js +410 -0
- package/src/build/worktree.js +169 -0
- package/src/check/ci-event.js +52 -0
- package/src/check/context.js +129 -0
- package/src/check/index.js +140 -0
- package/src/check/rules/.gitkeep +0 -0
- package/src/check/rules/ci-body.js +22 -0
- package/src/check/rules/ci-title.js +43 -0
- package/src/check/rules/citations.js +224 -0
- package/src/check/rules/commands.js +146 -0
- package/src/check/rules/coverage.js +248 -0
- package/src/check/rules/hooks.js +58 -0
- package/src/check/rules/journal.js +17 -0
- package/src/check/rules/layout.js +56 -0
- package/src/check/rules/managed.js +31 -0
- package/src/check/rules/queue.js +106 -0
- package/src/check/rules/references.js +249 -0
- package/src/check/rules/style.js +177 -0
- package/src/check/rules/trailer.js +67 -0
- package/src/cli/baseline.js +66 -0
- package/src/cli/branch.js +86 -0
- package/src/cli/build.js +239 -0
- package/src/cli/check.js +40 -0
- package/src/cli/decide.js +59 -0
- package/src/cli/gaps.js +73 -0
- package/src/cli/hook.js +28 -0
- package/src/cli/index.js +83 -0
- package/src/cli/init.js +96 -0
- package/src/cli/instructions.js +63 -0
- package/src/cli/intake.js +107 -0
- package/src/cli/journal.js +82 -0
- package/src/cli/plan.js +29 -0
- package/src/cli/pr.js +83 -0
- package/src/cli/process.js +59 -0
- package/src/cli/ready-label.js +119 -0
- package/src/cli/review.js +64 -0
- package/src/cli/spec.js +31 -0
- package/src/cli/stage.js +37 -0
- package/src/cli/state.js +106 -0
- package/src/cli/status.js +108 -0
- package/src/cli/update.js +62 -0
- package/src/cli/workflow.js +48 -0
- package/src/config.js +203 -0
- package/src/decisions.js +289 -0
- package/src/evidence.js +27 -0
- package/src/fs.js +38 -0
- package/src/gaps.js +271 -0
- package/src/git.js +209 -0
- package/src/githooks.js +37 -0
- package/src/hook-cli.js +63 -0
- package/src/hooks/io.js +205 -0
- package/src/hooks/paths.js +82 -0
- package/src/hooks/pre-bash.js +715 -0
- package/src/hooks/pre-compact.js +139 -0
- package/src/hooks/pre-edit.js +170 -0
- package/src/hooks/session-end.js +118 -0
- package/src/hooks/session-start.js +209 -0
- package/src/hooks/shapes.js +103 -0
- package/src/hooks/stop.js +37 -0
- package/src/hooks/subagent-marker.js +88 -0
- package/src/hooks/subagent-start.js +100 -0
- package/src/hooks/subagent-stop.js +106 -0
- package/src/ids.js +43 -0
- package/src/init.js +276 -0
- package/src/instructions.js +235 -0
- package/src/intake.js +409 -0
- package/src/journal.js +326 -0
- package/src/lock.js +35 -0
- package/src/markdown.js +155 -0
- package/src/paths.js +33 -0
- package/src/plan.js +25 -0
- package/src/pr.js +73 -0
- package/src/prbody.js +266 -0
- package/src/ready-label.js +107 -0
- package/src/redact.js +33 -0
- package/src/render/compare.js +23 -0
- package/src/render/entry.js +101 -0
- package/src/render/index.js +27 -0
- package/src/render/managed.js +128 -0
- package/src/render/manifest.js +24 -0
- package/src/render/settings.js +76 -0
- package/src/render/update.js +151 -0
- package/src/slicefile.js +173 -0
- package/src/spec-verify.js +58 -0
- package/src/stage.js +325 -0
- package/src/state/build.js +156 -0
- package/src/state/covers.js +58 -0
- package/src/state/index.js +191 -0
- package/src/state/sync.js +64 -0
- package/src/state/transitions.js +282 -0
- package/src/verdict.js +203 -0
- package/src/which.js +37 -0
- package/src/workflow.js +177 -0
- package/src/worktrees.js +68 -0
- package/templates/claude-code/agents/auditor.md +7 -0
- package/templates/claude-code/agents/designer.md +7 -0
- package/templates/claude-code/agents/developer.md +7 -0
- package/templates/claude-code/agents/fixer.md +7 -0
- package/templates/claude-code/agents/ops.md +7 -0
- package/templates/claude-code/agents/reviewer.md +7 -0
- package/templates/claude-code/commands/slicekit-audit.md +7 -0
- package/templates/claude-code/commands/slicekit-build.md +7 -0
- package/templates/claude-code/commands/slicekit-gaps.md +6 -0
- package/templates/claude-code/commands/slicekit-intake.md +7 -0
- package/templates/claude-code/commands/slicekit-ops.md +7 -0
- package/templates/claude-code/commands/slicekit-plan.md +6 -0
- package/templates/claude-code/commands/slicekit-release.md +7 -0
- package/templates/claude-code/commands/slicekit-review.md +7 -0
- package/templates/claude-code/commands/slicekit-specify.md +6 -0
- package/templates/claude-code/commands/slicekit.md +7 -0
- package/templates/claude-code/hooks.json +90 -0
- package/templates/claude-code/manifest.json +171 -0
- package/templates/claude-code/skills/slicekit-ids/SKILL.md +16 -0
- package/templates/claude-code/skills/slicekit-loop/SKILL.md +23 -0
- package/templates/claude-code/skills/slicekit-writing/SKILL.md +24 -0
- package/templates/docs/BUILD.md +5 -0
- package/templates/docs/decisions.md +15 -0
- package/templates/docs/intake/.keep +0 -0
- package/templates/docs/observability.md +25 -0
- package/templates/docs/phases/.keep +0 -0
- package/templates/docs/platform.md +25 -0
- package/templates/docs/releases/.keep +0 -0
- package/templates/docs/runbook.md +21 -0
- package/templates/docs/spec/00-overview.md +8 -0
- package/templates/docs/spec/contracts/.keep +0 -0
- package/templates/docs/spec/gaps.md +6 -0
- package/templates/docs/spec/stack.md +3 -0
- package/templates/githooks/pre-commit +59 -0
- package/templates/githooks/pre-merge-commit +59 -0
- package/templates/githooks/prepare-commit-msg +74 -0
- package/templates/instructions/agents/auditor.md +33 -0
- package/templates/instructions/agents/designer.md +21 -0
- package/templates/instructions/agents/developer.md +49 -0
- package/templates/instructions/agents/fixer.md +41 -0
- package/templates/instructions/agents/ops.md +21 -0
- package/templates/instructions/agents/reviewer.md +63 -0
- package/templates/instructions/commands/build.md +234 -0
- package/templates/instructions/commands/gaps.md +65 -0
- package/templates/instructions/commands/intake.md +90 -0
- package/templates/instructions/commands/plan.md +60 -0
- package/templates/instructions/commands/review.md +117 -0
- package/templates/instructions/commands/specify.md +49 -0
- package/templates/style.json +11 -0
- package/templates/workflow/pins.json +6 -0
- package/templates/workflow/slicekit.yml +110 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// `build sync` (REQ-2.8): a slice worktree fast-forwarded to its branch on origin. Two worktrees can
|
|
2
|
+
// hold a slice once `review start` made the review one, and both push to the slice branch: the one
|
|
3
|
+
// that did not push is behind, and `build pr`, `build verdict` and `build finish` refuse it before
|
|
4
|
+
// pushing until it takes the other's commits here.
|
|
5
|
+
import { GitError, behindUpstream, git, headSha } from '../git.js';
|
|
6
|
+
import { BuildError, findWorktree } from './worktree.js';
|
|
7
|
+
|
|
8
|
+
export const commits = (n) => `${n} commit${n === 1 ? '' : 's'}`;
|
|
9
|
+
|
|
10
|
+
// The commits of the upstream as the last fetch left it that HEAD lacks; 0 without one.
|
|
11
|
+
function behindLastFetch(wt) {
|
|
12
|
+
try {
|
|
13
|
+
return Number(git(wt, ['rev-list', '--count', 'HEAD..@{u}']));
|
|
14
|
+
} catch (e) {
|
|
15
|
+
if (!(e instanceof GitError)) throw e;
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Refuses, before anything is pushed, a worktree whose upstream has commits it lacks. A fetch that
|
|
21
|
+
// fails is git's refusal, unless `onFetchFail` says otherwise: 'last-fetch' judges on the last fetch
|
|
22
|
+
// (`build verdict` finishing a round already recorded, whose push failed: nothing new is recorded,
|
|
23
|
+
// and git refuses a push that is not a fast-forward anyway); a string is the refusal to give.
|
|
24
|
+
export function assertNotBehind(wt, branch, id, { onFetchFail } = {}) {
|
|
25
|
+
let n;
|
|
26
|
+
try {
|
|
27
|
+
n = behindUpstream(wt);
|
|
28
|
+
} catch (e) {
|
|
29
|
+
if (!(e instanceof GitError) || onFetchFail === undefined) throw e;
|
|
30
|
+
if (onFetchFail !== 'last-fetch') throw new BuildError(onFetchFail);
|
|
31
|
+
n = behindLastFetch(wt);
|
|
32
|
+
}
|
|
33
|
+
if (n > 0) throw new BuildError(`${branch} is ${commits(n)} behind origin; run slicekit build sync ${id}`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// -> {head, behind}: the worktree's head after the fast-forward, and how many commits it took.
|
|
37
|
+
export function syncWorktree(root, cfg, id, { worktree } = {}) {
|
|
38
|
+
const held = findWorktree(root, id, { worktree });
|
|
39
|
+
const wt = held.path;
|
|
40
|
+
// behindUpstream fetches the upstream's remote first; 0 without an upstream.
|
|
41
|
+
const behind = behindUpstream(wt);
|
|
42
|
+
if (behind === 0) return { head: headSha(wt), behind };
|
|
43
|
+
const ahead = Number(git(wt, ['rev-list', '--count', '@{u}..HEAD']));
|
|
44
|
+
if (ahead > 0) throw new BuildError(`${held.branch} has diverged from origin; resolve it by hand`);
|
|
45
|
+
git(wt, ['pull', '-q', '--no-rebase', '--ff-only']);
|
|
46
|
+
return { head: headSha(wt), behind };
|
|
47
|
+
}
|
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
// `build verdict` (REQ-2.11, REQ-2.6 step 6): one review round of a slice's pull request. The
|
|
2
|
+
// reviewer writes its verdict into the session root; this checks it, moves it into the slice
|
|
3
|
+
// worktree at `.slicekit/reviews/<P-S>-r<k>.md`, commits it, records `in-review`, pushes, and says
|
|
4
|
+
// what comes next. Every refusal comes before anything moves. A run that stopped part way (moved but
|
|
5
|
+
// not committed, committed but not recorded, recorded but not pushed) finishes on a re-run with the
|
|
6
|
+
// same file name.
|
|
7
|
+
//
|
|
8
|
+
// Two in-loop rounds (D-18): a third is refused before anything moves, and a blocker left at round 2
|
|
9
|
+
// records `changes-requested` and stops the loop with the pull request still a draft. After every
|
|
10
|
+
// verdict the body's "Reviewer blocked" names each blocker and whether it was fixed.
|
|
11
|
+
//
|
|
12
|
+
// Finding IDs name one finding for the whole slice: a finding that survives keeps its ID, a new one
|
|
13
|
+
// takes a number never used before in the slice (B and H counted apart). An ID absent from the
|
|
14
|
+
// previous verdict is new, so a finding that vanished and came back must take a new number.
|
|
15
|
+
import fs from 'node:fs';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { git, headSha, pushBranch } from '../git.js';
|
|
18
|
+
import { sliceFromBranch, verdictFileName, verdictFilePattern } from '../ids.js';
|
|
19
|
+
import { readSlice } from '../state/index.js';
|
|
20
|
+
import { headCovers } from '../state/covers.js';
|
|
21
|
+
import { INDEPENDENT_ONLY } from '../state/transitions.js';
|
|
22
|
+
import { bannedPhrasesIn } from '../check/rules/style.js';
|
|
23
|
+
import { PrBodyError, getSection, prBodyProblems, setSection } from '../prbody.js';
|
|
24
|
+
import { parseVerdict, verdictProblems } from '../verdict.js';
|
|
25
|
+
import { posixRel } from './red.js';
|
|
26
|
+
import { commitBookkeeping, recordState } from './record.js';
|
|
27
|
+
import { assertNotBehind } from './sync.js';
|
|
28
|
+
import { GitHostError } from '../adapters/githost/errors.js';
|
|
29
|
+
import { isReviewWorktreeAt, listWorktrees } from '../worktrees.js';
|
|
30
|
+
import { BuildError, findWorktree, samePath } from './worktree.js';
|
|
31
|
+
|
|
32
|
+
// The states a verdict is recorded from: the `in-review` edges. An independent verdict (D-39) is
|
|
33
|
+
// also recorded from in-review, ci-green and ready, and sends a green slice back to review.
|
|
34
|
+
const FROM = ['draft-pr', 'changes-requested'];
|
|
35
|
+
const fromStates = (independent) => (independent ? [...FROM, ...INDEPENDENT_ONLY] : FROM);
|
|
36
|
+
const orList = (xs) => (xs.length < 3 ? xs.join(' or ') : `${xs.slice(0, -1).join(', ')} or ${xs.at(-1)}`);
|
|
37
|
+
export const LOOP_ROUNDS = 2;
|
|
38
|
+
const REVIEWS = '.slicekit/reviews';
|
|
39
|
+
const BLOCKED = 'Reviewer blocked';
|
|
40
|
+
const ID = /^([BH])-([1-9]\d*)$/;
|
|
41
|
+
|
|
42
|
+
function readText(file, shown) {
|
|
43
|
+
try {
|
|
44
|
+
return fs.readFileSync(file, 'utf8');
|
|
45
|
+
} catch (e) {
|
|
46
|
+
throw new BuildError(`cannot read the verdict ${shown}: ${e.code ?? e.message}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// A recorded verdict's text as the commit that added it holds it: a hand edit of the working copy
|
|
51
|
+
// after recording changes nothing the kit judges.
|
|
52
|
+
export function committedVerdictText(wt, rel) {
|
|
53
|
+
const sha = git(wt, ['--literal-pathspecs', 'log', '-1', '--format=%H', '--diff-filter=A', '--', rel]);
|
|
54
|
+
if (sha === '') throw new BuildError(`the recorded verdict ${rel} is not committed`);
|
|
55
|
+
return git(wt, ['show', `${sha}:${rel}`]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A recorded verdict, parsed from its commit.
|
|
59
|
+
export const committedVerdict = (wt, rel) => parseVerdict(committedVerdictText(wt, rel), rel);
|
|
60
|
+
|
|
61
|
+
// Every finding ID of an earlier verdict, read from its commit, in round order.
|
|
62
|
+
function earlierIds(wt, verdicts) {
|
|
63
|
+
return [...verdicts]
|
|
64
|
+
.sort((a, b) => a.round - b.round)
|
|
65
|
+
.map((v) => committedVerdict(wt, v.path).findings.map((f) => f.id));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// One line per new ID that does not take a number above every number the slice has used.
|
|
69
|
+
function reusedNumbers(shown, ids, earlier) {
|
|
70
|
+
const previous = new Set(earlier.at(-1) ?? []);
|
|
71
|
+
const max = { B: 0, H: 0 };
|
|
72
|
+
for (const id of earlier.flat()) {
|
|
73
|
+
const m = ID.exec(id);
|
|
74
|
+
if (m) max[m[1]] = Math.max(max[m[1]], Number(m[2]));
|
|
75
|
+
}
|
|
76
|
+
const out = [];
|
|
77
|
+
for (const id of ids) {
|
|
78
|
+
const m = ID.exec(id);
|
|
79
|
+
if (!m || previous.has(id) || Number(m[2]) > max[m[1]]) continue;
|
|
80
|
+
out.push(`verdict ${shown}: ${id} is new but reuses a number; new findings take the next unused number (${m[1]}-${max[m[1]] + 1})`);
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The parsed verdict, or a refusal naming each problem: the shape, then the file's own Independent
|
|
86
|
+
// line against the name it was given.
|
|
87
|
+
function checked(text, shown, name, independent) {
|
|
88
|
+
const v = parseVerdict(text, shown);
|
|
89
|
+
const problems = verdictProblems(v).map((p) => `verdict ${shown}: ${p}`);
|
|
90
|
+
if (v.independent && !independent) problems.push(`verdict ${shown}: Independent does not match ${name}`);
|
|
91
|
+
if (problems.length > 0) throw new BuildError(problems.join('\n'));
|
|
92
|
+
return v;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Moves `from` to `to`; a copy and a removal when a rename cannot cross the two.
|
|
96
|
+
function move(from, to) {
|
|
97
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
98
|
+
try {
|
|
99
|
+
fs.renameSync(from, to);
|
|
100
|
+
} catch (e) {
|
|
101
|
+
if (e.code !== 'EXDEV') throw e;
|
|
102
|
+
fs.copyFileSync(from, to);
|
|
103
|
+
fs.rmSync(from);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// HEAD is this round's verdict commit: the kit's subject, adding `rel` and nothing else.
|
|
108
|
+
function landedByKit(wt, id, k, rel) {
|
|
109
|
+
return (
|
|
110
|
+
git(wt, ['log', '-1', '--format=%s', 'HEAD']) === `chore(slicekit): ${id} verdict r${k}` &&
|
|
111
|
+
git(wt, ['diff-tree', '--no-commit-id', '--name-status', '--no-renames', '-r', 'HEAD']) === `A\t${rel}`
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const tracked = (wt, rel) => git(wt, ['--literal-pathspecs', 'ls-files', '--', rel]) !== '';
|
|
116
|
+
|
|
117
|
+
// The verdict's text: from the session root, or from the worktree where a run that stopped part way
|
|
118
|
+
// left it (moved and not committed, or committed by the kit and not recorded).
|
|
119
|
+
function verdictSource(wt, id, k, src, dest, rel, shown) {
|
|
120
|
+
const here = !samePath(src, dest) && fs.existsSync(src);
|
|
121
|
+
const there = fs.existsSync(dest);
|
|
122
|
+
const moved = there && (!tracked(wt, rel) || landedByKit(wt, id, k, rel));
|
|
123
|
+
if (there && !moved) throw new BuildError(`${rel} is already in the worktree and was not put there by build verdict ${id}`);
|
|
124
|
+
if (here && moved && fs.readFileSync(src, 'utf8') !== fs.readFileSync(dest, 'utf8')) {
|
|
125
|
+
throw new BuildError(`${rel} in the worktree differs from ${shown}; remove the one not to record and re-run`);
|
|
126
|
+
}
|
|
127
|
+
return { text: readText(moved ? dest : src, shown), here, moved };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const inLoop = (verdicts) => verdicts.filter((x) => !x.independent).length;
|
|
131
|
+
|
|
132
|
+
// A verdict file's absolute path in the session root, with forward slashes: the reviewer works in
|
|
133
|
+
// the worktree, so a relative path would land there.
|
|
134
|
+
const inSessionRoot = (root, name) => path.resolve(root, ...REVIEWS.split('/'), name).split(path.sep).join('/');
|
|
135
|
+
|
|
136
|
+
// The absolute session-root path the next in-loop reviewer writes, `<root>/.slicekit/reviews/<P-S>-r<k>.md`
|
|
137
|
+
// with k the slice's verdict count plus one; null once the in-loop rounds are used (D-18). `build pr`
|
|
138
|
+
// and `build verdict` print it so the procedure never computes k.
|
|
139
|
+
export function nextVerdictPath(root, id, verdicts = []) {
|
|
140
|
+
// Once an independent review has given a verdict, the next review is a new session's `review start`.
|
|
141
|
+
if (inLoop(verdicts) >= LOOP_ROUNDS || verdicts.some((v) => v.independent)) return null;
|
|
142
|
+
return inSessionRoot(root, verdictFileName(id, verdicts.length + 1));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// The absolute session-root path an independent reviewer writes, `<root>/.slicekit/reviews/<P-S>i-r<k>.md`
|
|
146
|
+
// with k the slice's verdict count plus one: `review start` prints it.
|
|
147
|
+
export const independentVerdictPath = (root, id, verdicts = []) => inSessionRoot(root, verdictFileName(id, verdicts.length + 1, { independent: true }));
|
|
148
|
+
|
|
149
|
+
// The latest recorded verdict's session-root path, or null: `build verdict` with it re-prints that
|
|
150
|
+
// round's next step and records nothing again (a session resumed at in-review).
|
|
151
|
+
export function latestVerdictPath(root, verdicts = []) {
|
|
152
|
+
const last = verdicts.at(-1);
|
|
153
|
+
return last ? inSessionRoot(root, path.posix.basename(last.path)) : null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// The next verdict path after a round: only when the round asks for a fix or a should-have decision
|
|
157
|
+
// and another in-loop round is allowed; `stuck` and `ci` name none. After an independent verdict
|
|
158
|
+
// there is no in-loop path: the next independent round's path comes from `review start`.
|
|
159
|
+
const withNextPath = (root, id, result, verdicts, independent) => ({
|
|
160
|
+
...result,
|
|
161
|
+
verdictPath: !independent && (result.next === 'fix' || result.next === 'ask') ? nextVerdictPath(root, id, verdicts) : null,
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
// An independent verdict sits outside the in-loop cap (D-18): its blockers ask for a fix, never
|
|
165
|
+
// `stuck`, and without blockers it goes to CI; its should-haves are the review procedure's to list.
|
|
166
|
+
function outcome(k, v, verdicts, independent) {
|
|
167
|
+
const blockers = v.findings.filter((f) => f.kind === 'blocker').map((f) => f.id);
|
|
168
|
+
const shouldHaves = v.findings.filter((f) => f.kind === 'should-have').map((f) => f.id);
|
|
169
|
+
const roundsUsed = inLoop(verdicts);
|
|
170
|
+
let next = 'ci';
|
|
171
|
+
if (blockers.length > 0) next = independent || roundsUsed < LOOP_ROUNDS ? 'fix' : 'stuck';
|
|
172
|
+
else if (shouldHaves.length > 0 && !independent) next = 'ask';
|
|
173
|
+
return { round: k, blockers, shouldHaves, roundsUsed, next };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const push = (wt, cfg) => pushBranch(wt, { protectedBranches: cfg.protectedBranches, defaultBranch: cfg.defaultBranch });
|
|
177
|
+
|
|
178
|
+
const blockersOf = (v) => (v?.findings ?? []).filter((f) => f.kind === 'blocker');
|
|
179
|
+
|
|
180
|
+
// The longest "what is wrong" the line quotes, in characters, the closing `…` included.
|
|
181
|
+
const WHAT_MAX = 160;
|
|
182
|
+
|
|
183
|
+
// A finding's "what is wrong" as a code span: its backticks removed, cut to WHAT_MAX characters.
|
|
184
|
+
function quoted(wrong) {
|
|
185
|
+
const chars = Array.from(String(wrong).replace(/`/g, '').trim());
|
|
186
|
+
const cut = chars.length > WHAT_MAX ? `${chars.slice(0, WHAT_MAX - 1).join('')}…` : chars.join('');
|
|
187
|
+
return `\`${cut}\``;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// The pull request body's "Reviewer blocked" (REQ-2.10) over the slice's verdicts in round order,
|
|
191
|
+
// each `{round, findings, headSha?, independent?}` with findings as parseVerdict reads them. A
|
|
192
|
+
// blocker of an earlier round that the latest does not hold is fixed in the round after its last
|
|
193
|
+
// appearance when code changed between the two verdicts' heads; when only bookkeeping lies between
|
|
194
|
+
// them (`covers(from, to)`, by default the same sha), the next verdict just did not raise it. Each
|
|
195
|
+
// blocker of the latest is open after the round it was first seen in, or, when the loop stopped
|
|
196
|
+
// (`stuck`), not fixed after the latest round. `nothing` when there are none. Round numbers are
|
|
197
|
+
// shared with independent rounds, so each names the real round.
|
|
198
|
+
export function reviewerBlocked(verdicts, { stuck = false, covers = sameHead } = {}) {
|
|
199
|
+
const sorted = [...verdicts].sort((a, b) => a.round - b.round);
|
|
200
|
+
const latest = sorted.at(-1);
|
|
201
|
+
const open = new Set(blockersOf(latest).map((f) => f.id));
|
|
202
|
+
const seen = new Map();
|
|
203
|
+
for (const v of sorted) for (const f of blockersOf(v)) if (!seen.has(f.id)) seen.set(f.id, v.round);
|
|
204
|
+
// In order of first appearance, with the text of the last.
|
|
205
|
+
const fixed = new Map();
|
|
206
|
+
sorted.slice(0, -1).forEach((v, i) => {
|
|
207
|
+
for (const f of blockersOf(v)) {
|
|
208
|
+
if (open.has(f.id)) continue;
|
|
209
|
+
const after = sorted[i + 1];
|
|
210
|
+
const unchanged = typeof v.headSha === 'string' && typeof after.headSha === 'string' && covers(v.headSha, after.headSha);
|
|
211
|
+
const how = !unchanged ? 'fixed in' : after.independent ? 'not raised by the independent review in' : 'not raised in';
|
|
212
|
+
fixed.set(f.id, `${f.id} ${quoted(f.wrong)} — ${how} round ${after.round}`);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
const out = [...fixed.values()];
|
|
216
|
+
for (const f of blockersOf(latest)) {
|
|
217
|
+
out.push(`${f.id} ${quoted(f.wrong)} — ${stuck ? `not fixed after round ${latest.round}` : `open after round ${seen.get(f.id)}`}`);
|
|
218
|
+
}
|
|
219
|
+
return out.length > 0 ? out.join('; ') : 'nothing';
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// The recorded verdicts as reviewerBlocked takes them, read from their files in the worktree.
|
|
223
|
+
const parsedVerdicts = (wt, verdicts) =>
|
|
224
|
+
verdicts.map((x) => ({ round: x.round, findings: committedVerdict(wt, x.path).findings, headSha: x.headSha, independent: Boolean(x.independent) }));
|
|
225
|
+
|
|
226
|
+
const sameHead = (a, b) => a === b;
|
|
227
|
+
// Whether only the kit's bookkeeping lies between two verdicts' heads in the worktree.
|
|
228
|
+
const coversIn = (wt) => (a, b) => headCovers(wt, a, b);
|
|
229
|
+
|
|
230
|
+
const BREAKS = 'the section would break the body: ';
|
|
231
|
+
|
|
232
|
+
// The pull request body with "Reviewer blocked" set to `text` -> {next, problems}: `next` is null
|
|
233
|
+
// when the line is already `text`; `problems` are what the new body would add, judged under `cfg`.
|
|
234
|
+
function withBlocked(host, number, text, cfg) {
|
|
235
|
+
const pr = host.getPullRequest(number);
|
|
236
|
+
const body = pr.body ?? '';
|
|
237
|
+
if (getSection(body, BLOCKED) === text) return { next: null, problems: [] };
|
|
238
|
+
let next;
|
|
239
|
+
try {
|
|
240
|
+
next = setSection(body, BLOCKED, text);
|
|
241
|
+
} catch (e) {
|
|
242
|
+
if (!(e instanceof PrBodyError)) throw e;
|
|
243
|
+
const problems = e.message.startsWith(BREAKS) ? e.message.slice(BREAKS.length).split('; ') : [e.message];
|
|
244
|
+
return { next: null, problems };
|
|
245
|
+
}
|
|
246
|
+
const before = new Set(prBodyProblems(pr.title ?? '', body, cfg));
|
|
247
|
+
return { next, problems: prBodyProblems(pr.title ?? '', next, cfg).filter((p) => !before.has(p)) };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// Sets the pull request's "Reviewer blocked" from the recorded verdict files, writing the body only
|
|
251
|
+
// when the line changes.
|
|
252
|
+
function updateBlocked(wt, cfg, host, number, verdicts, stuck) {
|
|
253
|
+
const { next, problems } = withBlocked(host, number, reviewerBlocked(parsedVerdicts(wt, verdicts), { stuck, covers: coversIn(wt) }), cfg);
|
|
254
|
+
if (problems.length > 0) throw new BuildError(`cannot set "${BLOCKED}" on pull request #${number}: ${problems.join('; ')}`);
|
|
255
|
+
if (next !== null) host.updatePullRequestBody(number, next);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Each banned phrase (style.banned) in the verdict: by finding where a finding's text holds it, then
|
|
259
|
+
// any left in the rest of the file. The style rule checks the committed file, and the body quotes
|
|
260
|
+
// each "what is wrong".
|
|
261
|
+
function bannedProblems(cfg, v, text, shown) {
|
|
262
|
+
const banned = cfg.style?.banned ?? [];
|
|
263
|
+
const out = [];
|
|
264
|
+
const named = new Set();
|
|
265
|
+
for (const f of v.findings) {
|
|
266
|
+
for (const p of bannedPhrasesIn([f.wrong, f.why, f.verified].join('\n\n'), banned)) {
|
|
267
|
+
out.push(`verdict ${shown}: ${f.id} uses "${p}"; reword it`);
|
|
268
|
+
named.add(p.toLowerCase());
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
for (const p of bannedPhrasesIn(text, banned)) if (!named.has(p.toLowerCase())) out.push(`verdict ${shown}: uses "${p}"; reword it`);
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// The round is committed and recorded when this runs; a host failure says so, and a re-run of the
|
|
276
|
+
// same command resumes and finishes it.
|
|
277
|
+
function markDraft(host, number, round) {
|
|
278
|
+
try {
|
|
279
|
+
if (host.getPullRequest(number).draft === false) host.markDraft(number);
|
|
280
|
+
} catch (e) {
|
|
281
|
+
if (!(e instanceof GitHostError)) throw e;
|
|
282
|
+
throw new BuildError(`could not mark pull request #${number} draft: ${e.message}; round ${round} is recorded locally; run the same command again to finish`);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// After a round is recorded: a stopped loop records changes-requested (once); an independent verdict
|
|
287
|
+
// with blockers that sent a green slice back to review (D-39) marks a ready pull request draft again,
|
|
288
|
+
// so the host agrees with the state, and a clean one leaves it as it is, so GitHub does not notify
|
|
289
|
+
// its reviewers a second time; then the branch is pushed and the body's "Reviewer blocked" brought up to date.
|
|
290
|
+
function finish(wt, cfg, host, id, current, result, verdicts, independent) {
|
|
291
|
+
const stuck = result.next === 'stuck';
|
|
292
|
+
if (stuck && current.state === 'in-review') recordState(wt, cfg, id, 'changes-requested', {});
|
|
293
|
+
if (independent && current.state === 'in-review' && result.blockers.length > 0) markDraft(host, current.pr.number, result.round);
|
|
294
|
+
push(wt, cfg);
|
|
295
|
+
updateBlocked(wt, cfg, host, current.pr.number, verdicts, stuck);
|
|
296
|
+
return result;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// The path of the slice's review worktree, or null when review start has not made one.
|
|
300
|
+
function reviewWorktreeOf(root, id) {
|
|
301
|
+
const w = listWorktrees(root).find((x) => x.branch !== null && sliceFromBranch(x.branch) === id && isReviewWorktreeAt(x.path, id));
|
|
302
|
+
return w ? w.path : null;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// The verdict is given on the recorded head; code committed since has not been through build pr.
|
|
306
|
+
function assertBuilt(wt, id, current) {
|
|
307
|
+
if (!headCovers(wt, current.pr?.headSha ?? '', headSha(wt))) {
|
|
308
|
+
throw new BuildError(`${id} has commits since build pr; run slicekit build pr ${id} first`);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// -> {round, blockers, shouldHaves, roundsUsed, next, verdictPath}: `blockers` and `shouldHaves` are
|
|
313
|
+
// finding IDs; `next` is `fix`, `ask`, `ci`, or `stuck` when an in-loop verdict leaves blockers at the last round.
|
|
314
|
+
// `stuck` is returned, not thrown: the loop has stopped and changes-requested is recorded, and a
|
|
315
|
+
// caller must exit 1 on it (the CLI does). `verdictPath` is the next round's file (nextVerdictPath)
|
|
316
|
+
// on `fix` or `ask` of an in-loop verdict, else null.
|
|
317
|
+
//
|
|
318
|
+
// `independent` (D-39): the verdict of an independent review, named `<P-S>i-r<k>.md`, recorded from
|
|
319
|
+
// the review worktree `review start` makes, from draft-pr, changes-requested, in-review, ci-green or
|
|
320
|
+
// ready, outside the two in-loop rounds.
|
|
321
|
+
export function recordVerdict(root, cfg, host, id, file, { worktree, independent = false } = {}) {
|
|
322
|
+
// Without --worktree an independent verdict goes to the review worktree when there is one; with
|
|
323
|
+
// none, the build worktree is found and refused below.
|
|
324
|
+
const review = independent && worktree === undefined ? reviewWorktreeOf(root, id) : null;
|
|
325
|
+
const held = findWorktree(root, id, { worktree: review ?? worktree });
|
|
326
|
+
const wt = held.path;
|
|
327
|
+
const shown = typeof file === 'string' ? file.split(path.sep).join('/') : String(file);
|
|
328
|
+
const name = path.basename(String(file));
|
|
329
|
+
const m = verdictFilePattern(id, { independent }).exec(name);
|
|
330
|
+
if (!m) {
|
|
331
|
+
// The name and the flag disagree: an `i` name without --independent, or --independent without one.
|
|
332
|
+
const crossed = verdictFilePattern(id, { independent: !independent }).test(name);
|
|
333
|
+
const want = crossed ? `an independent verdict is named ${verdictFileName(id, '<k>', { independent: true })}` : `a verdict of ${id} is named ${verdictFileName(id, '<k>', { independent })}`;
|
|
334
|
+
throw new BuildError(want, 2);
|
|
335
|
+
}
|
|
336
|
+
const k = Number(m[2]);
|
|
337
|
+
const src = path.resolve(root, String(file));
|
|
338
|
+
const dest = path.join(wt, ...REVIEWS.split('/'), name);
|
|
339
|
+
const rel = posixRel(wt, dest);
|
|
340
|
+
|
|
341
|
+
const current = readSlice(wt, cfg, id);
|
|
342
|
+
const verdicts = current.verdicts ?? [];
|
|
343
|
+
|
|
344
|
+
// The building session never approves itself through its own worktree: an independent verdict is
|
|
345
|
+
// recorded only in the review worktree `review start` makes, decided by its path and its branch
|
|
346
|
+
// together, and never in the worktree `build start` made. That the session is fresh is the
|
|
347
|
+
// person's to keep (D-18).
|
|
348
|
+
if (independent && !isReviewWorktreeAt(held.path, id)) {
|
|
349
|
+
throw new BuildError(`an independent verdict is recorded from the review worktree; run slicekit review start ${current.pr?.number ?? '<PR>'} in a new session`);
|
|
350
|
+
}
|
|
351
|
+
// This round is the latest recorded: a run that stopped after recording it (before changes-requested,
|
|
352
|
+
// the push or the body). Finish what is left; record the round nothing more. The push carries only
|
|
353
|
+
// what build pr has seen.
|
|
354
|
+
const last = verdicts.at(-1);
|
|
355
|
+
const resuming = ['in-review', 'changes-requested'].includes(current.state) && last?.round === k && last.path === rel;
|
|
356
|
+
|
|
357
|
+
// Every path below pushes: a worktree behind its branch on origin takes the other worktree's
|
|
358
|
+
// commits first (build sync), before anything moves. Only a round already recorded is finished on
|
|
359
|
+
// the last fetch when origin cannot be reached; a new round needs a fresh one, so a stale worktree
|
|
360
|
+
// never records on a head origin has moved past.
|
|
361
|
+
assertNotBehind(wt, held.branch, id, {
|
|
362
|
+
onFetchFail: resuming ? 'last-fetch' : `could not reach origin to check ${held.branch}; a new verdict needs a fresh fetch`,
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
if (resuming) {
|
|
366
|
+
assertBuilt(wt, id, current);
|
|
367
|
+
// The round as committed: a hand edit of the working copy since does not change what it says.
|
|
368
|
+
const text = committedVerdictText(wt, rel);
|
|
369
|
+
if (!samePath(src, dest) && fs.existsSync(src)) {
|
|
370
|
+
if (fs.readFileSync(src, 'utf8').trim() !== text.trim()) throw new BuildError(`round ${k} of ${id} is already recorded from ${rel}; ${shown} differs from it`);
|
|
371
|
+
fs.rmSync(src);
|
|
372
|
+
}
|
|
373
|
+
const v = checked(text, rel, name, independent);
|
|
374
|
+
return withNextPath(root, id, finish(wt, cfg, host, id, current, outcome(k, v, verdicts, independent), verdicts, independent), verdicts, independent);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// D-18: two in-loop rounds; independent verdicts (D-39) do not count against them.
|
|
378
|
+
if (!independent && inLoop(verdicts) >= LOOP_ROUNDS) throw new BuildError('two review rounds used; the loop stopped (D-18)');
|
|
379
|
+
|
|
380
|
+
const from = fromStates(independent);
|
|
381
|
+
if (!from.includes(current.state)) {
|
|
382
|
+
throw new BuildError(`${id} is ${current.state}; build verdict runs from ${orList(from)}`);
|
|
383
|
+
}
|
|
384
|
+
if (k !== verdicts.length + 1) throw new BuildError(`the next verdict of ${id} is round ${verdicts.length + 1}, not ${k}`);
|
|
385
|
+
assertBuilt(wt, id, current);
|
|
386
|
+
|
|
387
|
+
const { text, here, moved } = verdictSource(wt, id, k, src, dest, rel, shown);
|
|
388
|
+
const v = checked(text, shown, name, independent);
|
|
389
|
+
const reused = reusedNumbers(shown, v.findings.map((f) => f.id), earlierIds(wt, verdicts));
|
|
390
|
+
if (reused.length > 0) throw new BuildError(reused.join('\n'));
|
|
391
|
+
const banned = bannedProblems(cfg, v, text, shown);
|
|
392
|
+
if (banned.length > 0) throw new BuildError(banned.join('\n'));
|
|
393
|
+
// The line this round would write, judged against the live body before anything moves.
|
|
394
|
+
const stuck = outcome(k, v, [...verdicts, { independent }], independent).next === 'stuck';
|
|
395
|
+
const line = reviewerBlocked([...parsedVerdicts(wt, verdicts), { round: k, findings: v.findings, headSha: current.pr.headSha, independent }], {
|
|
396
|
+
stuck,
|
|
397
|
+
covers: coversIn(wt),
|
|
398
|
+
});
|
|
399
|
+
const { problems } = withBlocked(host, current.pr.number, line, cfg);
|
|
400
|
+
if (problems.length > 0) {
|
|
401
|
+
throw new BuildError(problems.map((p) => `verdict ${shown}: the Reviewer blocked line would break the pull request body: ${p}`).join('\n'));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (here && moved) fs.rmSync(src);
|
|
405
|
+
else if (here) move(src, dest);
|
|
406
|
+
commitBookkeeping(wt, id, `verdict r${k}`, [rel]);
|
|
407
|
+
const blockers = v.findings.filter((f) => f.kind === 'blocker').length;
|
|
408
|
+
const state = recordState(wt, cfg, id, 'in-review', { verdict: { round: k, path: rel, blockers, independent } });
|
|
409
|
+
return withNextPath(root, id, finish(wt, cfg, host, id, state, outcome(k, v, state.verdicts, independent), state.verdicts, independent), state.verdicts, independent);
|
|
410
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// A slice's worktree (REQ-2.6 step 1): `build start` makes it at `<root>/.worktrees/P<n>-S-<nn>` on
|
|
2
|
+
// `slice/P<n>-S-<nn>-<descr>`, commits one empty claim and pushes it at once, so another clone's
|
|
3
|
+
// `build next` skips the slice; every later `build` subcommand finds it again from the slice ID.
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { GitError, assertRef, git, hasRemote, pushBranch } from '../git.js';
|
|
8
|
+
import { parseSliceAddr, sliceFromBranch } from '../ids.js';
|
|
9
|
+
import { findSliceFiles } from '../slicefile.js';
|
|
10
|
+
import { REVIEW_DESCR, branchPrefix, listWorktrees, pad, reviewBranch, reviewWorktreeDir, samePath, worktreeDir } from '../worktrees.js';
|
|
11
|
+
import { readSlice } from '../state/index.js';
|
|
12
|
+
import { heldSlices, prepare, runnable, waitingOn } from './order.js';
|
|
13
|
+
|
|
14
|
+
// A refusal from a `build` step: `code` 1 refused, 2 usage or unknown ID (the CLI's exit code).
|
|
15
|
+
export class BuildError extends Error {
|
|
16
|
+
constructor(message, code = 1) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'BuildError';
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export { REVIEW_DESCR, branchPrefix, listWorktrees, reviewBranch, reviewWorktreeDir, samePath, worktreeDir } from '../worktrees.js';
|
|
24
|
+
|
|
25
|
+
// The review worktree `review start` makes for the slice at `addr`, known by its branch or its path.
|
|
26
|
+
export const isReviewWorktree = (root, addr, w) => w.branch === reviewBranch(addr) || samePath(w.path, reviewWorktreeDir(root, addr));
|
|
27
|
+
|
|
28
|
+
// The worktree holding `id`: the one `--worktree` names, else the build worktree. Without
|
|
29
|
+
// `--worktree` the review worktree is never picked, so the building session needs no flag while a
|
|
30
|
+
// review session runs; the review session always names its worktree.
|
|
31
|
+
export function findWorktree(root, id, { worktree } = {}) {
|
|
32
|
+
const all = listWorktrees(root).filter((w) => w.branch !== null && sliceFromBranch(w.branch) === id);
|
|
33
|
+
if (worktree !== undefined) {
|
|
34
|
+
const match = all.find((w) => samePath(w.path, path.resolve(root, worktree)));
|
|
35
|
+
if (!match) throw new BuildError(`${worktree} is not a worktree holding ${id}`);
|
|
36
|
+
return match;
|
|
37
|
+
}
|
|
38
|
+
const addr = parseSliceAddr(id);
|
|
39
|
+
const held = addr ? all.filter((w) => !isReviewWorktree(root, addr, w)) : all;
|
|
40
|
+
if (held.length === 0) throw new BuildError(`no worktree holds ${id}; run slicekit build start ${id}`);
|
|
41
|
+
if (held.length > 1) {
|
|
42
|
+
throw new BuildError(`two worktrees hold ${id}: ${held.map((w) => w.path).join(', ')}; pass --worktree`, 2);
|
|
43
|
+
}
|
|
44
|
+
return held[0];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function sliceFileOf(root, cfg, addr) {
|
|
48
|
+
const name = `S-${pad(addr.slice)}`;
|
|
49
|
+
return findSliceFiles(root, cfg).find(
|
|
50
|
+
(f) => f.phaseId === `P${addr.phase}` && (path.basename(f.path) === `${name}.md` || path.basename(f.path).startsWith(`${name}-`)),
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// `slice/P<n>-S-<nn>-<descr>` when git accepts it as a branch name and it is not the review
|
|
55
|
+
// branch, else a usage refusal. `file` is the slice file the descr was taken from, if it was. The
|
|
56
|
+
// review name is refused in any case: on a case-insensitive file system `Review` is the same ref.
|
|
57
|
+
function branchName(root, addr, descr, file) {
|
|
58
|
+
const name = `${branchPrefix(addr)}-${descr}`;
|
|
59
|
+
if (descr.toLowerCase() === REVIEW_DESCR) {
|
|
60
|
+
const from = file ? `the slice file ${file} gives that name, so ` : '';
|
|
61
|
+
throw new BuildError(`the branch name ${name} is kept for the review worktree; ${from}choose another --descr`, 2);
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
assertRef(name);
|
|
65
|
+
git(root, ['check-ref-format', '--branch', name]);
|
|
66
|
+
} catch (e) {
|
|
67
|
+
if (!(e instanceof GitError)) throw e;
|
|
68
|
+
throw new BuildError(`branch name ${name} is not valid; pass --descr`, 2);
|
|
69
|
+
}
|
|
70
|
+
return name;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// The slice's branches as origin has them now, not as the last fetch saw them.
|
|
74
|
+
function claimsOnOrigin(root, id) {
|
|
75
|
+
const out = git(root, ['ls-remote', '--heads', 'origin']);
|
|
76
|
+
return (out === '' ? [] : out.split('\n'))
|
|
77
|
+
.map((l) => l.split(/\s+/)[1] ?? '')
|
|
78
|
+
.filter((ref) => ref.startsWith('refs/heads/'))
|
|
79
|
+
.map((ref) => ref.slice('refs/heads/'.length))
|
|
80
|
+
.filter((b) => sliceFromBranch(b) === id);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const stderrWarning = (msg) => process.stderr.write(`${msg}\n`);
|
|
84
|
+
|
|
85
|
+
// `beforePush` is a test seam: it runs between the claim commit and its push.
|
|
86
|
+
export function startSlice(root, cfg, id, { descr, onWarning = stderrWarning, beforePush } = {}) {
|
|
87
|
+
prepare(root, cfg);
|
|
88
|
+
const addr = parseSliceAddr(id);
|
|
89
|
+
const file = addr && sliceFileOf(root, cfg, addr);
|
|
90
|
+
if (!file) throw new BuildError(`unknown slice ${id}`, 2);
|
|
91
|
+
let sliceFile;
|
|
92
|
+
if (descr === undefined) {
|
|
93
|
+
const m = /^S-\d+-(.+)\.md$/.exec(path.basename(file.path));
|
|
94
|
+
if (!m) throw new BuildError(`${path.basename(file.path)} names no description; pass --descr`, 2);
|
|
95
|
+
descr = m[1];
|
|
96
|
+
sliceFile = path.basename(file.path);
|
|
97
|
+
}
|
|
98
|
+
const branch = branchName(root, addr, descr, sliceFile);
|
|
99
|
+
const dir = worktreeDir(root, addr);
|
|
100
|
+
|
|
101
|
+
// A worktree of this clone on the slice's branch: the start already happened, so this is a resume
|
|
102
|
+
// at the state that worktree holds. Nothing is committed or pushed. The review worktree `review
|
|
103
|
+
// start` made is never the build worktree (M-3).
|
|
104
|
+
const mine = listWorktrees(root).find((w) => w.branch !== null && sliceFromBranch(w.branch) === id && !samePath(w.path, root) && !isReviewWorktree(root, addr, w));
|
|
105
|
+
if (mine) return { worktree: mine.path, branch: mine.branch, resumed: true, state: readSlice(mine.path, cfg, id).state };
|
|
106
|
+
|
|
107
|
+
const ready = runnable(root, cfg, { prepared: true });
|
|
108
|
+
const held = heldSlices(root).get(id);
|
|
109
|
+
if (held?.startsWith('origin/')) throw new BuildError(`${id} is already started in ${held}; another clone holds it`);
|
|
110
|
+
if (held) throw new BuildError(`${id} is already started in ${held}`);
|
|
111
|
+
if (fs.existsSync(dir)) throw new BuildError(`${dir} exists and holds no worktree of ${id}; remove it`);
|
|
112
|
+
if (!ready.some((s) => s.id === id)) {
|
|
113
|
+
const line = waitingOn(root, cfg, id);
|
|
114
|
+
if (line) throw new BuildError(line);
|
|
115
|
+
throw new BuildError(`${id} is ${readSlice(root, cfg, id).state}; build start runs from todo`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const base = assertRef(cfg.defaultBranch);
|
|
119
|
+
const origin = hasRemote(root, 'origin');
|
|
120
|
+
// prepare fetched origin and found HEAD equal to its default branch. Full refs: a tag named like
|
|
121
|
+
// the default branch is never what the branch is cut from. --no-track: never push to main.
|
|
122
|
+
const from = origin ? `refs/remotes/origin/${base}` : `refs/heads/${base}`;
|
|
123
|
+
git(root, ['worktree', 'add', '-q', '--no-track', '-b', branch, dir, from]);
|
|
124
|
+
const takeBack = () => {
|
|
125
|
+
git(root, ['worktree', 'remove', '--force', dir]);
|
|
126
|
+
git(root, ['branch', '-q', '-D', branch]);
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// The claim: one empty commit of this start's own, so a second push of the same name is not a
|
|
130
|
+
// fast-forward and origin refuses it. The nonce keeps two claims made in one second distinct.
|
|
131
|
+
try {
|
|
132
|
+
const nonce = randomBytes(8).toString('hex');
|
|
133
|
+
git(dir, ['commit', '-q', '--allow-empty', '-m', `chore(slicekit): ${id} started\n\nclaim ${nonce}\n\nSlice: ${id}`]);
|
|
134
|
+
} catch (e) {
|
|
135
|
+
takeBack();
|
|
136
|
+
throw e;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
if (!origin) {
|
|
140
|
+
onWarning(`slicekit: no origin; other clones will not see ${branch}`);
|
|
141
|
+
return { worktree: dir, branch };
|
|
142
|
+
}
|
|
143
|
+
beforePush?.();
|
|
144
|
+
try {
|
|
145
|
+
pushBranch(dir, { protectedBranches: cfg.protectedBranches, defaultBranch: cfg.defaultBranch });
|
|
146
|
+
} catch (e) {
|
|
147
|
+
if (!(e instanceof GitError)) throw e;
|
|
148
|
+
takeBack();
|
|
149
|
+
let other = null;
|
|
150
|
+
try {
|
|
151
|
+
other = claimsOnOrigin(root, id)[0] ?? null;
|
|
152
|
+
} catch (le) {
|
|
153
|
+
if (!(le instanceof GitError)) throw le;
|
|
154
|
+
}
|
|
155
|
+
if (other) throw new BuildError(`${id} was claimed by ${other} while starting`);
|
|
156
|
+
throw new BuildError(`could not push ${branch} (${e.stderr.split('\n')[0]}); ${id} was not started`);
|
|
157
|
+
}
|
|
158
|
+
// Another clone may have pushed a branch of another name for this slice between our fetch and our
|
|
159
|
+
// push: then we back out, deleting only the branch we just pushed. Whoever checks second backs out,
|
|
160
|
+
// whatever the names: a name tie-break would let a second checker with the lower name keep it
|
|
161
|
+
// while the first, which saw nothing, keeps it too.
|
|
162
|
+
const others = claimsOnOrigin(root, id).filter((b) => b !== branch);
|
|
163
|
+
if (others.length > 0) {
|
|
164
|
+
git(dir, ['push', '-q', 'origin', '--delete', branch]);
|
|
165
|
+
takeBack();
|
|
166
|
+
throw new BuildError(`${id} was claimed by ${others[0]} while starting`);
|
|
167
|
+
}
|
|
168
|
+
return { worktree: dir, branch };
|
|
169
|
+
}
|