slicekit 0.0.1 → 0.1.2

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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +252 -3
  3. package/bin/slicekit.js +4 -0
  4. package/package.json +21 -4
  5. package/src/adapters/githost/errors.js +17 -0
  6. package/src/adapters/githost/fixture.js +136 -0
  7. package/src/adapters/githost/gh-json.js +99 -0
  8. package/src/adapters/githost/github.js +127 -0
  9. package/src/adapters/githost/index.js +12 -0
  10. package/src/adapters/tracker/errors.js +53 -0
  11. package/src/adapters/tracker/fixture.js +71 -0
  12. package/src/adapters/tracker/github-issues.js +65 -0
  13. package/src/adapters/tracker/index.js +14 -0
  14. package/src/baseline.js +109 -0
  15. package/src/build/commit.js +201 -0
  16. package/src/build/decline.js +81 -0
  17. package/src/build/finish.js +155 -0
  18. package/src/build/order.js +158 -0
  19. package/src/build/overlap.js +173 -0
  20. package/src/build/parallel.js +50 -0
  21. package/src/build/pr.js +263 -0
  22. package/src/build/record.js +28 -0
  23. package/src/build/red.js +207 -0
  24. package/src/build/review.js +123 -0
  25. package/src/build/sync.js +47 -0
  26. package/src/build/verdict.js +410 -0
  27. package/src/build/worktree.js +169 -0
  28. package/src/check/ci-event.js +52 -0
  29. package/src/check/context.js +129 -0
  30. package/src/check/index.js +140 -0
  31. package/src/check/rules/.gitkeep +0 -0
  32. package/src/check/rules/ci-body.js +22 -0
  33. package/src/check/rules/ci-title.js +43 -0
  34. package/src/check/rules/citations.js +224 -0
  35. package/src/check/rules/commands.js +146 -0
  36. package/src/check/rules/coverage.js +248 -0
  37. package/src/check/rules/hooks.js +58 -0
  38. package/src/check/rules/journal.js +17 -0
  39. package/src/check/rules/layout.js +56 -0
  40. package/src/check/rules/managed.js +31 -0
  41. package/src/check/rules/queue.js +106 -0
  42. package/src/check/rules/references.js +249 -0
  43. package/src/check/rules/style.js +177 -0
  44. package/src/check/rules/trailer.js +67 -0
  45. package/src/cli/baseline.js +66 -0
  46. package/src/cli/branch.js +86 -0
  47. package/src/cli/build.js +239 -0
  48. package/src/cli/check.js +40 -0
  49. package/src/cli/decide.js +59 -0
  50. package/src/cli/gaps.js +73 -0
  51. package/src/cli/hook.js +28 -0
  52. package/src/cli/index.js +83 -0
  53. package/src/cli/init.js +96 -0
  54. package/src/cli/instructions.js +63 -0
  55. package/src/cli/intake.js +107 -0
  56. package/src/cli/journal.js +82 -0
  57. package/src/cli/plan.js +29 -0
  58. package/src/cli/pr.js +83 -0
  59. package/src/cli/process.js +59 -0
  60. package/src/cli/ready-label.js +119 -0
  61. package/src/cli/review.js +64 -0
  62. package/src/cli/spec.js +31 -0
  63. package/src/cli/stage.js +37 -0
  64. package/src/cli/state.js +106 -0
  65. package/src/cli/status.js +108 -0
  66. package/src/cli/update.js +62 -0
  67. package/src/cli/workflow.js +48 -0
  68. package/src/config.js +203 -0
  69. package/src/decisions.js +289 -0
  70. package/src/evidence.js +27 -0
  71. package/src/fs.js +38 -0
  72. package/src/gaps.js +271 -0
  73. package/src/git.js +209 -0
  74. package/src/githooks.js +37 -0
  75. package/src/hook-cli.js +63 -0
  76. package/src/hooks/io.js +205 -0
  77. package/src/hooks/paths.js +82 -0
  78. package/src/hooks/pre-bash.js +715 -0
  79. package/src/hooks/pre-compact.js +139 -0
  80. package/src/hooks/pre-edit.js +170 -0
  81. package/src/hooks/session-end.js +118 -0
  82. package/src/hooks/session-start.js +209 -0
  83. package/src/hooks/shapes.js +103 -0
  84. package/src/hooks/stop.js +37 -0
  85. package/src/hooks/subagent-marker.js +88 -0
  86. package/src/hooks/subagent-start.js +100 -0
  87. package/src/hooks/subagent-stop.js +106 -0
  88. package/src/ids.js +43 -0
  89. package/src/init.js +281 -0
  90. package/src/instructions.js +235 -0
  91. package/src/intake.js +409 -0
  92. package/src/journal.js +326 -0
  93. package/src/lock.js +35 -0
  94. package/src/markdown.js +155 -0
  95. package/src/paths.js +33 -0
  96. package/src/plan.js +25 -0
  97. package/src/pr.js +73 -0
  98. package/src/prbody.js +266 -0
  99. package/src/ready-label.js +107 -0
  100. package/src/redact.js +33 -0
  101. package/src/render/compare.js +23 -0
  102. package/src/render/entry.js +101 -0
  103. package/src/render/index.js +27 -0
  104. package/src/render/managed.js +128 -0
  105. package/src/render/manifest.js +24 -0
  106. package/src/render/settings.js +76 -0
  107. package/src/render/update.js +151 -0
  108. package/src/slicefile.js +173 -0
  109. package/src/spec-verify.js +58 -0
  110. package/src/stage.js +325 -0
  111. package/src/state/build.js +156 -0
  112. package/src/state/covers.js +58 -0
  113. package/src/state/index.js +191 -0
  114. package/src/state/sync.js +64 -0
  115. package/src/state/transitions.js +282 -0
  116. package/src/verdict.js +203 -0
  117. package/src/which.js +37 -0
  118. package/src/workflow.js +177 -0
  119. package/src/worktrees.js +68 -0
  120. package/templates/claude-code/agents/auditor.md +7 -0
  121. package/templates/claude-code/agents/designer.md +7 -0
  122. package/templates/claude-code/agents/developer.md +7 -0
  123. package/templates/claude-code/agents/fixer.md +7 -0
  124. package/templates/claude-code/agents/ops.md +7 -0
  125. package/templates/claude-code/agents/reviewer.md +7 -0
  126. package/templates/claude-code/commands/slicekit-audit.md +7 -0
  127. package/templates/claude-code/commands/slicekit-build.md +7 -0
  128. package/templates/claude-code/commands/slicekit-gaps.md +6 -0
  129. package/templates/claude-code/commands/slicekit-intake.md +7 -0
  130. package/templates/claude-code/commands/slicekit-ops.md +7 -0
  131. package/templates/claude-code/commands/slicekit-plan.md +6 -0
  132. package/templates/claude-code/commands/slicekit-release.md +7 -0
  133. package/templates/claude-code/commands/slicekit-review.md +7 -0
  134. package/templates/claude-code/commands/slicekit-specify.md +6 -0
  135. package/templates/claude-code/commands/slicekit.md +7 -0
  136. package/templates/claude-code/hooks.json +90 -0
  137. package/templates/claude-code/manifest.json +171 -0
  138. package/templates/claude-code/skills/slicekit-ids/SKILL.md +16 -0
  139. package/templates/claude-code/skills/slicekit-loop/SKILL.md +23 -0
  140. package/templates/claude-code/skills/slicekit-writing/SKILL.md +24 -0
  141. package/templates/docs/BUILD.md +5 -0
  142. package/templates/docs/decisions.md +15 -0
  143. package/templates/docs/intake/.keep +0 -0
  144. package/templates/docs/observability.md +25 -0
  145. package/templates/docs/phases/.keep +0 -0
  146. package/templates/docs/platform.md +25 -0
  147. package/templates/docs/releases/.keep +0 -0
  148. package/templates/docs/runbook.md +21 -0
  149. package/templates/docs/spec/00-overview.md +8 -0
  150. package/templates/docs/spec/contracts/.keep +0 -0
  151. package/templates/docs/spec/gaps.md +6 -0
  152. package/templates/docs/spec/stack.md +3 -0
  153. package/templates/githooks/pre-commit +79 -0
  154. package/templates/githooks/pre-merge-commit +79 -0
  155. package/templates/githooks/prepare-commit-msg +110 -0
  156. package/templates/instructions/agents/auditor.md +33 -0
  157. package/templates/instructions/agents/designer.md +21 -0
  158. package/templates/instructions/agents/developer.md +49 -0
  159. package/templates/instructions/agents/fixer.md +41 -0
  160. package/templates/instructions/agents/ops.md +21 -0
  161. package/templates/instructions/agents/reviewer.md +63 -0
  162. package/templates/instructions/commands/build.md +234 -0
  163. package/templates/instructions/commands/gaps.md +65 -0
  164. package/templates/instructions/commands/intake.md +90 -0
  165. package/templates/instructions/commands/plan.md +60 -0
  166. package/templates/instructions/commands/review.md +117 -0
  167. package/templates/instructions/commands/specify.md +49 -0
  168. package/templates/style.json +11 -0
  169. package/templates/workflow/pins.json +6 -0
  170. package/templates/workflow/slicekit.yml +110 -0
@@ -0,0 +1,106 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { ConfigError, loadConfig } from '../config.js';
3
+ import { STATES } from '../state/transitions.js';
4
+ import { LockError, TransitionError, readSlice, setState, unfreeze } from '../state/index.js';
5
+
6
+ const USAGE =
7
+ '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>';
9
+
10
+ const OPTIONS = {
11
+ commit: { type: 'string' },
12
+ 'test-exit': { type: 'string' },
13
+ 'check-exit': { type: 'string' },
14
+ tests: { type: 'string' },
15
+ 'pr-number': { type: 'string' },
16
+ 'pr-title': { type: 'string' },
17
+ 'pr-url': { type: 'string' },
18
+ 'pr-sha': { type: 'string' },
19
+ verdict: { type: 'string' },
20
+ round: { type: 'string' },
21
+ blockers: { type: 'string' },
22
+ independent: { type: 'boolean' },
23
+ 'ci-status': { type: 'string' },
24
+ 'ci-sha': { type: 'string' },
25
+ 'merged-at': { type: 'string' },
26
+ release: { type: 'string' },
27
+ backfill: { type: 'boolean' },
28
+ json: { type: 'boolean' },
29
+ };
30
+
31
+ const num = (s) => (s === undefined ? undefined : Number(s));
32
+
33
+ function evidenceFrom(v) {
34
+ const ev = {};
35
+ if (v.commit !== undefined) ev.commit = v.commit;
36
+ if (v['test-exit'] !== undefined) ev.testExit = num(v['test-exit']);
37
+ if (v['check-exit'] !== undefined) ev.checkExit = num(v['check-exit']);
38
+ if (v.tests !== undefined) ev.tests = v.tests.split(',').map((t) => t.trim()).filter(Boolean);
39
+ if (['pr-number', 'pr-title', 'pr-url', 'pr-sha'].some((k) => v[k] !== undefined)) {
40
+ ev.pr = { number: num(v['pr-number']), url: v['pr-url'], headSha: v['pr-sha'], title: v['pr-title'] };
41
+ }
42
+ if (v.verdict !== undefined) {
43
+ ev.verdict = {
44
+ round: num(v.round),
45
+ path: v.verdict,
46
+ blockers: num(v.blockers),
47
+ independent: Boolean(v.independent),
48
+ };
49
+ }
50
+ if (v['ci-status'] !== undefined || v['ci-sha'] !== undefined) {
51
+ ev.ci = { status: v['ci-status'], sha: v['ci-sha'] };
52
+ }
53
+ if (v['merged-at'] !== undefined) ev.mergedAt = v['merged-at'];
54
+ if (v.release !== undefined) ev.release = v.release;
55
+ if (v.backfill) ev.backfill = true;
56
+ return ev;
57
+ }
58
+
59
+ async function run(args, io) {
60
+ let parsed;
61
+ try {
62
+ parsed = parseArgs({ args, options: OPTIONS, allowPositionals: true });
63
+ } catch (e) {
64
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
65
+ return 2;
66
+ }
67
+ const { values, positionals } = parsed;
68
+ const [sub, id, arg] = positionals;
69
+ const wanted = { set: 3, unfreeze: 3, show: 2 }[sub];
70
+ if (!wanted || positionals.length !== wanted) {
71
+ io.stderr(`usage: slicekit ${USAGE}\n`);
72
+ return 2;
73
+ }
74
+ if (sub === 'set' && !STATES.includes(arg)) {
75
+ io.stderr(`slicekit: unknown state '${arg}'; one of ${STATES.join(', ')}\n`);
76
+ return 2;
77
+ }
78
+ const root = io.cwd;
79
+ try {
80
+ const cfg = loadConfig(root);
81
+ if (sub === 'set') {
82
+ const s = setState(root, cfg, id, arg, evidenceFrom(values));
83
+ io.stdout(`${id} ${s.state}\n`);
84
+ } else if (sub === 'unfreeze') {
85
+ unfreeze(root, cfg, id, arg);
86
+ io.stdout(`${id} unfroze ${arg}\n`);
87
+ } else {
88
+ const s = readSlice(root, cfg, id);
89
+ const pr = s.pr?.number != null ? `#${s.pr.number}` : '-';
90
+ io.stdout(values.json ? `${JSON.stringify(s, null, 2)}\n` : `${id} ${s.state} PR ${pr}\n`);
91
+ }
92
+ return 0;
93
+ } catch (e) {
94
+ if (e instanceof TransitionError) {
95
+ io.stderr(`refused: ${e.reason}\n`);
96
+ return 1;
97
+ }
98
+ if (e instanceof ConfigError || e instanceof LockError || /^unknown slice /.test(e.message)) {
99
+ io.stderr(`slicekit: ${e.message}\n`);
100
+ return 2;
101
+ }
102
+ throw e;
103
+ }
104
+ }
105
+
106
+ export const stateCommand = { run, usage: USAGE };
@@ -0,0 +1,108 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { ConfigError, loadConfig } from '../config.js';
3
+ import { exists, readText, writeText } from '../fs.js';
4
+ import { kitPaths } from '../paths.js';
5
+ import { SliceFileError, findSliceFiles, parseSliceFile } from '../slicefile.js';
6
+ import { programStage } from '../stage.js';
7
+ import { renderBuild } from '../state/build.js';
8
+ import { LockError, readSlice } from '../state/index.js';
9
+ import { syncFromHost } from '../state/sync.js';
10
+ import { getHost } from '../adapters/githost/index.js';
11
+ import { GitHostError } from '../adapters/githost/errors.js';
12
+
13
+ const USAGE = 'status [--json] [--write] [--sync]';
14
+
15
+ const OPTIONS = {
16
+ json: { type: 'boolean' },
17
+ write: { type: 'boolean' },
18
+ sync: { type: 'boolean' },
19
+ };
20
+
21
+ function slices(root, cfg) {
22
+ return findSliceFiles(root, cfg).map((f) => {
23
+ const slice = parseSliceFile(readText(f.path), f.path);
24
+ const state = readSlice(root, cfg, slice.id);
25
+ return { id: slice.id, state: state.state, pr: state.pr?.number ?? null, name: slice.name, phase: f.phaseId };
26
+ });
27
+ }
28
+
29
+ // The errors status reports and exits 2 on: a bad config or slice file, the host saying no, a held lock.
30
+ const expected = (e) =>
31
+ e instanceof ConfigError || e instanceof SliceFileError || e instanceof GitHostError || e instanceof LockError;
32
+
33
+ // Under --json, stdout carries exactly one JSON document on every path:
34
+ // success { stage, slices, synced (with --sync), warnings, build (with --write) }
35
+ // failure { error, synced, warnings }, exit 2
36
+ // Without --json, changes go to stdout and warnings and errors to stderr.
37
+ async function run(args, io) {
38
+ let values;
39
+ try {
40
+ ({ values } = parseArgs({ args, options: OPTIONS, allowPositionals: false }));
41
+ } catch (e) {
42
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
43
+ return 2;
44
+ }
45
+ const root = io.cwd;
46
+ const warnings = [];
47
+ const synced = [];
48
+ const warn = (w) => {
49
+ warnings.push(w);
50
+ if (!values.json) io.stderr(`slicekit: ${w}\n`);
51
+ };
52
+ const record = ({ changes, warnings: ws }) => {
53
+ for (const c of changes) {
54
+ synced.push(c);
55
+ if (!values.json) io.stdout(`synced ${c.id} → ${c.to} (PR #${c.pr})\n`);
56
+ }
57
+ for (const w of ws) warn(w);
58
+ };
59
+ try {
60
+ const cfg = loadConfig(root);
61
+ if (values.sync) {
62
+ let result;
63
+ try {
64
+ result = syncFromHost(root, cfg, getHost(cfg, io.env ?? process.env, root));
65
+ } catch (e) {
66
+ // Whatever stopped the sync, every change already on disk is reported first.
67
+ if (e?.partial) record(e.partial);
68
+ throw e;
69
+ }
70
+ record(result);
71
+ }
72
+ let build;
73
+ if (values.write) {
74
+ const file = kitPaths(root, cfg).build;
75
+ const before = exists(file) ? readText(file) : '';
76
+ const after = renderBuild(root, cfg, before, { onWarning: warn });
77
+ build = after === before ? 'unchanged' : 'updated';
78
+ if (build === 'updated') writeText(file, after);
79
+ }
80
+ if (values.json) {
81
+ const out = {
82
+ stage: programStage(root, cfg),
83
+ slices: slices(root, cfg),
84
+ ...(values.sync ? { synced } : {}),
85
+ warnings,
86
+ ...(build ? { build } : {}),
87
+ };
88
+ io.stdout(`${JSON.stringify(out, null, 2)}\n`);
89
+ return 0;
90
+ }
91
+ if (build) {
92
+ io.stdout(`BUILD.md ${build}\n`);
93
+ return 0;
94
+ }
95
+ const list = slices(root, cfg);
96
+ for (const s of list) io.stdout(`${s.id} ${s.state} PR ${s.pr === null ? '-' : `#${s.pr}`} ${s.name}\n`);
97
+ return 0;
98
+ } catch (e) {
99
+ if (values.json) io.stdout(`${JSON.stringify({ error: e.message, synced, warnings }, null, 2)}\n`);
100
+ if (expected(e)) {
101
+ io.stderr(`slicekit: ${e.message}\n`);
102
+ return 2;
103
+ }
104
+ throw e;
105
+ }
106
+ }
107
+
108
+ export const statusCommand = { run, usage: USAGE };
@@ -0,0 +1,62 @@
1
+ import path from 'node:path';
2
+ import { parseArgs } from 'node:util';
3
+ import { ConfigError, loadConfig } from '../config.js';
4
+ import { exists } from '../fs.js';
5
+ import { checkCli } from '../hook-cli.js';
6
+ import { kitVersion, RENDERED } from '../render/index.js';
7
+ import { applyUpdate, planUpdate } from '../render/update.js';
8
+
9
+ const USAGE = 'update [--yes] [--check] [--force]';
10
+
11
+ const OPTIONS = {
12
+ yes: { type: 'boolean' },
13
+ check: { type: 'boolean' },
14
+ force: { type: 'boolean' },
15
+ };
16
+
17
+ async function run(args, io) {
18
+ let values;
19
+ try {
20
+ ({ values } = parseArgs({ args, options: OPTIONS, allowPositionals: false }));
21
+ } catch (e) {
22
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
23
+ return 2;
24
+ }
25
+ const root = io.cwd;
26
+ const version = kitVersion();
27
+ const force = values.force === true;
28
+ let plan;
29
+ let cfg;
30
+ try {
31
+ cfg = loadConfig(root);
32
+ plan = planUpdate(root, cfg, { version });
33
+ } catch (e) {
34
+ if (!(e instanceof ConfigError)) throw e;
35
+ io.stderr(`slicekit: ${e.message}\n`);
36
+ return 2;
37
+ }
38
+ const pending = plan.filter((p) => p.status !== 'same');
39
+ for (const { dest, status, diff } of pending) {
40
+ io.stdout(`${status} ${dest}\n`);
41
+ if (diff !== '') io.stdout(diff);
42
+ }
43
+ if (values.check) {
44
+ if (!exists(path.join(root, RENDERED))) io.stdout(`${RENDERED}/ is missing; commit it so drift can be told from kit changes\n`);
45
+ return pending.some((p) => p.status === 'drifted' || p.status === 'missing') ? 1 : 0;
46
+ }
47
+ if (!values.yes) {
48
+ const writes = pending.some((p) => p.status === 'changed' || p.status === 'missing' || (p.status === 'drifted' && force));
49
+ if (writes) io.stdout('run again with --yes to apply\n');
50
+ return 0;
51
+ }
52
+ // Apply the plan that was printed.
53
+ const { written, skipped } = applyUpdate(root, cfg, plan, { version, force });
54
+ for (const dest of written) io.stdout(`wrote ${dest}\n`);
55
+ for (const { warning } of skipped) io.stderr(`slicekit: ${warning}\n`);
56
+ const unanswered = checkCli(cfg.cli, { version, cwd: root });
57
+ if (unanswered) io.stderr(`slicekit: ${unanswered}\n`);
58
+ // Drift left in place is not success.
59
+ return skipped.some((s) => s.status === 'drifted') ? 1 : 0;
60
+ }
61
+
62
+ export const updateCommand = { run, usage: USAGE };
@@ -0,0 +1,48 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { ConfigError, loadConfig } from '../config.js';
3
+ import { writeText } from '../fs.js';
4
+ import { WORKFLOW_DRIFT, WORKFLOW_PATH, workflowState } from '../workflow.js';
5
+
6
+ const USAGE = 'workflow [--write | --check]';
7
+
8
+ // Prints the workflow the config renders; --write puts it at .github/workflows/slicekit.yml and
9
+ // --check exits 1 when that file is missing or differs from the render (REQ-3.11, REQ-5.5).
10
+ async function run(args, io) {
11
+ let values;
12
+ try {
13
+ ({ values } = parseArgs({ args, options: { write: { type: 'boolean' }, check: { type: 'boolean' } }, allowPositionals: false }));
14
+ } catch (e) {
15
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
16
+ return 2;
17
+ }
18
+ if (values.write && values.check) {
19
+ io.stderr(`slicekit: --write and --check do not go together\nusage: slicekit ${USAGE}\n`);
20
+ return 2;
21
+ }
22
+ let state;
23
+ try {
24
+ state = workflowState(io.cwd, loadConfig(io.cwd));
25
+ } catch (e) {
26
+ if (!(e instanceof ConfigError)) throw e;
27
+ io.stderr(`slicekit: ${e.message}\n`);
28
+ return 2;
29
+ }
30
+ if (values.check) {
31
+ if (state.current === state.expected) return 0;
32
+ io.stderr(`slicekit: ${state.current === null ? `${WORKFLOW_PATH} is missing; run slicekit workflow --write to create it` : WORKFLOW_DRIFT}\n`);
33
+ return 1;
34
+ }
35
+ if (values.write) {
36
+ if (state.current === state.expected) {
37
+ io.stdout(`unchanged ${WORKFLOW_PATH}\n`);
38
+ } else {
39
+ writeText(state.file, state.expected);
40
+ io.stdout(`${state.current === null ? 'created' : 'updated'} ${WORKFLOW_PATH}\n`);
41
+ }
42
+ return 0;
43
+ }
44
+ io.stdout(state.expected);
45
+ return 0;
46
+ }
47
+
48
+ export const workflowCommand = { run, usage: USAGE };
package/src/config.js ADDED
@@ -0,0 +1,203 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export const CONFIG_VERSION = 1;
6
+ export const SHAPES = ['backend', 'fullstack', 'data'];
7
+ export const CONFIG_PATH = path.join('.slicekit', 'config.json');
8
+
9
+ const COMMAND_KEYS = ['test', 'lint', 'build', 'e2e'];
10
+ const REVIEW_MODES = ['required', 'optional'];
11
+ const BRANCH = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
12
+
13
+ // Matched case-insensitively: compileDestructive adds the i flag, so `drop table` is caught too.
14
+ // No force-push entry: pre-bash's rule 3 refuses force pushes from the parsed command.
15
+ const DESTRUCTIVE = [
16
+ '\\brm\\s+-rf\\s+(/|~|\\.\\.)',
17
+ '\\bDROP\\s+(TABLE|DATABASE|SCHEMA)\\b',
18
+ '\\bTRUNCATE\\s+TABLE\\b',
19
+ 'git\\s+reset\\s+--hard\\s+origin/',
20
+ ];
21
+
22
+ export class ConfigError extends Error {
23
+ constructor(errors) {
24
+ super(errors.join('; '));
25
+ this.name = 'ConfigError';
26
+ this.errors = errors;
27
+ }
28
+ }
29
+
30
+ // The kit's own filler list, before any team extends it.
31
+ export function seedBanned() {
32
+ const file = fileURLToPath(new URL('../templates/style.json', import.meta.url));
33
+ return JSON.parse(fs.readFileSync(file, 'utf8')).banned;
34
+ }
35
+
36
+ // 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' }) {
38
+ return {
39
+ configVersion: CONFIG_VERSION,
40
+ name,
41
+ shape,
42
+ docsRoot,
43
+ defaultBranch: 'main',
44
+ cli,
45
+ protectedBranches: ['main'],
46
+ commands: { test: '', lint: '', build: '', e2e: '', ...commands },
47
+ repos: [],
48
+ gitHost: { kind: 'github' },
49
+ tracker: { kind: 'github-issues' },
50
+ review: { independent: 'required' },
51
+ freezeTests: true,
52
+ style: { banned: seedBanned() },
53
+ destructive: [...DESTRUCTIVE],
54
+ ci: { matrix: false, observabilitySteps: [], botActors: [...DEFAULT_BOT_ACTORS], timeoutMinutes: DEFAULT_TIMEOUT_MINUTES },
55
+ };
56
+ }
57
+
58
+ // D-37: pull requests these actors open skip ci-title and ci-body.
59
+ export const DEFAULT_BOT_ACTORS = Object.freeze(['dependabot[bot]', 'renovate[bot]']);
60
+ // The timeout of each generated gate, command and observability job, in minutes.
61
+ export const DEFAULT_TIMEOUT_MINUTES = 30;
62
+
63
+ const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
64
+ const isStringArray = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
65
+
66
+ // One message per docsRoot; a hand-edited config must already be clean (the CLI normalises --docs).
67
+ function docsRootError(d) {
68
+ if (d.includes('\\')) return 'docsRoot: use forward slashes';
69
+ if (d.startsWith('/') || /^[A-Za-z]:/.test(d)) return 'docsRoot: must be relative';
70
+ if (d.split('/').includes('..')) return 'docsRoot: no .. segment';
71
+ if (d.endsWith('/')) return 'docsRoot: no trailing slash';
72
+ if (/\s/.test(d)) return 'docsRoot must not contain spaces (git attribute patterns cannot hold them)';
73
+ return null;
74
+ }
75
+
76
+ const STEP_KEYS = ['name', 'run', 'env'];
77
+ // A ${{ … }} inside a run: line is expanded by GitHub before the shell sees it, so a pull request title
78
+ // could become a command; values reach a command through env: instead (REQ-3.11).
79
+ export const GITHUB_EXPRESSION = /\$\{\{/;
80
+ // The line breaks YAML honours beyond CR and LF; the workflow cannot carry them in a command.
81
+ export const LINE_SEPARATOR = /[\u0085\u2028\u2029]/;
82
+
83
+ // Errors for text that lands in the generated workflow; expression false where ${{ … }} is the intended use (env).
84
+ function workflowTextErrors(at, value, { expression = true } = {}) {
85
+ if (typeof value !== 'string') return [];
86
+ const errors = [];
87
+ if (expression && GITHUB_EXPRESSION.test(value)) errors.push(`${at}: contains a GitHub expression; pass values through env:`);
88
+ if (LINE_SEPARATOR.test(value)) errors.push(`${at}: contains a line separator YAML cannot carry`);
89
+ return errors;
90
+ }
91
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
92
+ const nonEmpty = (v) => typeof v === 'string' && v.trim() !== '';
93
+
94
+ // ci.matrix is optional (absent reads as false), ci.botActors and ci.timeoutMinutes too (absent
95
+ // reads as the default); each observability step renders as one CI job (REQ-3.11).
96
+ function ciErrors(ci) {
97
+ if (!isObject(ci)) return ['ci: must be an object'];
98
+ const errors = [];
99
+ if (ci.matrix !== undefined && typeof ci.matrix !== 'boolean') errors.push('ci.matrix: must be a boolean');
100
+ if (ci.botActors !== undefined && !(isStringArray(ci.botActors) && ci.botActors.every(nonEmpty))) {
101
+ errors.push('ci.botActors: must be an array of non-empty strings');
102
+ }
103
+ const t = ci.timeoutMinutes;
104
+ if (t !== undefined && !(Number.isInteger(t) && t >= 1 && t <= 360)) errors.push('ci.timeoutMinutes: must be an integer from 1 to 360');
105
+ if (!Array.isArray(ci.observabilitySteps)) return [...errors, 'ci.observabilitySteps: must be an array'];
106
+ ci.observabilitySteps.forEach((step, i) => {
107
+ const at = `ci.observabilitySteps[${i}]`;
108
+ if (!isObject(step)) return errors.push(`${at}: must be an object`);
109
+ for (const key of ['name', 'run']) if (!nonEmpty(step[key])) errors.push(`${at}.${key}: must be a non-empty string`);
110
+ errors.push(...workflowTextErrors(`${at}.name`, step.name, { expression: false }));
111
+ errors.push(...workflowTextErrors(`${at}.run`, step.run));
112
+ if (step.env !== undefined) {
113
+ const ok = isObject(step.env) && Object.entries(step.env).every(([k, v]) => ENV_NAME.test(k) && typeof v === 'string');
114
+ if (!ok) errors.push(`${at}.env: must map names to strings`);
115
+ else if (Object.values(step.env).some((v) => LINE_SEPARATOR.test(v))) errors.push(`${at}.env: contains a line separator YAML cannot carry`);
116
+ }
117
+ for (const key of Object.keys(step)) {
118
+ if (!STEP_KEYS.includes(key)) errors.push(`${at}.${key}: unknown key; use ${STEP_KEYS.join(', ')}`);
119
+ }
120
+ });
121
+ return errors;
122
+ }
123
+
124
+ export function validateConfig(cfg) {
125
+ if (!isObject(cfg)) return ['config: must be an object'];
126
+ const errors = [];
127
+ if (cfg.configVersion !== CONFIG_VERSION) errors.push(`configVersion: must be ${CONFIG_VERSION}`);
128
+ for (const key of ['name', 'docsRoot', 'defaultBranch', 'cli']) {
129
+ if (typeof cfg[key] !== 'string' || cfg[key] === '') errors.push(`${key}: must be a non-empty string`);
130
+ }
131
+ errors.push(...workflowTextErrors('cli', cfg.cli));
132
+ if (typeof cfg.docsRoot === 'string' && cfg.docsRoot !== '') {
133
+ const error = docsRootError(cfg.docsRoot);
134
+ if (error) errors.push(error);
135
+ }
136
+ if (typeof cfg.defaultBranch === 'string' && cfg.defaultBranch !== '' && !BRANCH.test(cfg.defaultBranch)) {
137
+ errors.push('defaultBranch: must be a branch name');
138
+ }
139
+ if (!SHAPES.includes(cfg.shape)) errors.push(`shape: must be one of ${SHAPES.join(', ')}`);
140
+ if (!isStringArray(cfg.protectedBranches)) {
141
+ errors.push('protectedBranches: must be an array of strings');
142
+ } else {
143
+ cfg.protectedBranches.forEach((b, i) => {
144
+ if (!BRANCH.test(b)) errors.push(`protectedBranches[${i}]: must be a branch name`);
145
+ });
146
+ }
147
+ if (!isObject(cfg.commands)) {
148
+ errors.push('commands: must be an object');
149
+ } else {
150
+ for (const key of COMMAND_KEYS) {
151
+ if (typeof cfg.commands[key] !== 'string') errors.push(`commands.${key}: must be a string`);
152
+ errors.push(...workflowTextErrors(`commands.${key}`, cfg.commands[key]));
153
+ }
154
+ for (const key of Object.keys(cfg.commands)) {
155
+ if (!COMMAND_KEYS.includes(key)) errors.push(`commands.${key}: unknown command; use ${COMMAND_KEYS.join(', ')}`);
156
+ }
157
+ }
158
+ if (!Array.isArray(cfg.repos)) errors.push('repos: must be an array');
159
+ for (const key of ['gitHost', 'tracker']) {
160
+ if (!isObject(cfg[key]) || typeof cfg[key].kind !== 'string') errors.push(`${key}.kind: must be a string`);
161
+ }
162
+ if (!isObject(cfg.review) || !REVIEW_MODES.includes(cfg.review.independent)) {
163
+ errors.push(`review.independent: must be ${REVIEW_MODES.join(' or ')}`);
164
+ }
165
+ if (typeof cfg.freezeTests !== 'boolean') errors.push('freezeTests: must be a boolean');
166
+ if (!isObject(cfg.style) || !isStringArray(cfg.style.banned)) errors.push('style.banned: must be an array of strings');
167
+ if (!isStringArray(cfg.destructive)) {
168
+ errors.push('destructive: must be an array of strings');
169
+ } else {
170
+ cfg.destructive.forEach((src, i) => {
171
+ try {
172
+ new RegExp(src, 'i');
173
+ } catch {
174
+ errors.push(`destructive[${i}]: must be a valid regular expression`);
175
+ }
176
+ });
177
+ }
178
+ errors.push(...ciErrors(cfg.ci));
179
+ return errors;
180
+ }
181
+
182
+ export function compileDestructive(cfg) {
183
+ return cfg.destructive.map((src) => new RegExp(src, 'i'));
184
+ }
185
+
186
+ export function loadConfig(root) {
187
+ const file = path.join(root, CONFIG_PATH);
188
+ let text;
189
+ try {
190
+ text = fs.readFileSync(file, 'utf8');
191
+ } catch {
192
+ throw new ConfigError([`config: cannot read ${CONFIG_PATH}`]);
193
+ }
194
+ let cfg;
195
+ try {
196
+ cfg = JSON.parse(text);
197
+ } catch {
198
+ throw new ConfigError([`config: ${CONFIG_PATH} is not valid JSON`]);
199
+ }
200
+ const errors = validateConfig(cfg);
201
+ if (errors.length > 0) throw new ConfigError(errors);
202
+ return cfg;
203
+ }