slicekit 0.3.2 → 0.3.4
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/package.json +1 -1
- package/src/audit.js +233 -0
- package/src/build/pr.js +10 -19
- package/src/check/ci-event.js +3 -2
- package/src/check/rules/runbook.js +60 -0
- package/src/cli/audit.js +89 -0
- package/src/cli/branch.js +66 -7
- package/src/cli/index.js +6 -0
- package/src/cli/ops.js +78 -0
- package/src/cli/release.js +57 -0
- package/src/cli/update.js +4 -0
- package/src/cli/workflow.js +2 -0
- package/src/config.js +1 -1
- package/src/hooks/subagent-start.js +7 -3
- package/src/init.js +23 -1
- package/src/markdown.js +2 -1
- package/src/observability.js +203 -0
- package/src/ops.js +223 -0
- package/src/paths.js +1 -0
- package/src/release.js +296 -0
- package/src/reports.js +131 -0
- package/src/runbook.js +96 -0
- package/src/workflow.js +23 -7
- package/templates/claude-code/agents/ops.md +3 -3
- package/templates/instructions/agents/auditor.md +13 -2
- package/templates/instructions/agents/ops.md +30 -9
- package/templates/instructions/commands/audit.md +38 -0
- package/templates/instructions/commands/intake.md +10 -0
- package/templates/instructions/commands/ops.md +38 -0
- package/templates/instructions/commands/release.md +51 -0
package/src/ops.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// `slicekit ops` (REQ-2.13, D-57): what `/slicekit ops` hands the ops agent for a symptom, and the
|
|
2
|
+
// check of the report the agent replies with. Both read graph.json and files; neither runs git, calls
|
|
3
|
+
// the host or takes an action.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { history } from './graph/history.js';
|
|
7
|
+
import { indexGraph, loadGraph, normalisePath } from './graph/load.js';
|
|
8
|
+
import { GraphError, cmp, keyOf } from './graph/schema.js';
|
|
9
|
+
import { re } from './ids.js';
|
|
10
|
+
import { kitPaths } from './paths.js';
|
|
11
|
+
import { cellsOf, footerProblems, isDivider, isRow, lineExists, nextReport, reportSections } from './reports.js';
|
|
12
|
+
|
|
13
|
+
// A word naming more files than this is too broad to expand.
|
|
14
|
+
export const BROAD = 50;
|
|
15
|
+
|
|
16
|
+
const posix = (p) => p.split(path.sep).join('/');
|
|
17
|
+
const segmentsOf = (file) => file.toLowerCase().split(/[/._-]/).filter((s) => s !== '');
|
|
18
|
+
|
|
19
|
+
// The files a symptom names (D-57). Words are the runs of letters and digits of three or more
|
|
20
|
+
// characters, lower-cased, unique, in order; a word names each file one of whose path segments
|
|
21
|
+
// (split on `/`, `.`, `-`, `_`) equals it. A word naming more than BROAD files names none and is
|
|
22
|
+
// reported; so is a word naming no file. Each of `paths` names the files `slicekit history` would
|
|
23
|
+
// match for it. -> {files, words: [{word, files}], broad: [{word, count}], unmatched}
|
|
24
|
+
export function symptomFiles(index, symptom, paths = []) {
|
|
25
|
+
const all = index.byKind('file').map((n) => keyOf(n.id));
|
|
26
|
+
const bySegment = new Map();
|
|
27
|
+
for (const file of all) {
|
|
28
|
+
for (const s of new Set(segmentsOf(file))) {
|
|
29
|
+
if (!bySegment.has(s)) bySegment.set(s, []);
|
|
30
|
+
bySegment.get(s).push(file);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const found = new Set();
|
|
34
|
+
const words = [];
|
|
35
|
+
const broad = [];
|
|
36
|
+
const unmatched = [];
|
|
37
|
+
for (const word of new Set((String(symptom ?? '').match(/[A-Za-z0-9]{3,}/g) ?? []).map((w) => w.toLowerCase()))) {
|
|
38
|
+
const named = bySegment.get(word) ?? [];
|
|
39
|
+
if (named.length === 0) unmatched.push(word);
|
|
40
|
+
else if (named.length > BROAD) broad.push({ word, count: named.length });
|
|
41
|
+
else {
|
|
42
|
+
words.push({ word, files: [...named].sort(cmp) });
|
|
43
|
+
for (const f of named) found.add(f);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
for (const p of paths) {
|
|
47
|
+
const want = normalisePath(p);
|
|
48
|
+
const dir = `${want}/`;
|
|
49
|
+
const named = want === '' || want === '.' ? all : all.filter((f) => f === want || f.startsWith(dir));
|
|
50
|
+
if (named.length === 0) throw new GraphError(2, `${p} is not in the graph`);
|
|
51
|
+
for (const f of named) found.add(f);
|
|
52
|
+
}
|
|
53
|
+
return { files: [...found].sort(cmp), words, broad, unmatched };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// The release record of the highest phase, as its repository-relative path; null when there is none.
|
|
57
|
+
function lastRelease(index) {
|
|
58
|
+
const phaseOf = (n) => Number(/^P(\d+)$/.exec(keyOf(n.id))?.[1] ?? -1);
|
|
59
|
+
const newest = [...index.byKind('release')].sort((a, b) => phaseOf(b) - phaseOf(a) || cmp(a.id, b.id))[0];
|
|
60
|
+
return newest ? String(newest.from ?? '').replace(/:\d+$/, '') || null : null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Everything the ops agent is handed for `symptom`. The report path is reserved last, so a symptom
|
|
64
|
+
// that names no file leaves no empty report behind. Paths are repository-relative.
|
|
65
|
+
export function opsContext(root, cfg, symptom, { paths = [] } = {}) {
|
|
66
|
+
const index = indexGraph(loadGraph(root, cfg));
|
|
67
|
+
const { files, broad, unmatched } = symptomFiles(index, symptom, paths);
|
|
68
|
+
if (files.length === 0) throw new GraphError(1, 'the symptom names no file in the graph; name one with --path <path>');
|
|
69
|
+
const p = kitPaths(root, cfg);
|
|
70
|
+
const rel = (file) => posix(path.relative(root, file));
|
|
71
|
+
const entries = history(index, files);
|
|
72
|
+
return {
|
|
73
|
+
report: nextReport(root, cfg, 'ops'),
|
|
74
|
+
symptom,
|
|
75
|
+
files,
|
|
76
|
+
broad,
|
|
77
|
+
unmatched,
|
|
78
|
+
history: entries,
|
|
79
|
+
runbook: rel(p.runbook),
|
|
80
|
+
observability: rel(p.observability),
|
|
81
|
+
missing: [p.runbook, p.observability].filter((f) => !fs.existsSync(f)).map(rel),
|
|
82
|
+
lastRelease: lastRelease(index),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const OPS_SECTIONS = ['Likely slices and pull requests', 'First checks', 'Proposed actions'];
|
|
87
|
+
|
|
88
|
+
const FOOTER = /^(?:Skipped|Not checked):/;
|
|
89
|
+
const ITEM = /^\s*(?:[-*+]|\d+[.)])\s+/;
|
|
90
|
+
const MARKED = /\((?:anyone|on-call|owner: [^()]*[^()\s][^()]*)\)[.\s]*$/;
|
|
91
|
+
const PR_REF = /(?<![\w&/#.-])([A-Za-z0-9._-]+)?#(\d+)\b/g;
|
|
92
|
+
const CITATION = /(?<![\w./-])([A-Za-z0-9_.][\w./-]*):(\d+)\b/g;
|
|
93
|
+
|
|
94
|
+
// The file extensions a path can end in without naming a file of the graph: the cited file may be
|
|
95
|
+
// missing, and its extension still says it was meant as a file.
|
|
96
|
+
const EXTENSIONS = new Set(
|
|
97
|
+
'c cc cfg cjs conf cpp cs css csv env go gradle h hpp html ini java js json jsx kt lock log lua md mjs php properties proto ps1 py rb rs scss sh sql svelte swift tf toml ts tsx txt vue xml yaml yml'.split(' '),
|
|
98
|
+
);
|
|
99
|
+
const extensionOf = (file) => /\.([A-Za-z0-9]+)$/.exec(file.split('/').at(-1))?.[1].toLowerCase() ?? null;
|
|
100
|
+
|
|
101
|
+
// Whether the text before the colon of a `<path>:<line>` token in First checks makes it a citation
|
|
102
|
+
// (P5/S-23 review H-6), with a slash in it or without. It is one when the path is a file in the
|
|
103
|
+
// repository or a file of the graph, and when its last segment ends in a file extension: one of
|
|
104
|
+
// EXTENSIONS, or the extension of a file of the graph. A token that names no file and ends in no file
|
|
105
|
+
// extension, such as `localhost:8080`, `svc.internal/health:8080` or `registry/app:2`, is none.
|
|
106
|
+
function isCitation(root, index, file) {
|
|
107
|
+
if (file === '' || file === '.') return false;
|
|
108
|
+
if (index.node(`file:${file}`)) return true;
|
|
109
|
+
try {
|
|
110
|
+
if (fs.statSync(path.join(root, file)).isFile()) return true;
|
|
111
|
+
} catch {
|
|
112
|
+
// Not a file on disk: the extension decides.
|
|
113
|
+
}
|
|
114
|
+
const ext = extensionOf(file);
|
|
115
|
+
return ext !== null && (EXTENSIONS.has(ext) || index.byKind('file').some((n) => extensionOf(keyOf(n.id)) === ext));
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const FENCE = /^\s*(```|~~~)/;
|
|
119
|
+
const SUBHEADING = /^\s{0,3}#{3,6}\s/;
|
|
120
|
+
const NO_MARK = 'who may take it: (anyone), (on-call) or (owner: <name>)';
|
|
121
|
+
|
|
122
|
+
// The actions of the Proposed actions section, in each form the section can hold one, as
|
|
123
|
+
// {first, marked, message}: `first` the action's first line number. A list item, with the lines that
|
|
124
|
+
// continue it (indented, or right under it), and a paragraph of plain lines are each one action,
|
|
125
|
+
// marked when the joined text ends with the mark. A table row is one action, marked when one of its
|
|
126
|
+
// cells ends with the mark; the header row and the divider are none. A sub-heading and a fenced
|
|
127
|
+
// block are no action. `ls` holds the section's lines that are not blank.
|
|
128
|
+
function actions(ls) {
|
|
129
|
+
const out = [];
|
|
130
|
+
let open = null;
|
|
131
|
+
let last = 0;
|
|
132
|
+
let fenced = false;
|
|
133
|
+
const start = (first, t) => {
|
|
134
|
+
open = { first, text: t.trimEnd(), item: ITEM.test(t) };
|
|
135
|
+
out.push(open);
|
|
136
|
+
};
|
|
137
|
+
ls.forEach(({ text: t, line }, i) => {
|
|
138
|
+
const adjacent = line === last + 1;
|
|
139
|
+
last = line;
|
|
140
|
+
if (FENCE.test(t)) {
|
|
141
|
+
fenced = !fenced;
|
|
142
|
+
open = null;
|
|
143
|
+
} else if (fenced || SUBHEADING.test(t)) {
|
|
144
|
+
open = null;
|
|
145
|
+
} else if (isRow(t)) {
|
|
146
|
+
open = null;
|
|
147
|
+
const header = ls[i + 1] && ls[i + 1].line === line + 1 && isDivider(ls[i + 1].text);
|
|
148
|
+
if (!header && !isDivider(t)) out.push({ first: line, row: cellsOf(t) });
|
|
149
|
+
} else if (ITEM.test(t)) {
|
|
150
|
+
start(line, t);
|
|
151
|
+
} else if (open && (adjacent || (open.item && /^\s+\S/.test(t)))) {
|
|
152
|
+
open.text += ` ${t.trim()}`;
|
|
153
|
+
} else {
|
|
154
|
+
start(line, t);
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
return out.map((a) =>
|
|
158
|
+
a.row
|
|
159
|
+
? { first: a.first, marked: a.row.some((cell) => MARKED.test(cell)), message: `the action names in no cell ${NO_MARK}` }
|
|
160
|
+
: { first: a.first, marked: MARKED.test(a.text), message: `the action does not end with ${NO_MARK}` },
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// A Proposed actions section that proposes no action is this one line.
|
|
165
|
+
const NONE = 'None.';
|
|
166
|
+
|
|
167
|
+
// The lines of a section above its first closing line, `Skipped:` or `Not checked:`, outside a fenced
|
|
168
|
+
// block. The closing lines end the section: a closing line that wraps, or a list under it, is no action.
|
|
169
|
+
function beforeFooter(ls) {
|
|
170
|
+
let fenced = false;
|
|
171
|
+
for (let i = 0; i < ls.length; i++) {
|
|
172
|
+
if (FENCE.test(ls[i].text)) fenced = !fenced;
|
|
173
|
+
else if (!fenced && FOOTER.test(ls[i].text)) return ls.slice(0, i);
|
|
174
|
+
}
|
|
175
|
+
return ls;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// What is wrong with an ops report, one `<rel>:<line> <message>` per problem (REQ-2.13): each of the
|
|
179
|
+
// three sections present and holding a line; every slice and pull request named in the first one in
|
|
180
|
+
// the graph; every `<file>:<line>` cited in First checks a line that exists; every proposed action,
|
|
181
|
+
// whether a list item, a plain line or a table row, marked by who may take it, up to the first closing
|
|
182
|
+
// line, or the one line `None.` for no action; the two closing lines.
|
|
183
|
+
export function opsReportProblems(root, index, rel, text) {
|
|
184
|
+
const out = [];
|
|
185
|
+
const sections = reportSections(text);
|
|
186
|
+
const content = (name, closed = false) => {
|
|
187
|
+
const section = sections.get(name.toLowerCase());
|
|
188
|
+
if (!section) {
|
|
189
|
+
out.push(`${rel}:1 no "## ${name}" section`);
|
|
190
|
+
return [];
|
|
191
|
+
}
|
|
192
|
+
const upTo = closed ? beforeFooter(section.lines) : section.lines;
|
|
193
|
+
const held = upTo.filter((l) => l.text.trim() !== '' && !FOOTER.test(l.text));
|
|
194
|
+
if (held.length === 0) out.push(`${rel}:${section.line} the "## ${name}" section is empty`);
|
|
195
|
+
return held;
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
for (const { text: l, line } of content(OPS_SECTIONS[0])) {
|
|
199
|
+
for (const addr of new Set(l.match(new RegExp(`\\b${re('sliceAddr').source}\\b`, 'g')) ?? [])) {
|
|
200
|
+
if (!index.node(`slice:${addr}`)) out.push(`${rel}:${line} ${addr} is not a slice in the graph`);
|
|
201
|
+
}
|
|
202
|
+
for (const ref of new Set([...l.matchAll(PR_REF)].map((m) => `${m[1] ?? ''}#${m[2]}`))) {
|
|
203
|
+
if (!index.find(ref)) out.push(`${rel}:${line} ${ref} is not a pull request in the graph`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
for (const { text: l, line } of content(OPS_SECTIONS[1])) {
|
|
208
|
+
for (const m of l.matchAll(CITATION)) {
|
|
209
|
+
const file = normalisePath(m[1]);
|
|
210
|
+
if (!isCitation(root, index, file)) continue;
|
|
211
|
+
if (!lineExists(root, file, Number(m[2]))) out.push(`${rel}:${line} ${m[1]}:${m[2]} is not a line of a file in the repository`);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const proposed = content(OPS_SECTIONS[2], true);
|
|
216
|
+
if (!(proposed.length === 1 && proposed[0].text.trim() === NONE)) {
|
|
217
|
+
for (const action of actions(proposed)) {
|
|
218
|
+
if (!action.marked) out.push(`${rel}:${action.first} ${action.message}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return [...out, ...footerProblems(rel, text)];
|
|
223
|
+
}
|
package/src/paths.js
CHANGED
|
@@ -11,6 +11,7 @@ export function kitPaths(root, cfg) {
|
|
|
11
11
|
baselines: path.join(kit, 'baselines'),
|
|
12
12
|
journalDir: path.join(kit, 'journal'),
|
|
13
13
|
graph: path.join(kit, 'graph'),
|
|
14
|
+
reports: path.join(kit, 'reports'),
|
|
14
15
|
workspace: path.join(kit, 'workspace.json'),
|
|
15
16
|
docs,
|
|
16
17
|
intake: path.join(docs, 'intake'),
|
package/src/release.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
// `slicekit release P<n>` (02 REQ-2.9, D-12, D-54, D-55): the release record of a phase. It refuses
|
|
2
|
+
// while a slice of the phase is not merged or fails the runbook judgement, and otherwise writes
|
|
3
|
+
// `<docsRoot>/releases/P<n>.md`, sets each slice released and rewrites BUILD.md. It commits nothing
|
|
4
|
+
// (D-19: the procedure opens the `[release] P<n>` pull request through `pr open`) and deploys
|
|
5
|
+
// nothing (D-12). The record is the same bytes from the same inputs: the default branch's commit,
|
|
6
|
+
// the slice files, the spec, decisions.md, the runbook and what the git host says of each pull request.
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { readDecisions } from './decisions.js';
|
|
11
|
+
import { exists, readText, writeText } from './fs.js';
|
|
12
|
+
import { commitExists, currentBranch, git } from './git.js';
|
|
13
|
+
import { stateFileName } from './ids.js';
|
|
14
|
+
import { headings, lines } from './markdown.js';
|
|
15
|
+
import { kitPaths } from './paths.js';
|
|
16
|
+
import { getSection } from './prbody.js';
|
|
17
|
+
import { defaultRef, mergeBase, runbookRel, runbookSections, runbookVerdict } from './runbook.js';
|
|
18
|
+
import { findSliceFiles, parsePhaseFile, parseSliceFile, phaseOfDir } from './slicefile.js';
|
|
19
|
+
import { reqBlocks } from './stage.js';
|
|
20
|
+
import { renderBuild } from './state/build.js';
|
|
21
|
+
import { readSlice, setState } from './state/index.js';
|
|
22
|
+
|
|
23
|
+
// code 1: refused; code 2: usage, or a phase that is not one.
|
|
24
|
+
export class ReleaseError extends Error {
|
|
25
|
+
constructor(code, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = 'ReleaseError';
|
|
28
|
+
this.code = code;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const PHASE = /^P[1-9]\d*$/;
|
|
33
|
+
const RELEASE_BRANCH = /^release\/[a-z0-9][a-z0-9-]{0,59}$/;
|
|
34
|
+
const posix = (root, file) => path.relative(root, file).split(path.sep).join('/');
|
|
35
|
+
|
|
36
|
+
// The slices of the phase, in slice order: [{slice, state, phaseDir}].
|
|
37
|
+
function phaseSlices(root, cfg, phase) {
|
|
38
|
+
if (!PHASE.test(String(phase))) throw new ReleaseError(2, `${phase} is not a phase`);
|
|
39
|
+
const files = findSliceFiles(root, cfg).filter((f) => f.phaseId === phase);
|
|
40
|
+
if (files.length === 0) throw new ReleaseError(2, `${phase} is not a phase`);
|
|
41
|
+
return files.map((f) => {
|
|
42
|
+
const slice = parseSliceFile(readText(f.path), f.path);
|
|
43
|
+
return { slice, state: readSlice(root, cfg, slice.id), phaseDir: f.phaseDir };
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The commit a merged head left the default branch at. Once a merge commit has brought the head
|
|
48
|
+
// into the default branch, the merge base of the two is the head itself; the base is then the merge
|
|
49
|
+
// base of the head and the first parent of the commit that brought it in. A head that was
|
|
50
|
+
// fast-forwarded or rebased in has no such parent, and its base stays the head.
|
|
51
|
+
// A state written by backfill records the merge commit itself as the head: the head is then a
|
|
52
|
+
// commit of the default branch's own line with two parents, and what it brought is the diff from
|
|
53
|
+
// its first parent.
|
|
54
|
+
function baseOfMerged(root, cfg, head) {
|
|
55
|
+
const base = mergeBase(root, cfg, head);
|
|
56
|
+
const full = git(root, ['rev-parse', '--verify', `${head}^{commit}`]);
|
|
57
|
+
if (base !== full) return base;
|
|
58
|
+
const parentsOf = (sha) => git(root, ['rev-list', '--parents', '-n', '1', sha]).split(' ').slice(1);
|
|
59
|
+
const later = git(root, ['rev-list', '--first-parent', '--ancestry-path', `${full}..${defaultRef(root, cfg)}`]);
|
|
60
|
+
const merge = later === '' ? null : later.split('\n').at(-1);
|
|
61
|
+
const parents = merge ? parentsOf(merge) : [];
|
|
62
|
+
if (!merge || parents[0] === full) {
|
|
63
|
+
const own = parentsOf(full);
|
|
64
|
+
return own.length >= 2 ? own[0] : base;
|
|
65
|
+
}
|
|
66
|
+
if (parents.length < 2) return base;
|
|
67
|
+
return git(root, ['merge-base', parents[0], full]);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// What stops the release, one line per slice, in slice order; [] when nothing does.
|
|
71
|
+
export function releaseBlockers(root, cfg, phase, host) {
|
|
72
|
+
const rel = runbookRel(root, cfg);
|
|
73
|
+
const out = [];
|
|
74
|
+
for (const { slice, state } of phaseSlices(root, cfg, phase)) {
|
|
75
|
+
const id = slice.id;
|
|
76
|
+
if (state.state !== 'merged') {
|
|
77
|
+
out.push(`${id} is ${state.state}, not merged`);
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const n = state.pr?.number;
|
|
81
|
+
if (!Number.isInteger(n)) {
|
|
82
|
+
out.push(`${id} has no recorded pull request`);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (!slice.runbook) continue;
|
|
86
|
+
// D-55: the body first, read through the host; else the diff to the recorded head.
|
|
87
|
+
const body = host.getPullRequest(n).body ?? '';
|
|
88
|
+
if (runbookVerdict({ flag: true, sections: [], body, rel }) === null) continue;
|
|
89
|
+
const head = state.pr.headSha;
|
|
90
|
+
if (typeof head !== 'string' || !/^[0-9a-f]{7,40}$/.test(head) || !commitExists(root, head)) {
|
|
91
|
+
out.push(`${id}: commit ${String(head ?? 'unknown').slice(0, 7)} of #${n} is not here; fetch it or give the pull request body a Runbook line`);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const sections = runbookSections(root, rel, baseOfMerged(root, cfg, head), head);
|
|
95
|
+
const message = runbookVerdict({ flag: true, sections, body, rel });
|
|
96
|
+
if (message !== null) out.push(`${id} (#${n}): ${message}`);
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// `REQ-3.10` before `REQ-10.1`, `D-9` before `D-10`: by each number in the ID.
|
|
102
|
+
const numbers = (id) => (id.match(/\d+/g) ?? []).map(Number);
|
|
103
|
+
function byNumbers(a, b) {
|
|
104
|
+
const x = numbers(a);
|
|
105
|
+
const y = numbers(b);
|
|
106
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) {
|
|
107
|
+
const d = (x[i] ?? -1) - (y[i] ?? -1);
|
|
108
|
+
if (d !== 0) return d;
|
|
109
|
+
}
|
|
110
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// The phase's name: the phase file's `# Phase <n> — <name>` heading, else the directory's name.
|
|
114
|
+
function phaseTitle(phase, phaseDir) {
|
|
115
|
+
const own = `${phase}.md`;
|
|
116
|
+
const candidates = fs
|
|
117
|
+
.readdirSync(phaseDir)
|
|
118
|
+
.filter((f) => f.endsWith('.md') && !/^S-\d+/.test(f))
|
|
119
|
+
.sort((a, b) => (a === own ? -1 : b === own ? 1 : a < b ? -1 : a > b ? 1 : 0));
|
|
120
|
+
for (const f of candidates) {
|
|
121
|
+
const parsed = parsePhaseFile(readText(path.join(phaseDir, f)));
|
|
122
|
+
if (parsed && parsed.id === phase) return parsed.name;
|
|
123
|
+
}
|
|
124
|
+
return phaseOfDir(path.basename(phaseDir))?.name ?? phase;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// REQ id -> its heading's text after the ID.
|
|
128
|
+
function reqTitles(root, cfg) {
|
|
129
|
+
const out = new Map();
|
|
130
|
+
const texts = new Map();
|
|
131
|
+
for (const b of reqBlocks(root, cfg)) {
|
|
132
|
+
if (out.has(b.id)) continue;
|
|
133
|
+
if (!texts.has(b.file)) texts.set(b.file, lines(readText(path.join(root, ...b.file.split('/')))));
|
|
134
|
+
const heading = (texts.get(b.file)[b.line - 1] ?? '').replace(/^#+\s*/, '').replace(/\s*#*\s*$/, '');
|
|
135
|
+
out.set(b.id, heading.startsWith(b.id) ? heading.slice(b.id.length).trim() : '');
|
|
136
|
+
}
|
|
137
|
+
return out;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// The runbook's `## Rollback` section, quoted with its file and line.
|
|
141
|
+
function rollbackLines(root, cfg) {
|
|
142
|
+
const file = kitPaths(root, cfg).runbook;
|
|
143
|
+
const rel = runbookRel(root, cfg);
|
|
144
|
+
const text = exists(file) ? readText(file) : '';
|
|
145
|
+
const hs = headings(text);
|
|
146
|
+
const i = hs.findIndex((h) => h.level === 2 && h.text === 'Rollback');
|
|
147
|
+
if (i === -1) return ['The runbook has no ## Rollback section.'];
|
|
148
|
+
const all = lines(text);
|
|
149
|
+
const next = hs.slice(i + 1).find((h) => h.level <= 2);
|
|
150
|
+
const body = all.slice(hs[i].line, next ? next.line - 1 : all.length);
|
|
151
|
+
while (body.length > 0 && body[0].trim() === '') body.shift();
|
|
152
|
+
while (body.length > 0 && body.at(-1).trim() === '') body.pop();
|
|
153
|
+
return [`From ${rel}:${hs[i].line}:`, '', ...body.map((l) => (l.trim() === '' ? '>' : `> ${l.trimEnd()}`))];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// The record's text: LF endings, one newline at the end. `sha` is the default branch's commit.
|
|
157
|
+
export function renderRelease(root, cfg, phase, { host, sha }) {
|
|
158
|
+
const slices = phaseSlices(root, cfg, phase);
|
|
159
|
+
const committed = new Date(Number(git(root, ['log', '-1', '--format=%ct', sha])) * 1000).toISOString().replace(/\.\d{3}Z$/, 'Z');
|
|
160
|
+
const out = [
|
|
161
|
+
`# Release ${phase} — ${phaseTitle(phase, slices[0].phaseDir)}`,
|
|
162
|
+
'',
|
|
163
|
+
`Default branch: ${cfg.defaultBranch} at ${sha}, committed ${committed}.`,
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
const titles = reqTitles(root, cfg);
|
|
167
|
+
const reqs = new Map();
|
|
168
|
+
for (const { slice } of slices) {
|
|
169
|
+
for (const r of slice.requirements) {
|
|
170
|
+
if (!reqs.has(r)) reqs.set(r, []);
|
|
171
|
+
if (!reqs.get(r).includes(slice.id)) reqs.get(r).push(slice.id);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
out.push('', '## Requirements delivered', '');
|
|
175
|
+
for (const r of [...reqs.keys()].sort(byNumbers)) out.push(`- ${[r, titles.get(r)].filter(Boolean).join(' ')} (${reqs.get(r).join(', ')})`);
|
|
176
|
+
if (reqs.size === 0) out.push('None.');
|
|
177
|
+
|
|
178
|
+
// Each pull request as the host has it; the state file's record where the host leaves a field out.
|
|
179
|
+
const prs = new Map();
|
|
180
|
+
for (const { state } of slices) {
|
|
181
|
+
const n = state.pr?.number;
|
|
182
|
+
if (!Number.isInteger(n) || prs.has(n)) continue;
|
|
183
|
+
const live = host.getPullRequest(n);
|
|
184
|
+
prs.set(n, {
|
|
185
|
+
title: live.title ?? state.pr.title ?? '',
|
|
186
|
+
url: live.url ?? state.pr.url ?? '',
|
|
187
|
+
mergedAt: live.mergedAt ?? state.mergedAt ?? null,
|
|
188
|
+
body: live.body ?? '',
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const numbersOf = [...prs.keys()].sort((a, b) => a - b);
|
|
192
|
+
out.push('', '## Pull requests', '');
|
|
193
|
+
for (const n of numbersOf) {
|
|
194
|
+
const p = prs.get(n);
|
|
195
|
+
out.push(`- ${[`#${n}`, p.title, p.url].filter((s) => s !== '').join(' ')}${p.mergedAt ? `, merged ${p.mergedAt}` : ''}`);
|
|
196
|
+
}
|
|
197
|
+
if (numbersOf.length === 0) out.push('None.');
|
|
198
|
+
|
|
199
|
+
const decisionsFile = kitPaths(root, cfg).decisions;
|
|
200
|
+
const known = new Map((exists(decisionsFile) ? readDecisions(readText(decisionsFile)).rows : []).map((r) => [r.id, r]));
|
|
201
|
+
const taken = new Map();
|
|
202
|
+
for (const n of numbersOf) {
|
|
203
|
+
for (const m of (getSection(prs.get(n).body, 'Decisions') ?? '').matchAll(/(?<![\w-])D-\d+(?!\w)/g)) {
|
|
204
|
+
if (!known.has(m[0])) continue;
|
|
205
|
+
if (!taken.has(m[0])) taken.set(m[0], []);
|
|
206
|
+
if (!taken.get(m[0]).includes(n)) taken.get(m[0]).push(n);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
out.push('', '## Decisions', '');
|
|
210
|
+
for (const d of [...taken.keys()].sort(byNumbers)) out.push(`- ${d} ${known.get(d).question} (${taken.get(d).map((n) => `#${n}`).join(', ')})`);
|
|
211
|
+
if (taken.size === 0) out.push('None.');
|
|
212
|
+
|
|
213
|
+
out.push('', '## Rollback', '', ...rollbackLines(root, cfg));
|
|
214
|
+
return `${out.join('\n')}\n`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// -> {rel, text, slices}. A record that exists refuses; one HEAD does not hold was written by an
|
|
218
|
+
// earlier run and not committed, and the refusal then names `--undo`. With `dryRun` nothing is written and the branch is not judged, so the
|
|
219
|
+
// procedure can ask before it cuts the release branch; the text is then the record a release at the
|
|
220
|
+
// default branch's tip would write.
|
|
221
|
+
export function writeRelease(root, cfg, phase, { host, dryRun = false }) {
|
|
222
|
+
const slices = phaseSlices(root, cfg, phase).map(({ slice }) => slice.id);
|
|
223
|
+
const tip = git(root, ['rev-parse', '--verify', `${defaultRef(root, cfg)}^{commit}`]);
|
|
224
|
+
if (!dryRun) {
|
|
225
|
+
const branch = currentBranch(root);
|
|
226
|
+
if (!branch || !RELEASE_BRANCH.test(branch) || git(root, ['rev-parse', 'HEAD']) !== tip) {
|
|
227
|
+
throw new ReleaseError(1, `release runs on a release branch at the tip of ${cfg.defaultBranch}; run slicekit branch release <slug>`);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
const file = path.join(kitPaths(root, cfg).releases, `${phase}.md`);
|
|
231
|
+
const rel = posix(root, file);
|
|
232
|
+
if (exists(file)) {
|
|
233
|
+
const way = blobAtHead(root, rel) === null ? `\n${rel} is not committed; slicekit release ${phase} --undo removes it and puts the state files and BUILD.md back` : '';
|
|
234
|
+
throw new ReleaseError(1, `${rel} exists; a phase is released once${way}`);
|
|
235
|
+
}
|
|
236
|
+
const blockers = releaseBlockers(root, cfg, phase, host);
|
|
237
|
+
if (blockers.length > 0) throw new ReleaseError(1, blockers.join('\n'));
|
|
238
|
+
const text = renderRelease(root, cfg, phase, { host, sha: tip });
|
|
239
|
+
if (dryRun) return { rel, text, slices };
|
|
240
|
+
|
|
241
|
+
// Through a temporary name and a rename: a reader never sees half a record. The record comes
|
|
242
|
+
// first because the move to released reads it. When a later write fails, the record is removed
|
|
243
|
+
// and each state file is put back as it was, so the next run is not refused by this one's remains.
|
|
244
|
+
const stateDir = kitPaths(root, cfg).state;
|
|
245
|
+
const before = slices.map((id) => {
|
|
246
|
+
const stateFile = path.join(stateDir, stateFileName(id));
|
|
247
|
+
return { stateFile, bytes: exists(stateFile) ? fs.readFileSync(stateFile) : null };
|
|
248
|
+
});
|
|
249
|
+
try {
|
|
250
|
+
writeText(file, text);
|
|
251
|
+
for (const id of slices) setState(root, cfg, id, 'released', { release: rel });
|
|
252
|
+
const build = kitPaths(root, cfg).build;
|
|
253
|
+
writeText(build, renderBuild(root, cfg, exists(build) ? readText(build) : ''));
|
|
254
|
+
} catch (e) {
|
|
255
|
+
fs.rmSync(file, { force: true });
|
|
256
|
+
for (const { stateFile, bytes } of before) {
|
|
257
|
+
if (bytes === null) fs.rmSync(stateFile, { force: true });
|
|
258
|
+
else if (!fs.readFileSync(stateFile).equals(bytes)) fs.writeFileSync(stateFile, bytes);
|
|
259
|
+
}
|
|
260
|
+
throw e;
|
|
261
|
+
}
|
|
262
|
+
return { rel, text, slices };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// The bytes of `rel` in HEAD, or null when HEAD has no such file.
|
|
266
|
+
function blobAtHead(root, rel) {
|
|
267
|
+
try {
|
|
268
|
+
return execFileSync('git', ['cat-file', 'blob', `HEAD:${rel}`], { cwd: root, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024 });
|
|
269
|
+
} catch {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// `release P<n> --undo`: takes back a release that was written and not committed, so the phase can
|
|
275
|
+
// be released again with no git command. It removes the record and puts each state file of the phase
|
|
276
|
+
// and BUILD.md back as HEAD has them, in the working tree and in the index. A record HEAD holds is
|
|
277
|
+
// not undone: that phase is released. -> {rel}
|
|
278
|
+
export function undoRelease(root, cfg, phase) {
|
|
279
|
+
const slices = phaseSlices(root, cfg, phase).map(({ slice }) => slice.id);
|
|
280
|
+
const paths = kitPaths(root, cfg);
|
|
281
|
+
const file = path.join(paths.releases, `${phase}.md`);
|
|
282
|
+
const rel = posix(root, file);
|
|
283
|
+
if (blobAtHead(root, rel) !== null) throw new ReleaseError(1, `${rel} exists; a phase is released once`);
|
|
284
|
+
if (!exists(file)) throw new ReleaseError(1, `${rel} is not written; nothing to undo`);
|
|
285
|
+
const back = [...slices.map((id) => path.join(paths.state, stateFileName(id))), paths.build];
|
|
286
|
+
const rels = [rel, ...back.map((f) => posix(root, f))];
|
|
287
|
+
// The index first: a pull request that failed after staging leaves these paths staged.
|
|
288
|
+
git(root, ['--literal-pathspecs', 'reset', '-q', '--', ...rels]);
|
|
289
|
+
for (const f of back) {
|
|
290
|
+
const bytes = blobAtHead(root, posix(root, f));
|
|
291
|
+
if (bytes === null) fs.rmSync(f, { force: true });
|
|
292
|
+
else if (!exists(f) || !fs.readFileSync(f).equals(bytes)) fs.writeFileSync(f, bytes);
|
|
293
|
+
}
|
|
294
|
+
fs.rmSync(file, { force: true });
|
|
295
|
+
return { rel };
|
|
296
|
+
}
|
package/src/reports.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// The reports of `/slicekit ops` and `/slicekit audit` (REQ-2.13, REQ-2.14, D-57, D-58): where the
|
|
2
|
+
// next one goes, and how a check reads one. A report lives under .slicekit/reports, which init's
|
|
3
|
+
// ignore rules cover, so writing one changes no tracked file.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { lines } from './markdown.js';
|
|
7
|
+
import { kitPaths } from './paths.js';
|
|
8
|
+
|
|
9
|
+
const posix = (p) => p.split(path.sep).join('/');
|
|
10
|
+
const FENCE = /^\s*(```|~~~)/;
|
|
11
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
12
|
+
|
|
13
|
+
// The next free report of `kind`, relative to the root with forward slashes:
|
|
14
|
+
// `.slicekit/reports/<kind>-<k>.md`, `k` one above the highest of that kind there, else 1. The path
|
|
15
|
+
// is reserved by creating the empty file with the exclusive flag, moving to the next `k` while
|
|
16
|
+
// another run holds it, so two runs at once never get one path. Nothing else is written.
|
|
17
|
+
export function nextReport(root, cfg, kind) {
|
|
18
|
+
const dir = kitPaths(root, cfg).reports;
|
|
19
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
20
|
+
const name = new RegExp(`^${escapeRe(kind)}-(\\d+)\\.md$`);
|
|
21
|
+
let k = 1;
|
|
22
|
+
for (const entry of fs.readdirSync(dir)) {
|
|
23
|
+
const m = name.exec(entry);
|
|
24
|
+
if (m && Number(m[1]) >= k) k = Number(m[1]) + 1;
|
|
25
|
+
}
|
|
26
|
+
for (;;) {
|
|
27
|
+
const file = path.join(dir, `${kind}-${k}.md`);
|
|
28
|
+
try {
|
|
29
|
+
fs.closeSync(fs.openSync(file, 'wx'));
|
|
30
|
+
return posix(path.relative(root, file));
|
|
31
|
+
} catch (e) {
|
|
32
|
+
if (e.code !== 'EEXIST') throw e;
|
|
33
|
+
k++;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The `##` sections of a report outside fenced blocks: lower-case heading -> {line, lines}, `line`
|
|
39
|
+
// the heading's 1-based line and `lines` every line after it, as {text, line}, up to the next `#` or
|
|
40
|
+
// `##` heading. The first section of a name wins.
|
|
41
|
+
export function reportSections(text) {
|
|
42
|
+
const out = new Map();
|
|
43
|
+
let fenced = false;
|
|
44
|
+
let current = null;
|
|
45
|
+
lines(text).forEach((raw, i) => {
|
|
46
|
+
if (FENCE.test(raw)) {
|
|
47
|
+
fenced = !fenced;
|
|
48
|
+
} else if (!fenced) {
|
|
49
|
+
const m = /^(#{1,2})\s+(.*?)\s*#*\s*$/.exec(raw);
|
|
50
|
+
if (m) {
|
|
51
|
+
current = null;
|
|
52
|
+
const key = m[2].toLowerCase();
|
|
53
|
+
if (m[1].length === 2 && !out.has(key)) {
|
|
54
|
+
current = { line: i + 1, lines: [] };
|
|
55
|
+
out.set(key, current);
|
|
56
|
+
}
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (current) current.lines.push({ text: raw, line: i + 1 });
|
|
61
|
+
});
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const isRow = (l) => /^\s*\|.*\|\s*$/.test(l);
|
|
66
|
+
export const isDivider = (l) => /^\s*\|(\s*:?-+:?\s*\|)+\s*$/.test(l);
|
|
67
|
+
// A row's cells; a `\|` is a pipe inside its cell.
|
|
68
|
+
export const cellsOf = (row) =>
|
|
69
|
+
row
|
|
70
|
+
.replace(/^\s*\|/, '')
|
|
71
|
+
.replace(/(?<!\\)\|\s*$/, '')
|
|
72
|
+
.split(/(?<!\\)\|/)
|
|
73
|
+
.map((c) => c.trim().replace(/\\\|/g, '|'));
|
|
74
|
+
|
|
75
|
+
// The first table of the section `heading`: {header: {cells, line}, rows: [{cells, line}]}, or null
|
|
76
|
+
// when the section is missing or holds no table.
|
|
77
|
+
export function sectionTable(text, heading) {
|
|
78
|
+
const section = reportSections(text).get(heading.toLowerCase());
|
|
79
|
+
if (!section) return null;
|
|
80
|
+
const ls = section.lines;
|
|
81
|
+
for (let i = 0; i + 1 < ls.length; i++) {
|
|
82
|
+
if (!isRow(ls[i].text) || !isDivider(ls[i + 1].text)) continue;
|
|
83
|
+
const rows = [];
|
|
84
|
+
for (let j = i + 2; j < ls.length && isRow(ls[j].text); j++) rows.push({ cells: cellsOf(ls[j].text), line: ls[j].line });
|
|
85
|
+
return { header: { cells: cellsOf(ls[i].text), line: ls[i].line }, rows };
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// The rows of the first table of the section `heading`, the header row dropped: [{cells, line}].
|
|
91
|
+
export function reportTable(text, heading) {
|
|
92
|
+
return sectionTable(text, heading)?.rows ?? [];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Whether `<file>:<line>` names a line that exists: a file under the root with at least that many lines.
|
|
96
|
+
export function lineExists(root, file, line) {
|
|
97
|
+
const abs = path.resolve(root, file);
|
|
98
|
+
const rel = path.relative(root, abs);
|
|
99
|
+
if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return false;
|
|
100
|
+
let text;
|
|
101
|
+
try {
|
|
102
|
+
if (!fs.statSync(abs).isFile()) return false;
|
|
103
|
+
text = fs.readFileSync(abs, 'utf8');
|
|
104
|
+
} catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
const all = text.split('\n');
|
|
108
|
+
const count = all.at(-1) === '' ? all.length - 1 : all.length;
|
|
109
|
+
return Number.isInteger(line) && line >= 1 && line <= count;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// One `<rel>:<line> <message>` per closing line the report lacks: `Skipped:` and `Not checked:`, each
|
|
113
|
+
// at the start of its own line.
|
|
114
|
+
export function footerProblems(rel, text) {
|
|
115
|
+
const all = lines(text);
|
|
116
|
+
const last = Math.max(1, all.at(-1) === '' ? all.length - 1 : all.length);
|
|
117
|
+
return ['Skipped:', 'Not checked:'].filter((label) => !all.some((l) => l.startsWith(label))).map((label) => `${rel}:${last} no "${label}" line`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// The text of a report named on the command line, with its path as the messages print it. A path
|
|
121
|
+
// that is no file is `null` text.
|
|
122
|
+
export function readReport(root, given) {
|
|
123
|
+
const abs = path.resolve(root, given);
|
|
124
|
+
const rel = posix(path.relative(root, abs));
|
|
125
|
+
try {
|
|
126
|
+
return { rel, text: fs.readFileSync(abs, 'utf8').replace(/^/, '') };
|
|
127
|
+
} catch (e) {
|
|
128
|
+
if (e.code === 'ENOENT' || e.code === 'EISDIR') return { rel, text: null };
|
|
129
|
+
throw e;
|
|
130
|
+
}
|
|
131
|
+
}
|