slicekit 0.1.2 → 0.2.1

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 (66) 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 +39 -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 +90 -3
  38. package/src/git.js +35 -0
  39. package/src/graph/build.js +312 -0
  40. package/src/graph/docs.js +241 -0
  41. package/src/graph/git-walk.js +91 -0
  42. package/src/graph/history.js +60 -0
  43. package/src/graph/impact.js +143 -0
  44. package/src/graph/kitfiles.js +60 -0
  45. package/src/graph/load.js +93 -0
  46. package/src/graph/prs.js +136 -0
  47. package/src/graph/render.js +28 -0
  48. package/src/graph/schema.js +108 -0
  49. package/src/graph/shipped.js +32 -0
  50. package/src/graph/tests.js +45 -0
  51. package/src/graph/trace.js +83 -0
  52. package/src/graph/uncovered.js +16 -0
  53. package/src/graph/workspace.js +188 -0
  54. package/src/hook-cli.js +1 -1
  55. package/src/init.js +5 -2
  56. package/src/instructions.js +26 -8
  57. package/src/state/index.js +35 -4
  58. package/src/verdict.js +14 -2
  59. package/src/visualize/client.js +489 -0
  60. package/src/visualize/page.js +100 -0
  61. package/src/visualize/server.js +46 -0
  62. package/src/workflow.js +87 -9
  63. package/templates/instructions/agents/reviewer.md +7 -7
  64. package/templates/instructions/commands/build.md +34 -4
  65. package/templates/workflow/pins.json +2 -1
  66. 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';
@@ -9,6 +10,8 @@ export const CONFIG_PATH = path.join('.slicekit', 'config.json');
9
10
  const COMMAND_KEYS = ['test', 'lint', 'build', 'e2e'];
10
11
  const REVIEW_MODES = ['required', 'optional'];
11
12
  const BRANCH = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
13
+ // A branch name the config accepts as defaultBranch or a protected branch.
14
+ export const isBranchName = (name) => BRANCH.test(name);
12
15
 
13
16
  // Matched case-insensitively: compileDestructive adds the i flag, so `drop table` is caught too.
14
17
  // No force-push entry: pre-bash's rule 3 refuses force pushes from the parsed command.
@@ -34,15 +37,15 @@ export function seedBanned() {
34
37
  }
35
38
 
36
39
  // init always passes cli (from --cli or the D-30 probe); the default serves callers that do not.
37
- export function defaultConfig({ name, shape, docsRoot = 'docs', commands = {}, cli = 'slicekit' }) {
40
+ export function defaultConfig({ name, shape, docsRoot = 'docs', commands = {}, cli = 'slicekit', defaultBranch = 'main' }) {
38
41
  return {
39
42
  configVersion: CONFIG_VERSION,
40
43
  name,
41
44
  shape,
42
45
  docsRoot,
43
- defaultBranch: 'main',
46
+ defaultBranch,
44
47
  cli,
45
- protectedBranches: ['main'],
48
+ protectedBranches: [defaultBranch],
46
49
  commands: { test: '', lint: '', build: '', e2e: '', ...commands },
47
50
  repos: [],
48
51
  gitHost: { kind: 'github' },
@@ -91,6 +94,16 @@ function workflowTextErrors(at, value, { expression = true } = {}) {
91
94
  const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
92
95
  const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
93
96
 
97
+ // ci.shards (D-49, optional, absent is none): operating system to the number of parallel jobs the
98
+ // test command's job is split into on it. Exported so the workflow generator refuses the same values.
99
+ export function shardErrors(shards) {
100
+ if (shards === undefined) return [];
101
+ if (!isObject(shards)) return ['ci.shards: must map operating systems to shard counts'];
102
+ return Object.entries(shards)
103
+ .filter(([, n]) => !(Number.isInteger(n) && n >= 1))
104
+ .map(([os]) => `ci.shards.${os}: must be a positive integer`);
105
+ }
106
+
94
107
  // ci.matrix is optional (absent reads as false), ci.botActors and ci.timeoutMinutes too (absent
95
108
  // reads as the default); each observability step renders as one CI job (REQ-3.11).
96
109
  function ciErrors(ci) {
@@ -102,6 +115,7 @@ function ciErrors(ci) {
102
115
  }
103
116
  const t = ci.timeoutMinutes;
104
117
  if (t !== undefined && !(Number.isInteger(t) && t >= 1 && t <= 360)) errors.push('ci.timeoutMinutes: must be an integer from 1 to 360');
118
+ errors.push(...shardErrors(ci.shards));
105
119
  if (!Array.isArray(ci.observabilitySteps)) return [...errors, 'ci.observabilitySteps: must be an array'];
106
120
  ci.observabilitySteps.forEach((step, i) => {
107
121
  const at = `ci.observabilitySteps[${i}]`;
@@ -176,6 +190,23 @@ export function validateConfig(cfg) {
176
190
  });
177
191
  }
178
192
  errors.push(...ciErrors(cfg.ci));
193
+ errors.push(...testFilesErrors(cfg.testFiles));
194
+ return errors;
195
+ }
196
+
197
+ // D-46: testFiles is optional; when present, regular expressions over the repository-relative POSIX
198
+ // path that name the test files (absent reads as the graph's DEFAULT_TEST_FILES).
199
+ function testFilesErrors(list) {
200
+ if (list === undefined) return [];
201
+ if (!isStringArray(list)) return ['testFiles: must be an array of strings'];
202
+ const errors = [];
203
+ list.forEach((src, i) => {
204
+ try {
205
+ new RegExp(src);
206
+ } catch (e) {
207
+ errors.push(`testFiles[${i}]: ${e.message}`);
208
+ }
209
+ });
179
210
  return errors;
180
211
  }
181
212
 
@@ -201,3 +232,59 @@ export function loadConfig(root) {
201
232
  if (errors.length > 0) throw new ConfigError(errors);
202
233
  return cfg;
203
234
  }
235
+
236
+ // The machine's own settings (D-43): `.slicekit/local.json`, untracked, in the session root (the
237
+ // main checkout). Only `testCommand` is read, by the build steps that run the test command on this
238
+ // machine (`build red`, `build commit --require-green`, `build pr`), and by the `commands` rule
239
+ // outside CI, which looks up the command this machine runs. The committed commands.test is left as
240
+ // it is: CI's workflow and `check --ci` judge and run it.
241
+ export const LOCAL_PATH = '.slicekit/local.json';
242
+
243
+ // The main checkout of the repository `dir` is in (a slice worktree's session root), or `dir` when
244
+ // it is no repository or the repository has no main checkout.
245
+ export function mainCheckout(dir) {
246
+ let common;
247
+ try {
248
+ common = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
249
+ } catch {
250
+ return dir;
251
+ }
252
+ return path.basename(common) === '.git' ? path.dirname(common) : dir;
253
+ }
254
+
255
+ // -> the local test command, or null when the file is absent or sets none; a file that does not
256
+ // parse, or a testCommand that is not a non-empty string, is a ConfigError.
257
+ export function localTestCommand(root, env = process.env) {
258
+ // Under CI the file is never read: CI runs the committed command.
259
+ if (typeof env.CI === 'string' && env.CI !== '') return null;
260
+ const file = path.join(root, ...LOCAL_PATH.split('/'));
261
+ let text;
262
+ try {
263
+ text = fs.readFileSync(file, 'utf8');
264
+ } catch (e) {
265
+ if (e.code === 'ENOENT') return null;
266
+ throw new ConfigError([`config: cannot read ${LOCAL_PATH}: ${e.code ?? e.message}`]);
267
+ }
268
+ let local;
269
+ try {
270
+ local = JSON.parse(text);
271
+ } catch {
272
+ throw new ConfigError([`config: ${LOCAL_PATH} is not valid JSON`]);
273
+ }
274
+ if (local === null || typeof local !== 'object' || Array.isArray(local)) throw new ConfigError([`config: ${LOCAL_PATH} must be a JSON object`]);
275
+ if (local.testCommand === undefined) return null;
276
+ if (typeof local.testCommand !== 'string' || local.testCommand.trim() === '') {
277
+ throw new ConfigError([`config: ${LOCAL_PATH} testCommand must be a non-empty string`]);
278
+ }
279
+ return local.testCommand;
280
+ }
281
+
282
+ // The test command the build steps run here: the local one when set, else commands.test.
283
+ // -> { command, local } where `local` is true for the local file's command.
284
+ export function buildTestCommand(root, cfg, env = process.env) {
285
+ const local = localTestCommand(mainCheckout(root), env);
286
+ if (local !== null) return { command: local, local: true };
287
+ return { command: cfg.commands?.test ?? '', local: false };
288
+ }
289
+
290
+ export const localNote = (command) => `ran the test command from ${LOCAL_PATH}: ${command}`;
package/src/git.js CHANGED
@@ -45,6 +45,41 @@ export function currentBranch(root) {
45
45
 
46
46
  export const headSha = (root) => git(root, ['rev-parse', 'HEAD']);
47
47
 
48
+ // The branch a new config names as its default (P3/S-36, issue #78). In order: the one origin's
49
+ // HEAD points at; else main, master or git's init.defaultBranch, the first that is a local branch;
50
+ // else, in an empty repository (a plain `git init` has no branch yet), the branch HEAD is on when it
51
+ // is one of those three names; else main. main comes before init.defaultBranch because that setting
52
+ // may be the machine's, not this project's (Git for Windows sets master system-wide), while an empty
53
+ // repository's HEAD was named by it. Any other branch HEAD is on is not taken: a branch named the
54
+ // default is protected and refuses commits, so a feature branch guessed wrong would block work,
55
+ // where a wrong main only stops `graph` with a message (issue #87). A name `accept` refuses (one
56
+ // the config would reject) is passed over. Outside a repository there is no branch to read: main.
57
+ export function detectDefaultBranch(root, { accept = () => true } = {}) {
58
+ if (!isRepo(root)) return 'main';
59
+ const read = (args) => {
60
+ try {
61
+ return git(root, args);
62
+ } catch (e) {
63
+ if (e instanceof GitError) return '';
64
+ throw e;
65
+ }
66
+ };
67
+ const ok = (b) => b !== '' && accept(b);
68
+ const local = (b) => read(['rev-parse', '--verify', '-q', `refs/heads/${b}`]) !== '';
69
+ const empty = !hasCommits(root);
70
+ // origin's HEAD counts only while its branch exists: after the remote renames its default and a
71
+ // pruning fetch drops the old branch, HEAD still names it, and graph could not find it. An empty
72
+ // repository has no branch at all yet, so there its name is taken as it is.
73
+ const origin = read(['symbolic-ref', '-q', 'refs/remotes/origin/HEAD']);
74
+ const fromOrigin = origin.startsWith('refs/remotes/origin/') ? origin.slice('refs/remotes/origin/'.length) : '';
75
+ if (ok(fromOrigin) && (empty || read(['rev-parse', '--verify', '-q', origin]) !== '')) return fromOrigin;
76
+ const named = ['main', 'master', read(['config', '--get', 'init.defaultBranch'])].filter(ok);
77
+ const found = named.find(local);
78
+ if (found) return found;
79
+ const head = empty ? read(['symbolic-ref', '-q', 'HEAD']).replace(/^refs\/heads\//, '') : '';
80
+ return named.includes(head) ? head : 'main';
81
+ }
82
+
48
83
  // Whether `sha` names a commit object in the repository at root.
49
84
  export function commitExists(root, sha) {
50
85
  assertRef(sha);