slicekit 0.0.1 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +252 -3
- package/bin/slicekit.js +4 -0
- package/package.json +21 -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,127 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { assertDate, assertSha } from '../../evidence.js';
|
|
3
|
+
import { redact } from '../../redact.js';
|
|
4
|
+
import { GitHostError, GitHostNotFound } from './errors.js';
|
|
5
|
+
import {
|
|
6
|
+
assertBranch,
|
|
7
|
+
assertLabel,
|
|
8
|
+
assertLabelColor,
|
|
9
|
+
assertPrNumber,
|
|
10
|
+
assertTitle,
|
|
11
|
+
BRANCH_PR_FIELDS,
|
|
12
|
+
filterMergedSince,
|
|
13
|
+
mapPullRequest,
|
|
14
|
+
parsePullRequestUrl,
|
|
15
|
+
pickBranchPullRequest,
|
|
16
|
+
reduceRuns,
|
|
17
|
+
} from './gh-json.js';
|
|
18
|
+
|
|
19
|
+
// C-1 for GitHub through the `gh` CLI. This file owns only the spawn; the JSON mapping is gh-json.js.
|
|
20
|
+
|
|
21
|
+
export const GH_NOT_FOUND = 'gh not found; install GitHub CLI or set SLICEKIT_GITHOST_FIXTURE';
|
|
22
|
+
|
|
23
|
+
const PR_FIELDS = 'number,url,state,mergedAt,headRefOid,headRefName,isDraft,title,body,labels';
|
|
24
|
+
const LIST_FIELDS = 'number,mergedAt,headRefOid,title';
|
|
25
|
+
const RUN_FIELDS = 'status,conclusion,url,createdAt';
|
|
26
|
+
|
|
27
|
+
// A non-zero gh exit, typed: "no such pull request" is a GitHostNotFound, anything else a GitHostError
|
|
28
|
+
// whose message carries the first line of gh's stderr, with any token shape masked.
|
|
29
|
+
export function ghExitError(args, stderr) {
|
|
30
|
+
if (args[0] === 'pr' && args[1] === 'view' && /Could not resolve to a PullRequest/i.test(stderr)) {
|
|
31
|
+
return new GitHostNotFound(`pull request ${args[2]} not found`, { stderr });
|
|
32
|
+
}
|
|
33
|
+
const first = stderr.split(/\r?\n/).find((l) => l.trim() !== '')?.trim() ?? '';
|
|
34
|
+
return new GitHostError(`gh ${args.slice(0, 2).join(' ')} failed: ${redact(first)}`, { stderr });
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// `input`, when given, is piped to gh's stdin (a body passed as `--body-file -`, never on the
|
|
38
|
+
// command line). Exported for the tracker adapter (C-2), which spawns gh the same way.
|
|
39
|
+
export function gh(exec, args, { input, ...opts } = {}) {
|
|
40
|
+
const stdin = input === undefined ? 'ignore' : 'pipe';
|
|
41
|
+
try {
|
|
42
|
+
return exec('gh', args, { encoding: 'utf8', stdio: [stdin, 'pipe', 'pipe'], ...opts, ...(input === undefined ? {} : { input }) });
|
|
43
|
+
} catch (e) {
|
|
44
|
+
if (e.code === 'ENOENT') throw new GitHostError(GH_NOT_FOUND);
|
|
45
|
+
if (typeof e.status !== 'number') throw new GitHostError(`gh could not be run: ${e.message}`);
|
|
46
|
+
throw ghExitError(args, String(e.stderr ?? '').trim() || e.message);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// gh picks the repository from its working directory, so every call runs in the project root.
|
|
51
|
+
// `exec` is the test seam; it defaults to execFileSync.
|
|
52
|
+
export function githubHost(env = process.env, root = process.cwd(), exec = execFileSync) {
|
|
53
|
+
const ghJson = (args) => {
|
|
54
|
+
const out = gh(exec, args, { env, cwd: root });
|
|
55
|
+
try {
|
|
56
|
+
return JSON.parse(out);
|
|
57
|
+
} catch (e) {
|
|
58
|
+
throw new GitHostError(`gh ${args.slice(0, 2).join(' ')} printed something that is not JSON: ${e.message}`);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
return {
|
|
62
|
+
kind: 'github',
|
|
63
|
+
getPullRequest(n) {
|
|
64
|
+
assertPrNumber(n);
|
|
65
|
+
return mapPullRequest(ghJson(['pr', 'view', String(n), '--json', PR_FIELDS]));
|
|
66
|
+
},
|
|
67
|
+
// The search narrows to pull requests merged on or after the instant's UTC day; the client-side
|
|
68
|
+
// filter then keeps those merged at or after the instant itself.
|
|
69
|
+
listMergedSince(isoDate) {
|
|
70
|
+
const since = assertDate(isoDate);
|
|
71
|
+
const day = new Date(since).toISOString().slice(0, 10);
|
|
72
|
+
const args = ['pr', 'list', '--state', 'merged', '--search', `merged:>=${day}`, '--limit', '200', '--json', LIST_FIELDS];
|
|
73
|
+
return filterMergedSince(ghJson(args), since);
|
|
74
|
+
},
|
|
75
|
+
ciStatus(sha) {
|
|
76
|
+
assertSha(sha);
|
|
77
|
+
return reduceRuns(ghJson(['run', 'list', '--commit', sha, '--limit', '20', '--json', RUN_FIELDS]));
|
|
78
|
+
},
|
|
79
|
+
// Adds the label when present is true, removes it otherwise. A label the repository does not
|
|
80
|
+
// have is gh's error, reported as a GitHostError.
|
|
81
|
+
setLabel(n, name, present) {
|
|
82
|
+
assertPrNumber(n);
|
|
83
|
+
assertLabel(name);
|
|
84
|
+
gh(exec, ['pr', 'edit', String(n), present ? '--add-label' : '--remove-label', name], { env, cwd: root });
|
|
85
|
+
},
|
|
86
|
+
// Opens a pull request from `branch` into `base`; the body goes on stdin. gh prints the new
|
|
87
|
+
// pull request's url, and its number is read from `/pull/<n>`. Each value is one `--flag=value`
|
|
88
|
+
// argument, so a title starting with "-" is not read as a flag.
|
|
89
|
+
openPullRequest({ branch, base, title, body, draft }) {
|
|
90
|
+
assertBranch(branch);
|
|
91
|
+
assertBranch(base);
|
|
92
|
+
assertTitle(title);
|
|
93
|
+
const args = ['pr', 'create', `--head=${branch}`, `--base=${base}`, `--title=${title}`, '--body-file', '-', ...(draft ? ['--draft'] : [])];
|
|
94
|
+
const out = gh(exec, args, { env, cwd: root, input: String(body ?? '') });
|
|
95
|
+
const made = parsePullRequestUrl(out);
|
|
96
|
+
if (made === null) throw new GitHostError('gh pr create printed no pull request url');
|
|
97
|
+
return made;
|
|
98
|
+
},
|
|
99
|
+
updatePullRequestBody(n, body) {
|
|
100
|
+
assertPrNumber(n);
|
|
101
|
+
gh(exec, ['pr', 'edit', String(n), '--body-file', '-'], { env, cwd: root, input: String(body ?? '') });
|
|
102
|
+
},
|
|
103
|
+
markReady(n) {
|
|
104
|
+
assertPrNumber(n);
|
|
105
|
+
gh(exec, ['pr', 'ready', String(n)], { env, cwd: root });
|
|
106
|
+
},
|
|
107
|
+
// Back to draft: a slice that returns to draft-pr after its pull request was marked ready.
|
|
108
|
+
markDraft(n) {
|
|
109
|
+
assertPrNumber(n);
|
|
110
|
+
gh(exec, ['pr', 'ready', String(n), '--undo'], { env, cwd: root });
|
|
111
|
+
},
|
|
112
|
+
// The open pull request whose head is `branch` in this repository, as { number, url, base }, or
|
|
113
|
+
// null. Every open one with that head name is listed (a fork's included), then filtered.
|
|
114
|
+
pullRequestForBranch(branch, { base } = {}) {
|
|
115
|
+
assertBranch(branch);
|
|
116
|
+
const list = ghJson(['pr', 'list', '--head', branch, '--state', 'open', '--json', BRANCH_PR_FIELDS]);
|
|
117
|
+
return pickBranchPullRequest(list, branch, base);
|
|
118
|
+
},
|
|
119
|
+
// Creates the label, or with --force updates its colour and description: safe to run every time.
|
|
120
|
+
ensureLabel(name, { color, description }) {
|
|
121
|
+
assertLabel(name);
|
|
122
|
+
assertLabelColor(color);
|
|
123
|
+
assertLabel(description);
|
|
124
|
+
gh(exec, ['label', 'create', name, '--color', color, '--description', description, '--force'], { env, cwd: root });
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { GitHostError } from './errors.js';
|
|
2
|
+
import { fixtureHost } from './fixture.js';
|
|
3
|
+
import { githubHost } from './github.js';
|
|
4
|
+
|
|
5
|
+
// C-1: the only door to a git host. A second host is a second file and one more branch here.
|
|
6
|
+
// `root` is the project the host is asked about; gh reads the repository from it.
|
|
7
|
+
export function getHost(cfg, env = process.env, root = process.cwd()) {
|
|
8
|
+
if (env.SLICEKIT_GITHOST_FIXTURE) return fixtureHost(env.SLICEKIT_GITHOST_FIXTURE);
|
|
9
|
+
const kind = cfg?.gitHost?.kind;
|
|
10
|
+
if (kind === 'github') return githubHost(env, root);
|
|
11
|
+
throw new GitHostError(`unsupported git host: ${kind}`);
|
|
12
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Every failure a tracker raises is a TrackerError, so a caller can tell "the tracker said no" from
|
|
2
|
+
// a bug in the kit.
|
|
3
|
+
import { parseSliceAddr } from '../../ids.js';
|
|
4
|
+
|
|
5
|
+
export class TrackerError extends Error {
|
|
6
|
+
constructor(message, { stderr } = {}) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = 'TrackerError';
|
|
9
|
+
if (stderr !== undefined) this.stderr = stderr;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
// The checks both trackers make before they spend a call.
|
|
14
|
+
export function assertSlice(id) {
|
|
15
|
+
if (typeof id !== 'string' || !parseSliceAddr(id)) throw new Error(`slice must be P<n>/S-<nn>, got ${JSON.stringify(id)}`);
|
|
16
|
+
return id;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function assertFinding(id) {
|
|
20
|
+
if (typeof id !== 'string' || !/^[BH]-[1-9]\d*$/.test(id)) throw new Error(`finding must be B-<n> or H-<n>, got ${JSON.stringify(id)}`);
|
|
21
|
+
return id;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function assertIssueTitle(title) {
|
|
25
|
+
if (typeof title !== 'string' || title.trim() === '' || /[\r\n]/.test(title)) {
|
|
26
|
+
throw new Error(`issue title must be a non-empty single line, got ${JSON.stringify(title)}`);
|
|
27
|
+
}
|
|
28
|
+
return title;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function assertIssueId(id) {
|
|
32
|
+
if (!Number.isInteger(id) || id < 1) throw new Error(`issue id must be a positive integer, got ${id}`);
|
|
33
|
+
return id;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function assertLabels(labels) {
|
|
37
|
+
if (!Array.isArray(labels) || !labels.every((l) => typeof l === 'string' && l.trim() !== '' && !/[\r\n]/.test(l))) {
|
|
38
|
+
throw new Error(`labels must be a list of non-empty single-line strings, got ${JSON.stringify(labels)}`);
|
|
39
|
+
}
|
|
40
|
+
return labels;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The title every kit-opened issue for a finding starts with; `find` matches on it.
|
|
44
|
+
export const findingTitlePrefix = (slice, finding) => `[${slice}] ${finding}:`;
|
|
45
|
+
|
|
46
|
+
// The first issue among `list` ({number, url, title, state}) whose title starts with the finding's
|
|
47
|
+
// prefix, as {id, url, state}; state is `open` or `closed`, and an issue with none reads as open.
|
|
48
|
+
export function pickFinding(list, slice, finding) {
|
|
49
|
+
const prefix = findingTitlePrefix(slice, finding);
|
|
50
|
+
const hit = (Array.isArray(list) ? list : []).find((i) => i && typeof i.title === 'string' && i.title.startsWith(prefix) && Number.isInteger(i.number));
|
|
51
|
+
if (!hit) return null;
|
|
52
|
+
return { id: hit.number, url: hit.url, state: String(hit.state ?? 'open').toLowerCase() === 'closed' ? 'closed' : 'open' };
|
|
53
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { redact } from '../../redact.js';
|
|
4
|
+
import { TrackerError, assertFinding, assertIssueId, assertIssueTitle, assertLabels, assertSlice, pickFinding } from './errors.js';
|
|
5
|
+
|
|
6
|
+
// The test seam for C-2: a directory holding the tracker's issues.
|
|
7
|
+
// issues.json [{number, url, title, body, labels, comments, state}]; missing reads as [],
|
|
8
|
+
// and an issue with no state is open
|
|
9
|
+
// issue-create-error.txt the tracker refusing `open`
|
|
10
|
+
// issue-calls.jsonl written: `{op, ...input}` per write (open, comment), in order
|
|
11
|
+
// `open` appends an issue numbered one above the highest there, at https://example.test/issues/<n>.
|
|
12
|
+
// Nothing here closes an issue.
|
|
13
|
+
const issuesFile = (dir) => path.join(dir, 'issues.json');
|
|
14
|
+
|
|
15
|
+
function readIssues(dir) {
|
|
16
|
+
try {
|
|
17
|
+
const list = JSON.parse(fs.readFileSync(issuesFile(dir), 'utf8'));
|
|
18
|
+
if (!Array.isArray(list)) throw new Error('not a list');
|
|
19
|
+
return list;
|
|
20
|
+
} catch (e) {
|
|
21
|
+
if (e.code === 'ENOENT') return [];
|
|
22
|
+
throw new TrackerError(`tracker fixture ${issuesFile(dir)}: ${e.message}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const writeIssues = (dir, list) => fs.writeFileSync(issuesFile(dir), `${JSON.stringify(list, null, 2)}\n`);
|
|
27
|
+
const record = (dir, call) => fs.appendFileSync(path.join(dir, 'issue-calls.jsonl'), `${JSON.stringify(call)}\n`);
|
|
28
|
+
|
|
29
|
+
function refuse(dir, file, call) {
|
|
30
|
+
let refusal;
|
|
31
|
+
try {
|
|
32
|
+
refusal = fs.readFileSync(path.join(dir, file), 'utf8').trim();
|
|
33
|
+
} catch (e) {
|
|
34
|
+
if (e.code !== 'ENOENT') throw new TrackerError(`tracker fixture ${dir}: ${e.message}`);
|
|
35
|
+
}
|
|
36
|
+
if (refusal !== undefined) throw new TrackerError(`${call} failed: ${redact(refusal)}`, { stderr: refusal });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function fixtureTracker(dir) {
|
|
40
|
+
return {
|
|
41
|
+
kind: 'fixture',
|
|
42
|
+
open({ title, body, labels = [], slice }) {
|
|
43
|
+
assertIssueTitle(title);
|
|
44
|
+
assertLabels(labels);
|
|
45
|
+
assertSlice(slice);
|
|
46
|
+
refuse(dir, 'issue-create-error.txt', 'gh issue create');
|
|
47
|
+
const list = readIssues(dir);
|
|
48
|
+
const number = list.reduce((n, i) => Math.max(n, Number.isInteger(i?.number) ? i.number : 0), 0) + 1;
|
|
49
|
+
const url = `https://example.test/issues/${number}`;
|
|
50
|
+
const text = String(body ?? '');
|
|
51
|
+
writeIssues(dir, [...list, { number, url, title, body: text, labels: [...labels], comments: [], state: 'open' }]);
|
|
52
|
+
record(dir, { op: 'open', title, body: text, labels: [...labels], slice });
|
|
53
|
+
return { id: number, url };
|
|
54
|
+
},
|
|
55
|
+
comment(id, body) {
|
|
56
|
+
assertIssueId(id);
|
|
57
|
+
const list = readIssues(dir);
|
|
58
|
+
const issue = list.find((i) => i?.number === id);
|
|
59
|
+
if (!issue) throw new TrackerError(`issue ${id} not found`);
|
|
60
|
+
const text = String(body ?? '');
|
|
61
|
+
issue.comments = [...(issue.comments ?? []), { body: text }];
|
|
62
|
+
writeIssues(dir, list);
|
|
63
|
+
record(dir, { op: 'comment', id, body: text });
|
|
64
|
+
},
|
|
65
|
+
find(slice, finding) {
|
|
66
|
+
assertSlice(slice);
|
|
67
|
+
assertFinding(finding);
|
|
68
|
+
return pickFinding(readIssues(dir), slice, finding);
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { GitHostError } from '../githost/errors.js';
|
|
3
|
+
import { gh } from '../githost/github.js';
|
|
4
|
+
import { TrackerError, assertFinding, assertIssueId, assertIssueTitle, assertLabels, assertSlice, findingTitlePrefix, pickFinding } from './errors.js';
|
|
5
|
+
|
|
6
|
+
// C-2 for GitHub Issues through the `gh` CLI, spawned the way the git host spawns it. gh picks the
|
|
7
|
+
// repository from its working directory, so every call runs in the project root. `exec` is the test
|
|
8
|
+
// seam; it defaults to execFileSync. Nothing here closes an issue.
|
|
9
|
+
const LIST_FIELDS = 'number,url,title,state';
|
|
10
|
+
|
|
11
|
+
// The number and url gh prints for an issue it made: the last line holding `/issues/<n>`.
|
|
12
|
+
export function parseIssueUrl(out) {
|
|
13
|
+
const line = String(out ?? '')
|
|
14
|
+
.split(/\r?\n/)
|
|
15
|
+
.map((l) => l.trim())
|
|
16
|
+
.reverse()
|
|
17
|
+
.find((l) => /^https?:\/\/\S+\/issues\/\d+$/.test(l));
|
|
18
|
+
if (line === undefined) return null;
|
|
19
|
+
return { id: Number(/\/issues\/(\d+)$/.exec(line)[1]), url: line };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function githubIssues(env = process.env, root = process.cwd(), exec = execFileSync) {
|
|
23
|
+
const run = (args, input) => {
|
|
24
|
+
try {
|
|
25
|
+
return gh(exec, args, { env, cwd: root, ...(input === undefined ? {} : { input }) });
|
|
26
|
+
} catch (e) {
|
|
27
|
+
if (e instanceof GitHostError) throw new TrackerError(e.message, { stderr: e.stderr });
|
|
28
|
+
throw e;
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
return {
|
|
32
|
+
kind: 'github-issues',
|
|
33
|
+
// Each value is one `--flag=value` argument, so a title or label starting with "-" is not read
|
|
34
|
+
// as a flag; the body goes on stdin.
|
|
35
|
+
open({ title, body, labels = [], slice }) {
|
|
36
|
+
assertIssueTitle(title);
|
|
37
|
+
assertLabels(labels);
|
|
38
|
+
assertSlice(slice);
|
|
39
|
+
const args = ['issue', 'create', `--title=${title}`, '--body-file', '-', ...labels.map((l) => `--label=${l}`)];
|
|
40
|
+
const made = parseIssueUrl(run(args, String(body ?? '')));
|
|
41
|
+
if (made === null) throw new TrackerError('gh issue create printed no issue url');
|
|
42
|
+
return made;
|
|
43
|
+
},
|
|
44
|
+
comment(id, body) {
|
|
45
|
+
assertIssueId(id);
|
|
46
|
+
run(['issue', 'comment', String(id), '--body-file', '-'], String(body ?? ''));
|
|
47
|
+
},
|
|
48
|
+
// The search asks for the exact title phrase, oldest first, so the issue the kit opened first is on
|
|
49
|
+
// page one; GitHub's phrase match is still loose, so its hits are narrowed to a title that begins
|
|
50
|
+
// `[<slice>] <finding>:`.
|
|
51
|
+
find(slice, finding) {
|
|
52
|
+
assertSlice(slice);
|
|
53
|
+
assertFinding(finding);
|
|
54
|
+
const query = `"${findingTitlePrefix(slice, finding)}" in:title sort:created-asc`;
|
|
55
|
+
const out = run(['issue', 'list', '--state', 'all', '--search', query, '--json', LIST_FIELDS, '--limit', '50']);
|
|
56
|
+
let list;
|
|
57
|
+
try {
|
|
58
|
+
list = JSON.parse(out);
|
|
59
|
+
} catch (e) {
|
|
60
|
+
throw new TrackerError(`gh issue list printed something that is not JSON: ${e.message}`);
|
|
61
|
+
}
|
|
62
|
+
return pickFinding(list, slice, finding);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { TrackerError } from './errors.js';
|
|
2
|
+
import { fixtureTracker } from './fixture.js';
|
|
3
|
+
import { githubIssues } from './github-issues.js';
|
|
4
|
+
|
|
5
|
+
export { TrackerError };
|
|
6
|
+
|
|
7
|
+
// C-2: the only door to a tracker. A second tracker (Jira) is a second file and one more branch here.
|
|
8
|
+
// `root` is the project the tracker is asked about; gh reads the repository from it.
|
|
9
|
+
export function getTracker(cfg, env = process.env, root = process.cwd()) {
|
|
10
|
+
if (env.SLICEKIT_TRACKER_FIXTURE) return fixtureTracker(env.SLICEKIT_TRACKER_FIXTURE);
|
|
11
|
+
const kind = cfg?.tracker?.kind;
|
|
12
|
+
if (kind === 'github-issues') return githubIssues(env, root);
|
|
13
|
+
throw new TrackerError(`unsupported tracker: ${kind}`);
|
|
14
|
+
}
|
package/src/baseline.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { readText, writeText } from './fs.js';
|
|
4
|
+
|
|
5
|
+
const dirOf = (root) => path.join(root, '.slicekit', 'baselines');
|
|
6
|
+
const RULE_ID = /^[a-z0-9-]+$/;
|
|
7
|
+
|
|
8
|
+
function fileOf(root, rule) {
|
|
9
|
+
if (typeof rule !== 'string' || !RULE_ID.test(rule)) throw new Error(`baseline: rule id '${rule}' must match ${RULE_ID}`);
|
|
10
|
+
return path.join(dirOf(root), `${rule}.json`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const count = (n) => (Number.isInteger(n) && n >= 0 ? n : 0);
|
|
14
|
+
|
|
15
|
+
// A catalogue bucket (`catalogue` or `catalogue:<file>`) says the filler list itself lost a seed
|
|
16
|
+
// phrase (REQ-3.10). It is fixed in the list, never adopted, so no baseline may raise it.
|
|
17
|
+
const isCatalogue = (bucket) => bucket === 'catalogue' || bucket.startsWith('catalogue:');
|
|
18
|
+
|
|
19
|
+
// A baseline file is `{ "<bucket>": n }`. Anything unreadable reads as `{}` (every bucket at zero,
|
|
20
|
+
// the strictest reading) and a value that is not a non-negative integer reads as zero; each is
|
|
21
|
+
// reported in `problems` ({file, problem, damaged}), so a damaged file can only make the gate fail.
|
|
22
|
+
function readFile(file) {
|
|
23
|
+
const name = path.basename(file);
|
|
24
|
+
let data;
|
|
25
|
+
try {
|
|
26
|
+
data = JSON.parse(readText(file));
|
|
27
|
+
} catch {
|
|
28
|
+
return { buckets: {}, problems: [{ file: name, problem: 'is not valid JSON', damaged: true }] };
|
|
29
|
+
}
|
|
30
|
+
if (typeof data !== 'object' || data === null || Array.isArray(data)) {
|
|
31
|
+
return { buckets: {}, problems: [{ file: name, problem: 'is not a JSON object of counts', damaged: true }] };
|
|
32
|
+
}
|
|
33
|
+
const buckets = {};
|
|
34
|
+
const problems = [];
|
|
35
|
+
for (const [k, v] of Object.entries(data)) {
|
|
36
|
+
buckets[k] = count(v);
|
|
37
|
+
if (!(Number.isInteger(v) && v >= 0)) {
|
|
38
|
+
problems.push({ file: name, problem: `${k} is not a non-negative integer (read as 0)`, damaged: false });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return { buckets, problems };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// `{ baselines: { [rule]: { [bucket]: n } }, problems: [{file, problem, damaged}] }` for every `*.json`.
|
|
45
|
+
export function readBaselinesWithProblems(root) {
|
|
46
|
+
const dir = dirOf(root);
|
|
47
|
+
const baselines = {};
|
|
48
|
+
const problems = [];
|
|
49
|
+
if (!fs.existsSync(dir)) return { baselines, problems };
|
|
50
|
+
for (const name of fs.readdirSync(dir).sort()) {
|
|
51
|
+
if (!name.endsWith('.json')) continue;
|
|
52
|
+
const r = readFile(path.join(dir, name));
|
|
53
|
+
baselines[name.slice(0, -'.json'.length)] = r.buckets;
|
|
54
|
+
problems.push(...r.problems);
|
|
55
|
+
}
|
|
56
|
+
return { baselines, problems };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function readBaselines(root) {
|
|
60
|
+
return readBaselinesWithProblems(root).baselines;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const sortedJson = (buckets) => {
|
|
64
|
+
const out = {};
|
|
65
|
+
for (const k of Object.keys(buckets).sort()) out[k] = buckets[k];
|
|
66
|
+
return `${JSON.stringify(out, null, 2)}\n`;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// Baselines only go down. For each rule in `counts`, a bucket whose new count is at or below its
|
|
70
|
+
// baseline is kept at the new count; one that is higher is refused and keeps its old value; one
|
|
71
|
+
// that no longer appears is now zero and is removed (reported with to: 0). A bucket with no
|
|
72
|
+
// baseline reads as zero, so a new bucket with findings is refused too. With `adopt` (a first
|
|
73
|
+
// adoption, from a developer machine) a higher count is written and returned in `adopted`, and a
|
|
74
|
+
// damaged or invalid file is rewritten from the counts and returned in `rewrote`.
|
|
75
|
+
export function updateBaselines(root, counts, { adopt = false } = {}) {
|
|
76
|
+
const written = [];
|
|
77
|
+
const refused = [];
|
|
78
|
+
const adopted = [];
|
|
79
|
+
const rewrote = [];
|
|
80
|
+
for (const rule of Object.keys(counts ?? {}).sort()) {
|
|
81
|
+
const file = fileOf(root, rule);
|
|
82
|
+
const read = fs.existsSync(file) ? readFile(file) : { buckets: {}, problems: [] };
|
|
83
|
+
const old = read.buckets;
|
|
84
|
+
const next = {};
|
|
85
|
+
const mine = [];
|
|
86
|
+
for (const bucket of new Set([...Object.keys(old), ...Object.keys(counts[rule])])) {
|
|
87
|
+
const from = count(old[bucket]);
|
|
88
|
+
const to = count(counts[rule][bucket]);
|
|
89
|
+
if (to > from && isCatalogue(bucket)) {
|
|
90
|
+
refused.push({ rule, bucket, from, to, reason: 'catalogue buckets are never adopted' });
|
|
91
|
+
if (bucket in old) next[bucket] = old[bucket];
|
|
92
|
+
} else if (to > from && !adopt) {
|
|
93
|
+
refused.push({ rule, bucket, from, to });
|
|
94
|
+
if (bucket in old) next[bucket] = old[bucket];
|
|
95
|
+
} else {
|
|
96
|
+
if (to > 0) next[bucket] = to;
|
|
97
|
+
if (to > from) adopted.push({ rule, bucket, from, to });
|
|
98
|
+
else if (to !== from) mine.push({ rule, bucket, from, to });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const fix = adopt && read.problems.length > 0;
|
|
102
|
+
if (fix) rewrote.push({ rule, file: path.basename(file), problem: read.problems[0].problem });
|
|
103
|
+
const changed = fix || mine.length > 0 || adopted.some((a) => a.rule === rule) || Object.keys(next).length !== Object.keys(old).length;
|
|
104
|
+
if (changed) writeText(file, sortedJson(next));
|
|
105
|
+
written.push(...mine);
|
|
106
|
+
}
|
|
107
|
+
const byKey = (a, b) => (a.rule + '\0' + a.bucket < b.rule + '\0' + b.bucket ? -1 : 1);
|
|
108
|
+
return { written: written.sort(byKey), refused: refused.sort(byKey), adopted: adopted.sort(byKey), rewrote };
|
|
109
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// `build commit` and `build amend` (REQ-2.6 step 4, D-10): the developer's work is committed with the
|
|
2
|
+
// test run that went with it, never touching a frozen test; a frozen test changes only after the
|
|
3
|
+
// human has amended the slice file, and then only that one test.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { GitError, commitPaths, git, parseTrailers } from '../git.js';
|
|
7
|
+
import { stateFileName, verdictFilePattern } from '../ids.js';
|
|
8
|
+
import { kitPaths } from '../paths.js';
|
|
9
|
+
import { TransitionError, readSlice, unfreeze } from '../state/index.js';
|
|
10
|
+
import { isKitFile, posixRel, runCommand, sliceIn, toWorktreePath, unusableRun } from './red.js';
|
|
11
|
+
import { commitBookkeeping } from './record.js';
|
|
12
|
+
import { BuildError, findWorktree } from './worktree.js';
|
|
13
|
+
|
|
14
|
+
const short = (sha) => sha.slice(0, 7);
|
|
15
|
+
const lines = (out) => out.split('\n').filter((l) => l !== '');
|
|
16
|
+
|
|
17
|
+
// A fix for review findings is committed the same way while the pull request is in review, and after
|
|
18
|
+
// CI or the independent review passed (build pr then takes the slice back to draft-pr).
|
|
19
|
+
const COMMIT_FROM = ['building', 'in-review', 'changes-requested', 'ci-green', 'ready'];
|
|
20
|
+
|
|
21
|
+
function building(wt, cfg, id, step, from = ['building']) {
|
|
22
|
+
const current = readSlice(wt, cfg, id);
|
|
23
|
+
if (!from.includes(current.state)) throw new BuildError(`${id} is ${current.state}; ${step} runs from ${from.join(', ')}`);
|
|
24
|
+
return current;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Every changed path in the worktree (staged, unstaged, untracked; both sides of a rename), POSIX.
|
|
28
|
+
function changedPaths(wt) {
|
|
29
|
+
const list = (args) => git(wt, args).split('\0').filter((e) => e !== '');
|
|
30
|
+
// --no-renames: a rename is its deletion and its addition, so both paths are committed.
|
|
31
|
+
const tracked = list(['diff', '--name-only', '--no-renames', '-z', 'HEAD']);
|
|
32
|
+
const untracked = list(['ls-files', '--others', '--exclude-standard', '-z']);
|
|
33
|
+
return [...new Set([...tracked, ...untracked])];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const blobAt = (wt, rev, file) => {
|
|
37
|
+
try {
|
|
38
|
+
return git(wt, ['rev-parse', '--verify', '--quiet', `${rev}:${file}`]);
|
|
39
|
+
} catch (e) {
|
|
40
|
+
if (e instanceof GitError) return null;
|
|
41
|
+
throw e;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// The first frozen test (not unfrozen) that differs from the red commit, and how: hidden from git by
|
|
46
|
+
// skip-worktree or assume-unchanged, different bytes or missing on disk (an edit through Bash never
|
|
47
|
+
// meets the pre-edit hook), or different in the index or a commit since (a mode change, a removal).
|
|
48
|
+
function frozenProblem(wt, current) {
|
|
49
|
+
for (const t of current.frozenTests) {
|
|
50
|
+
if (current.unfrozen.includes(t)) continue;
|
|
51
|
+
const flag = git(wt, ['--literal-pathspecs', 'ls-files', '-v', '--', t]).slice(0, 1);
|
|
52
|
+
if (flag === 'S' || (flag !== '' && flag !== flag.toUpperCase())) {
|
|
53
|
+
return `frozen test ${t} is marked skip-worktree or assume-unchanged, so git cannot see its changes; clear the mark`;
|
|
54
|
+
}
|
|
55
|
+
const red = blobAt(wt, current.redCommit, t);
|
|
56
|
+
const onDisk = fs.existsSync(path.join(wt, ...t.split('/'))) ? git(wt, ['hash-object', '--', t]) : null;
|
|
57
|
+
const elsewhere = ['--cached', 'HEAD'].some(
|
|
58
|
+
(where) => git(wt, ['--literal-pathspecs', 'diff', '--name-only', ...(where === 'HEAD' ? [current.redCommit, 'HEAD'] : [where, current.redCommit]), '--', t]) !== '',
|
|
59
|
+
);
|
|
60
|
+
if (onDisk !== red || elsewhere) {
|
|
61
|
+
return `frozen test ${t} changed since ${short(current.redCommit)}; amend the slice file to change the evaluation set`;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const REVIEWS = '.slicekit/reviews/';
|
|
68
|
+
|
|
69
|
+
// The kit's own commits on the slice branch, recognised by subject, trailer and paths; a hand commit
|
|
70
|
+
// that imitates all three passes. The test command is read from the MAIN checkout's
|
|
71
|
+
// .slicekit/config.json, so someone writing outside the worktree could change commands.test and make
|
|
72
|
+
// --require-green meaningless; CI, which runs the committed config, is the backstop.
|
|
73
|
+
// `changes` are the commit's { status, file }, POSIX paths.
|
|
74
|
+
function kitCommit(id, subject, trailers, changes, stateRel, buildRel, sliceRel) {
|
|
75
|
+
if (trailers.Slice !== id) return false;
|
|
76
|
+
const files = changes.map((c) => c.file);
|
|
77
|
+
if (subject.startsWith(`chore(slicekit): ${id} `)) {
|
|
78
|
+
const pattern = verdictFilePattern(id);
|
|
79
|
+
const round = (f) => (f.startsWith(REVIEWS) ? pattern.exec(f.slice(REVIEWS.length))?.[2] : undefined);
|
|
80
|
+
if (!files.some((f) => round(f) !== undefined)) return files.every((f) => f === stateRel || f === buildRel);
|
|
81
|
+
// build verdict's commit: one verdict file, added, of the round its subject names, and nothing else.
|
|
82
|
+
// A change or removal of a recorded verdict, or a second one, is never the kit's.
|
|
83
|
+
if (changes.length !== 1 || changes[0].status !== 'A') return false;
|
|
84
|
+
return subject === `chore(slicekit): ${id} verdict r${round(files[0])}`;
|
|
85
|
+
}
|
|
86
|
+
if (subject === `docs(${id}): amend evaluation set`) return files.length === 1 && files[0] === sliceRel;
|
|
87
|
+
return false;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// A kit path changed since the red commit in a commit the kit did not make: a hand commit could
|
|
91
|
+
// otherwise unfreeze a test or rewrite the evaluation set.
|
|
92
|
+
function forgedKitChange(wt, cfg, id, current, slice) {
|
|
93
|
+
const paths = kitPaths(wt, cfg);
|
|
94
|
+
const stateRel = posixRel(wt, path.join(paths.state, stateFileName(id)));
|
|
95
|
+
const buildRel = posixRel(wt, paths.build);
|
|
96
|
+
const sliceRel = posixRel(wt, slice.path);
|
|
97
|
+
for (const sha of lines(git(wt, ['rev-list', '--no-merges', `${current.redCommit}..HEAD`]))) {
|
|
98
|
+
const changes = lines(git(wt, ['diff-tree', '--no-commit-id', '--name-status', '--no-renames', '-r', sha])).map((l) => {
|
|
99
|
+
const [status, ...rest] = l.split('\t');
|
|
100
|
+
return { status, file: rest.join('\t') };
|
|
101
|
+
});
|
|
102
|
+
const kit = changes.map((c) => c.file).find((f) => isKitFile(wt, cfg, slice, f));
|
|
103
|
+
if (!kit) continue;
|
|
104
|
+
const subject = git(wt, ['log', '-1', '--format=%s', sha]);
|
|
105
|
+
const trailers = parseTrailers(git(wt, ['log', '-1', '--format=%B', sha]));
|
|
106
|
+
if (!kitCommit(id, subject, trailers, changes, stateRel, buildRel, sliceRel)) {
|
|
107
|
+
return `${kit} was changed in ${short(sha)} outside the kit; only build commands write it`;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export function commitWork(root, cfg, id, { message, requireGreen = false, worktree } = {}) {
|
|
114
|
+
if (typeof message !== 'string' || message.trim() === '') throw new BuildError('--message is required', 2);
|
|
115
|
+
const wt = findWorktree(root, id, { worktree }).path;
|
|
116
|
+
const current = building(wt, cfg, id, 'commit', COMMIT_FROM);
|
|
117
|
+
const slice = sliceIn(wt, cfg, id);
|
|
118
|
+
const forged = forgedKitChange(wt, cfg, id, current, slice);
|
|
119
|
+
if (forged) throw new BuildError(forged);
|
|
120
|
+
const frozen = frozenProblem(wt, current);
|
|
121
|
+
if (frozen) throw new BuildError(frozen);
|
|
122
|
+
const paths = changedPaths(wt);
|
|
123
|
+
const kit = paths.find((p) => isKitFile(wt, cfg, slice, p));
|
|
124
|
+
if (kit) throw new BuildError(`${kit} is a kit file; build commit does not commit it`);
|
|
125
|
+
const command = cfg.commands?.test ?? '';
|
|
126
|
+
if (command.trim() === '') throw new BuildError('commands.test is not declared in .slicekit/config.json');
|
|
127
|
+
|
|
128
|
+
const run = runCommand(wt, command);
|
|
129
|
+
const unusable = unusableRun(command, run);
|
|
130
|
+
if (unusable) throw unusable;
|
|
131
|
+
if (requireGreen && run.exit !== 0) throw new BuildError(`tests fail (exit ${run.exit}): ${run.summary}`);
|
|
132
|
+
if (paths.length === 0) return { sha: null, exit: run.exit };
|
|
133
|
+
// Only the paths the status named: the developer's work, never the kit's files.
|
|
134
|
+
const sha = commitPaths(wt, paths, `${message.trim()}\n\nran: ${command} → exit ${run.exit}\n\nSlice: ${id}`);
|
|
135
|
+
return { sha, exit: run.exit };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// HEAD is this slice's amendment commit: the subject, the trailer, and the slice file alone.
|
|
139
|
+
function headIsAmendment(wt, id, sliceRel) {
|
|
140
|
+
const subject = git(wt, ['log', '-1', '--format=%s', 'HEAD']);
|
|
141
|
+
const trailers = parseTrailers(git(wt, ['log', '-1', '--format=%B', 'HEAD']));
|
|
142
|
+
const files = lines(git(wt, ['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD']));
|
|
143
|
+
return subject === `docs(${id}): amend evaluation set` && trailers.Slice === id && files.length === 1 && files[0] === sliceRel;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// The state file on disk differs from HEAD's copy only by this unfreeze: its bookkeeping commit did
|
|
147
|
+
// not land.
|
|
148
|
+
function pendingUnfreeze(wt, stateRel, file) {
|
|
149
|
+
let committed;
|
|
150
|
+
try {
|
|
151
|
+
committed = JSON.parse(git(wt, ['show', `HEAD:${stateRel}`]));
|
|
152
|
+
} catch {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
const now = JSON.parse(fs.readFileSync(path.join(wt, ...stateRel.split('/')), 'utf8'));
|
|
156
|
+
const added = now.history.at(-1);
|
|
157
|
+
const strip = (s) => JSON.stringify({ ...s, unfrozen: null, history: null });
|
|
158
|
+
return (
|
|
159
|
+
strip(now) === strip(committed) &&
|
|
160
|
+
JSON.stringify(now.unfrozen) === JSON.stringify([...committed.unfrozen, file]) &&
|
|
161
|
+
now.history.length === committed.history.length + 1 &&
|
|
162
|
+
JSON.stringify(now.history.slice(0, -1)) === JSON.stringify(committed.history) &&
|
|
163
|
+
added?.evidence?.unfreeze === file
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// -> { sha, test }: the slice file's amendment commit, and the test as stored. A run that stopped part
|
|
168
|
+
// way (the slice file committed, or the state written but not committed) is finished, not refused.
|
|
169
|
+
export function amend(root, cfg, id, { test, reason, worktree } = {}) {
|
|
170
|
+
if (typeof reason !== 'string' || reason.trim() === '') throw new BuildError('--reason is required', 2);
|
|
171
|
+
if (typeof test !== 'string' || test.trim() === '') throw new BuildError('--test is required', 2);
|
|
172
|
+
const wt = findWorktree(root, id, { worktree }).path;
|
|
173
|
+
const current = building(wt, cfg, id, 'amend');
|
|
174
|
+
const file = toWorktreePath(wt, test);
|
|
175
|
+
// Checked before the slice file is committed; the words are unfreeze's own TransitionError reason.
|
|
176
|
+
if (!current.frozenTests.includes(file)) throw new BuildError(`${file} is not a frozen test of ${id}`);
|
|
177
|
+
const stateRel = posixRel(wt, path.join(kitPaths(wt, cfg).state, stateFileName(id)));
|
|
178
|
+
const sliceRel = posixRel(wt, sliceIn(wt, cfg, id).path);
|
|
179
|
+
const lastAmendment = () => git(wt, ['log', '-1', '--format=%H', `--grep=^docs(${id}): amend evaluation set$`, '--', sliceRel]);
|
|
180
|
+
if (current.unfrozen.includes(file)) {
|
|
181
|
+
if (!pendingUnfreeze(wt, stateRel, file)) throw new BuildError(`${file} is already unfrozen`);
|
|
182
|
+
commitBookkeeping(wt, id, `unfreeze ${file}`, [stateRel]);
|
|
183
|
+
return { sha: lastAmendment(), test: file };
|
|
184
|
+
}
|
|
185
|
+
let sha;
|
|
186
|
+
if (git(wt, ['--literal-pathspecs', 'status', '--porcelain', '--', sliceRel]) !== '') {
|
|
187
|
+
sha = commitPaths(wt, [sliceRel], `docs(${id}): amend evaluation set\n\n${reason.trim()}\n\nSlice: ${id}`);
|
|
188
|
+
} else if (headIsAmendment(wt, id, sliceRel)) {
|
|
189
|
+
sha = git(wt, ['rev-parse', 'HEAD']);
|
|
190
|
+
} else {
|
|
191
|
+
throw new BuildError('amend the slice file first; it has no change');
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
unfreeze(wt, cfg, id, file, { amendCommit: sha, reason: reason.trim() });
|
|
195
|
+
} catch (e) {
|
|
196
|
+
if (e instanceof TransitionError) throw new BuildError(e.reason);
|
|
197
|
+
throw e;
|
|
198
|
+
}
|
|
199
|
+
commitBookkeeping(wt, id, `unfreeze ${file}`, [stateRel]);
|
|
200
|
+
return { sha, test: file };
|
|
201
|
+
}
|