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
package/src/build/pr.js
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// `build pr` (REQ-2.6 step 5, REQ-2.10, REQ-1.8): the test, lint and build commands and `slicekit
|
|
2
|
+
// check` pass in the worktree, then the branch is pushed, its draft pull request opened (or its body
|
|
3
|
+
// updated) with the REQ-2.10 body, and `draft-pr` recorded on the pushed head. Every refusal comes
|
|
4
|
+
// before the push. A run that stopped part way (pushed but not opened, opened but not recorded,
|
|
5
|
+
// recorded but the bookkeeping commit not pushed) finishes on a re-run without a second pull request.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { check } from '../check/index.js';
|
|
9
|
+
import { git, headSha, pushBranch, pushTarget } from '../git.js';
|
|
10
|
+
import { stateFileName } from '../ids.js';
|
|
11
|
+
import { kitPaths } from '../paths.js';
|
|
12
|
+
import { openOrUpdate } from '../pr.js';
|
|
13
|
+
import { PrBodyError, getSection, renderPrBody } from '../prbody.js';
|
|
14
|
+
import { readSlice } from '../state/index.js';
|
|
15
|
+
import { headCovers } from '../state/covers.js';
|
|
16
|
+
import { posixRel, runCommand, sliceIn, unusableRun } from './red.js';
|
|
17
|
+
import { commitBookkeeping, recordState } from './record.js';
|
|
18
|
+
import { overlapWith, planDefectLine } from './overlap.js';
|
|
19
|
+
import { assertNotBehind } from './sync.js';
|
|
20
|
+
import { nextVerdictPath } from './verdict.js';
|
|
21
|
+
import { BuildError, findWorktree } from './worktree.js';
|
|
22
|
+
|
|
23
|
+
const FROM = ['building', 'draft-pr', 'in-review', 'changes-requested', 'ci-green', 'ready'];
|
|
24
|
+
const NOTES_SHAPE = 'notes need tryIt (three steps) and skipped';
|
|
25
|
+
const NO_CHANGE = 'no operational change: the slice touches no configuration, infrastructure, migration, alert, queue or integration';
|
|
26
|
+
const RUNBOOK_REFUSAL = 'the slice touches operations; change the runbook or give notes.runbook "no operational change: <reason>"';
|
|
27
|
+
const COMMANDS = ['test', 'lint', 'build'];
|
|
28
|
+
// The sections the notes give: with no notes, the live body must hold each of them.
|
|
29
|
+
const NOTED_SECTIONS = ['Decisions', 'Runbook', 'Infra / migration', 'Try it', 'Skipped / not checked'];
|
|
30
|
+
|
|
31
|
+
const text = (v) => typeof v === 'string' && v.trim() !== '';
|
|
32
|
+
|
|
33
|
+
// The notes, from an object or a JSON file (relative to `root`): what only the agent can say.
|
|
34
|
+
function readNotes(root, notes) {
|
|
35
|
+
let n = notes;
|
|
36
|
+
if (typeof notes === 'string') {
|
|
37
|
+
try {
|
|
38
|
+
n = JSON.parse(fs.readFileSync(path.resolve(root, notes), 'utf8'));
|
|
39
|
+
} catch (e) {
|
|
40
|
+
throw new BuildError(`cannot read the notes file ${notes}: ${e.code ?? e.message}`, 2);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
if (n === null || typeof n !== 'object' || Array.isArray(n)) throw new BuildError(NOTES_SHAPE, 2);
|
|
44
|
+
// The field that is wrong is named with the type it needs: a list given for `skipped` must not read
|
|
45
|
+
// as a missing `skipped`.
|
|
46
|
+
const wrong = [];
|
|
47
|
+
if (!Array.isArray(n.tryIt) || n.tryIt.length !== 3 || !n.tryIt.every(text)) wrong.push('notes.tryIt must be a list of exactly three non-empty strings');
|
|
48
|
+
if (!text(n.skipped)) wrong.push('notes.skipped must be one non-empty string');
|
|
49
|
+
if (wrong.length > 0) throw new BuildError(`${NOTES_SHAPE}: ${wrong.join('; ')}`, 2);
|
|
50
|
+
if (n.decisions !== undefined && !(Array.isArray(n.decisions) && n.decisions.every(text))) {
|
|
51
|
+
throw new BuildError('notes.decisions must be a list of non-empty strings', 2);
|
|
52
|
+
}
|
|
53
|
+
for (const k of ['runbook', 'infra']) {
|
|
54
|
+
if (n[k] !== undefined && !text(n[k])) throw new BuildError(`notes.${k} must be a non-empty string`, 2);
|
|
55
|
+
}
|
|
56
|
+
return n;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const lines = (out) => out.split('\n').filter((l) => l !== '');
|
|
60
|
+
|
|
61
|
+
// The worktree is clean, or holds only the state file and BUILD.md of a draft-pr recording whose
|
|
62
|
+
// bookkeeping commit did not land: that commit is made now.
|
|
63
|
+
function cleanOrFinish(wt, cfg, id, current) {
|
|
64
|
+
// Paths from name lists, never from status columns: git() trims its output, and a leading space
|
|
65
|
+
// is part of the first porcelain line.
|
|
66
|
+
const changed = [
|
|
67
|
+
...lines(git(wt, ['diff', '--name-only', '--no-renames', 'HEAD'])),
|
|
68
|
+
...lines(git(wt, ['ls-files', '--others', '--exclude-standard'])),
|
|
69
|
+
];
|
|
70
|
+
const files = [...new Set(changed)];
|
|
71
|
+
if (files.length === 0) return;
|
|
72
|
+
const paths = kitPaths(wt, cfg);
|
|
73
|
+
const stateRel = posixRel(wt, path.join(paths.state, stateFileName(id)));
|
|
74
|
+
const buildRel = posixRel(wt, paths.build);
|
|
75
|
+
const onlyBookkeeping = files.includes(stateRel) && files.every((f) => f === stateRel || f === buildRel);
|
|
76
|
+
if (current.state === 'draft-pr' && onlyBookkeeping && pendingDraftPr(wt, stateRel, current)) {
|
|
77
|
+
commitBookkeeping(wt, id, 'draft-pr', files);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
throw new BuildError(`the worktree has uncommitted changes (${files.slice(0, 5).join(', ')}); build commit them first`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// The state on disk is HEAD's plus one move to draft-pr.
|
|
84
|
+
function pendingDraftPr(wt, stateRel, current) {
|
|
85
|
+
let committed;
|
|
86
|
+
try {
|
|
87
|
+
committed = JSON.parse(git(wt, ['show', `HEAD:${stateRel}`]));
|
|
88
|
+
} catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
const h = current.history ?? [];
|
|
92
|
+
return (
|
|
93
|
+
h.length === (committed.history ?? []).length + 1 &&
|
|
94
|
+
JSON.stringify(h.slice(0, -1)) === JSON.stringify(committed.history ?? []) &&
|
|
95
|
+
h.at(-1)?.to === 'draft-pr'
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Whether the branch changed the runbook since it left the default branch.
|
|
100
|
+
function runbookChanged(wt, cfg, rel) {
|
|
101
|
+
const origin = `refs/remotes/origin/${cfg.defaultBranch}`;
|
|
102
|
+
let from;
|
|
103
|
+
try {
|
|
104
|
+
git(wt, ['rev-parse', '--verify', '--quiet', origin]);
|
|
105
|
+
from = origin;
|
|
106
|
+
} catch {
|
|
107
|
+
from = `refs/heads/${cfg.defaultBranch}`;
|
|
108
|
+
}
|
|
109
|
+
const base = git(wt, ['merge-base', 'HEAD', from]);
|
|
110
|
+
return git(wt, ['--literal-pathspecs', 'diff', '--name-only', base, 'HEAD', '--', rel]) !== '';
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// The test run's pass and fail totals, from the last line naming each; the summary line when the
|
|
114
|
+
// output does not name both on separate lines.
|
|
115
|
+
function proofSummary(run) {
|
|
116
|
+
const all = run.output.split(/\r?\n/).map((l) => l.trim()).filter((l) => l !== '');
|
|
117
|
+
const pass = all.filter((l) => /\bpass(ed|es|ing)?\b/i.test(l)).at(-1);
|
|
118
|
+
const fail = all.filter((l) => /\bfail(ed|s|ures?)?\b/i.test(l)).at(-1);
|
|
119
|
+
return pass && fail && pass !== fail ? `${pass} · ${fail}` : run.summary;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Each declared command in the worktree; -> the test run's pass and fail totals.
|
|
123
|
+
function runCommands(wt, cfg) {
|
|
124
|
+
const commands = cfg.commands ?? {};
|
|
125
|
+
if (!text(commands.test)) throw new BuildError('commands.test is not declared in .slicekit/config.json');
|
|
126
|
+
let summary = '';
|
|
127
|
+
for (const name of COMMANDS) {
|
|
128
|
+
const command = commands[name];
|
|
129
|
+
if (!text(command)) continue;
|
|
130
|
+
const run = runCommand(wt, command);
|
|
131
|
+
const unusable = unusableRun(command, run);
|
|
132
|
+
if (unusable) throw unusable;
|
|
133
|
+
if (run.exit !== 0) throw new BuildError(`${name} failed (exit ${run.exit}): ${run.summary}`);
|
|
134
|
+
if (name === 'test') summary = proofSummary(run);
|
|
135
|
+
}
|
|
136
|
+
return summary;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function assertNoOverlap(wt, cfg, id) {
|
|
140
|
+
const defects = overlapWith(wt, cfg, id);
|
|
141
|
+
if (defects.length > 0) throw new BuildError(defects.map((d) => planDefectLine(id, d)).join('\n'));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function checkClean(wt) {
|
|
145
|
+
const result = check(wt);
|
|
146
|
+
if (result.exitCode === 0) return;
|
|
147
|
+
const found = result.lines.slice(0, -1).filter((l) => !l.startsWith('(baseline) '));
|
|
148
|
+
throw new BuildError(['slicekit check failed:', ...found.slice(0, 10), result.lines.at(-1)].join('\n'));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// `notes` may be left out for a slice that already has a pull request (the reviewing session does not
|
|
152
|
+
// have the building session's notes): each section the notes do not give keeps the live body's text.
|
|
153
|
+
export function openSlicePr(root, cfg, host, id, { notes, worktree } = {}) {
|
|
154
|
+
const given = notes === undefined ? null : readNotes(root, notes);
|
|
155
|
+
const held = findWorktree(root, id, { worktree });
|
|
156
|
+
const wt = held.path;
|
|
157
|
+
const current = readSlice(wt, cfg, id);
|
|
158
|
+
if (!FROM.includes(current.state)) throw new BuildError(`${id} is ${current.state}; build pr runs from building to ready`);
|
|
159
|
+
if (!given && !current.pr) throw new BuildError(`${id} has no pull request yet; build pr needs --notes to open it`, 2);
|
|
160
|
+
const slice = sliceIn(wt, cfg, id);
|
|
161
|
+
// Behind origin first: a head with commits origin has and this worktree lacks is synced, not
|
|
162
|
+
// judged against the reviewed head (a different refusal, below).
|
|
163
|
+
const { target } = pushTarget(wt);
|
|
164
|
+
assertNotBehind(wt, held.branch, id);
|
|
165
|
+
cleanOrFinish(wt, cfg, id, current);
|
|
166
|
+
// After a verdict, a return to draft-pr needs a new head (the state refuses the same one): refused
|
|
167
|
+
// here, before the push, rather than after it.
|
|
168
|
+
const afterReview = current.state !== 'building' && current.state !== 'draft-pr';
|
|
169
|
+
// A head that adds only bookkeeping (a verdict, the state, BUILD.md) to the reviewed one is the same work.
|
|
170
|
+
if (afterReview && current.pr && headCovers(wt, current.pr.headSha, headSha(wt))) {
|
|
171
|
+
throw new BuildError(`${id} has nothing new since review of ${current.pr.headSha.slice(0, 7)}; push a fix to return to draft-pr`);
|
|
172
|
+
}
|
|
173
|
+
// A path another slice of the same Order step already changes on origin (D-06): a plan defect,
|
|
174
|
+
// refused before the notes, the body and the commands, so a defect in the plan stops the run before
|
|
175
|
+
// minutes of test runs, and before anything is pushed. After the behind-origin refusal, which a
|
|
176
|
+
// sync answers, and the nothing-new refusal, whose head was pushed and checked before. Asked again,
|
|
177
|
+
// with a fresh fetch, just before the first push (below).
|
|
178
|
+
assertNoOverlap(wt, cfg, id);
|
|
179
|
+
|
|
180
|
+
// The pull request already open for the branch, and its live body, asked once when first needed.
|
|
181
|
+
let asked = null;
|
|
182
|
+
const openPr = () => {
|
|
183
|
+
if (!asked) {
|
|
184
|
+
const open = host.pullRequestForBranch(target);
|
|
185
|
+
asked = { open, livePr: open ? host.getPullRequest(open.number) : null };
|
|
186
|
+
}
|
|
187
|
+
return asked;
|
|
188
|
+
};
|
|
189
|
+
const kept = (name, fallback) => {
|
|
190
|
+
const { open, livePr } = openPr();
|
|
191
|
+
return (open ? getSection(livePr?.body ?? '', name) : null) ?? fallback;
|
|
192
|
+
};
|
|
193
|
+
// A field the notes give, else the live body's section when one is open, else the fallback.
|
|
194
|
+
const noted = (field, name, fallback) => given?.[field] ?? kept(name, fallback);
|
|
195
|
+
// With no notes, every section they would give comes from the live body: checked before any command runs.
|
|
196
|
+
if (!given) {
|
|
197
|
+
const { open, livePr } = openPr();
|
|
198
|
+
if (!open) throw new BuildError(`${id} has no open pull request; build pr needs --notes to open one`, 2);
|
|
199
|
+
const missing = NOTED_SECTIONS.find((name) => !(getSection(livePr?.body ?? '', name) ?? '').trim());
|
|
200
|
+
if (missing) throw new BuildError(`the pull request body has no "${missing}"; pass --notes <file> to supply it`);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const runbookRel = cfg.docsRoot === '.' ? 'runbook.md' : `${cfg.docsRoot}/runbook.md`;
|
|
204
|
+
const changed = runbookChanged(wt, cfg, runbookRel);
|
|
205
|
+
const runbookNote = changed ? null : (given?.runbook ?? (current.pr ? kept('Runbook', null) : null));
|
|
206
|
+
if (slice.runbook && !changed && !(runbookNote ?? '').trim().startsWith('no operational change')) {
|
|
207
|
+
throw new BuildError(RUNBOOK_REFUSAL);
|
|
208
|
+
}
|
|
209
|
+
const summary = runCommands(wt, cfg);
|
|
210
|
+
checkClean(wt);
|
|
211
|
+
|
|
212
|
+
// The pull request already open for the branch: the recorded one once there is a recording.
|
|
213
|
+
const { open, livePr } = openPr();
|
|
214
|
+
if (current.state !== 'building' && (!open || open.number !== current.pr?.number)) {
|
|
215
|
+
throw new BuildError(`pull request #${current.pr?.number} of ${id} is not open for ${target}`);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const title = `[${id}] ${slice.name}`;
|
|
219
|
+
let body;
|
|
220
|
+
try {
|
|
221
|
+
body = renderPrBody({
|
|
222
|
+
slice: id,
|
|
223
|
+
name: slice.name,
|
|
224
|
+
sections: {
|
|
225
|
+
'Done when': slice.doneWhen.map((c, i) => `${i + 1}. ${c}`).join(' '),
|
|
226
|
+
Proof: `\`${cfg.commands.test}\` → ${summary} · CI: pending`,
|
|
227
|
+
Decisions: given?.decisions === undefined ? kept('Decisions', 'none') : given.decisions.join('; ') || 'none',
|
|
228
|
+
Runbook: changed ? `changed: ${runbookRel}` : (runbookNote ?? NO_CHANGE),
|
|
229
|
+
'Infra / migration': noted('infra', 'Infra / migration', 'none'),
|
|
230
|
+
'Try it': given ? given.tryIt.map((s, i) => `${i + 1}. ${s.trim()}`).join(' ') : kept('Try it', ''),
|
|
231
|
+
'Reviewer blocked': kept('Reviewer blocked', 'nothing'),
|
|
232
|
+
'Should-haves declined': kept('Should-haves declined', 'none'),
|
|
233
|
+
'Skipped / not checked': given ? given.skipped : kept('Skipped / not checked', ''),
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
} catch (e) {
|
|
237
|
+
if (e instanceof PrBodyError) throw new BuildError(e.message);
|
|
238
|
+
throw e;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Again just before openOrUpdate's push: another slice of the step may have pushed while the
|
|
242
|
+
// commands ran. What is left is the moment between this fetch and the push; only a check on the
|
|
243
|
+
// server could close that.
|
|
244
|
+
assertNoOverlap(wt, cfg, id);
|
|
245
|
+
const made = openOrUpdate(wt, cfg, host, { title, body, draft: true });
|
|
246
|
+
// The absolute session-root path the next in-loop reviewer writes (null once the loop's rounds are
|
|
247
|
+
// used or an independent verdict is recorded): recording draft-pr adds no verdict, so the count read before is the count after.
|
|
248
|
+
const verdictPath = nextVerdictPath(root, id, current.verdicts ?? []);
|
|
249
|
+
// The reviewer writes there at once: its directory is made here, as the path is printed.
|
|
250
|
+
if (verdictPath) fs.mkdirSync(path.dirname(verdictPath), { recursive: true });
|
|
251
|
+
const result = { number: made.number, url: made.url, created: made.created, verdictPath };
|
|
252
|
+
// `build finish` marked it ready; a slice back at draft-pr has a draft pull request again.
|
|
253
|
+
if (livePr?.draft === false) host.markDraft(made.number);
|
|
254
|
+
// At draft-pr there is no draft-pr → draft-pr move: the reviewer reads the live head.
|
|
255
|
+
if (current.state === 'draft-pr') return result;
|
|
256
|
+
recordState(wt, cfg, id, 'draft-pr', {
|
|
257
|
+
testExit: 0,
|
|
258
|
+
checkExit: 0,
|
|
259
|
+
pr: { number: made.number, url: made.url, headSha: headSha(wt), title },
|
|
260
|
+
});
|
|
261
|
+
pushBranch(wt, { protectedBranches: cfg.protectedBranches, defaultBranch: cfg.defaultBranch });
|
|
262
|
+
return result;
|
|
263
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// State moves of a `build` step (REQ-1.8, D-35): setState, BUILD.md, and one bookkeeping commit that
|
|
2
|
+
// touches nothing else, so a verdict given on the head before it still holds.
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { exists, readText, writeText } from '../fs.js';
|
|
5
|
+
import { commitPaths } from '../git.js';
|
|
6
|
+
import { stateFileName } from '../ids.js';
|
|
7
|
+
import { kitPaths } from '../paths.js';
|
|
8
|
+
import { renderBuild } from '../state/build.js';
|
|
9
|
+
import { setState } from '../state/index.js';
|
|
10
|
+
|
|
11
|
+
const posixRel = (wt, abs) => path.relative(wt, abs).split(path.sep).join('/');
|
|
12
|
+
|
|
13
|
+
export function commitBookkeeping(wt, id, what, paths) {
|
|
14
|
+
return commitPaths(wt, paths, `chore(slicekit): ${id} ${what}\n\nSlice: ${id}`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// A TransitionError from setState passes through unchanged, before anything is written.
|
|
18
|
+
export function recordState(wt, cfg, id, to, evidence) {
|
|
19
|
+
const state = setState(wt, cfg, id, to, evidence);
|
|
20
|
+
const paths = kitPaths(wt, cfg);
|
|
21
|
+
const before = exists(paths.build) ? readText(paths.build) : '';
|
|
22
|
+
const after = renderBuild(wt, cfg, before);
|
|
23
|
+
if (after !== before) writeText(paths.build, after);
|
|
24
|
+
const files = [posixRel(wt, path.join(paths.state, stateFileName(id)))];
|
|
25
|
+
if (exists(paths.build)) files.push(posixRel(wt, paths.build));
|
|
26
|
+
commitBookkeeping(wt, id, to, files);
|
|
27
|
+
return state;
|
|
28
|
+
}
|
package/src/build/red.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// `build red` (REQ-2.6 step 3, D-10): the developer's tests must fail before any code is written.
|
|
2
|
+
// They are committed alone, recorded as the slice's frozen tests at `tests-red`, and the slice moves
|
|
3
|
+
// on to `building`.
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { readText } from '../fs.js';
|
|
8
|
+
import { commitPaths, git, headSha } from '../git.js';
|
|
9
|
+
import { stateFileName } from '../ids.js';
|
|
10
|
+
import { kitPaths } from '../paths.js';
|
|
11
|
+
import { findSliceFiles, parseSliceFile } from '../slicefile.js';
|
|
12
|
+
import { readSlice } from '../state/index.js';
|
|
13
|
+
import { commitBookkeeping, recordState } from './record.js';
|
|
14
|
+
import { BuildError, findWorktree } from './worktree.js';
|
|
15
|
+
|
|
16
|
+
const nonEmpty = (text) => text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l !== '');
|
|
17
|
+
const TOTALS = /\b(pass|fail|tests?)\b/i;
|
|
18
|
+
|
|
19
|
+
// Runs `command` through the shell in `wt`. `summary` is the last output line naming pass, fail or
|
|
20
|
+
// tests (a runner's totals), else the last line of stdout, else of stderr; `output` is stdout then
|
|
21
|
+
// stderr. `error` is null for a run that finished, else why it did not (it could not be spawned, a
|
|
22
|
+
// signal ended it, or its output overflowed `maxBuffer`); its `exit` is then 1.
|
|
23
|
+
// NODE_TEST_CONTEXT is dropped: inherited from a `node --test` parent, it turns the team's own
|
|
24
|
+
// `node --test` into a child reporter that exits 0 whatever its tests do.
|
|
25
|
+
export function runCommand(wt, command, { maxBuffer = 256 * 1024 * 1024 } = {}) {
|
|
26
|
+
const env = { ...process.env };
|
|
27
|
+
delete env.NODE_TEST_CONTEXT;
|
|
28
|
+
const r = spawnSync(command, { cwd: wt, shell: true, env, encoding: 'utf8', maxBuffer });
|
|
29
|
+
const stdout = r.stdout ?? '';
|
|
30
|
+
const stderr = r.stderr ?? '';
|
|
31
|
+
const finished = typeof r.status === 'number' && !r.error;
|
|
32
|
+
const error = finished ? null : r.error ? String(r.error.code ?? r.error.message) : `signal ${r.signal}`;
|
|
33
|
+
const lines = [...nonEmpty(stdout), ...nonEmpty(stderr)];
|
|
34
|
+
const summary = lines.filter((l) => TOTALS.test(l)).at(-1) ?? nonEmpty(stdout).at(-1) ?? nonEmpty(stderr).at(-1) ?? error ?? '';
|
|
35
|
+
return { exit: finished ? r.status : 1, summary, output: `${stdout}${stderr}`, error };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// A shell that found no such command, or npm that found no such script: the tests never ran.
|
|
39
|
+
const NOT_RUN_EXITS = [126, 127, 9009];
|
|
40
|
+
export function couldNotRun(run) {
|
|
41
|
+
if (NOT_RUN_EXITS.includes(run.exit)) return true;
|
|
42
|
+
if (process.platform === 'win32' && /is not recognized as an internal or external command/.test(run.output)) return true;
|
|
43
|
+
return /npm (ERR!|error) Missing script/.test(run.output);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const real = (p) => {
|
|
47
|
+
try {
|
|
48
|
+
return fs.realpathSync.native(p);
|
|
49
|
+
} catch {
|
|
50
|
+
return path.resolve(p);
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// Each given path, absolute or relative to the worktree and with either slash, as a POSIX path
|
|
55
|
+
// relative to the worktree; outside it is a usage error, and so is a path that is not a file.
|
|
56
|
+
function resolveTests(wt, tests) {
|
|
57
|
+
const list = (Array.isArray(tests) ? tests : String(tests ?? '').split(','))
|
|
58
|
+
.map((t) => t.trim())
|
|
59
|
+
.filter((t) => t !== '');
|
|
60
|
+
if (list.length === 0) throw new BuildError('--tests names no test file', 2);
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const given of list) {
|
|
63
|
+
const abs = path.resolve(wt, given.replace(/\\/g, '/'));
|
|
64
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) throw new BuildError(`${given} is not a file`, 2);
|
|
65
|
+
const posix = toWorktreePath(wt, given);
|
|
66
|
+
if (!out.includes(posix)) out.push(posix);
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// A path given absolute or relative to the worktree, with either slash, as a POSIX path relative to
|
|
72
|
+
// it; outside it is a usage error. An existing path is compared through real paths (8.3 names and
|
|
73
|
+
// links resolved); a missing one, as written.
|
|
74
|
+
export function toWorktreePath(wt, given) {
|
|
75
|
+
const abs = path.resolve(wt, String(given).trim().replace(/\\/g, '/'));
|
|
76
|
+
const there = fs.existsSync(abs);
|
|
77
|
+
const rel = path.relative(there ? real(wt) : path.resolve(wt), there ? real(abs) : abs);
|
|
78
|
+
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) throw new BuildError(`${given} is outside the worktree`, 2);
|
|
79
|
+
return rel.split(path.sep).join('/');
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function sliceIn(wt, cfg, id) {
|
|
83
|
+
for (const f of findSliceFiles(wt, cfg)) {
|
|
84
|
+
const slice = parseSliceFile(readText(f.path), f.path);
|
|
85
|
+
if (slice.id === id) return slice;
|
|
86
|
+
}
|
|
87
|
+
throw new BuildError(`unknown slice ${id}`, 2);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const posixRel = (wt, abs) => path.relative(wt, abs).split(path.sep).join('/');
|
|
91
|
+
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
92
|
+
|
|
93
|
+
// A path (POSIX, relative to the worktree) the kit owns: anything under `.slicekit/` or `.githooks/`,
|
|
94
|
+
// BUILD.md, the config, the slice file and `.claude/settings.json`. The kit's commands change these;
|
|
95
|
+
// a test or the developer's work never does.
|
|
96
|
+
export function isKitFile(wt, cfg, slice, rel) {
|
|
97
|
+
const paths = kitPaths(wt, cfg);
|
|
98
|
+
const key = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
|
|
99
|
+
const own = [paths.build, paths.config, slice.path, path.join(paths.claude, 'settings.json')].map((p) => posixRel(wt, p));
|
|
100
|
+
const dirs = [paths.kit, paths.githooks].map((p) => posixRel(wt, p));
|
|
101
|
+
return dirs.some((d) => key(rel).startsWith(`${key(d)}/`)) || own.some((o) => key(o) === key(rel));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// The kit's own files are never tests: freezing one would lock the kit out of its own bookkeeping.
|
|
105
|
+
function refuseKitFiles(wt, cfg, slice, tests) {
|
|
106
|
+
for (const t of tests) if (isKitFile(wt, cfg, slice, t)) throw new BuildError(`${t} is a kit file, not a test`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// A run that did not finish or never started is evidence of nothing, red or green.
|
|
110
|
+
export function unusableRun(command, run) {
|
|
111
|
+
if (run.error) return new BuildError(`${command} did not finish (${run.error}); a run that does not finish is not a failing test`);
|
|
112
|
+
if (couldNotRun(run)) return new BuildError(`${command} could not run (exit ${run.exit}): ${run.summary}`);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// The rows as { row, file, name }: `<file> » <name>`, or a bare `<file>` with no name.
|
|
117
|
+
function rows(slice) {
|
|
118
|
+
return slice.evaluation.map(({ test }) => {
|
|
119
|
+
const row = test.replace(/^`|`$/g, '').trim();
|
|
120
|
+
const at = row.indexOf(' » ');
|
|
121
|
+
return {
|
|
122
|
+
row,
|
|
123
|
+
file: (at === -1 ? row : row.slice(0, at)).trim(),
|
|
124
|
+
name: at === -1 ? null : row.slice(at + ' » '.length).trim(),
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const endsWithFile = (t, file) => t === file || t.endsWith(`/${file}`);
|
|
130
|
+
// The name inside one string literal on one line: between matching quotes or backticks.
|
|
131
|
+
const holdsName = (text, name) =>
|
|
132
|
+
["'", '"', '`'].some((q) => new RegExp(`${q}[^${q}\\n]*${escape(name)}[^${q}\\n]*${q}`).test(text));
|
|
133
|
+
|
|
134
|
+
// Every row names a listed file ending in <file> that holds <name> as a string; every listed file
|
|
135
|
+
// holds at least one row.
|
|
136
|
+
function checkEvaluation(wt, slice, tests) {
|
|
137
|
+
const all = rows(slice);
|
|
138
|
+
for (const { row, file, name } of all) {
|
|
139
|
+
const found = tests.some((t) => endsWithFile(t, file) && (name === null || holdsName(readText(path.join(wt, t)), name)));
|
|
140
|
+
if (!found) throw new BuildError(`evaluation test "${row}" is not in the test files`);
|
|
141
|
+
}
|
|
142
|
+
for (const t of tests) {
|
|
143
|
+
if (!all.some(({ file }) => endsWithFile(t, file))) throw new BuildError(`${t} holds no evaluation test`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// HEAD is this slice's red commit when it touches exactly the listed tests under the evaluation-set
|
|
148
|
+
// subject: the commit of an earlier run whose recording did not land.
|
|
149
|
+
function headIsRedCommit(wt, id, tests) {
|
|
150
|
+
const touched = git(wt, ['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD']).split('\n').filter(Boolean).sort();
|
|
151
|
+
const want = [...tests].sort();
|
|
152
|
+
const subject = git(wt, ['log', '-1', '--format=%s', 'HEAD']);
|
|
153
|
+
return touched.length === want.length && touched.every((t, i) => t === want[i]) && subject.startsWith(`test(${id}): evaluation set`);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// The listed tests with no change against HEAD (tracked and unmodified).
|
|
157
|
+
function unchanged(wt, tests) {
|
|
158
|
+
return tests.filter((t) => {
|
|
159
|
+
const tracked = git(wt, ['--literal-pathspecs', 'ls-files', '--', t]) !== '';
|
|
160
|
+
return tracked && git(wt, ['--literal-pathspecs', 'status', '--porcelain', '--', t]) === '';
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const noChange = (files) => new BuildError(`${files.join(', ')} have no change to commit; red needs the evaluation set as new or changed files`);
|
|
165
|
+
|
|
166
|
+
// A run from tests-red: setState wrote tests-red but its bookkeeping commit, or the move to building,
|
|
167
|
+
// did not land. The tests must be the frozen ones; nothing is run again.
|
|
168
|
+
function finishRed(wt, cfg, id, current, tests) {
|
|
169
|
+
const files = resolveTests(wt, tests).sort();
|
|
170
|
+
const frozen = [...current.frozenTests].sort();
|
|
171
|
+
if (files.length !== frozen.length || files.some((f, i) => f !== frozen[i])) {
|
|
172
|
+
throw new BuildError(`${id} is tests-red with frozen tests ${current.frozenTests.join(', ')}; pass the same --tests`);
|
|
173
|
+
}
|
|
174
|
+
const paths = kitPaths(wt, cfg);
|
|
175
|
+
const bookkeeping = [posixRel(wt, path.join(paths.state, stateFileName(id)))];
|
|
176
|
+
if (fs.existsSync(paths.build)) bookkeeping.push(posixRel(wt, paths.build));
|
|
177
|
+
commitBookkeeping(wt, id, 'tests-red', bookkeeping);
|
|
178
|
+
recordState(wt, cfg, id, 'building', {});
|
|
179
|
+
return { commit: current.redCommit, tests: current.frozenTests };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function red(root, cfg, id, { tests, worktree } = {}) {
|
|
183
|
+
const wt = findWorktree(root, id, { worktree }).path;
|
|
184
|
+
const current = readSlice(wt, cfg, id);
|
|
185
|
+
if (current.state === 'tests-red') return finishRed(wt, cfg, id, current, tests);
|
|
186
|
+
if (current.state !== 'todo') throw new BuildError(`${id} is ${current.state}; red runs from todo`);
|
|
187
|
+
const command = cfg.commands?.test ?? '';
|
|
188
|
+
if (command.trim() === '') throw new BuildError('commands.test is not declared in .slicekit/config.json');
|
|
189
|
+
const files = resolveTests(wt, tests);
|
|
190
|
+
const slice = sliceIn(wt, cfg, id);
|
|
191
|
+
refuseKitFiles(wt, cfg, slice, files);
|
|
192
|
+
checkEvaluation(wt, slice, files);
|
|
193
|
+
const same = unchanged(wt, files);
|
|
194
|
+
if (same.length > 0 && !headIsRedCommit(wt, id, files)) throw noChange(same);
|
|
195
|
+
|
|
196
|
+
const run = runCommand(wt, command);
|
|
197
|
+
const unusable = unusableRun(command, run);
|
|
198
|
+
if (unusable) throw unusable;
|
|
199
|
+
if (run.exit === 0) throw new BuildError(`the evaluation set must fail before the build; ${command} → exit 0: ${run.summary}`);
|
|
200
|
+
|
|
201
|
+
const made = commitPaths(wt, files, `test(${id}): evaluation set\n\nran: ${command} → exit ${run.exit}\n\nSlice: ${id}`);
|
|
202
|
+
if (made === null && !headIsRedCommit(wt, id, files)) throw noChange(files);
|
|
203
|
+
const commit = made ?? headSha(wt);
|
|
204
|
+
recordState(wt, cfg, id, 'tests-red', { commit, testExit: run.exit, tests: files });
|
|
205
|
+
recordState(wt, cfg, id, 'building', {});
|
|
206
|
+
return { commit, tests: files };
|
|
207
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// `review start <PR>` (REQ-2.8, D-39): a slice pull request's head in a fresh review worktree, for an
|
|
2
|
+
// independent review from a new session. The worktree is `<root>/.worktrees/review-P<n>-S-<nn>` on
|
|
3
|
+
// `slice/P<n>-S-<nn>-review`, the only place `build verdict --independent` records from. The branch
|
|
4
|
+
// tracks the pull request's branch on origin, so `pushBranch` pushes the review's fixes and verdicts
|
|
5
|
+
// to the slice branch, and the hooks and pre-edit read the slice from the branch name.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { GitError, assertRef, git } from '../git.js';
|
|
9
|
+
import { parseSliceAddr, sliceFromBranch, stateFileName } from '../ids.js';
|
|
10
|
+
import { kitPaths } from '../paths.js';
|
|
11
|
+
import { readSlice } from '../state/index.js';
|
|
12
|
+
import { titleSlice } from '../check/rules/ci-title.js';
|
|
13
|
+
import { posixRel } from './red.js';
|
|
14
|
+
import { commits } from './sync.js';
|
|
15
|
+
import { independentVerdictPath } from './verdict.js';
|
|
16
|
+
import { BuildError, listWorktrees, reviewBranch, reviewWorktreeDir, samePath } from './worktree.js';
|
|
17
|
+
|
|
18
|
+
const fwd = (p) => p.replaceAll('\\', '/');
|
|
19
|
+
const lines = (out) => out.split('\n').filter((l) => l !== '');
|
|
20
|
+
|
|
21
|
+
// Whether git takes `name` as a branch name, as written: `check-ref-format --branch` also expands
|
|
22
|
+
// `@{-1}`-style names, so its output must be the name itself.
|
|
23
|
+
function validBranch(root, name) {
|
|
24
|
+
try {
|
|
25
|
+
assertRef(name);
|
|
26
|
+
return git(root, ['check-ref-format', '--branch', name]) === name;
|
|
27
|
+
} catch (e) {
|
|
28
|
+
if (e instanceof GitError) return false;
|
|
29
|
+
throw e;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// A review worktree left by an earlier start is removed, so the review starts fresh; one holding work
|
|
34
|
+
// (uncommitted, or committed and not on origin) is refused and left as it is. One whose folder was
|
|
35
|
+
// deleted by hand is pruned: nothing in it can be lost.
|
|
36
|
+
function clearOld(root, id, dir, branch) {
|
|
37
|
+
const old = listWorktrees(root).find((w) => samePath(w.path, dir));
|
|
38
|
+
if (old && !fs.existsSync(dir)) {
|
|
39
|
+
git(root, ['worktree', 'prune']);
|
|
40
|
+
} else if (old) {
|
|
41
|
+
if (git(dir, ['status', '--porcelain']) !== '') throw new BuildError(`${fwd(dir)} has uncommitted changes`);
|
|
42
|
+
let ahead = 0;
|
|
43
|
+
try {
|
|
44
|
+
ahead = Number(git(dir, ['rev-list', '--count', '@{u}..HEAD']));
|
|
45
|
+
} catch (e) {
|
|
46
|
+
if (!(e instanceof GitError)) throw e;
|
|
47
|
+
// No upstream (or it is gone from origin): nothing to compare, the worktree is the kit's own.
|
|
48
|
+
}
|
|
49
|
+
if (ahead > 0) {
|
|
50
|
+
throw new BuildError(
|
|
51
|
+
`${fwd(dir)} has ${commits(ahead)} not on origin; push them with slicekit build pr ${id} --worktree ${fwd(dir)}, or remove the worktree by hand`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
git(root, ['worktree', 'remove', dir]);
|
|
55
|
+
} else if (fs.existsSync(dir)) {
|
|
56
|
+
throw new BuildError(`${fwd(dir)} exists and holds no worktree; remove it`);
|
|
57
|
+
}
|
|
58
|
+
if (lines(git(root, ['branch', '--list', branch])).length > 0) git(root, ['branch', '-q', '-D', branch]);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// The pull request number the slice's state on `ref` records, or null when it records none.
|
|
62
|
+
function recordedNumber(root, cfg, id, ref) {
|
|
63
|
+
const rel = posixRel(root, path.join(kitPaths(root, cfg).state, stateFileName(id)));
|
|
64
|
+
let text;
|
|
65
|
+
try {
|
|
66
|
+
text = git(root, ['show', `${ref}:${rel}`]);
|
|
67
|
+
} catch (e) {
|
|
68
|
+
if (!(e instanceof GitError)) throw e;
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return JSON.parse(text).pr?.number ?? null;
|
|
73
|
+
} catch {
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// -> {id, worktree, branch, round, verdictPath}: `round` is the slice's verdict count plus one, and
|
|
79
|
+
// `verdictPath` the absolute session-root path of that round's independent verdict. Every refusal
|
|
80
|
+
// comes before an earlier review worktree is touched.
|
|
81
|
+
export function startReview(root, cfg, host, number) {
|
|
82
|
+
const pr = host.getPullRequest(number);
|
|
83
|
+
const id = titleSlice(pr.title ?? '');
|
|
84
|
+
const addr = id && parseSliceAddr(id);
|
|
85
|
+
if (!addr) throw new BuildError(`pull request #${number} is not a slice pull request`, 2);
|
|
86
|
+
if (pr.state !== 'OPEN') {
|
|
87
|
+
throw new BuildError(`pull request #${number} is ${String(pr.state ?? 'not open').toLowerCase()}; review start runs on an open pull request`);
|
|
88
|
+
}
|
|
89
|
+
const headRef = pr.headRef;
|
|
90
|
+
const branch = reviewBranch(addr);
|
|
91
|
+
// The name is checked before git sees it in a fetch, where `*` would make a glob refspec.
|
|
92
|
+
if (typeof headRef !== 'string' || !validBranch(root, headRef)) {
|
|
93
|
+
throw new BuildError(`pull request #${number}'s branch ${headRef ?? '(none)'} is not a valid branch name`, 2);
|
|
94
|
+
}
|
|
95
|
+
if (sliceFromBranch(headRef) !== id || headRef === branch) {
|
|
96
|
+
throw new BuildError(`pull request #${number} is from ${headRef}, not a build branch of ${id}`);
|
|
97
|
+
}
|
|
98
|
+
if (git(root, ['ls-remote', '--heads', 'origin', `refs/heads/${headRef}`]) === '') {
|
|
99
|
+
throw new BuildError(`pull request #${number}'s branch ${headRef} is not on origin; a fork's pull request cannot be reviewed here`);
|
|
100
|
+
}
|
|
101
|
+
// The head as origin has it now: `+` because a slice branch the review pushed to may since have been
|
|
102
|
+
// pushed to from the build worktree.
|
|
103
|
+
const tracking = `refs/remotes/origin/${headRef}`;
|
|
104
|
+
git(root, ['fetch', '-q', 'origin', `+refs/heads/${headRef}:${tracking}`]);
|
|
105
|
+
// The pull request's own head, not another branch of the same name: a fork's has a head origin's
|
|
106
|
+
// branch does not.
|
|
107
|
+
const tip = git(root, ['rev-parse', tracking]);
|
|
108
|
+
if (typeof pr.headSha === 'string' && pr.headSha !== '' && pr.headSha !== tip) {
|
|
109
|
+
throw new BuildError(`pull request #${number}'s head ${pr.headSha.slice(0, 7)} is not origin/${headRef}; is it from a fork? If the branch was just pushed, run the same command again in a minute`);
|
|
110
|
+
}
|
|
111
|
+
const recorded = recordedNumber(root, cfg, id, tracking);
|
|
112
|
+
if (recorded !== null && recorded !== number) throw new BuildError(`pull request #${number} is not the one recorded for ${id} (#${recorded})`);
|
|
113
|
+
|
|
114
|
+
const dir = reviewWorktreeDir(root, addr);
|
|
115
|
+
clearOld(root, id, dir, branch);
|
|
116
|
+
git(root, ['worktree', 'add', '-q', '--track', '-b', branch, dir, tracking]);
|
|
117
|
+
|
|
118
|
+
const verdicts = readSlice(dir, cfg, id).verdicts ?? [];
|
|
119
|
+
const verdictPath = independentVerdictPath(root, id, verdicts);
|
|
120
|
+
// The reviewer writes there at once: its directory is made here, as the path is printed.
|
|
121
|
+
fs.mkdirSync(path.dirname(verdictPath), { recursive: true });
|
|
122
|
+
return { id, worktree: dir, branch, round: verdicts.length + 1, verdictPath };
|
|
123
|
+
}
|