slicekit 0.2.1 → 0.3.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 (44) hide show
  1. package/README.md +7 -2
  2. package/bin/slicekit.js +0 -0
  3. package/package.json +1 -1
  4. package/src/adapters/githost/fixture.js +106 -0
  5. package/src/adapters/githost/gh-json.js +201 -0
  6. package/src/adapters/githost/github.js +141 -0
  7. package/src/adapters/tracker/index.js +5 -1
  8. package/src/adapters/tracker/jira.js +133 -0
  9. package/src/build/commit.js +85 -7
  10. package/src/build/decline.js +17 -8
  11. package/src/build/record.js +11 -1
  12. package/src/check/ci-event.js +38 -6
  13. package/src/check/index.js +6 -1
  14. package/src/check/rules/ci-body.js +1 -1
  15. package/src/check/rules/ci-title.js +10 -4
  16. package/src/check/rules/frozen.js +127 -0
  17. package/src/check/rules/host-rules.js +149 -0
  18. package/src/check/rules/journal.js +130 -3
  19. package/src/check/rules/references.js +31 -0
  20. package/src/check/rules/sync-release.js +94 -0
  21. package/src/cli/build.js +8 -7
  22. package/src/cli/index.js +2 -0
  23. package/src/cli/init.js +29 -2
  24. package/src/cli/journal.js +44 -2
  25. package/src/cli/status.js +14 -2
  26. package/src/cli/sync.js +52 -0
  27. package/src/config.js +72 -0
  28. package/src/git.js +30 -1
  29. package/src/hooks/paths.js +103 -0
  30. package/src/hooks/pre-bash.js +642 -43
  31. package/src/hooks/pre-edit.js +23 -3
  32. package/src/init.js +134 -6
  33. package/src/journal.js +153 -12
  34. package/src/pr.js +1 -1
  35. package/src/prbody.js +1 -1
  36. package/src/release-version.js +196 -0
  37. package/src/render/settings.js +26 -2
  38. package/src/render/update.js +1 -1
  39. package/src/state/index.js +11 -0
  40. package/src/state/sync.js +182 -0
  41. package/src/workflow.js +141 -29
  42. package/templates/instructions/commands/build.md +12 -2
  43. package/templates/workflow/pins.json +2 -1
  44. package/templates/workflow/slicekit.yml +46 -11
package/src/cli/status.js CHANGED
@@ -7,6 +7,7 @@ import { programStage } from '../stage.js';
7
7
  import { renderBuild } from '../state/build.js';
8
8
  import { LockError, readSlice } from '../state/index.js';
9
9
  import { syncFromHost } from '../state/sync.js';
10
+ import { ReleaseError, applyRelease } from '../release-version.js';
10
11
  import { getHost } from '../adapters/githost/index.js';
11
12
  import { GitHostError } from '../adapters/githost/errors.js';
12
13
 
@@ -28,10 +29,11 @@ function slices(root, cfg) {
28
29
 
29
30
  // The errors status reports and exits 2 on: a bad config or slice file, the host saying no, a held lock.
30
31
  const expected = (e) =>
31
- e instanceof ConfigError || e instanceof SliceFileError || e instanceof GitHostError || e instanceof LockError;
32
+ e instanceof ConfigError || e instanceof SliceFileError || e instanceof GitHostError || e instanceof LockError || e instanceof ReleaseError;
32
33
 
33
34
  // Under --json, stdout carries exactly one JSON document on every path:
34
- // success { stage, slices, synced (with --sync), warnings, build (with --write) }
35
+ // success { stage, slices, synced (with --sync), warnings, build (with --write), version (when
36
+ // --sync --write set one under release.auto, D-90) }
35
37
  // failure { error, synced, warnings }, exit 2
36
38
  // Without --json, changes go to stdout and warnings and errors to stderr.
37
39
  async function run(args, io) {
@@ -45,6 +47,7 @@ async function run(args, io) {
45
47
  const root = io.cwd;
46
48
  const warnings = [];
47
49
  const synced = [];
50
+ let version = null;
48
51
  const warn = (w) => {
49
52
  warnings.push(w);
50
53
  if (!values.json) io.stderr(`slicekit: ${w}\n`);
@@ -68,6 +71,14 @@ async function run(args, io) {
68
71
  throw e;
69
72
  }
70
73
  record(result);
74
+ // With --write and release.auto, the sync also sets the next version (D-90).
75
+ if (values.write) {
76
+ const release = applyRelease(root, cfg, result.changes);
77
+ if (release) {
78
+ version = release.version;
79
+ if (!values.json) io.stdout(`version ${version}: package.json and CHANGELOG.md\n`);
80
+ }
81
+ }
71
82
  }
72
83
  let build;
73
84
  if (values.write) {
@@ -84,6 +95,7 @@ async function run(args, io) {
84
95
  ...(values.sync ? { synced } : {}),
85
96
  warnings,
86
97
  ...(build ? { build } : {}),
98
+ ...(version ? { version } : {}),
87
99
  };
88
100
  io.stdout(`${JSON.stringify(out, null, 2)}\n`);
89
101
  return 0;
@@ -0,0 +1,52 @@
1
+ // `slicekit sync open` (03 REQ-3.11, D-78, D-80): the CI sync job's second step, after `status --sync
2
+ // --write` on the default branch. It puts the state change on a `sync/<short sha>` branch, opens a
3
+ // `[sync]` pull request for it through the git host (C-1) and starts the workflow there; see
4
+ // openSyncPullRequest. With that pull request already open it opens no second one and starts the
5
+ // workflow on the branch again. Exit 0 when it opened one, found one open, or had nothing to open; 1 when git,
6
+ // the host or the body refuses; 2 on bad usage or a bad config.
7
+ import { parseArgs } from 'node:util';
8
+ import { ConfigError, loadConfig } from '../config.js';
9
+ import { GitError } from '../git.js';
10
+ import { getHost } from '../adapters/githost/index.js';
11
+ import { GitHostError } from '../adapters/githost/errors.js';
12
+ import { SLICEKIT_WORKFLOW } from '../adapters/githost/gh-json.js';
13
+ import { SyncOpenError, openSyncPullRequest } from '../state/sync.js';
14
+
15
+ const USAGE = 'sync open';
16
+
17
+ const fail = (io, message, code) => {
18
+ for (const line of message.split('\n')) io.stderr(`slicekit: ${line}\n`);
19
+ return code;
20
+ };
21
+
22
+ async function run(args, io) {
23
+ let positionals;
24
+ try {
25
+ ({ positionals } = parseArgs({ args, options: {}, allowPositionals: true }));
26
+ } catch (e) {
27
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
28
+ return 2;
29
+ }
30
+ if (positionals.length !== 1 || positionals[0] !== 'open') {
31
+ io.stderr(`usage: slicekit ${USAGE}\n`);
32
+ return 2;
33
+ }
34
+ const root = io.cwd;
35
+ try {
36
+ const cfg = loadConfig(root);
37
+ const host = getHost(cfg, io.env ?? process.env, root);
38
+ const r = openSyncPullRequest(root, cfg, host);
39
+ if (r.outcome === 'unchanged') io.stdout('sync: no state change; nothing to open\n');
40
+ else if (r.outcome === 'newer') io.stdout(`sync: #${r.number} ${r.url} on ${r.head}, cut from a later merge, already carries this state; nothing to open\n`);
41
+ else if (r.outcome === 'open') io.stdout(`sync: #${r.number} ${r.url} is already open for ${r.branch}\ndispatched ${SLICEKIT_WORKFLOW.file} on ${r.branch}\n`);
42
+ else io.stdout(`#${r.number} ${r.url}\ndispatched ${SLICEKIT_WORKFLOW.file} on ${r.branch}\n`);
43
+ for (const n of r.closed ?? []) io.stdout(`closed #${n}: superseded by #${r.number}\n`);
44
+ return 0;
45
+ } catch (e) {
46
+ if (e instanceof ConfigError) return fail(io, e.message, 2);
47
+ if (e instanceof SyncOpenError || e instanceof GitError || e instanceof GitHostError) return fail(io, e.message, 1);
48
+ throw e;
49
+ }
50
+ }
51
+
52
+ export const syncCommand = { run, usage: USAGE, subcommands: ['open'] };
package/src/config.js CHANGED
@@ -104,6 +104,30 @@ export function shardErrors(shards) {
104
104
  .map(([os]) => `ci.shards.${os}: must be a positive integer`);
105
105
  }
106
106
 
107
+ // The systems the test job runs on with ci.matrix, and the runner of every job without ci.runsOn (D-67).
108
+ export const MATRIX_OS = ['ubuntu-latest', 'windows-latest', 'macos-latest'];
109
+ export const DEFAULT_RUNS_ON = 'ubuntu-latest';
110
+
111
+ // D-49, D-67: a ci.shards key names a system the test job runs on. With ci.matrix that is one of
112
+ // MATRIX_OS; without it the test job runs on the one runner ci.runsOn names, keyed by one of its
113
+ // labels. Exported so the workflow generator refuses the same keys validateConfig refuses.
114
+ export function shardRunnerErrors(ci) {
115
+ const keys = isObject(ci?.shards) ? Object.keys(ci.shards) : [];
116
+ if (keys.length === 0) return [];
117
+ if (ci.matrix === true) {
118
+ return keys.filter((k) => !MATRIX_OS.includes(k)).map((k) => `ci.shards.${k}: the test job runs only on ${MATRIX_OS.join(', ')}`);
119
+ }
120
+ const r = ci.runsOn;
121
+ const labels = r === undefined ? [DEFAULT_RUNS_ON] : Array.isArray(r) ? r : [r];
122
+ const errors = keys
123
+ .filter((k) => !labels.includes(k))
124
+ .map((k) => `ci.shards.${k}: the test job runs only on the runner labelled ${labels.join(', ')}`);
125
+ if (errors.length === 0 && keys.length > 1) {
126
+ errors.push(`ci.shards: ${keys.join(', ')} are labels of the one runner the test job runs on; name one of them`);
127
+ }
128
+ return errors;
129
+ }
130
+
107
131
  // ci.matrix is optional (absent reads as false), ci.botActors and ci.timeoutMinutes too (absent
108
132
  // reads as the default); each observability step renders as one CI job (REQ-3.11).
109
133
  function ciErrors(ci) {
@@ -115,7 +139,26 @@ function ciErrors(ci) {
115
139
  }
116
140
  const t = ci.timeoutMinutes;
117
141
  if (t !== undefined && !(Number.isInteger(t) && t >= 1 && t <= 360)) errors.push('ci.timeoutMinutes: must be an integer from 1 to 360');
142
+ const beforeRunners = errors.length;
118
143
  errors.push(...shardErrors(ci.shards));
144
+ // D-67: one runner label or the list of labels a self-hosted runner carries; absent is ubuntu-latest.
145
+ const r = ci.runsOn;
146
+ if (r !== undefined) {
147
+ const labels = Array.isArray(r) ? r : [r];
148
+ if (labels.length === 0 || !labels.every(nonEmpty)) errors.push('ci.runsOn: must be a runner label or a non-empty list of runner labels');
149
+ else {
150
+ labels.forEach((l) => errors.push(...workflowTextErrors('ci.runsOn', l)));
151
+ // A line break inside a label ends the runs-on: value and breaks the workflow's YAML.
152
+ if (labels.some((l) => /[\r\n]/.test(l))) errors.push('ci.runsOn: a runner label cannot contain a line break');
153
+ }
154
+ }
155
+ // Keys are matched to the runner only once the counts and ci.runsOn are well formed.
156
+ if (errors.length === beforeRunners) errors.push(...shardRunnerErrors(ci));
157
+ // D-85: the JDK a Java repository's command jobs set up; absent is 25.
158
+ const j = ci.java;
159
+ if (j !== undefined && !((Number.isInteger(j) && j >= 1) || (typeof j === 'string' && /^\d+(?:\.\d+)*$/.test(j)))) {
160
+ errors.push('ci.java: must be a JDK version, such as 25 or "21"');
161
+ }
119
162
  if (!Array.isArray(ci.observabilitySteps)) return [...errors, 'ci.observabilitySteps: must be an array'];
120
163
  ci.observabilitySteps.forEach((step, i) => {
121
164
  const at = `ci.observabilitySteps[${i}]`;
@@ -191,9 +234,38 @@ export function validateConfig(cfg) {
191
234
  }
192
235
  errors.push(...ciErrors(cfg.ci));
193
236
  errors.push(...testFilesErrors(cfg.testFiles));
237
+ errors.push(...agentsErrors(cfg.agents));
238
+ errors.push(...releaseErrors(cfg.release));
194
239
  return errors;
195
240
  }
196
241
 
242
+ // REQ-5.5, D-90: release is optional, an object whose one key is auto. release.auto (absent reads as
243
+ // false) turns on the version the sync pull request sets after a slice merge; the release step
244
+ // itself refuses one that is not a boolean (releaseAutoError), so every other command still loads
245
+ // the config.
246
+ function releaseErrors(release) {
247
+ if (release === undefined) return [];
248
+ if (!isObject(release)) return ['release: must be an object'];
249
+ return Object.keys(release).filter((key) => key !== 'auto').map((key) => `release.${key}: unknown key; use auto`);
250
+ }
251
+
252
+ // The release step's check of release.auto: null when it is absent or a boolean.
253
+ export function releaseAutoError(cfg) {
254
+ const auto = cfg?.release?.auto;
255
+ return auto === undefined || typeof auto === 'boolean' ? null : 'release.auto: must be a boolean';
256
+ }
257
+
258
+ // REQ-3.13, D-72: agents is optional; agents.denyPaths holds glob patterns over repository-relative
259
+ // POSIX paths that agents may not read or change, and reads as the empty list when absent.
260
+ function agentsErrors(agents) {
261
+ if (agents === undefined) return [];
262
+ if (!isObject(agents)) return ['agents: must be an object'];
263
+ const list = agents.denyPaths;
264
+ if (list === undefined) return [];
265
+ if (!(isStringArray(list) && list.every((s) => s !== ''))) return ['agents.denyPaths: must be an array of non-empty strings'];
266
+ return [];
267
+ }
268
+
197
269
  // D-46: testFiles is optional; when present, regular expressions over the repository-relative POSIX
198
270
  // path that name the test files (absent reads as the graph's DEFAULT_TEST_FILES).
199
271
  function testFilesErrors(list) {
package/src/git.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import path from 'node:path';
2
3
 
3
4
  export class GitError extends Error {
4
5
  constructor(args, stderr) {
@@ -167,12 +168,40 @@ export function switchBranch(root, name, { create = false, from, track = false }
167
168
  else git(root, ['switch', '-q', '--no-guess', name]);
168
169
  }
169
170
 
171
+ // The paths staged in the index against HEAD, as [{ status, file }] (POSIX paths; a rename is its
172
+ // deletion and its addition). Empty when nothing is staged.
173
+ export function stagedChanges(root) {
174
+ if (!hasCommits(root)) return [];
175
+ const fields = git(root, ['diff', '--cached', '--name-status', '--no-renames', '-z', 'HEAD']).split('\0').filter((f) => f !== '');
176
+ const out = [];
177
+ for (let i = 0; i + 1 < fields.length; i += 2) out.push({ status: fields[i], file: fields[i + 1] });
178
+ return out;
179
+ }
180
+
181
+ // Writes every path of the index, as staged, under the directory `dir` (which must exist); the
182
+ // worktree and the index are not changed.
183
+ export function checkoutIndexTo(root, dir) {
184
+ const prefix = `${path.resolve(dir).split(path.sep).join('/')}/`;
185
+ git(root, ['checkout-index', '-a', '-f', `--prefix=${prefix}`]);
186
+ }
187
+
188
+ // Commits the index as it stands: the staged paths alone, the rest of the worktree untouched.
189
+ export function commitStaged(root, message) {
190
+ if (succeeds(root, ['diff', '--cached', '--quiet'])) return null;
191
+ git(root, ['commit', '-q', '-m', message]);
192
+ return headSha(root);
193
+ }
194
+
170
195
  // Stages `paths` (additions, changes and deletions) and commits only them. Null when none of them
171
196
  // has a change to commit; otherwise the new commit's SHA.
172
197
  export function commitPaths(root, paths, message) {
173
198
  if (!Array.isArray(paths) || paths.length === 0) throw new GitError(['commit'], 'no paths to commit');
199
+ // A path already staged as deleted is in neither the index nor the worktree, so `git add` of it
200
+ // fails with "pathspec did not match"; it is committed as staged.
201
+ const deleted = new Set(stagedChanges(root).filter((c) => c.status === 'D').map((c) => c.file));
202
+ const toAdd = paths.filter((p) => !deleted.has(p));
174
203
  // --literal-pathspecs: a path is a path, never a glob or a magic pathspec such as `:/`.
175
- git(root, ['--literal-pathspecs', 'add', '-A', '--', ...paths]);
204
+ if (toAdd.length > 0) git(root, ['--literal-pathspecs', 'add', '-A', '--', ...toAdd]);
176
205
  if (succeeds(root, ['--literal-pathspecs', 'diff', '--cached', '--quiet', '--', ...paths])) return null;
177
206
  git(root, ['--literal-pathspecs', 'commit', '-q', '-m', message, '--', ...paths]);
178
207
  return headSha(root);
@@ -80,3 +80,106 @@ export function activeSlice(root, cfg) {
80
80
  return { id, error: e?.message ?? String(e) };
81
81
  }
82
82
  }
83
+
84
+ // The slice states in which its frozen tests are guarded (REQ-3.3).
85
+ export const GUARDED_STATES = new Set(['tests-red', 'building']);
86
+
87
+ const stringList = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
88
+
89
+ // The tests frozen for root's active slice: {id, files: [POSIX path relative to root's real path]},
90
+ // with `unfrozen` ones left out; null when tests are not frozen, no slice is active, or the slice is
91
+ // not in a guarded state. Throws when the state file cannot be read or its lists are malformed, so a
92
+ // guard calling it fails closed.
93
+ export function frozenTests(root, cfg) {
94
+ if (!cfg.freezeTests) return null;
95
+ const active = activeSlice(root, cfg);
96
+ if (!active) return null;
97
+ if (active.error) throw new Error(active.error);
98
+ for (const field of ['frozenTests', 'unfrozen']) {
99
+ if (!stringList(active.state[field])) throw new Error(`${active.id} state: ${field} must be an array of strings`);
100
+ }
101
+ if (!GUARDED_STATES.has(active.state.state)) return null;
102
+ const canon = real(path.resolve(root));
103
+ const rel = (f) => toPosix(path.relative(canon, real(path.resolve(canon, fromGitBash(f.replace(/\\/g, '/'))))));
104
+ const key = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
105
+ const unfrozen = new Set(active.state.unfrozen.map((f) => key(rel(f))));
106
+ const files = active.state.frozenTests.map(rel).filter((f) => !unfrozen.has(key(f)));
107
+ return { id: active.id, files };
108
+ }
109
+
110
+ // ---- agents.denyPaths (REQ-3.13, D-72) ----
111
+
112
+ // One gitignore-style pattern over repository-relative POSIX paths as an anchored regular expression:
113
+ // `**` crosses segments, `*` and `?` stay in one, `[...]` is a class; a leading `/` or `./` anchors at
114
+ // the root, which a pattern with no inner `/` is not (it matches at any depth); a trailing `/` names a
115
+ // directory. Case-insensitive on win32.
116
+ function denyRe(pattern) {
117
+ let p = pattern.replace(/\\/g, '/');
118
+ p = p.replace(/^\.\//, '');
119
+ let anchored = p.startsWith('/');
120
+ p = p.replace(/^\/+/, '').replace(/\/+$/, '');
121
+ if (p.includes('/')) anchored = true;
122
+ let src = '';
123
+ for (let i = 0; i < p.length; i++) {
124
+ const c = p[i];
125
+ if (c === '*' && p[i + 1] === '*') {
126
+ const atStart = i === 0 || p[i - 1] === '/';
127
+ const atEnd = i + 2 === p.length || p[i + 2] === '/';
128
+ if (atStart && p[i + 2] === '/') {
129
+ src += '(?:.*/)?';
130
+ i += 2;
131
+ } else if (atStart && atEnd) {
132
+ src += '.*';
133
+ i += 1;
134
+ } else {
135
+ src += '[^/]*';
136
+ i += 1;
137
+ }
138
+ } else if (c === '*') src += '[^/]*';
139
+ else if (c === '?') src += '[^/]';
140
+ else if (c === '[' && p.indexOf(']', i + 2) !== -1) {
141
+ const end = p.indexOf(']', i + 2);
142
+ const body = p.slice(i + 1, end).replace(/^!/, '^').replace(/\\/g, '\\\\');
143
+ src += `[${body}]`;
144
+ i = end;
145
+ } else src += c.replace(/[.+^${}()|\\[\]]/g, '\\$&');
146
+ }
147
+ return new RegExp(`^${anchored ? '' : '(?:.*/)?'}${src}$`, process.platform === 'win32' ? 'i' : '');
148
+ }
149
+
150
+ // -> the first pattern of `patterns` that matches the repository-relative POSIX path `rel` or one of
151
+ // its parent directories, or null. Shared by pre-edit and pre-bash.
152
+ export function matchesDeny(rel, patterns) {
153
+ if (!Array.isArray(patterns) || patterns.length === 0 || typeof rel !== 'string' || rel === '') return null;
154
+ const segs = rel.replace(/\\/g, '/').replace(/^\.\//, '').split('/').filter((s) => s !== '' && s !== '.');
155
+ if (segs.length === 0) return null;
156
+ const prefixes = segs.map((_, k) => segs.slice(0, k + 1).join('/'));
157
+ for (const pattern of patterns) {
158
+ if (typeof pattern !== 'string' || pattern === '') continue;
159
+ const re = denyRe(pattern);
160
+ if (prefixes.some((pre) => re.test(pre))) return pattern;
161
+ }
162
+ return null;
163
+ }
164
+
165
+ // -> the first pattern anchored at the root whose literal leading directories, up to its first glob
166
+ // segment, are exactly the repository-relative directory `rel` (`data` for `data/**` or
167
+ // `data/*.xml`), or null. A command naming that directory reads what the pattern covers.
168
+ export function denyDir(rel, patterns) {
169
+ if (!Array.isArray(patterns) || typeof rel !== 'string' || rel === '') return null;
170
+ const key = (s) => (process.platform === 'win32' ? s.toLowerCase() : s);
171
+ const want = key(rel.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, ''));
172
+ for (const pattern of patterns) {
173
+ if (typeof pattern !== 'string' || pattern === '') continue;
174
+ const p = pattern.replace(/\\/g, '/').replace(/^\.\//, '').replace(/^\/+/, '').replace(/\/+$/, '');
175
+ if (!p.includes('/')) continue;
176
+ const segs = p.split('/');
177
+ const first = segs.findIndex((s) => /[*?[]/.test(s));
178
+ if (first <= 0) continue;
179
+ if (key(segs.slice(0, first).join('/')) === want) return pattern;
180
+ }
181
+ return null;
182
+ }
183
+
184
+ // The config's deny list, the empty list when absent.
185
+ export const denyPaths = (cfg) => (Array.isArray(cfg?.agents?.denyPaths) ? cfg.agents.denyPaths : []);