slicekit 0.3.1 → 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.1",
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 };
@@ -1,4 +1,4 @@
1
- // sync-release (05 REQ-5.5, D-43, D-89, D-90): under --ci on a sync pull request (a `sync/<short sha>`
1
+ // sync-release (05 REQ-5.5, D-43, D-89, D-90, D-92): under --ci on a sync pull request (a `sync/<short sha>`
2
2
  // branch), the files the release step writes (package.json, CHANGELOG.md and the rendered files) must
3
3
  // equal what CI computes for the merge the branch names: a fresh checkout of that merge in a temporary
4
4
  // worktree, synced from the git host and given the version, section and render the sync step would
@@ -78,12 +78,13 @@ function blob(root, rev, file) {
78
78
  }
79
79
 
80
80
  // Runs the sync step in the merge's worktree and returns the release paths it changed, with their
81
- // new content (null for a removed file).
81
+ // new content (null for a removed file). The version comes from the function the sync job runs
82
+ // (applyRelease): the merged slices no changelog section at the merge names (D-92).
82
83
  function expectedFiles(root, ctx, wt, owns) {
83
84
  const cfg = loadConfig(wt);
84
85
  const host = getHost(cfg, ctx.env ?? process.env, root);
85
- const { changes } = syncFromHost(wt, cfg, host);
86
- applyRelease(wt, cfg, changes, { merge: 'HEAD', isKit: isKitRoot(root) });
86
+ syncFromHost(wt, cfg, host);
87
+ applyRelease(wt, cfg, { merge: 'HEAD', isKit: isKitRoot(root) });
87
88
  const tracked = nul(git(wt, ['diff', '--name-only', '--no-renames', '-z', 'HEAD']));
88
89
  const untracked = nul(git(wt, ['ls-files', '--others', '--exclude-standard', '-z']));
89
90
  const out = new Map();
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 };
package/src/cli/status.js CHANGED
@@ -7,7 +7,7 @@ import { programStage } from '../stage.js';
7
7
  import { renderBuild } from '../state/build.js';
8
8
  import { LockError, readSlice } from '../state/index.js';
9
9
  import { syncFromHost } from '../state/sync.js';
10
- import { ReleaseError, applyRelease } from '../release-version.js';
10
+ import { ReleaseError, applyRelease, onDefaultTip } from '../release-version.js';
11
11
  import { getHost } from '../adapters/githost/index.js';
12
12
  import { GitHostError } from '../adapters/githost/errors.js';
13
13
 
@@ -71,9 +71,12 @@ async function run(args, io) {
71
71
  throw e;
72
72
  }
73
73
  record(result);
74
- // With --write and release.auto, the sync also sets the next version (D-90).
75
- if (values.write) {
76
- const release = applyRelease(root, cfg, result.changes);
74
+ // With --write and release.auto, the sync also sets the next version (D-90, D-92), and only
75
+ // when HEAD is the tip of the default branch (issue #142): a version counts from that branch.
76
+ if (values.write && cfg.release?.auto === true && !onDefaultTip(root, cfg)) {
77
+ io.stderr(`slicekit: version not set: HEAD is not the tip of ${cfg.defaultBranch}\n`);
78
+ } else if (values.write) {
79
+ const release = applyRelease(root, cfg);
77
80
  if (release) {
78
81
  version = release.version;
79
82
  if (!values.json) io.stdout(`version ${version}: package.json and CHANGELOG.md\n`);
@@ -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
+ }