slicekit 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli/ops.js ADDED
@@ -0,0 +1,78 @@
1
+ // slicekit ops context <symptom> [--path <p>]… [--json] and slicekit ops check <report> (REQ-2.13,
2
+ // D-57): what `/slicekit ops` hands the ops agent, and the check of the report it replies with.
3
+ // Neither runs git, calls the host or takes an action.
4
+ import { parseArgs } from 'node:util';
5
+ import { ConfigError, loadConfig } from '../config.js';
6
+ import { historyLine } from '../graph/history.js';
7
+ import { indexGraph, loadGraph } from '../graph/load.js';
8
+ import { GraphError } from '../graph/schema.js';
9
+ import { opsContext, opsReportProblems } from '../ops.js';
10
+ import { readReport } from '../reports.js';
11
+
12
+ const USAGE = 'ops context <symptom> [--path <p>]… [--json]\n ops check <report>';
13
+ const SUBCOMMANDS = ['context', 'check'];
14
+
15
+ const usage = (io, why) => {
16
+ io.stderr(`${why ? `slicekit: ${why}\n` : ''}usage: slicekit ${USAGE}\n`);
17
+ return 2;
18
+ };
19
+
20
+ function contextLines(c) {
21
+ return [
22
+ c.report,
23
+ `symptom: ${c.symptom}`,
24
+ ...c.files.map((f) => `file: ${f}`),
25
+ ...c.broad.map((b) => `too broad: ${b.word} (${b.count} files)`),
26
+ ...(c.unmatched.length > 0 ? [`no file: ${c.unmatched.join(', ')}`] : []),
27
+ 'history:',
28
+ ...c.history.map(historyLine),
29
+ `runbook: ${c.runbook}${c.missing.includes(c.runbook) ? ' (missing)' : ''}`,
30
+ `observability: ${c.observability}${c.missing.includes(c.observability) ? ' (missing)' : ''}`,
31
+ `last release: ${c.lastRelease ?? 'none'}`,
32
+ ];
33
+ }
34
+
35
+ async function run(args, io) {
36
+ let values;
37
+ let positionals;
38
+ try {
39
+ ({ values, positionals } = parseArgs({ args, options: { path: { type: 'string', multiple: true }, json: { type: 'boolean' } }, allowPositionals: true }));
40
+ } catch (e) {
41
+ return usage(io, e.message);
42
+ }
43
+ const [sub, ...rest] = positionals;
44
+ if (!SUBCOMMANDS.includes(sub)) return usage(io, sub === undefined ? 'missing subcommand' : `unknown subcommand '${sub}'`);
45
+ const json = Boolean(values.json);
46
+ const refuse = (message, code) => {
47
+ io.stderr(`slicekit: ${message}\n`);
48
+ if (json) io.stdout(`${JSON.stringify({ error: message }, null, 2)}\n`);
49
+ return code;
50
+ };
51
+ const root = io.cwd;
52
+ try {
53
+ const cfg = loadConfig(root);
54
+ if (sub === 'context') {
55
+ // The words of a symptom typed without quotes are one symptom.
56
+ const symptom = rest.join(' ').trim();
57
+ const paths = values.path ?? [];
58
+ if (symptom === '' && paths.length === 0) return usage(io, 'missing symptom');
59
+ const context = opsContext(root, cfg, symptom, { paths });
60
+ io.stdout(json ? `${JSON.stringify(context, null, 2)}\n` : contextLines(context).map((l) => `${l}\n`).join(''));
61
+ return 0;
62
+ }
63
+ if (rest.length !== 1) return usage(io, rest.length === 0 ? 'missing report' : `unexpected argument ${rest[1]}`);
64
+ if (values.path) return usage(io, 'ops check takes no --path');
65
+ const { rel, text } = readReport(root, rest[0]);
66
+ if (text === null) return refuse(`${rel} is not a file`, 2);
67
+ const problems = opsReportProblems(root, indexGraph(loadGraph(root, cfg)), rel, text);
68
+ if (json) io.stdout(`${JSON.stringify({ report: rel, problems }, null, 2)}\n`);
69
+ else io.stdout(problems.length > 0 ? problems.map((p) => `${p}\n`).join('') : `ok ${rel}\n`);
70
+ return problems.length > 0 ? 1 : 0;
71
+ } catch (e) {
72
+ if (e instanceof GraphError) return refuse(e.message, e.code);
73
+ if (e instanceof ConfigError) return refuse(e.message, 2);
74
+ throw e;
75
+ }
76
+ }
77
+
78
+ export const opsCommand = { run, usage: USAGE, subcommands: SUBCOMMANDS };
@@ -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/update.js CHANGED
@@ -2,6 +2,7 @@ import path from 'node:path';
2
2
  import { parseArgs } from 'node:util';
3
3
  import { ConfigError, loadConfig } from '../config.js';
4
4
  import { exists } from '../fs.js';
5
+ import { missingReportsRule } from '../init.js';
5
6
  import { checkCli } from '../hook-cli.js';
6
7
  import { kitVersion, RENDERED } from '../render/index.js';
7
8
  import { applyUpdate, planUpdate } from '../render/update.js';
@@ -40,6 +41,9 @@ async function run(args, io) {
40
41
  io.stdout(`${status} ${dest}\n`);
41
42
  if (diff !== '') io.stdout(diff);
42
43
  }
44
+ // update never writes the ignore file (REQ-5.6): a project that lacks the rule is told the line.
45
+ const rule = missingReportsRule(root, cfg);
46
+ if (rule) io.stdout(`.gitignore has no rule for ${rule}, where /slicekit ops and /slicekit audit write their reports; add the line ${rule}\n`);
43
47
  if (values.check) {
44
48
  if (!exists(path.join(root, RENDERED))) io.stdout(`${RENDERED}/ is missing; commit it so drift can be told from kit changes\n`);
45
49
  return pending.some((p) => p.status === 'drifted' || p.status === 'missing') ? 1 : 0;
@@ -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:`);
@@ -15,6 +15,10 @@ import { addAgent, usableId } from './subagent-marker.js';
15
15
  export { roleOf };
16
16
  export const BRIEF_MAX = 8000;
17
17
  export const NO_GIT = 'You never run a git command that commits, pushes or moves a branch; report and the command commits.';
18
+ // The ops agent holds no tool that runs a command or writes a file, and nothing of its work is
19
+ // committed (D-57): it is told what becomes of its reply instead.
20
+ export const OPS_REPLY = 'You run no command and write no file. Your reply is the report: the main session writes it under .slicekit/reports/ and checks it, and it is never committed.';
21
+ const closing = (role) => (role === 'ops' ? OPS_REPLY : NO_GIT);
18
22
  const SKILL = path.join('.claude', 'skills', 'slicekit-writing', 'SKILL.md');
19
23
  const KIT_SKILL = fileURLToPath(new URL('../../templates/claude-code/skills/slicekit-writing/SKILL.md', import.meta.url));
20
24
 
@@ -74,11 +78,11 @@ function withoutRules(text) {
74
78
  return out.join('\n').trim();
75
79
  }
76
80
 
77
- // The brief, the rules and the no-git sentence in at most BRIEF_MAX characters, the rules and the
78
- // sentence always last and whole. A brief that does not fit is cut from its end and followed by a
81
+ // The brief, the rules and the role's closing sentence (the no-git sentence; for ops, OPS_REPLY) in
82
+ // at most BRIEF_MAX characters, the rules and the sentence always last and whole. A brief that does not fit is cut from its end and followed by a
79
83
  // line naming where the full text is. Only when the rules alone do not fit are they cut too.
80
84
  function assemble(brief, rules, role, cli) {
81
- const tail = `\n\n${NO_GIT}`;
85
+ const tail = `\n\n${closing(role)}`;
82
86
  const end = rules.text === '' ? tail : `\n\n${rules.text}${tail}`;
83
87
  if (brief.length + end.length <= BRIEF_MAX) return brief + end;
84
88
  const note = `\n(brief truncated; full text in ${cli} instructions ${role})`;
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
 
@@ -23,6 +23,8 @@ const IGNORE_RULES = [
23
23
  { rule: '.slicekit/.subagent-*', forms: new Set(['.slicekit/.subagent-*', '/.slicekit/.subagent-*']) },
24
24
  // The machine's own settings (D-43), such as a local test command: never part of the project.
25
25
  { rule: '.slicekit/local.json', forms: new Set(['.slicekit/local.json', '/.slicekit/local.json']) },
26
+ // The reports of `/slicekit ops` and `/slicekit audit` (D-57, D-58): written on one machine, never committed.
27
+ { rule: '.slicekit/reports/', forms: new Set(['.slicekit/reports/', '/.slicekit/reports/', '.slicekit/reports', '/.slicekit/reports']) },
26
28
  { rule: '!.slicekit/journal/', forms: new Set(['!.slicekit/journal/', '!/.slicekit/journal/']) },
27
29
  { rule: '!.slicekit/journal/*.log', forms: new Set(['!.slicekit/journal/*.log', '!/.slicekit/journal/*.log']) },
28
30
  { rule: '.slicekit/journal/*.lock', forms: new Set(['.slicekit/journal/*.lock', '/.slicekit/journal/*.lock']) },
@@ -40,6 +42,8 @@ const IGNORE_RULES = [
40
42
  const UNIGNORE_RULES = ['!.slicekit/journal/', '!.slicekit/journal/*.log', '.slicekit/journal/*.lock', '!.slicekit/journal-heads.log'];
41
43
  const UNIGNORE_PROBES = ['.slicekit/journal-heads.log', '.slicekit/journal/main--00000000.log'];
42
44
 
45
+ const REPORTS_RULE = '.slicekit/reports/';
46
+
43
47
  function ignoredByGit(root, rel) {
44
48
  try {
45
49
  git(root, ['check-ignore', '--quiet', '--no-index', rel]);
@@ -94,6 +98,21 @@ function reassertUnignores(root, file) {
94
98
  return { appended, note };
95
99
  }
96
100
 
101
+ // The ignore rule for the reports directory when the project lacks it, else null. `update` never
102
+ // writes the ignore file (REQ-5.6: managed blocks only), so it prints this line for a project
103
+ // initialised before the rule existed (P5/S-23 review H-4). In a git repository git decides whether
104
+ // a report is ignored; outside one, a line in any spelling init accepts counts.
105
+ export function missingReportsRule(root, cfg) {
106
+ const paths = kitPaths(root, cfg);
107
+ if (isRepo(root)) {
108
+ const report = path.relative(root, path.join(paths.reports, 'ops-1.md')).split(path.sep).join('/');
109
+ return ignoredByGit(root, report) ? null : REPORTS_RULE;
110
+ }
111
+ const { forms } = IGNORE_RULES.find((r) => r.rule === REPORTS_RULE);
112
+ const present = exists(paths.gitignore) ? fs.readFileSync(paths.gitignore, 'utf8').split(/\r?\n/).map((l) => l.trim()) : [];
113
+ return present.some((l) => forms.has(l)) ? null : REPORTS_RULE;
114
+ }
115
+
97
116
  // Hooks checked out with CRLF break sh (REQ-3.9).
98
117
  // Intake snapshots (S-10) are stored byte for byte, so git must not convert their line endings. The
99
118
  // pattern comes from kitPaths as S-10 builds it, so `./docs` and `docs` write the same line.
@@ -255,6 +274,7 @@ function resolveConfig(root, { name, shape, docsRoot, commands, cli, defaultBran
255
274
  if (!raw) return { cfg, cliWarning: null, cliFilled: false };
256
275
  const errors = validateConfig(raw);
257
276
  if (errors.length > 0) throw new ConfigError(errors);
277
+ workflowSteps(root, raw); // as in init(): refused before the config is written back
258
278
  writeText(file, `${JSON.stringify(raw, null, 2)}\n`);
259
279
  return { cfg: loadConfig(root), cliWarning: probed.warning, cliFilled: true };
260
280
  }
@@ -356,6 +376,7 @@ export function protect(root, { env = process.env } = {}) {
356
376
  export function init(root, { name, shape, docsRoot, commands = {}, cli, defaultBranch, env = process.env }) {
357
377
  const { cfg, cliWarning, cliFilled } = resolveConfig(root, { name, shape, docsRoot, commands, cli, defaultBranch, env });
358
378
  readSettings(root); // a corrupt .claude/settings.json stops init before anything is written
379
+ workflowSteps(root, cfg); // so does a step of observability.md the workflow cannot carry (D-56)
359
380
 
360
381
  const paths = kitPaths(root, cfg);
361
382
  const rel = (abs) => path.relative(root, abs).split(path.sep).join('/');
@@ -386,6 +407,7 @@ export function init(root, { name, shape, docsRoot, commands = {}, cli, defaultB
386
407
  }
387
408
  // The CI workflow (REQ-3.11): written when absent; an existing one is the team's and stays as is.
388
409
  const workflow = workflowState(root, cfg);
410
+ warnings.push(...workflow.warnings);
389
411
  if (workflow.current === null) {
390
412
  writeText(workflow.file, workflow.expected);
391
413
  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
+ }