slicekit 0.1.2 → 0.2.0

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.
Files changed (65) hide show
  1. package/README.md +15 -13
  2. package/package.json +3 -2
  3. package/src/adapters/githost/fixture.js +24 -1
  4. package/src/adapters/githost/gh-json.js +69 -2
  5. package/src/adapters/githost/github.js +16 -1
  6. package/src/build/commit.js +152 -26
  7. package/src/build/config.js +50 -0
  8. package/src/build/pr.js +30 -15
  9. package/src/build/record.js +8 -2
  10. package/src/build/red.js +4 -3
  11. package/src/build/render.js +155 -0
  12. package/src/build/verdict.js +29 -0
  13. package/src/build/worktree.js +26 -5
  14. package/src/check/ci-event.js +17 -0
  15. package/src/check/rules/citations.js +53 -2
  16. package/src/check/rules/commands.js +32 -4
  17. package/src/check/rules/trailer.js +5 -16
  18. package/src/check/rules/workspace.js +86 -0
  19. package/src/cli/build.js +34 -8
  20. package/src/cli/ci.js +150 -0
  21. package/src/cli/decide.js +4 -3
  22. package/src/cli/gaps.js +6 -5
  23. package/src/cli/graph.js +79 -0
  24. package/src/cli/history.js +17 -0
  25. package/src/cli/hook.js +1 -1
  26. package/src/cli/impact.js +17 -0
  27. package/src/cli/index.js +28 -3
  28. package/src/cli/instructions.js +1 -1
  29. package/src/cli/intake.js +3 -3
  30. package/src/cli/query.js +39 -0
  31. package/src/cli/shipped.js +32 -0
  32. package/src/cli/state.js +42 -2
  33. package/src/cli/trace.js +21 -0
  34. package/src/cli/uncovered.js +32 -0
  35. package/src/cli/visualize.js +88 -0
  36. package/src/cli/workflow.js +6 -2
  37. package/src/config.js +85 -0
  38. package/src/graph/build.js +312 -0
  39. package/src/graph/docs.js +241 -0
  40. package/src/graph/git-walk.js +91 -0
  41. package/src/graph/history.js +60 -0
  42. package/src/graph/impact.js +143 -0
  43. package/src/graph/kitfiles.js +60 -0
  44. package/src/graph/load.js +93 -0
  45. package/src/graph/prs.js +136 -0
  46. package/src/graph/render.js +28 -0
  47. package/src/graph/schema.js +108 -0
  48. package/src/graph/shipped.js +32 -0
  49. package/src/graph/tests.js +45 -0
  50. package/src/graph/trace.js +83 -0
  51. package/src/graph/uncovered.js +16 -0
  52. package/src/graph/workspace.js +188 -0
  53. package/src/hook-cli.js +1 -1
  54. package/src/init.js +2 -0
  55. package/src/instructions.js +26 -8
  56. package/src/state/index.js +35 -4
  57. package/src/verdict.js +14 -2
  58. package/src/visualize/client.js +489 -0
  59. package/src/visualize/page.js +100 -0
  60. package/src/visualize/server.js +46 -0
  61. package/src/workflow.js +87 -9
  62. package/templates/instructions/agents/reviewer.md +7 -7
  63. package/templates/instructions/commands/build.md +34 -4
  64. package/templates/workflow/pins.json +2 -1
  65. package/templates/workflow/slicekit.yml +32 -1
@@ -0,0 +1,39 @@
1
+ // The shell every query command is made from (S-18, S-20): argument parsing with --json, the config
2
+ // and the graph loaded, the missing-graph and unknown-ID refusals. A query runs no git and no host call.
3
+ import { parseArgs } from 'node:util';
4
+ import { ConfigError, loadConfig } from '../config.js';
5
+ import { indexGraph, loadGraph } from '../graph/load.js';
6
+ import { GraphError } from '../graph/schema.js';
7
+
8
+ // answer(index, {positionals, values, root, cfg}) -> {lines: string[], json}
9
+ export function queryCommand({ name, usage, options = {}, answer }) {
10
+ async function run(args, io) {
11
+ let parsed;
12
+ try {
13
+ parsed = parseArgs({ args, options: { ...options, json: { type: 'boolean' } }, allowPositionals: true });
14
+ } catch (e) {
15
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${usage}\n`);
16
+ if (args.includes('--json')) io.stdout(`${JSON.stringify({ error: e.message })}\n`);
17
+ return 2;
18
+ }
19
+ const json = Boolean(parsed.values.json);
20
+ const refuse = (message, code) => {
21
+ io.stderr(`slicekit: ${message}\n`);
22
+ if (json) io.stdout(`${JSON.stringify({ error: message }, null, 2)}\n`);
23
+ return code;
24
+ };
25
+ try {
26
+ const cfg = loadConfig(io.cwd);
27
+ const index = indexGraph(loadGraph(io.cwd, cfg));
28
+ const result = await answer(index, { positionals: parsed.positionals, values: parsed.values, root: io.cwd, cfg });
29
+ io.stdout(json ? `${JSON.stringify(result.json, null, 2)}\n` : result.lines.map((l) => `${l}\n`).join(''));
30
+ return 0;
31
+ } catch (e) {
32
+ if (e instanceof GraphError) return refuse(e.message, e.code);
33
+ if (e instanceof ConfigError) return refuse(e.message, 2);
34
+ throw e;
35
+ }
36
+ }
37
+ void name;
38
+ return { run, usage };
39
+ }
@@ -0,0 +1,32 @@
1
+ // slicekit shipped P<n> [--json] (REQ-4.5): the release record of a phase, its requirements and its
2
+ // pull requests with their URLs, from graph.json.
3
+ import { GraphError, keyOf } from '../graph/schema.js';
4
+ import { shipped } from '../graph/shipped.js';
5
+ import { queryCommand } from './query.js';
6
+
7
+ const USAGE = 'shipped P<n> [--json]';
8
+
9
+ export const shippedCommand = queryCommand({
10
+ name: 'shipped',
11
+ usage: USAGE,
12
+ answer(index, { positionals }) {
13
+ if (positionals.length !== 1) throw new GraphError(2, `give one phase\nusage: slicekit ${USAGE}`);
14
+ const phase = positionals[0];
15
+ const s = shipped(index, phase);
16
+ const lines = [
17
+ `${keyOf(s.release.id)} ${s.path}`,
18
+ `requirements: ${s.requirements.length}`,
19
+ ...s.requirements.map((r) => ` ${keyOf(r.id)} ${r.label} ${r.from}`),
20
+ `pull requests: ${s.pullRequests.length}`,
21
+ ...s.pullRequests.map((p) => ` #${p.number ?? keyOf(p.id)} ${p.label} ${p.url ?? ''}`.trimEnd()),
22
+ ];
23
+ return {
24
+ lines,
25
+ json: {
26
+ release: { id: s.release.id, path: s.path, from: s.release.from },
27
+ requirements: s.requirements.map((r) => ({ id: r.id, label: r.label, from: r.from })),
28
+ pullRequests: s.pullRequests.map((p) => ({ id: p.id, number: p.number ?? Number(keyOf(p.id)), title: p.label, url: p.url ?? null })),
29
+ },
30
+ };
31
+ },
32
+ });
package/src/cli/state.js CHANGED
@@ -1,11 +1,15 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import { ConfigError, loadConfig } from '../config.js';
3
+ import { getHost } from '../adapters/githost/index.js';
4
+ import { GitHostError } from '../adapters/githost/errors.js';
5
+ import { parseSliceAddr } from '../ids.js';
6
+ import { branchPrefix } from '../worktrees.js';
3
7
  import { STATES } from '../state/transitions.js';
4
8
  import { LockError, TransitionError, readSlice, setState, unfreeze } from '../state/index.js';
5
9
 
6
10
  const USAGE =
7
11
  'state set <id> <to> [--commit sha] [--test-exit n] [--check-exit n] [--tests a,b] [--pr-number n --pr-title t --pr-url u --pr-sha s] [--verdict path --round n --blockers n [--independent]] [--ci-status s --ci-sha s] [--merged-at iso] [--release path] [--backfill]\n' +
8
- ' slicekit state show <id> [--json]\n slicekit state unfreeze <id> <path>';
12
+ ' state show <id> [--json]\n state unfreeze <id> <path>';
9
13
 
10
14
  const OPTIONS = {
11
15
  commit: { type: 'string' },
@@ -56,6 +60,36 @@ function evidenceFrom(v) {
56
60
  return ev;
57
61
  }
58
62
 
63
+ // A merge done outside `build finish` is recorded only as the git host reports it (D-43): the slice's
64
+ // pull request (the recorded one, else --pr-number) must be merged, and its merge time and head come
65
+ // from the host. --merged-at and --pr-sha cannot stand in for the host's report.
66
+ function hostMerge(root, cfg, id, ev, env) {
67
+ const recorded = readSlice(root, cfg, id).pr?.number;
68
+ const given = ev.pr?.number;
69
+ if (recorded !== undefined && recorded !== null && given !== undefined && given !== recorded) {
70
+ throw new TransitionError(`${id} records pull request #${recorded}; --pr-number ${given} names another`);
71
+ }
72
+ const number = recorded ?? given;
73
+ if (!Number.isInteger(number)) throw new TransitionError(`backfill to merged needs the pull request number (--pr-number); ${id} records none`);
74
+ const pr = getHost(cfg, env, root).getPullRequest(number);
75
+ // A number given with no recorded pull request names the slice's own only when the host's title
76
+ // begins [<id>] or its branch is the slice's branch: a mistyped number records no merge.
77
+ if (recorded === undefined || recorded === null) {
78
+ const title = String(pr.title ?? '');
79
+ const branch = String(pr.headRef ?? '');
80
+ const prefix = branchPrefix(parseSliceAddr(id));
81
+ const titled = title === `[${id}]` || title.startsWith(`[${id}] `);
82
+ const onBranch = branch === prefix || branch.startsWith(`${prefix}-`);
83
+ if (!titled && !onBranch) {
84
+ throw new TransitionError(`the git host reports pull request #${number} titled "${title}" on branch ${branch || '(none)'}; it is not ${id}'s pull request`);
85
+ }
86
+ }
87
+ if (!pr.mergedAt) throw new TransitionError(`the git host reports pull request #${number} ${String(pr.state ?? 'open').toLowerCase()}, not merged; backfill to merged needs a merged pull request`);
88
+ if (typeof pr.headSha !== 'string' || pr.headSha === '') throw new TransitionError(`the git host reports no head for pull request #${number}`);
89
+ const { mergedAt: _m, pr: _p, ...rest } = ev;
90
+ return { ...rest, source: 'host', mergedAt: pr.mergedAt, pr: { number, headSha: pr.headSha, ...(pr.url ? { url: pr.url } : {}) } };
91
+ }
92
+
59
93
  async function run(args, io) {
60
94
  let parsed;
61
95
  try {
@@ -79,7 +113,9 @@ async function run(args, io) {
79
113
  try {
80
114
  const cfg = loadConfig(root);
81
115
  if (sub === 'set') {
82
- const s = setState(root, cfg, id, arg, evidenceFrom(values));
116
+ let ev = evidenceFrom(values);
117
+ if (values.backfill && arg === 'merged') ev = hostMerge(root, cfg, id, ev, io.env ?? process.env);
118
+ const s = setState(root, cfg, id, arg, ev);
83
119
  io.stdout(`${id} ${s.state}\n`);
84
120
  } else if (sub === 'unfreeze') {
85
121
  unfreeze(root, cfg, id, arg);
@@ -95,6 +131,10 @@ async function run(args, io) {
95
131
  io.stderr(`refused: ${e.reason}\n`);
96
132
  return 1;
97
133
  }
134
+ if (e instanceof GitHostError) {
135
+ io.stderr(`slicekit: ${e.message}\n`);
136
+ return 1;
137
+ }
98
138
  if (e instanceof ConfigError || e instanceof LockError || /^unknown slice /.test(e.message)) {
99
139
  io.stderr(`slicekit: ${e.message}\n`);
100
140
  return 2;
@@ -0,0 +1,21 @@
1
+ // slicekit trace <REQ> | trace --file <path> [--json] (REQ-4.5): the tree under a requirement or
2
+ // above a file, from graph.json.
3
+ import { GraphError } from '../graph/schema.js';
4
+ import { renderLines, traceFile, traceRequirement, treeJson } from '../graph/trace.js';
5
+ import { queryCommand } from './query.js';
6
+
7
+ const USAGE = 'trace <REQ-…> | trace --file <path> [--json]';
8
+
9
+ export const traceCommand = queryCommand({
10
+ name: 'trace',
11
+ usage: USAGE,
12
+ options: { file: { type: 'string' } },
13
+ answer(index, { positionals, values }) {
14
+ const hasFile = typeof values.file === 'string';
15
+ if (hasFile === positionals.length > 0 || positionals.length > 1) {
16
+ throw new GraphError(2, `give one requirement or --file <path>\nusage: slicekit ${USAGE}`);
17
+ }
18
+ const tree = hasFile ? traceFile(index, values.file) : traceRequirement(index, positionals[0]);
19
+ return { lines: renderLines(tree), json: treeJson(tree) };
20
+ },
21
+ });
@@ -0,0 +1,32 @@
1
+ // slicekit uncovered [--json] (REQ-4.5): requirements with no covering test, tests naming no
2
+ // requirement, and commits on the default branch with no slice trailer, from graph.json.
3
+ import { nodeLine } from '../graph/render.js';
4
+ import { GraphError } from '../graph/schema.js';
5
+ import { uncovered } from '../graph/uncovered.js';
6
+ import { queryCommand } from './query.js';
7
+
8
+ const USAGE = 'uncovered [--json]';
9
+
10
+ const brief = (n) => ({ id: n.id, kind: n.kind, label: n.label, from: n.from, ...(n.kind === 'commit' ? { date: n.date } : {}) });
11
+
12
+ export const uncoveredCommand = queryCommand({
13
+ name: 'uncovered',
14
+ usage: USAGE,
15
+ answer(index, { positionals }) {
16
+ if (positionals.length > 0) throw new GraphError(2, `uncovered takes no argument\nusage: slicekit ${USAGE}`);
17
+ const u = uncovered(index);
18
+ const def = index.graph.defaultBranch ?? 'main';
19
+ const lines = [
20
+ `requirements with no covering test: ${u.requirements.length}`,
21
+ ...u.requirements.map((n) => ` ${nodeLine(n)} ${n.from}`),
22
+ `tests naming no requirement: ${u.tests.length}`,
23
+ ...u.tests.map((n) => ` ${nodeLine(n)}`),
24
+ `commits on ${def} with no slice trailer: ${u.commits.length}`,
25
+ ...u.commits.map((n) => ` ${nodeLine(n)}`),
26
+ ];
27
+ return {
28
+ lines,
29
+ json: { defaultBranch: def, requirements: u.requirements.map(brief), tests: u.tests.map(brief), commits: u.commits.map(brief) },
30
+ };
31
+ },
32
+ });
@@ -0,0 +1,88 @@
1
+ // slicekit visualize [--port <n>] [--write <file>] (REQ-4.7): the graph as one self-contained page.
2
+ // --write writes the page to a file and prints its path; otherwise the page and graph.json are served
3
+ // from node:http on 127.0.0.1, the URL printed, nothing opened, until Ctrl-C. No git, no host call.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { parseArgs } from 'node:util';
7
+ import { ConfigError, loadConfig } from '../config.js';
8
+ import { loadGraph } from '../graph/load.js';
9
+ import { GraphError, serializeGraph } from '../graph/schema.js';
10
+ import { renderPage } from '../visualize/page.js';
11
+ import { startServer } from '../visualize/server.js';
12
+
13
+ const USAGE = 'visualize [--port <n>] [--write <file>]';
14
+
15
+ function usage(io, message) {
16
+ io.stderr(`slicekit: ${message}\nusage: slicekit ${USAGE}\n`);
17
+ return 2;
18
+ }
19
+
20
+ // Resolves when the process receives Ctrl-C.
21
+ function interrupted() {
22
+ return new Promise((resolve) => process.once('SIGINT', resolve));
23
+ }
24
+
25
+ async function run(args, io) {
26
+ let values;
27
+ try {
28
+ ({ values } = parseArgs({ args, options: { port: { type: 'string' }, write: { type: 'string' } }, allowPositionals: false }));
29
+ } catch (e) {
30
+ return usage(io, e.message);
31
+ }
32
+ if (values.port !== undefined && values.write !== undefined) return usage(io, 'give --port or --write, not both');
33
+ let port = 0;
34
+ if (values.port !== undefined) {
35
+ if (!/^\d{1,5}$/.test(values.port) || Number(values.port) > 65535) return usage(io, `--port must be an integer from 0 to 65535, not ${values.port}`);
36
+ port = Number(values.port);
37
+ }
38
+ if (values.write === '') return usage(io, '--write needs a file');
39
+
40
+ let graph;
41
+ try {
42
+ graph = loadGraph(io.cwd, loadConfig(io.cwd));
43
+ } catch (e) {
44
+ if (e instanceof ConfigError) {
45
+ io.stderr(`slicekit: ${e.message}\n`);
46
+ return 2;
47
+ }
48
+ if (e instanceof GraphError) {
49
+ io.stderr(`slicekit: ${e.message}\n`);
50
+ return e.code;
51
+ }
52
+ throw e;
53
+ }
54
+ const html = renderPage(graph);
55
+
56
+ if (values.write !== undefined) {
57
+ const file = path.resolve(io.cwd, values.write);
58
+ if (!fs.existsSync(path.dirname(file))) {
59
+ io.stderr(`slicekit: ${path.dirname(values.write)} does not exist\n`);
60
+ return 1;
61
+ }
62
+ try {
63
+ fs.writeFileSync(file, html);
64
+ } catch (e) {
65
+ // A directory, a read-only file or a locked path: one line, not a stack (S-19 review H-2).
66
+ io.stderr(`slicekit: cannot write ${values.write}: ${e.code ?? e.message}\n`);
67
+ return 1;
68
+ }
69
+ io.stdout(`${values.write}\n`);
70
+ return 0;
71
+ }
72
+
73
+ let server;
74
+ try {
75
+ server = await startServer({ html, graphJson: serializeGraph(graph), port });
76
+ } catch (e) {
77
+ if (!(e instanceof GraphError)) throw e;
78
+ io.stderr(`slicekit: ${e.message}\n`);
79
+ return e.code;
80
+ }
81
+ io.stdout(`${server.url}\n`);
82
+ io.stderr('serving the graph on 127.0.0.1 only; Ctrl-C stops it\n');
83
+ await (io.interrupted ?? interrupted)();
84
+ await server.close();
85
+ return 0;
86
+ }
87
+
88
+ export const visualizeCommand = { run, usage: USAGE };
@@ -1,7 +1,7 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import { ConfigError, loadConfig } from '../config.js';
3
3
  import { writeText } from '../fs.js';
4
- import { WORKFLOW_DRIFT, WORKFLOW_PATH, workflowState } from '../workflow.js';
4
+ import { WORKFLOW_DRIFT, WORKFLOW_PATH, shardWarnings, workflowState } from '../workflow.js';
5
5
 
6
6
  const USAGE = 'workflow [--write | --check]';
7
7
 
@@ -20,8 +20,10 @@ async function run(args, io) {
20
20
  return 2;
21
21
  }
22
22
  let state;
23
+ let cfg;
23
24
  try {
24
- state = workflowState(io.cwd, loadConfig(io.cwd));
25
+ cfg = loadConfig(io.cwd);
26
+ state = workflowState(io.cwd, cfg);
25
27
  } catch (e) {
26
28
  if (!(e instanceof ConfigError)) throw e;
27
29
  io.stderr(`slicekit: ${e.message}\n`);
@@ -33,6 +35,8 @@ async function run(args, io) {
33
35
  return 1;
34
36
  }
35
37
  if (values.write) {
38
+ // D-49: a test command that never reads SLICEKIT_SHARD runs whole in every shard.
39
+ for (const w of shardWarnings(io.cwd, cfg)) io.stderr(`slicekit: warning: ${w}\n`);
36
40
  if (state.current === state.expected) {
37
41
  io.stdout(`unchanged ${WORKFLOW_PATH}\n`);
38
42
  } else {
package/src/config.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import fs from 'node:fs';
2
3
  import path from 'node:path';
3
4
  import { fileURLToPath } from 'node:url';
@@ -91,6 +92,16 @@ function workflowTextErrors(at, value, { expression = true } = {}) {
91
92
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
92
93
  const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
93
94
 
95
+ // ci.shards (D-49, optional, absent is none): operating system to the number of parallel jobs the
96
+ // test command's job is split into on it. Exported so the workflow generator refuses the same values.
97
+ export function shardErrors(shards) {
98
+ if (shards === undefined) return [];
99
+ if (!isObject(shards)) return ['ci.shards: must map operating systems to shard counts'];
100
+ return Object.entries(shards)
101
+ .filter(([, n]) => !(Number.isInteger(n) && n >= 1))
102
+ .map(([os]) => `ci.shards.${os}: must be a positive integer`);
103
+ }
104
+
94
105
  // ci.matrix is optional (absent reads as false), ci.botActors and ci.timeoutMinutes too (absent
95
106
  // reads as the default); each observability step renders as one CI job (REQ-3.11).
96
107
  function ciErrors(ci) {
@@ -102,6 +113,7 @@ function ciErrors(ci) {
102
113
  }
103
114
  const t = ci.timeoutMinutes;
104
115
  if (t !== undefined && !(Number.isInteger(t) && t >= 1 && t <= 360)) errors.push('ci.timeoutMinutes: must be an integer from 1 to 360');
116
+ errors.push(...shardErrors(ci.shards));
105
117
  if (!Array.isArray(ci.observabilitySteps)) return [...errors, 'ci.observabilitySteps: must be an array'];
106
118
  ci.observabilitySteps.forEach((step, i) => {
107
119
  const at = `ci.observabilitySteps[${i}]`;
@@ -176,6 +188,23 @@ export function validateConfig(cfg) {
176
188
  });
177
189
  }
178
190
  errors.push(...ciErrors(cfg.ci));
191
+ errors.push(...testFilesErrors(cfg.testFiles));
192
+ return errors;
193
+ }
194
+
195
+ // D-46: testFiles is optional; when present, regular expressions over the repository-relative POSIX
196
+ // path that name the test files (absent reads as the graph's DEFAULT_TEST_FILES).
197
+ function testFilesErrors(list) {
198
+ if (list === undefined) return [];
199
+ if (!isStringArray(list)) return ['testFiles: must be an array of strings'];
200
+ const errors = [];
201
+ list.forEach((src, i) => {
202
+ try {
203
+ new RegExp(src);
204
+ } catch (e) {
205
+ errors.push(`testFiles[${i}]: ${e.message}`);
206
+ }
207
+ });
179
208
  return errors;
180
209
  }
181
210
 
@@ -201,3 +230,59 @@ export function loadConfig(root) {
201
230
  if (errors.length > 0) throw new ConfigError(errors);
202
231
  return cfg;
203
232
  }
233
+
234
+ // The machine's own settings (D-43): `.slicekit/local.json`, untracked, in the session root (the
235
+ // main checkout). Only `testCommand` is read, by the build steps that run the test command on this
236
+ // machine (`build red`, `build commit --require-green`, `build pr`), and by the `commands` rule
237
+ // outside CI, which looks up the command this machine runs. The committed commands.test is left as
238
+ // it is: CI's workflow and `check --ci` judge and run it.
239
+ export const LOCAL_PATH = '.slicekit/local.json';
240
+
241
+ // The main checkout of the repository `dir` is in (a slice worktree's session root), or `dir` when
242
+ // it is no repository or the repository has no main checkout.
243
+ export function mainCheckout(dir) {
244
+ let common;
245
+ try {
246
+ common = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
247
+ } catch {
248
+ return dir;
249
+ }
250
+ return path.basename(common) === '.git' ? path.dirname(common) : dir;
251
+ }
252
+
253
+ // -> the local test command, or null when the file is absent or sets none; a file that does not
254
+ // parse, or a testCommand that is not a non-empty string, is a ConfigError.
255
+ export function localTestCommand(root, env = process.env) {
256
+ // Under CI the file is never read: CI runs the committed command.
257
+ if (typeof env.CI === 'string' && env.CI !== '') return null;
258
+ const file = path.join(root, ...LOCAL_PATH.split('/'));
259
+ let text;
260
+ try {
261
+ text = fs.readFileSync(file, 'utf8');
262
+ } catch (e) {
263
+ if (e.code === 'ENOENT') return null;
264
+ throw new ConfigError([`config: cannot read ${LOCAL_PATH}: ${e.code ?? e.message}`]);
265
+ }
266
+ let local;
267
+ try {
268
+ local = JSON.parse(text);
269
+ } catch {
270
+ throw new ConfigError([`config: ${LOCAL_PATH} is not valid JSON`]);
271
+ }
272
+ if (local === null || typeof local !== 'object' || Array.isArray(local)) throw new ConfigError([`config: ${LOCAL_PATH} must be a JSON object`]);
273
+ if (local.testCommand === undefined) return null;
274
+ if (typeof local.testCommand !== 'string' || local.testCommand.trim() === '') {
275
+ throw new ConfigError([`config: ${LOCAL_PATH} testCommand must be a non-empty string`]);
276
+ }
277
+ return local.testCommand;
278
+ }
279
+
280
+ // The test command the build steps run here: the local one when set, else commands.test.
281
+ // -> { command, local } where `local` is true for the local file's command.
282
+ export function buildTestCommand(root, cfg, env = process.env) {
283
+ const local = localTestCommand(mainCheckout(root), env);
284
+ if (local !== null) return { command: local, local: true };
285
+ return { command: cfg.commands?.test ?? '', local: false };
286
+ }
287
+
288
+ export const localNote = (command) => `ran the test command from ${LOCAL_PATH}: ${command}`;