slicekit 0.2.0 → 0.3.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 (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 +13 -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 +77 -3
  28. package/src/git.js +65 -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 +136 -7
  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
@@ -1,9 +1,10 @@
1
1
  import fs from 'node:fs';
2
2
  import { parseArgs } from 'node:util';
3
3
  import { loadConfig } from '../config.js';
4
- import { appendOnlyProblems, journalBranch, journalFile, verifyJournal } from '../journal.js';
4
+ import { GitError } from '../git.js';
5
+ import { appendHeads, appendOnlyProblems, headsLines, journalBranch, journalFile, verifyJournal } from '../journal.js';
5
6
 
6
- const USAGE = 'journal verify [--against <ref>] | journal show [-n 10] [--branch <b>]';
7
+ const USAGE = 'journal verify [--against <ref>] | journal show [-n 10] [--branch <b>] | journal heads <merge sha>';
7
8
  const NO_ENTRIES = 'journal: no entries\n';
8
9
 
9
10
  // The config when there is one; otherwise the defaults the journal needs (docsRoot, defaultBranch).
@@ -71,10 +72,51 @@ function show(root, args, io) {
71
72
  return 0;
72
73
  }
73
74
 
75
+ // `slicekit journal heads <merge sha>` (REQ-3.8, D-71): the sync job's step. Appends to
76
+ // `.slicekit/journal-heads.log` one line per journal file headsFiles owes a line at the merge commit
77
+ // (its last hash differs from what the heads file at the merge records or implies): the file,
78
+ // its last hash, the merge commit, and the run id, workflow and actor from the CI run's environment
79
+ // (GITHUB_RUN_ID, GITHUB_WORKFLOW, GITHUB_ACTOR). The actor is the one who started the run, which a
80
+ // re-run keeps; GITHUB_TRIGGERING_ACTOR names whoever re-ran it and is not read. `check --ci` recomputes
81
+ // each line from git and the host's record of that run, its `actor` field (D-89). Exits 2 outside a CI run.
82
+ function heads(root, args, io) {
83
+ let positionals;
84
+ try {
85
+ ({ positionals } = parseArgs({ args, options: {}, allowPositionals: true }));
86
+ } catch (e) {
87
+ io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
88
+ return 2;
89
+ }
90
+ if (positionals.length !== 1 || !/^[0-9a-f]{7,40}$/.test(positionals[0])) {
91
+ io.stderr(`slicekit: journal heads takes one merge commit sha\nusage: slicekit ${USAGE}\n`);
92
+ return 2;
93
+ }
94
+ const env = io.env ?? process.env;
95
+ const run = env.GITHUB_RUN_ID;
96
+ const workflow = env.GITHUB_WORKFLOW;
97
+ const actor = env.GITHUB_ACTOR;
98
+ if (!run || !workflow || !actor) {
99
+ io.stderr('slicekit: journal heads runs in a CI run: GITHUB_RUN_ID, GITHUB_WORKFLOW and GITHUB_ACTOR must be set\n');
100
+ return 2;
101
+ }
102
+ const cfg = configOf(root);
103
+ let lines;
104
+ try {
105
+ lines = appendHeads(root, cfg, headsLines(root, cfg, positionals[0], { run, workflow, actor }));
106
+ } catch (e) {
107
+ if (!(e instanceof GitError)) throw e;
108
+ io.stderr(`slicekit: ${positionals[0]} is not a commit of this clone: ${e.message}\n`);
109
+ return 1;
110
+ }
111
+ io.stdout(`journal heads: ${lines.length} line${lines.length === 1 ? '' : 's'} for ${positionals[0].slice(0, 7)}\n`);
112
+ return 0;
113
+ }
114
+
74
115
  async function run(args, io) {
75
116
  const [sub, ...rest] = args;
76
117
  if (sub === 'verify') return verify(io.cwd, rest, io);
77
118
  if (sub === 'show') return show(io.cwd, rest, io);
119
+ if (sub === 'heads') return heads(io.cwd, rest, io);
78
120
  io.stderr(`usage: slicekit ${USAGE}\n`);
79
121
  return 2;
80
122
  }
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
@@ -10,6 +10,8 @@ export const CONFIG_PATH = path.join('.slicekit', 'config.json');
10
10
  const COMMAND_KEYS = ['test', 'lint', 'build', 'e2e'];
11
11
  const REVIEW_MODES = ['required', 'optional'];
12
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);
13
15
 
14
16
  // Matched case-insensitively: compileDestructive adds the i flag, so `drop table` is caught too.
15
17
  // No force-push entry: pre-bash's rule 3 refuses force pushes from the parsed command.
@@ -35,15 +37,15 @@ export function seedBanned() {
35
37
  }
36
38
 
37
39
  // init always passes cli (from --cli or the D-30 probe); the default serves callers that do not.
38
- export function defaultConfig({ name, shape, docsRoot = 'docs', commands = {}, cli = 'slicekit' }) {
40
+ export function defaultConfig({ name, shape, docsRoot = 'docs', commands = {}, cli = 'slicekit', defaultBranch = 'main' }) {
39
41
  return {
40
42
  configVersion: CONFIG_VERSION,
41
43
  name,
42
44
  shape,
43
45
  docsRoot,
44
- defaultBranch: 'main',
46
+ defaultBranch,
45
47
  cli,
46
- protectedBranches: ['main'],
48
+ protectedBranches: [defaultBranch],
47
49
  commands: { test: '', lint: '', build: '', e2e: '', ...commands },
48
50
  repos: [],
49
51
  gitHost: { kind: 'github' },
@@ -102,6 +104,30 @@ export function shardErrors(shards) {
102
104
  .map(([os]) => `ci.shards.${os}: must be a positive integer`);
103
105
  }
104
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
+
105
131
  // ci.matrix is optional (absent reads as false), ci.botActors and ci.timeoutMinutes too (absent
106
132
  // reads as the default); each observability step renders as one CI job (REQ-3.11).
107
133
  function ciErrors(ci) {
@@ -113,7 +139,26 @@ function ciErrors(ci) {
113
139
  }
114
140
  const t = ci.timeoutMinutes;
115
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;
116
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
+ }
117
162
  if (!Array.isArray(ci.observabilitySteps)) return [...errors, 'ci.observabilitySteps: must be an array'];
118
163
  ci.observabilitySteps.forEach((step, i) => {
119
164
  const at = `ci.observabilitySteps[${i}]`;
@@ -189,9 +234,38 @@ export function validateConfig(cfg) {
189
234
  }
190
235
  errors.push(...ciErrors(cfg.ci));
191
236
  errors.push(...testFilesErrors(cfg.testFiles));
237
+ errors.push(...agentsErrors(cfg.agents));
238
+ errors.push(...releaseErrors(cfg.release));
192
239
  return errors;
193
240
  }
194
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
+
195
269
  // D-46: testFiles is optional; when present, regular expressions over the repository-relative POSIX
196
270
  // path that name the test files (absent reads as the graph's DEFAULT_TEST_FILES).
197
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) {
@@ -45,6 +46,41 @@ export function currentBranch(root) {
45
46
 
46
47
  export const headSha = (root) => git(root, ['rev-parse', 'HEAD']);
47
48
 
49
+ // The branch a new config names as its default (P3/S-36, issue #78). In order: the one origin's
50
+ // HEAD points at; else main, master or git's init.defaultBranch, the first that is a local branch;
51
+ // else, in an empty repository (a plain `git init` has no branch yet), the branch HEAD is on when it
52
+ // is one of those three names; else main. main comes before init.defaultBranch because that setting
53
+ // may be the machine's, not this project's (Git for Windows sets master system-wide), while an empty
54
+ // repository's HEAD was named by it. Any other branch HEAD is on is not taken: a branch named the
55
+ // default is protected and refuses commits, so a feature branch guessed wrong would block work,
56
+ // where a wrong main only stops `graph` with a message (issue #87). A name `accept` refuses (one
57
+ // the config would reject) is passed over. Outside a repository there is no branch to read: main.
58
+ export function detectDefaultBranch(root, { accept = () => true } = {}) {
59
+ if (!isRepo(root)) return 'main';
60
+ const read = (args) => {
61
+ try {
62
+ return git(root, args);
63
+ } catch (e) {
64
+ if (e instanceof GitError) return '';
65
+ throw e;
66
+ }
67
+ };
68
+ const ok = (b) => b !== '' && accept(b);
69
+ const local = (b) => read(['rev-parse', '--verify', '-q', `refs/heads/${b}`]) !== '';
70
+ const empty = !hasCommits(root);
71
+ // origin's HEAD counts only while its branch exists: after the remote renames its default and a
72
+ // pruning fetch drops the old branch, HEAD still names it, and graph could not find it. An empty
73
+ // repository has no branch at all yet, so there its name is taken as it is.
74
+ const origin = read(['symbolic-ref', '-q', 'refs/remotes/origin/HEAD']);
75
+ const fromOrigin = origin.startsWith('refs/remotes/origin/') ? origin.slice('refs/remotes/origin/'.length) : '';
76
+ if (ok(fromOrigin) && (empty || read(['rev-parse', '--verify', '-q', origin]) !== '')) return fromOrigin;
77
+ const named = ['main', 'master', read(['config', '--get', 'init.defaultBranch'])].filter(ok);
78
+ const found = named.find(local);
79
+ if (found) return found;
80
+ const head = empty ? read(['symbolic-ref', '-q', 'HEAD']).replace(/^refs\/heads\//, '') : '';
81
+ return named.includes(head) ? head : 'main';
82
+ }
83
+
48
84
  // Whether `sha` names a commit object in the repository at root.
49
85
  export function commitExists(root, sha) {
50
86
  assertRef(sha);
@@ -132,12 +168,40 @@ export function switchBranch(root, name, { create = false, from, track = false }
132
168
  else git(root, ['switch', '-q', '--no-guess', name]);
133
169
  }
134
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
+
135
195
  // Stages `paths` (additions, changes and deletions) and commits only them. Null when none of them
136
196
  // has a change to commit; otherwise the new commit's SHA.
137
197
  export function commitPaths(root, paths, message) {
138
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));
139
203
  // --literal-pathspecs: a path is a path, never a glob or a magic pathspec such as `:/`.
140
- git(root, ['--literal-pathspecs', 'add', '-A', '--', ...paths]);
204
+ if (toAdd.length > 0) git(root, ['--literal-pathspecs', 'add', '-A', '--', ...toAdd]);
141
205
  if (succeeds(root, ['--literal-pathspecs', 'diff', '--cached', '--quiet', '--', ...paths])) return null;
142
206
  git(root, ['--literal-pathspecs', 'commit', '-q', '-m', message, '--', ...paths]);
143
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 : []);