slicekit 0.3.2 → 0.3.3

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slicekit",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "description": "Spec-driven agentic workflow kit",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/build/pr.js CHANGED
@@ -12,6 +12,7 @@ import { stateFileName } from '../ids.js';
12
12
  import { kitPaths } from '../paths.js';
13
13
  import { openOrUpdate } from '../pr.js';
14
14
  import { PrBodyError, getSection, renderPrBody } from '../prbody.js';
15
+ import { mergeBase, runbookRel, runbookSections, runbookVerdict } from '../runbook.js';
15
16
  import { readSlice, recordHead } from '../state/index.js';
16
17
  import { headCovers } from '../state/covers.js';
17
18
  import { posixRel, runCommand, sliceIn, unusableRun } from './red.js';
@@ -23,7 +24,7 @@ import { BuildError, findWorktree } from './worktree.js';
23
24
 
24
25
  const FROM = ['building', 'draft-pr', 'in-review', 'changes-requested', 'ci-green', 'ready'];
25
26
  const NOTES_SHAPE = 'notes need tryIt (three steps) and skipped';
26
- const NO_CHANGE = 'no operational change: the slice touches no configuration, infrastructure, migration, alert, queue or integration';
27
+ const NO_CHANGE_LINE = 'no operational change: the slice touches no configuration, infrastructure, migration, alert, queue or integration';
27
28
  const RUNBOOK_REFUSAL = 'the slice touches operations; change the runbook or give notes.runbook "no operational change: <reason>"';
28
29
  const COMMANDS = ['test', 'lint', 'build'];
29
30
  // The sections the notes give: with no notes, the live body must hold each of them.
@@ -97,20 +98,6 @@ function pendingDraftPr(wt, stateRel, current) {
97
98
  );
98
99
  }
99
100
 
100
- // Whether the branch changed the runbook since it left the default branch.
101
- function runbookChanged(wt, cfg, rel) {
102
- const origin = `refs/remotes/origin/${cfg.defaultBranch}`;
103
- let from;
104
- try {
105
- git(wt, ['rev-parse', '--verify', '--quiet', origin]);
106
- from = origin;
107
- } catch {
108
- from = `refs/heads/${cfg.defaultBranch}`;
109
- }
110
- const base = git(wt, ['merge-base', 'HEAD', from]);
111
- return git(wt, ['--literal-pathspecs', 'diff', '--name-only', base, 'HEAD', '--', rel]) !== '';
112
- }
113
-
114
101
  // The test run's pass and fail totals, from the last line naming each; the summary line when the
115
102
  // output does not name both on separate lines.
116
103
  function proofSummary(run) {
@@ -204,10 +191,14 @@ export function openSlicePr(root, cfg, host, id, { notes, worktree, env = proces
204
191
  if (missing) throw new BuildError(`the pull request body has no "${missing}"; pass --notes <file> to supply it`);
205
192
  }
206
193
 
207
- const runbookRel = cfg.docsRoot === '.' ? 'runbook.md' : `${cfg.docsRoot}/runbook.md`;
208
- const changed = runbookChanged(wt, cfg, runbookRel);
194
+ // One judgement with the `runbook` check rule and `slicekit release` (REQ-3.7, D-55): a `##` section
195
+ // of the runbook changed since the branch left the default branch, or a Runbook line that begins
196
+ // "no operational change". A change above the first `##` heading, or of trailing whitespace, is none.
197
+ const rel = runbookRel(wt, cfg);
198
+ const sections = runbookSections(wt, rel, mergeBase(wt, cfg), 'HEAD');
199
+ const changed = sections.length > 0;
209
200
  const runbookNote = changed ? null : (given?.runbook ?? (current.pr ? kept('Runbook', null) : null));
210
- if (slice.runbook && !changed && !(runbookNote ?? '').trim().startsWith('no operational change')) {
201
+ if (runbookVerdict({ flag: slice.runbook, sections, body: runbookNote === null ? null : `**Runbook:** ${runbookNote}`, rel }) !== null) {
211
202
  throw new BuildError(RUNBOOK_REFUSAL);
212
203
  }
213
204
  const { summary, command: testCommand, local } = runCommands(root, wt, cfg, env);
@@ -229,7 +220,7 @@ export function openSlicePr(root, cfg, host, id, { notes, worktree, env = proces
229
220
  'Done when': slice.doneWhen.map((c, i) => `${i + 1}. ${c}`).join(' '),
230
221
  Proof: `\`${testCommand}\` → ${summary} · CI: pending`,
231
222
  Decisions: given?.decisions === undefined ? kept('Decisions', 'none') : given.decisions.join('; ') || 'none',
232
- Runbook: changed ? `changed: ${runbookRel}` : (runbookNote ?? NO_CHANGE),
223
+ Runbook: changed ? `changed: ${rel} (${sections.join(', ')})` : (runbookNote ?? NO_CHANGE_LINE),
233
224
  'Infra / migration': noted('infra', 'Infra / migration', 'none'),
234
225
  'Try it': given ? given.tryIt.map((s, i) => `${i + 1}. ${s.trim()}`).join(' ') : kept('Try it', ''),
235
226
  'Reviewer blocked': kept('Reviewer blocked', 'nothing'),
@@ -77,8 +77,9 @@ export function isBotAuthor(cfg, pr) {
77
77
  return typeof pr?.author === 'string' && bots.includes(pr.author);
78
78
  }
79
79
 
80
- // A `[spec] `, `[plan] ` or `[sync] ` title: a spec, plan or state sync pull request, not a slice's.
81
- export const EXEMPT_TITLE = /^\[(spec|plan|sync)\] /;
80
+ // A `[spec] `, `[plan] `, `[sync] ` or `[release] ` title: a spec, plan, state sync or release record
81
+ // pull request (D-54), not a slice's.
82
+ export const EXEMPT_TITLE = /^\[(spec|plan|sync|release)\] /;
82
83
 
83
84
  // A `[sync] ` title: the state sync pull request, which belongs on a `sync/<short sha>` branch only.
84
85
  export const SYNC_TITLE = /^\[sync\] /;
@@ -0,0 +1,60 @@
1
+ // runbook (03 REQ-3.7, D-21, D-55): on a slice branch whose slice file says `runbook: yes` and whose
2
+ // state is draft-pr or later and not merged or released, the branch changes a `##` section of the
3
+ // runbook or the pull request body's Runbook line begins "no operational change". The body comes
4
+ // from the CI event or `SLICEKIT_PR_BODY`; with neither the rule does not judge, because `build pr`
5
+ // already refuses to open a pull request without one of the two (D-55). One finding, at the slice
6
+ // file's `runbook:` line.
7
+ import path from 'node:path';
8
+ import { readText } from '../../fs.js';
9
+ import { sliceFromBranch } from '../../ids.js';
10
+ import { lines } from '../../markdown.js';
11
+ import { mergeBase, runbookRel, runbookSections, runbookVerdict } from '../../runbook.js';
12
+ import { findSliceFiles, parseSliceFile } from '../../slicefile.js';
13
+ import { readSlice } from '../../state/index.js';
14
+ import { branchTip, readCiEvent } from '../ci-event.js';
15
+
16
+ export const id = 'runbook';
17
+ export const blocking = true;
18
+ export const ratchet = false;
19
+
20
+ const JUDGED = ['draft-pr', 'in-review', 'changes-requested', 'ci-green', 'ready'];
21
+
22
+ // The slice file of `slice`: {rel, text, flag}, or null when no readable slice file names it.
23
+ function sliceFileOf(root, cfg, slice) {
24
+ for (const f of findSliceFiles(root, cfg)) {
25
+ let text;
26
+ let parsed;
27
+ try {
28
+ text = readText(f.path);
29
+ parsed = parseSliceFile(text, f.path);
30
+ } catch {
31
+ continue;
32
+ }
33
+ if (parsed.id === slice) return { rel: path.relative(root, f.path).split(path.sep).join('/'), text, flag: parsed.runbook };
34
+ }
35
+ return null;
36
+ }
37
+
38
+ export function run(ctx) {
39
+ const { root, cfg } = ctx;
40
+ const at = branchTip(ctx);
41
+ if (!at) return [];
42
+ const slice = sliceFromBranch(at.branch);
43
+ if (!slice) return [];
44
+ const file = sliceFileOf(root, cfg, slice);
45
+ if (!file || !file.flag) return [];
46
+ if (!JUDGED.includes(readSlice(root, cfg, slice).state)) return [];
47
+ const env = ctx.env ?? {};
48
+ const hasEvent = typeof env.GITHUB_EVENT_PATH === 'string' && env.GITHUB_EVENT_PATH !== '';
49
+ if (!hasEvent && env.SLICEKIT_PR_BODY === undefined) return [];
50
+ const pr = readCiEvent(env, { cfg, root });
51
+ if (!pr) return [];
52
+ const rel = runbookRel(root, cfg);
53
+ const sections = runbookSections(root, rel, mergeBase(root, cfg, at.tip), at.tip);
54
+ const message = runbookVerdict({ flag: true, sections, body: pr.body, rel });
55
+ if (message === null) return [];
56
+ const line = lines(file.text).findIndex((l) => /^runbook\s*:/.test(l)) + 1;
57
+ return [{ file: file.rel, line, message }];
58
+ }
59
+
60
+ export default { id, blocking, ratchet, run };
package/src/cli/branch.js CHANGED
@@ -1,13 +1,18 @@
1
- // `slicekit branch <spec|gaps|plan> <slug>` (REQ-2.3..REQ-2.5): puts the session on the work branch
2
- // of a document pull request, cut from the default branch as origin has it. The command owns git
1
+ // `slicekit branch <spec|gaps|plan|release> <slug>` (REQ-2.3..REQ-2.5, REQ-2.9, D-54): puts the session on the
2
+ // work branch of a document pull request, cut from the default branch as origin has it. The command owns git
3
3
  // (D-19). A change to a tracked file (staged or not) is refused, so no edit is carried across;
4
4
  // untracked files go along as git carries them, so a source dropped in for intake survives.
5
+ // A `release/<slug>` branch that exists away from the default branch's tip is moved there or refused;
6
+ // one that holds its own commits is refused with its open pull request, read through the git host
7
+ // (C-1 pullRequestForBranch), or with the next free slug when the host says none is open.
8
+ import { getHost } from '../adapters/githost/index.js';
9
+ import { GitHostError } from '../adapters/githost/errors.js';
5
10
  import { ConfigError, loadConfig } from '../config.js';
6
11
  import { GitError, assertRef, currentBranch, git, hasRemote, switchBranch } from '../git.js';
7
12
 
8
- const KINDS = ['spec', 'gaps', 'plan'];
13
+ const KINDS = ['spec', 'gaps', 'plan', 'release'];
9
14
  const SLUG = /^[a-z0-9][a-z0-9-]{0,59}$/;
10
- const USAGE = 'branch <spec|gaps|plan> <slug>';
15
+ const USAGE = 'branch <spec|gaps|plan|release> <slug>';
11
16
 
12
17
  const resolves = (root, ref) => {
13
18
  try {
@@ -34,19 +39,24 @@ async function run(args, io) {
34
39
  try {
35
40
  const cfg = loadConfig(root);
36
41
  const base = assertRef(cfg.defaultBranch);
37
- if (currentBranch(root) === target) {
42
+ const onTarget = currentBranch(root) === target;
43
+ if (onTarget && kind !== 'release') {
38
44
  io.stdout(`${target}\n`);
39
45
  return 0;
40
46
  }
41
- if (git(root, ['status', '--porcelain', '--untracked-files=no']) !== '') {
47
+ const dirty = git(root, ['status', '--porcelain', '--untracked-files=no']) !== '';
48
+ if (dirty && !onTarget) {
42
49
  io.stderr('slicekit: commit or stash your changes first\n');
43
50
  return 1;
44
51
  }
45
52
  // The full ref: a tag named like the default branch must not be what the branch is cut from.
46
53
  let from = `refs/heads/${base}`;
47
- if (hasRemote(root, 'origin')) {
54
+ const origin = hasRemote(root, 'origin');
55
+ let fetched = false;
56
+ if (origin) {
48
57
  try {
49
58
  git(root, ['fetch', '-q', 'origin', base]);
59
+ fetched = true;
50
60
  if (resolves(root, `refs/remotes/origin/${base}`)) from = `refs/remotes/origin/${base}`;
51
61
  // The work branch too, so one pushed from another clone is found; origin not having it is
52
62
  // the usual case for a new branch, not an error.
@@ -65,6 +75,55 @@ async function run(args, io) {
65
75
  // A work branch someone already pushed is taken up where it stands, tracking origin's copy;
66
76
  // only a new one is cut from the default branch.
67
77
  const remote = `refs/remotes/origin/${target}`;
78
+ if (kind === 'release') {
79
+ // `slicekit release` runs only at the default branch's tip. A release branch that stands
80
+ // elsewhere, here or on origin, is moved to the tip when it holds no commit the default
81
+ // branch lacks; one that does is refused: with its open pull request when the host has one,
82
+ // else with the next free slug.
83
+ const tip = git(root, ['rev-parse', '--verify', `${from}^{commit}`]);
84
+ const copies = [`refs/heads/${target}`, remote].filter((ref) => resolves(root, ref));
85
+ const stale = copies.filter((ref) => git(root, ['rev-parse', '--verify', `${ref}^{commit}`]) !== tip);
86
+ if (stale.some((ref) => git(root, ['rev-list', '--count', `${from}..${ref}`]) !== '0')) {
87
+ // The branch may be that of the phase's open release pull request; a second slug would then
88
+ // open a second one beside it. A pull request needs its branch on origin, so the host is
89
+ // asked unless a fetch that worked found no such branch there.
90
+ if (origin && (!fetched || resolves(root, remote))) {
91
+ let open;
92
+ try {
93
+ open = getHost(cfg, io.env ?? process.env, root).pullRequestForBranch(target, { base });
94
+ } catch (e) {
95
+ if (!(e instanceof GitHostError)) throw e;
96
+ io.stderr(`slicekit: ${target} holds commits ${base} lacks, and the git host could not be asked for its open pull request (${e.message}); no branch is cut
97
+ `);
98
+ return 1;
99
+ }
100
+ if (open) {
101
+ io.stderr(`slicekit: ${target} is the branch of open pull request #${open.number} (${open.url}); the phase's release is already open
102
+ `);
103
+ return 1;
104
+ }
105
+ }
106
+ let n = 2;
107
+ while (resolves(root, `refs/heads/${target}-${n}`) || resolves(root, `refs/remotes/origin/${target}-${n}`)) n += 1;
108
+ io.stderr(`slicekit: ${target} holds commits ${base} lacks, so no release runs on it; run slicekit branch release ${slug}-${n}\n`);
109
+ return 1;
110
+ }
111
+ if (onTarget && stale.length === 0) {
112
+ io.stdout(`${target}\n`);
113
+ return 0;
114
+ }
115
+ if (stale.length > 0) {
116
+ if (dirty) {
117
+ io.stderr('slicekit: commit or stash your changes first\n');
118
+ return 1;
119
+ }
120
+ // -C makes the branch, or moves it, to stand at the tip; it held no commit of its own.
121
+ git(root, ['switch', '-q', '--no-track', '-C', target, from]);
122
+ io.stderr(`slicekit: ${target} was behind ${base}; moved to the tip of ${base}\n`);
123
+ io.stdout(`${target}\n`);
124
+ return 0;
125
+ }
126
+ }
68
127
  if (resolves(root, `refs/heads/${target}`)) switchBranch(root, target);
69
128
  else if (resolves(root, remote)) switchBranch(root, target, { create: true, from: remote, track: true });
70
129
  else switchBranch(root, target, { create: true, from });
package/src/cli/index.js CHANGED
@@ -17,6 +17,7 @@ import { journalCommand } from './journal.js';
17
17
  import { planCommand } from './plan.js';
18
18
  import { hookCommand } from './hook.js';
19
19
  import { readyLabelCommand } from './ready-label.js';
20
+ import { releaseCommand } from './release.js';
20
21
  import { reviewCommand } from './review.js';
21
22
  import { specCommand } from './spec.js';
22
23
  import { stageCommand } from './stage.js';
@@ -50,6 +51,7 @@ export const COMMANDS = {
50
51
  plan: planCommand,
51
52
  pr: prCommand,
52
53
  'ready-label': readyLabelCommand,
54
+ release: releaseCommand,
53
55
  review: reviewCommand,
54
56
  spec: specCommand,
55
57
  shipped: shippedCommand,
@@ -0,0 +1,57 @@
1
+ // `slicekit release P<n> [--dry-run | --undo]` (02 REQ-2.9, D-54): writes the phase's release record, sets
2
+ // each slice released and rewrites BUILD.md; it commits nothing and deploys nothing (D-12, D-19).
3
+ // Exit 0 with the record's path and one `released <id>` line per slice (with --dry-run, the record's
4
+ // text and nothing written); 1 when it refuses, one `slicekit: <line>` per reason; 2 on bad usage, a
5
+ // bad config or a phase that is not one. With --undo it releases nothing: it removes a record that is
6
+ // not committed and puts the phase's state files and BUILD.md back as HEAD has them, printing
7
+ // `removed <record>`; it refuses (1) a record HEAD holds, and when there is no record.
8
+ import { parseArgs } from 'node:util';
9
+ import { getHost } from '../adapters/githost/index.js';
10
+ import { GitHostError } from '../adapters/githost/errors.js';
11
+ import { ConfigError, loadConfig } from '../config.js';
12
+ import { GitError } from '../git.js';
13
+ import { ReleaseError, undoRelease, writeRelease } from '../release.js';
14
+ import { SliceFileError } from '../slicefile.js';
15
+ import { LockError, TransitionError } from '../state/index.js';
16
+
17
+ const USAGE = 'release P<n> [--dry-run | --undo]';
18
+
19
+ const fail = (io, message, code) => {
20
+ for (const line of message.split('\n')) io.stderr(`slicekit: ${line}\n`);
21
+ return code;
22
+ };
23
+
24
+ async function run(args, io) {
25
+ let values;
26
+ let positionals;
27
+ try {
28
+ ({ values, positionals } = parseArgs({ args, options: { 'dry-run': { type: 'boolean' }, undo: { type: 'boolean' } }, allowPositionals: true }));
29
+ } catch (e) {
30
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
31
+ return 2;
32
+ }
33
+ if (positionals.length !== 1 || !/^P[1-9]\d*$/.test(positionals[0]) || (values['dry-run'] && values.undo)) {
34
+ io.stderr(`usage: slicekit ${USAGE}\n`);
35
+ return 2;
36
+ }
37
+ const root = io.cwd;
38
+ try {
39
+ const cfg = loadConfig(root);
40
+ if (values.undo) {
41
+ io.stdout(`removed ${undoRelease(root, cfg, positionals[0]).rel}\n`);
42
+ return 0;
43
+ }
44
+ const host = getHost(cfg, io.env ?? process.env, root);
45
+ const r = writeRelease(root, cfg, positionals[0], { host, dryRun: values['dry-run'] === true });
46
+ if (values['dry-run']) io.stdout(r.text);
47
+ else io.stdout(`${r.rel}\n${r.slices.map((id) => `released ${id}\n`).join('')}`);
48
+ return 0;
49
+ } catch (e) {
50
+ if (e instanceof ConfigError) return fail(io, e.message, 2);
51
+ if (e instanceof ReleaseError) return fail(io, e.message, e.code);
52
+ if (e instanceof GitError || e instanceof GitHostError || e instanceof TransitionError || e instanceof LockError || e instanceof SliceFileError) return fail(io, e.message, 1);
53
+ throw e;
54
+ }
55
+ }
56
+
57
+ export const releaseCommand = { run, usage: USAGE };
@@ -29,6 +29,8 @@ async function run(args, io) {
29
29
  io.stderr(`slicekit: ${e.message}\n`);
30
30
  return 2;
31
31
  }
32
+ // D-56: a row of observability.md with no command renders no job.
33
+ for (const w of state.warnings) io.stderr(`slicekit: warning: ${w}\n`);
32
34
  if (values.check) {
33
35
  if (state.current === state.expected) return 0;
34
36
  io.stderr(`slicekit: ${state.current === null ? `${WORKFLOW_PATH} is missing; run slicekit workflow --write to create it` : WORKFLOW_DRIFT}\n`);
package/src/config.js CHANGED
@@ -84,7 +84,7 @@ export const GITHUB_EXPRESSION = /\$\{\{/;
84
84
  export const LINE_SEPARATOR = /[\u0085\u2028\u2029]/;
85
85
 
86
86
  // Errors for text that lands in the generated workflow; expression false where ${{ … }} is the intended use (env).
87
- function workflowTextErrors(at, value, { expression = true } = {}) {
87
+ export function workflowTextErrors(at, value, { expression = true } = {}) {
88
88
  if (typeof value !== 'string') return [];
89
89
  const errors = [];
90
90
  if (expression && GITHUB_EXPRESSION.test(value)) errors.push(`${at}: contains a GitHub expression; pass values through env:`);
package/src/init.js CHANGED
@@ -9,7 +9,7 @@ import { probeCli } from './hook-cli.js';
9
9
  import { kitPaths } from './paths.js';
10
10
  import { kitVersion, renderAll } from './render/index.js';
11
11
  import { readSettings } from './render/settings.js';
12
- import { WORKFLOW_DRIFT, WORKFLOW_PATH, workflowState } from './workflow.js';
12
+ import { WORKFLOW_DRIFT, WORKFLOW_PATH, workflowState, workflowSteps } from './workflow.js';
13
13
  import { getHost } from './adapters/githost/index.js';
14
14
  import { actionsPullRequestSetting, hasSyncJob, missingRules, requiredChecks } from './check/rules/host-rules.js';
15
15
 
@@ -255,6 +255,7 @@ function resolveConfig(root, { name, shape, docsRoot, commands, cli, defaultBran
255
255
  if (!raw) return { cfg, cliWarning: null, cliFilled: false };
256
256
  const errors = validateConfig(raw);
257
257
  if (errors.length > 0) throw new ConfigError(errors);
258
+ workflowSteps(root, raw); // as in init(): refused before the config is written back
258
259
  writeText(file, `${JSON.stringify(raw, null, 2)}\n`);
259
260
  return { cfg: loadConfig(root), cliWarning: probed.warning, cliFilled: true };
260
261
  }
@@ -356,6 +357,7 @@ export function protect(root, { env = process.env } = {}) {
356
357
  export function init(root, { name, shape, docsRoot, commands = {}, cli, defaultBranch, env = process.env }) {
357
358
  const { cfg, cliWarning, cliFilled } = resolveConfig(root, { name, shape, docsRoot, commands, cli, defaultBranch, env });
358
359
  readSettings(root); // a corrupt .claude/settings.json stops init before anything is written
360
+ workflowSteps(root, cfg); // so does a step of observability.md the workflow cannot carry (D-56)
359
361
 
360
362
  const paths = kitPaths(root, cfg);
361
363
  const rel = (abs) => path.relative(root, abs).split(path.sep).join('/');
@@ -386,6 +388,7 @@ export function init(root, { name, shape, docsRoot, commands = {}, cli, defaultB
386
388
  }
387
389
  // The CI workflow (REQ-3.11): written when absent; an existing one is the team's and stays as is.
388
390
  const workflow = workflowState(root, cfg);
391
+ warnings.push(...workflow.warnings);
389
392
  if (workflow.current === null) {
390
393
  writeText(workflow.file, workflow.expected);
391
394
  lists.created.push(WORKFLOW_PATH);
package/src/markdown.js CHANGED
@@ -65,7 +65,8 @@ export const tableCells = (row) =>
65
65
  .split(/(?<!\\)\|/)
66
66
  .map((c) => c.trim().replace(/\\\|/g, '|'));
67
67
  const cells = tableCells;
68
- const isRow = (l) => /^\s*\|.*\|\s*$/.test(l);
68
+ // U+2028 and U+2029 are inside a row, not its end: `.` would stop at them and the row would go unread.
69
+ const isRow = (l) => /^\s*\|[^\r\n]*\|\s*$/.test(l);
69
70
  const isDivider = (l) => /^\s*\|(\s*:?-+:?\s*\|)+\s*$/.test(l);
70
71
 
71
72
  export function tables(text) {
@@ -0,0 +1,203 @@
1
+ // REQ-3.11, D-56: the CI steps observability.md names. Intake writes them (D-20) as a table with the
2
+ // columns Step and Command under `## CI steps the monitoring setup requires`; each row renders as one
3
+ // obs-<n> job of the generated workflow, after the jobs of ci.observabilitySteps.
4
+ import { LINE_SEPARATOR, workflowTextErrors } from './config.js';
5
+ import { lines, tableCells } from './markdown.js';
6
+
7
+ export const STEPS_HEADING = 'CI steps the monitoring setup requires';
8
+
9
+ const COLUMNS = ['Step', 'Command'];
10
+ const FORM =
11
+ 'the steps table is a header line | Step | Command | in plain text, a divider line |---|---|, then one row per step, and each of its lines opens with a bar';
12
+
13
+ // A Step cell that is one code span reads as the span's text; any other reads as written. A span
14
+ // opens and closes with runs of backticks of one length and holds no run of that length.
15
+ function cellText(cell) {
16
+ const text = (cell ?? '').trim();
17
+ const span = /^(`+)(?!`)([\s\S]*[^`])\1$/.exec(text);
18
+ if (!span) return text;
19
+ const inner = span[2].match(/`+/g) ?? [];
20
+ return inner.some((run) => run.length === span[1].length) ? text : span[2].trim();
21
+ }
22
+
23
+ // A Command cell is text with no backtick, or one code span as CommonMark reads it: the run of
24
+ // backticks that opens the cell is closed by the next run of that length, and that run ends the
25
+ // cell. Any other cell holding a backtick returns null: its backticks would reach the job's shell.
26
+ function commandText(cell) {
27
+ const text = (cell ?? '').trim();
28
+ if (!text.includes('`')) return text;
29
+ const open = /^`+/.exec(text);
30
+ if (!open) return null;
31
+ const rest = text.slice(open[0].length);
32
+ for (const run of rest.matchAll(/`+/g)) {
33
+ if (run[0].length !== open[0].length) continue;
34
+ return run.index + run[0].length === rest.length ? rest.slice(0, run.index).trim() : null;
35
+ }
36
+ return null;
37
+ }
38
+
39
+ const opensWithBar = (line) => /^\s*\|/.test(line);
40
+ const isDivider = (line) => opensWithBar(line) && tableCells(line).every((c) => /^:?-+:?$/.test(c));
41
+ // A code fence opens on a run of three or more backticks or tildes; the text after a backtick run
42
+ // holds no backtick.
43
+ const FENCE_OPEN = /^\s*(?:(`{3,})[^`]*|(~{3,}).*)$/;
44
+ const INDENTED = /^(?: {4}| {0,3}\t)/;
45
+ const HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/;
46
+
47
+ // Every line of the file, each {line, n, hidden, heading}. The block state runs from the first line
48
+ // of the file, so a block that opens above the steps section is followed into it. A line is hidden
49
+ // when GitHub shows no table and no heading for it: a code fence and the lines inside it, a line
50
+ // indented as code (four spaces or a tab), and an HTML comment that opens its line, up to and
51
+ // including the line that closes it. A fence closes as CommonMark has it: on a line that is a run of
52
+ // the opening character, at least as long as the opening run, with only spaces after it. `heading`
53
+ // is {level, text} for a heading line that is not hidden, and null for any other line.
54
+ function fileLines(text) {
55
+ const out = [];
56
+ // The opening run of the fence the line is inside, or null.
57
+ let fence = null;
58
+ let inComment = false;
59
+ lines(text).forEach((line, i) => {
60
+ let hidden = false;
61
+ if (fence !== null) {
62
+ hidden = true;
63
+ const run = /^\s*(`+|~+)[ \t]*$/.exec(line)?.[1];
64
+ if (run && run[0] === fence[0] && run.length >= fence.length) fence = null;
65
+ } else if (inComment) {
66
+ hidden = true;
67
+ inComment = !line.includes('-->');
68
+ } else if (FENCE_OPEN.test(line)) {
69
+ hidden = true;
70
+ const open = FENCE_OPEN.exec(line);
71
+ fence = open[1] ?? open[2];
72
+ } else if (/^ {0,3}<!--/.test(line)) {
73
+ hidden = true;
74
+ inComment = !line.slice(line.indexOf('<!--') + 4).includes('-->');
75
+ } else if (INDENTED.test(line) && line.trim() !== '') {
76
+ hidden = true;
77
+ }
78
+ const m = hidden ? null : HEADING.exec(line);
79
+ out.push({ line, n: i + 1, hidden, heading: m ? { level: m[1].length, text: m[2] } : null });
80
+ });
81
+ return out;
82
+ }
83
+
84
+ // The steps table of one observability.md: `rel` is the file's path as the messages name it.
85
+ // The file takes one steps heading that is not hidden; a second is an error naming its line. The
86
+ // section is read whole and fails closed. A hidden line is not read. Of the other lines, one
87
+ // that holds no vertical bar is no part of a table (prose, `Not yet known`, `None`), and one that
88
+ // holds a bar is a line of the one steps table in its exact form or an error naming its line: no
89
+ // line that could read as a step to a person is passed over without a message.
90
+ export function docSteps(text, rel) {
91
+ const out = { steps: [], warnings: [], errors: [] };
92
+ const all = fileLines(text);
93
+ const refuse = (n, message) => {
94
+ out.errors.push(`${rel}:${n}: ${message}`);
95
+ return out;
96
+ };
97
+ const sections = all.filter((l) => l.heading?.level === 2 && l.heading.text === STEPS_HEADING);
98
+ if (sections.length === 0) return out;
99
+ // Only one section is read, so a table under a second would be passed over.
100
+ if (sections.length > 1) {
101
+ return refuse(sections[1].n, `a second heading "## ${STEPS_HEADING}"; the first is at line ${sections[0].n}, and the file takes one steps section`);
102
+ }
103
+ const start = sections[0].n;
104
+ const end = all.find((l) => l.n > start && l.heading && l.heading.level <= 2)?.n ?? Infinity;
105
+ const headingLines = new Set(all.filter((l) => l.heading).map((l) => l.n));
106
+ const body = all.filter((l) => l.n > start && l.n < end);
107
+
108
+ const seen = new Map();
109
+ // 'before' the header, in the 'rows', or 'after' the table's end.
110
+ let state = 'before';
111
+ for (let k = 0; k < body.length; k++) {
112
+ const { line, n, hidden } = body[k];
113
+ const where = `${rel}:${n}`;
114
+ if (state === 'rows') {
115
+ // A row indented as code may still show as a row of the table it follows, so it is not passed over.
116
+ if (hidden && INDENTED.test(line) && line.includes('|')) {
117
+ out.errors.push(`${where}: a row of the steps table is indented as code; write it from the start of the line, opening with a bar`);
118
+ continue;
119
+ }
120
+ // A blank line, a heading, a code fence or an HTML comment ends the table.
121
+ if (hidden || line.trim() === '' || headingLines.has(n)) state = 'after';
122
+ }
123
+ if (hidden || !line.includes('|')) continue;
124
+
125
+ if (state === 'after') {
126
+ return refuse(n, `a line holding a vertical bar after the steps table has ended; the section takes one steps table and no other line holding a bar: ${FORM}`);
127
+ }
128
+
129
+ if (state === 'before') {
130
+ if (!opensWithBar(line)) return refuse(n, `a line holding a vertical bar that is not the header of the steps table; ${FORM}`);
131
+ const header = tableCells(line);
132
+ if (header.length !== COLUMNS.length || !header.every((c, i) => c === COLUMNS[i])) {
133
+ return refuse(n, `the steps table has the columns ${header.join(', ')}; it takes two, Step then Command, in plain text and these capitals: ${FORM}`);
134
+ }
135
+ const next = body[k + 1];
136
+ if (!next || next.hidden || !isDivider(next.line)) return refuse(n, 'the header of the steps table needs a divider line under it, |---|---|');
137
+ const cells = tableCells(next.line).length;
138
+ if (cells !== COLUMNS.length) return refuse(next.n, `the divider line has ${cells} ${cells === 1 ? 'cell' : 'cells'} and the header has ${COLUMNS.length}; ${FORM}`);
139
+ state = 'rows';
140
+ k++;
141
+ continue;
142
+ }
143
+
144
+ if (!opensWithBar(line)) {
145
+ out.errors.push(`${where}: a line of the steps table holds a vertical bar and does not open with one; a row opens with a bar, | Step | Command |`);
146
+ continue;
147
+ }
148
+ // A carriage return alone does not end a line here, and a step is one line.
149
+ if (line.includes('\r')) {
150
+ out.errors.push(`${where}: the row holds a carriage return; write a step on one line`);
151
+ continue;
152
+ }
153
+ const row = tableCells(line);
154
+ // A bare pipe in a command ends its cell: the job would run only the text before it.
155
+ if (row.length > COLUMNS.length) {
156
+ out.errors.push(`${where}: the row has ${row.length} cells and the table has ${COLUMNS.length}; write a pipe inside a command as \\|`);
157
+ continue;
158
+ }
159
+ const name = cellText(row[0]);
160
+ const run = commandText(row[1]);
161
+ if (run === null) {
162
+ out.errors.push(`${where}: the Command cell mixes a code span with other text; write the whole command as one code span, or with no backtick`);
163
+ continue;
164
+ }
165
+ // GitHub shows no comment, and the job would run its text.
166
+ if (name.includes('<!--') || (run.includes('<!--') && !(row[1] ?? '').includes('`'))) {
167
+ out.errors.push(`${where}: the row holds an HTML comment; write a command that holds <!-- as one code span`);
168
+ continue;
169
+ }
170
+ if (name === '') {
171
+ out.errors.push(`${where}: a step needs a name`);
172
+ continue;
173
+ }
174
+ if (run === '') {
175
+ out.warnings.push(`${where}: step "${name}" has no command; no job rendered`);
176
+ continue;
177
+ }
178
+ const problems = [...workflowTextErrors(`${where}: Step`, name, { expression: false }), ...workflowTextErrors(`${where}: Command`, run)];
179
+ // A separator at the edge of a cell is trimmed with the spaces, so the row as written is read too.
180
+ if (problems.length === 0 && LINE_SEPARATOR.test(line)) problems.push(`${where}: contains a line separator YAML cannot carry`);
181
+ // Two jobs of one name: the runbook finds a failing job's step by its name.
182
+ if (problems.length === 0 && seen.has(name)) problems.push(`${where}: step "${name}" is also at ${seen.get(name)}; name it once`);
183
+ if (problems.length > 0) {
184
+ out.errors.push(...problems);
185
+ continue;
186
+ }
187
+ seen.set(name, where);
188
+ out.steps.push({ name, run, at: where });
189
+ }
190
+ return out;
191
+ }
192
+
193
+ // Config's steps first, then the doc's. One name in both places would make one job stand in for
194
+ // another, so it is refused, naming both. `doc` is what docSteps returned, or null when there is no file.
195
+ export function allSteps(cfg, doc) {
196
+ const configSteps = cfg.ci?.observabilitySteps ?? [];
197
+ const errors = [...(doc?.errors ?? [])];
198
+ for (const step of doc?.steps ?? []) {
199
+ const i = configSteps.findIndex((s) => s.name === step.name);
200
+ if (i !== -1) errors.push(`${step.at}: step "${step.name}" is also in ci.observabilitySteps[${i}]; name it in one place`);
201
+ }
202
+ return { steps: [...configSteps, ...(doc?.steps ?? [])], warnings: [...(doc?.warnings ?? [])], errors };
203
+ }
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/runbook.js ADDED
@@ -0,0 +1,96 @@
1
+ // The runbook judgement (03 REQ-3.7, D-21, D-55), shared by the `runbook` check rule, `build pr` and
2
+ // `slicekit release`: a slice that says `runbook: yes` changes a `##` section of the runbook, or its
3
+ // pull request body's Runbook line begins "no operational change".
4
+ import { execFileSync } from 'node:child_process';
5
+ import path from 'node:path';
6
+ import { GitError, git } from './git.js';
7
+ import { headings, lines } from './markdown.js';
8
+ import { kitPaths } from './paths.js';
9
+ import { getSection } from './prbody.js';
10
+
11
+ export const NO_CHANGE = 'no operational change';
12
+
13
+ // The runbook's POSIX path relative to the root: `runbook.md` when `docsRoot` is `.`.
14
+ export function runbookRel(root, cfg) {
15
+ return path.relative(root, kitPaths(root, cfg).runbook).split(path.sep).join('/');
16
+ }
17
+
18
+ const resolves = (root, ref) => {
19
+ try {
20
+ git(root, ['rev-parse', '--verify', '--quiet', ref]);
21
+ return true;
22
+ } catch (e) {
23
+ if (e instanceof GitError) return false;
24
+ throw e;
25
+ }
26
+ };
27
+
28
+ // The default branch as origin has it, else the local one.
29
+ export function defaultRef(root, cfg) {
30
+ const origin = `refs/remotes/origin/${cfg.defaultBranch}`;
31
+ return resolves(root, origin) ? origin : `refs/heads/${cfg.defaultBranch}`;
32
+ }
33
+
34
+ // The commit `tip` left the default branch at.
35
+ export function mergeBase(root, cfg, tip = 'HEAD') {
36
+ return git(root, ['merge-base', tip, defaultRef(root, cfg)]);
37
+ }
38
+
39
+ // The file at `rev`, byte for byte (git() trims, which would move every line number of a file that
40
+ // begins with a blank line); '' when the commit does not hold it.
41
+ function fileAt(root, rev, rel) {
42
+ try {
43
+ return execFileSync('git', ['show', `${rev}:${rel}`], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
44
+ } catch {
45
+ return '';
46
+ }
47
+ }
48
+
49
+ // line number (1-based) -> the text of the `##` heading whose section holds it, or null above the
50
+ // first one. A heading line belongs to its own section; a fenced `## ` line is not a heading.
51
+ function sectionFinder(text) {
52
+ const hs = headings(text).filter((h) => h.level === 2);
53
+ return (n) => {
54
+ let found = null;
55
+ for (const h of hs) {
56
+ if (h.line > n) break;
57
+ found = h.text;
58
+ }
59
+ return found;
60
+ };
61
+ }
62
+
63
+ const HUNK = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/;
64
+
65
+ // The `##` headings of the runbook whose section holds a line added or removed between `base` and
66
+ // `tip`, sorted and unique. Removed lines are placed with the base's file, added lines with the
67
+ // tip's. A change of trailing whitespace only is no change (D-55).
68
+ export function runbookSections(root, rel, base, tip) {
69
+ const diff = git(root, ['--literal-pathspecs', 'diff', '--no-color', '--no-ext-diff', '--no-renames', '--unified=0', '--ignore-space-at-eol', base, tip, '--', rel]);
70
+ if (diff === '') return [];
71
+ const inBase = sectionFinder(fileAt(root, base, rel));
72
+ const inTip = sectionFinder(fileAt(root, tip, rel));
73
+ const found = new Set();
74
+ const mark = (finder, start, count) => {
75
+ for (let n = start; n < start + count; n++) {
76
+ const s = finder(n);
77
+ if (s !== null) found.add(s);
78
+ }
79
+ };
80
+ for (const line of lines(diff)) {
81
+ const m = HUNK.exec(line);
82
+ if (!m) continue;
83
+ mark(inBase, Number(m[1]), m[2] === undefined ? 1 : Number(m[2]));
84
+ mark(inTip, Number(m[3]), m[4] === undefined ? 1 : Number(m[4]));
85
+ }
86
+ return [...found].sort();
87
+ }
88
+
89
+ // null when the slice passes, else the finding's message. `body` is a pull request body, or null
90
+ // when there is none to read; then only the flag and the changed sections count.
91
+ export function runbookVerdict({ flag, sections, body, rel }) {
92
+ if (!flag) return null;
93
+ if (sections.length > 0) return null;
94
+ if (typeof body === 'string' && (getSection(body, 'Runbook') ?? '').trim().startsWith(NO_CHANGE)) return null;
95
+ return `runbook: the slice says runbook: yes, ${rel} changed no section, and the Runbook line does not begin "${NO_CHANGE}"`;
96
+ }
package/src/workflow.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // The GitHub Actions workflow init writes (REQ-3.11): a gate, a job per declared team command, a job
2
- // per observability step (D-20), the ready label and the post-merge state sync (D-12), which opens a
2
+ // per observability step of config and of observability.md (D-20, D-56), the ready label and the post-merge state sync (D-12), which opens a
3
3
  // [sync] pull request and starts the workflow on its branch with workflow_dispatch (D-78, D-80). The YAML is
4
4
  // generated as text; every free-text value goes through yamlScalar so a quote, colon or hash in a
5
5
  // team's command cannot change the document's structure.
@@ -7,8 +7,10 @@ import { execFileSync } from 'node:child_process';
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
- import { DEFAULT_RUNS_ON, DEFAULT_TIMEOUT_MINUTES, GITHUB_EXPRESSION, LINE_SEPARATOR, MATRIX_OS, shardErrors, shardRunnerErrors } from './config.js';
10
+ import { ConfigError, DEFAULT_RUNS_ON, DEFAULT_TIMEOUT_MINUTES, GITHUB_EXPRESSION, LINE_SEPARATOR, MATRIX_OS, shardErrors, shardRunnerErrors } from './config.js';
11
11
  import { readText } from './fs.js';
12
+ import { allSteps, docSteps } from './observability.js';
13
+ import { kitPaths } from './paths.js';
12
14
  import { substitute } from './render/entry.js';
13
15
 
14
16
  export const WORKFLOW_TEMPLATE = fileURLToPath(new URL('../templates/workflow/slicekit.yml', import.meta.url));
@@ -277,7 +279,9 @@ function fillFreeText(line, vars) {
277
279
  return m[1] + yamlScalar(substitute(m[2], vars, FREE_TEXT_KEYS));
278
280
  }
279
281
 
280
- export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileSync(WORKFLOW_TEMPLATE, 'utf8'), root = null } = {}) {
282
+ // `steps` are the observability steps to render, one obs-<n> job each in that order: config's own when
283
+ // the caller passes none; workflowState passes config's followed by those of observability.md (D-56).
284
+ export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileSync(WORKFLOW_TEMPLATE, 'utf8'), root = null, steps = cfg.ci?.observabilitySteps ?? [] } = {}) {
281
285
  if (/[\r\n]/.test(cfg.cli)) throw new Error('cli: must be one line to render the workflow');
282
286
  const v = checkPins(pins);
283
287
  const matrix = cfg.ci?.matrix === true;
@@ -294,7 +298,6 @@ export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileS
294
298
  const shards = given && (matrix ? given : { [runsOn]: Object.values(given)[0] });
295
299
  const commands = COMMAND_ORDER.filter((name) => typeof cfg.commands[name] === 'string' && cfg.commands[name].trim() !== '');
296
300
  const jdk = setupJavaSteps(v, cfg.ci?.java ?? DEFAULT_JAVA, javaBuildTool(root, commands.map((c) => cfg.commands[c])), root);
297
- const steps = cfg.ci?.observabilitySteps ?? [];
298
301
  const texts = [cfg.cli, ...commands.map((c) => cfg.commands[c]), ...steps.map((s) => s.run)];
299
302
  if (texts.some((t) => GITHUB_EXPRESSION.test(t))) throw new Error('workflow: a command contains a GitHub expression; pass values through env:');
300
303
  const blocks = {
@@ -327,12 +330,25 @@ export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileS
327
330
  return out.join('\n');
328
331
  }
329
332
 
330
- // The rendered workflow and the repository's copy of it (null when absent), line endings normalised.
333
+ // The observability steps of a repository (D-56): config's, then the rows of the steps table of its
334
+ // observability.md when the file exists. A step the workflow cannot carry, or one named in both
335
+ // places, throws a ConfigError naming the file and line; a row with no command is a warning.
336
+ export function workflowSteps(root, cfg) {
337
+ const file = kitPaths(root, cfg).observability;
338
+ const rel = path.relative(root, file).split(path.sep).join('/');
339
+ const all = allSteps(cfg, fs.existsSync(file) ? docSteps(readText(file), rel) : null);
340
+ if (all.errors.length > 0) throw new ConfigError(all.errors);
341
+ return { steps: all.steps, warnings: all.warnings };
342
+ }
343
+
344
+ // The rendered workflow and the repository's copy of it (null when absent), line endings normalised,
345
+ // with the warnings of the steps read from observability.md.
331
346
  export function workflowState(root, cfg, pins = loadPins()) {
332
- const expected = renderWorkflow(cfg, pins, { root });
347
+ const { steps, warnings } = workflowSteps(root, cfg);
348
+ const expected = renderWorkflow(cfg, pins, { root, steps });
333
349
  const file = path.join(root, WORKFLOW_PATH);
334
350
  const current = fs.existsSync(file) ? readText(file) : null;
335
- return { file, expected, current };
351
+ return { file, expected, current, warnings };
336
352
  }
337
353
 
338
354
  // D-49: a team whose test command never reads SLICEKIT_SHARD runs the whole command in every shard.
@@ -74,6 +74,16 @@ The sections of `<docsRoot>/observability.md`:
74
74
 
75
75
  After each answer step, write the answer into its section of the file, followed by the D-ID in brackets, for example `One Postgres on Fly (D-07).`. Leave the single line "Not yet known" in each section the human cannot answer, and record that question with `--open`. Change nothing else in these two files.
76
76
 
77
+ Write the answer to `CI steps the monitoring setup requires` as a table with the two columns Step and Command, one command per row, and the D-ID on a line of its own below the table:
78
+
79
+ ```
80
+ | Step | Command |
81
+ |---|---|
82
+ | Trace check | `npm run trace-check` |
83
+ ```
84
+
85
+ Each row becomes one job of the generated workflow, named by its Step and running its Command. Write the table in exactly this form: the header cells are `Step` and `Command` in plain text with these capitals, the divider line has two cells, and every line of the table opens with a vertical bar. The table is the only place in the section where a vertical bar may stand: any other line holding one, a second table included, is refused with its file and line. A Command cell is the whole command as one code span, or text with no backtick; put nothing else in the cell, the D-ID included. Text in a code fence, in an indented code block or in an HTML comment is not read. A command is one line and holds no secret and no `${{ … }}` expression; a pipe inside a command is written `\|`, inside a code span too, and a row with a bare pipe is refused. A step that needs a secret does not go in the table: tell the human to add it to `ci.observabilitySteps` in `.slicekit/config.json` with the secret under `env`. When the monitoring setup asks nothing of CI, write `None` and no table. After the table changes, run `{{cli}} workflow --write`.
86
+
77
87
  ## 6. Finish
78
88
 
79
89
  `{{cli}} intake done`
@@ -0,0 +1,51 @@
1
+ # /slicekit release
2
+
3
+ Write the release record of a phase whose slices are all merged, set each slice released, then open
4
+ the release pull request (REQ-2.9). Arguments: {{args}} (the phase).
5
+
6
+ `<docsRoot>` below is the `docsRoot` in `.slicekit/config.json`. Every step that touches the
7
+ repository's history goes through `{{cli}}`; run no git or gh command yourself. The release records
8
+ what merged; it does not deploy (D-12).
9
+
10
+ ## Steps
11
+
12
+ 1. Run `{{cli}} release {{args}} --dry-run`. It writes nothing. When it exits 0 it prints the record
13
+ it would write. When it exits 1 it prints one line per reason: a slice that is not merged, a
14
+ slice with no recorded pull request, a slice that says `runbook: yes` and neither changed a
15
+ section of the runbook nor gave a Runbook line that begins "no operational change", or a record
16
+ that already exists. Print those lines to the human and stop: the release waits for each one.
17
+ 2. Run `{{cli}} branch release <slug>`, the slug being the phase in lower case (`p1` for `P1`). It
18
+ puts the session on `release/<slug>` at the tip of the default branch as origin has it; a
19
+ `release/<slug>` left behind that tip with no commit of its own is moved there, and the command
20
+ says so. When `release/<slug>` holds commits the default branch lacks, it asks the git host for
21
+ an open pull request of that branch and exits 1 with one of three lines:
22
+ 1. `release/<slug> is the branch of open pull request #<n> (<url>); the phase's release is
23
+ already open`: print the line to the human and stop. Take no other slug: merging or closing
24
+ that pull request is the human's.
25
+ 2. A line saying the git host could not be asked: print it to the human and stop. Take no other
26
+ slug.
27
+ 3. A line that names the next slug (`p1-2`): no pull request of that branch is open, so run the
28
+ command again with that slug.
29
+ 3. Run `{{cli}} release {{args}}`. It prints the record's path, `<docsRoot>/releases/{{args}}.md`,
30
+ then one `released <slice>` line per slice, and rewrites `BUILD.md`. When it exits 1, print its
31
+ lines to the human and stop.
32
+ 4. Run `{{cli}} check` and fix each finding it prints until it reports `0 findings`. Never edit the
33
+ record by hand. A finding in the record points at text the record quotes, and is fixed there:
34
+ 1. Run `{{cli}} release {{args}} --undo`. It removes the record, which is not committed yet, and
35
+ puts the state files and `BUILD.md` back as they were, so no change is left in the session.
36
+ 2. A pull request title or body is corrected on the host. The runbook or a decision row is
37
+ corrected on its own pull request, which a human merges; tell the human what to correct, and
38
+ stop until it has merged.
39
+ 3. Start again at step 1, with the same slug in step 2.
40
+ 5. Write the pull request body to a file outside the repository, with these three sections:
41
+
42
+ ```
43
+ **Done when:** every slice of {{args}} released
44
+ **Proof:** <the summary line check printed>
45
+ **Decisions:** <the lines under "## Decisions" in the record, one per line, or "none">
46
+ ```
47
+
48
+ 6. Run `{{cli}} pr open --title "[release] {{args}}" --body-file <file> --commit "docs(release): {{args}}" --paths <docsRoot>/releases/{{args}}.md,.slicekit/state,BUILD.md`.
49
+ 7. Print the pull request line `pr open` printed, and tell the human that merging the pull request
50
+ is the release of {{args}} in this repository, and that it deploys nothing: deployment stays the
51
+ team's (D-12).