slicekit 0.5.0 → 0.6.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slicekit",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Spec-driven agentic workflow kit",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -4,9 +4,14 @@ import { TrackerError, assertFinding, assertIssueId, assertIssueTitle, assertLab
4
4
  // C-2 for Jira Cloud through its REST API v3 (D-74). The base URL, project key and issue type come from
5
5
  // config (`tracker.baseUrl`, `tracker.project`, `tracker.issueType`); the email and API token come from
6
6
  // JIRA_EMAIL and JIRA_API_TOKEN at each call and are never stored. `fetchImpl` is the test seam. Every
7
- // error is scrubbed of the token and the Authorization value before it leaves this file. Nothing here
8
- // closes an issue. The three operations return promises.
7
+ // TrackerError is scrubbed of the token and the Authorization value before it leaves this file: the
8
+ // adapter's config check and its three operations each run inside `scrubbed`. Nothing here closes an
9
+ // issue. The three operations return promises.
9
10
  const SEARCH_LIMIT = 50;
11
+ // The most pages one find reads. A search that still hands out a token after this many ends in an error.
12
+ const PAGE_LIMIT = 200;
13
+ // The most characters of a page token an error prints.
14
+ const TOKEN_SHOWN = 40;
10
15
 
11
16
  // Throws a TrackerError naming the first config key that is missing or wrong.
12
17
  export function validate(cfg) {
@@ -39,21 +44,63 @@ function adf(text) {
39
44
  // A JQL string literal: backslash and double quote escaped.
40
45
  const jqlString = (s) => `"${String(s).replace(/[\\"]/g, (c) => `\\${c}`)}"`;
41
46
 
47
+ // The words of a title prefix as a value Jira's text search can parse. Jira refuses a `~` value with
48
+ // HTTP 400 when a reserved character of the text search stands in it unescaped, so none is sent:
49
+ // brackets, braces, parentheses, `^`, `:`, `/`, `&`, `|`, backslash and both quotes become a space,
50
+ // and `+`, `-`, `!`, `*`, `?` and `~` are cut from the start of each word. The value is looser than
51
+ // the prefix; pickFinding narrows the hits.
52
+ export function searchValue(prefix) {
53
+ const words = String(prefix ?? '')
54
+ .replace(/[()[\]{}^:/&|\\"']/g, ' ')
55
+ .split(/\s+/)
56
+ .map((w) => w.replace(/^[+\-!*?~]+/, ''))
57
+ .filter((w) => /[\p{L}\p{N}]/u.test(w));
58
+ if (words.length === 0) throw new TrackerError(`jira find: no word to search for in ${JSON.stringify(String(prefix ?? ''))}`);
59
+ return words.join(' ');
60
+ }
61
+
42
62
  export function jiraTracker(cfg, env = process.env, fetchImpl = (...a) => fetch(...a)) {
43
- const { base, project, issueType } = validate(cfg);
63
+ // The token and the two forms of the Authorization value, as far as the environment holds them.
64
+ function secrets() {
65
+ const token = typeof env?.JIRA_API_TOKEN === 'string' ? env.JIRA_API_TOKEN : '';
66
+ const email = typeof env?.JIRA_EMAIL === 'string' ? env.JIRA_EMAIL : '';
67
+ if (token === '') return [];
68
+ if (email === '') return [token];
69
+ const encoded = Buffer.from(`${email}:${token}`).toString('base64');
70
+ return [`Basic ${encoded}`, encoded, token];
71
+ }
72
+
73
+ function scrub(text) {
74
+ let out = String(text ?? '');
75
+ for (const s of secrets()) out = out.split(s).join('***');
76
+ return redact(out);
77
+ }
78
+
79
+ // The one way a TrackerError leaves this adapter: its message goes through scrub. Any other error
80
+ // passes as it is.
81
+ const clean = (e) => (e instanceof TrackerError ? new TrackerError(scrub(e.message)) : e);
82
+ const scrubbed = (fn) => async (...args) => {
83
+ try {
84
+ return await fn(...args);
85
+ } catch (e) {
86
+ throw clean(e);
87
+ }
88
+ };
89
+
90
+ let checked;
91
+ try {
92
+ checked = validate(cfg);
93
+ } catch (e) {
94
+ throw clean(e);
95
+ }
96
+ const { base, project, issueType } = checked;
44
97
 
45
98
  function credentials() {
46
99
  for (const name of ['JIRA_EMAIL', 'JIRA_API_TOKEN']) {
47
100
  if (typeof env[name] !== 'string' || env[name] === '') throw new TrackerError(`${name} is not set; the jira tracker needs JIRA_EMAIL and JIRA_API_TOKEN`);
48
101
  }
49
102
  const encoded = Buffer.from(`${env.JIRA_EMAIL}:${env.JIRA_API_TOKEN}`).toString('base64');
50
- return { token: env.JIRA_API_TOKEN, encoded, header: `Basic ${encoded}` };
51
- }
52
-
53
- function scrub(text, secret) {
54
- let out = String(text ?? '');
55
- for (const s of [secret.header, secret.encoded, secret.token]) out = out.split(s).join('***');
56
- return redact(out);
103
+ return { header: `Basic ${encoded}` };
57
104
  }
58
105
 
59
106
  async function call(op, method, path, body) {
@@ -67,7 +114,7 @@ export function jiraTracker(cfg, env = process.env, fetchImpl = (...a) => fetch(
67
114
  try {
68
115
  res = await fetchImpl(`${base}${path}`, init);
69
116
  } catch (e) {
70
- throw new TrackerError(`jira ${op} failed: ${scrub(e?.message ?? e, secret)}`);
117
+ throw new TrackerError(`jira ${op} failed: ${scrub(e?.message ?? e)}`);
71
118
  }
72
119
  let text = '';
73
120
  try {
@@ -84,13 +131,13 @@ export function jiraTracker(cfg, env = process.env, fetchImpl = (...a) => fetch(
84
131
  } catch {
85
132
  // not JSON: keep the text
86
133
  }
87
- throw new TrackerError(`jira ${op} failed: HTTP ${res.status}${detail ? `: ${scrub(detail, secret).slice(0, 500)}` : ''}`);
134
+ throw new TrackerError(`jira ${op} failed: HTTP ${res.status}${detail ? `: ${scrub(detail).slice(0, 500)}` : ''}`);
88
135
  }
89
136
  if (text === '') return {};
90
137
  try {
91
138
  return JSON.parse(text);
92
139
  } catch (e) {
93
- throw new TrackerError(`jira ${op} answered with something that is not JSON: ${scrub(e.message, secret)}`);
140
+ throw new TrackerError(`jira ${op} answered with something that is not JSON: ${scrub(e.message)}`);
94
141
  }
95
142
  }
96
143
 
@@ -98,7 +145,7 @@ export function jiraTracker(cfg, env = process.env, fetchImpl = (...a) => fetch(
98
145
 
99
146
  return {
100
147
  kind: 'jira',
101
- async open({ title, body, labels = [], slice }) {
148
+ open: scrubbed(async ({ title, body, labels = [], slice }) => {
102
149
  assertIssueTitle(title);
103
150
  assertLabels(labels);
104
151
  assertSlice(slice);
@@ -107,27 +154,42 @@ export function jiraTracker(cfg, env = process.env, fetchImpl = (...a) => fetch(
107
154
  const id = Number(made.id);
108
155
  if (!Number.isInteger(id) || id < 1 || typeof made.key !== 'string') throw new TrackerError('jira open answered with no issue id and key');
109
156
  return { id, url: browse(made.key) };
110
- },
111
- async comment(id, body) {
157
+ }),
158
+ comment: scrubbed(async (id, body) => {
112
159
  assertIssueId(id);
113
160
  await call('comment', 'POST', `/rest/api/3/issue/${id}/comment`, { body: adf(body) });
114
- },
161
+ }),
115
162
  // Jira's text search is loose, so its hits, oldest first, are narrowed to a summary that begins
116
- // `[<slice>] <finding>:`. A status in the done category reads as closed.
117
- async find(slice, finding) {
163
+ // `[<slice>] <finding>:`. A status in the done category reads as closed. The pages are read in
164
+ // order, following `nextPageToken`, until one holds such a summary or no token is left. A token
165
+ // given twice ends the search with an error, so a faulty server cannot hold the command in a loop.
166
+ // That error prints the token scrubbed and cut to TOKEN_SHOWN characters, the scrub before the cut.
167
+ find: scrubbed(async (slice, finding) => {
118
168
  assertSlice(slice);
119
169
  assertFinding(finding);
120
170
  const prefix = findingTitlePrefix(slice, finding);
121
- const jql = `project = ${jqlString(project)} AND summary ~ ${jqlString(prefix)} ORDER BY created ASC`;
122
- const q = new URLSearchParams({ jql, fields: 'summary,status,created', maxResults: String(SEARCH_LIMIT) });
123
- const out = await call('find', 'GET', `/rest/api/3/search/jql?${q}`);
124
- const list = (Array.isArray(out.issues) ? out.issues : []).map((i) => ({
125
- number: Number(i?.id),
126
- url: browse(i?.key),
127
- title: i?.fields?.summary,
128
- state: i?.fields?.status?.statusCategory?.key === 'done' ? 'closed' : 'open',
129
- }));
130
- return pickFinding(list, slice, finding);
131
- },
171
+ const jql = `project = ${jqlString(project)} AND summary ~ ${jqlString(searchValue(prefix))} ORDER BY created ASC`;
172
+ const given = new Set();
173
+ let token = null;
174
+ for (let page = 1; ; page += 1) {
175
+ const q = new URLSearchParams({ jql, fields: 'summary,status,created', maxResults: String(SEARCH_LIMIT) });
176
+ if (token !== null) q.set('nextPageToken', token);
177
+ const out = await call('find', 'GET', `/rest/api/3/search/jql?${q}`);
178
+ const list = (Array.isArray(out.issues) ? out.issues : []).map((i) => ({
179
+ number: Number(i?.id),
180
+ url: browse(i?.key),
181
+ title: i?.fields?.summary,
182
+ state: i?.fields?.status?.statusCategory?.key === 'done' ? 'closed' : 'open',
183
+ }));
184
+ const hit = pickFinding(list, slice, finding);
185
+ if (hit) return hit;
186
+ const next = out.nextPageToken;
187
+ if (typeof next !== 'string' || next === '') return null;
188
+ if (given.has(next)) throw new TrackerError(`jira find failed: the search gave the page token ${JSON.stringify(scrub(next).slice(0, TOKEN_SHOWN))} twice; stopped after ${page} pages`);
189
+ if (page >= PAGE_LIMIT) throw new TrackerError(`jira find failed: the search still gave a page token after ${PAGE_LIMIT} pages; stopped`);
190
+ given.add(next);
191
+ token = next;
192
+ }
193
+ }),
132
194
  };
133
195
  }
@@ -5,7 +5,7 @@ import fs from 'node:fs';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
7
  import { buildTestCommand } from '../config.js';
8
- import { GitError, assertRef, checkoutIndexTo, commitPaths, commitStaged, git, hasRemote, parseTrailers, stagedChanges } from '../git.js';
8
+ import { GitError, assertRef, commitPaths, commitStaged, git, hasRemote, parseTrailers, stagedChanges } from '../git.js';
9
9
  import { configSubject, namesConfigAt } from './config.js';
10
10
  import { freshAt, renderPathsOnly, renderSubject } from './render.js';
11
11
  import { stateFileName, verdictFilePattern } from '../ids.js';
@@ -46,6 +46,25 @@ const blobAt = (wt, rev, file) => {
46
46
  }
47
47
  };
48
48
 
49
+ // The slice's own state file, judged before any test runs (issue #71): what is frozen and what is
50
+ // unfrozen is read from it, so a copy git cannot see, or one that is not the committed one, decides
51
+ // nothing. -> the refusal, saying which of the three it found, or null.
52
+ // `held`: the state file is among the paths the commit would hold, so the line is the kit file refusal too.
53
+ function stateFileProblem(wt, stateRel, held) {
54
+ const flag = git(wt, ['--literal-pathspecs', 'ls-files', '-v', '--', stateRel]).slice(0, 1);
55
+ const hidden = 'so git cannot see its changes; clear the mark and restore the file from the last commit';
56
+ // `ls-files -v`: S is skip-worktree, a lower-case letter is assume-unchanged (s is both).
57
+ if (flag === 'S' || flag === 's') return `state file ${stateRel} is marked skip-worktree, ${hidden}`;
58
+ if (flag !== '' && flag !== flag.toUpperCase()) return `state file ${stateRel} is marked assume-unchanged, ${hidden}`;
59
+ const atHead = blobAt(wt, 'HEAD', stateRel);
60
+ const onDisk = fs.existsSync(path.join(wt, ...stateRel.split('/'))) ? git(wt, ['--literal-pathspecs', 'hash-object', '--', stateRel]) : null;
61
+ if (onDisk !== atHead) {
62
+ const why = 'differs on disk from the file at HEAD; only build commands write it, and each commits what it wrote';
63
+ return held ? `${stateRel} is a kit file; build commit does not commit it: the state file ${why}` : `state file ${stateRel} ${why}`;
64
+ }
65
+ return null;
66
+ }
67
+
49
68
  // The first frozen test (not unfrozen) that differs from the red commit, and how: hidden from git by
50
69
  // skip-worktree or assume-unchanged, different bytes or missing on disk (an edit through Bash never
51
70
  // meets the pre-edit hook), or different in the index or a commit since (a mode change, a removal).
@@ -203,23 +222,93 @@ function forgedKitChange(wt, cfg, id, current, slice) {
203
222
  return null;
204
223
  }
205
224
 
225
+ // Makes the worktree's files the index does not hold readable in the run directory at the same
226
+ // relative path (issue #107): the files git ignores or does not track, such as `.slice-tests` or
227
+ // `node_modules`. A directory git holds nothing of is linked whole; a file is hard-linked, or copied
228
+ // when a hard link cannot be made (another volume). -> the directory links made.
229
+ function bringUntracked(wt, dir) {
230
+ const links = [];
231
+ // --directory: a directory with no tracked file is one entry, `name/`, and is not walked.
232
+ const others = git(wt, ['ls-files', '--others', '--directory', '-z']).split('\0').filter((e) => e !== '');
233
+ for (const entry of others) {
234
+ const rel = entry.replace(/\/$/, '');
235
+ if (rel === '' || rel.split('/').includes('.git')) continue;
236
+ const from = path.join(wt, ...rel.split('/'));
237
+ const to = path.join(dir, ...rel.split('/'));
238
+ if (fs.existsSync(to)) continue;
239
+ try {
240
+ const stat = fs.lstatSync(from);
241
+ fs.mkdirSync(path.dirname(to), { recursive: true });
242
+ if (stat.isDirectory()) {
243
+ fs.symlinkSync(from, to, 'junction');
244
+ links.push(to);
245
+ } else if (stat.isFile()) {
246
+ try {
247
+ fs.linkSync(from, to);
248
+ } catch {
249
+ fs.copyFileSync(from, to);
250
+ }
251
+ }
252
+ } catch {
253
+ // A file that went away or cannot be read is left out of the run.
254
+ }
255
+ }
256
+ return links;
257
+ }
258
+
259
+ // Makes git usable in the run directory (issue #107): a `.git` directory of its own that holds a
260
+ // copy of the worktree's index and HEAD and names the repository's common directory for everything
261
+ // else. A git command there sees every tracked file as staged and no unstaged change, and writes at
262
+ // most that copy of the index. Nothing is registered in the repository, so removing the directory
263
+ // leaves no trace of it.
264
+ function gitIn(wt, dir) {
265
+ const own = path.join(dir, '.git');
266
+ if (fs.existsSync(own)) return;
267
+ const abs = (p) => path.resolve(wt, p);
268
+ const common = abs(git(wt, ['rev-parse', '--git-common-dir']));
269
+ const index = abs(git(wt, ['rev-parse', '--git-path', 'index']));
270
+ let head;
271
+ try {
272
+ head = `ref: ${git(wt, ['symbolic-ref', '-q', 'HEAD'])}`;
273
+ } catch (e) {
274
+ if (!(e instanceof GitError)) throw e;
275
+ head = git(wt, ['rev-parse', 'HEAD']);
276
+ }
277
+ fs.mkdirSync(own);
278
+ fs.writeFileSync(path.join(own, 'HEAD'), `${head}\n`);
279
+ fs.writeFileSync(path.join(own, 'commondir'), `${common.split(path.sep).join('/')}\n`);
280
+ if (fs.existsSync(index)) fs.copyFileSync(index, path.join(own, 'index'));
281
+ }
282
+
206
283
  // The test command run in a temporary directory holding the index as staged (git checkout-index),
207
- // never the worktree. The worktree's node_modules, when the index does not hold it, is linked in so
208
- // the run finds the installed packages. The directory is removed whether the run passes or fails.
284
+ // never the worktree. The files of the worktree that git ignores or does not track are linked or
285
+ // copied in, so the run finds the installed packages and a file such as `.slice-tests`, and git
286
+ // answers there (issue #107). The directory is removed whether the run passes or fails.
209
287
  function runOnIndex(wt, command) {
210
288
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'slicekit-index-'));
211
- const modules = path.join(dir, 'node_modules');
289
+ const links = [];
212
290
  try {
213
- checkoutIndexTo(wt, dir);
291
+ // The staged bytes as the index holds them: no line-ending conversion from this machine's git
292
+ // config, so the run reads what the commit will hold.
293
+ const prefix = `${path.resolve(dir).split(path.sep).join('/')}/`;
294
+ git(wt, ['-c', 'core.autocrlf=false', '-c', 'core.eol=lf', 'checkout-index', '-a', '-f', `--prefix=${prefix}`]);
295
+ links.push(...bringUntracked(wt, dir));
296
+ const modules = path.join(dir, 'node_modules');
214
297
  const installed = path.join(wt, 'node_modules');
215
- if (fs.existsSync(installed) && !fs.existsSync(modules)) fs.symlinkSync(installed, modules, 'junction');
298
+ if (fs.existsSync(installed) && !fs.existsSync(modules)) {
299
+ fs.symlinkSync(installed, modules, 'junction');
300
+ links.push(modules);
301
+ }
302
+ gitIn(wt, dir);
216
303
  return runCommand(dir, command);
217
304
  } finally {
218
- // The link first, so removing the directory never walks into the worktree's packages.
219
- try {
220
- if (fs.lstatSync(modules).isSymbolicLink()) fs.unlinkSync(modules);
221
- } catch {
222
- // no link was made
305
+ // The links first, so removing the directory never walks into the worktree.
306
+ for (const link of links) {
307
+ try {
308
+ if (fs.lstatSync(link).isSymbolicLink()) fs.unlinkSync(link);
309
+ } catch {
310
+ // the link is gone
311
+ }
223
312
  }
224
313
  fs.rmSync(dir, { recursive: true, force: true });
225
314
  }
@@ -232,11 +321,14 @@ export function commitWork(root, cfg, id, { message, requireGreen = false, workt
232
321
  const slice = sliceIn(wt, cfg, id);
233
322
  const forged = forgedKitChange(wt, cfg, id, current, slice);
234
323
  if (forged) throw new BuildError(forged);
235
- const frozen = frozenProblem(wt, current);
236
- if (frozen) throw new BuildError(frozen);
324
+ const stateRel = posixRel(wt, path.join(kitPaths(wt, cfg).state, stateFileName(id)));
237
325
  // Paths staged: those alone are committed, as staged. Nothing staged: every changed path.
238
326
  const staged = stagedChanges(wt).map((c) => c.file);
239
327
  const paths = staged.length > 0 ? staged : changedPaths(wt);
328
+ const hidden = stateFileProblem(wt, stateRel, paths.includes(stateRel));
329
+ if (hidden) throw new BuildError(hidden);
330
+ const frozen = frozenProblem(wt, current);
331
+ if (frozen) throw new BuildError(frozen);
240
332
  const kit = paths.find((p) => isKitFile(wt, cfg, slice, p));
241
333
  if (kit) {
242
334
  const config = kit === posixRel(wt, kitPaths(wt, cfg).config) ? `; run slicekit build config ${id}` : '';
@@ -5,8 +5,13 @@
5
5
  // with `assume-unchanged` or `skip-worktree` is judged by its committed content (issue #71).
6
6
  //
7
7
  // The tip is HEAD, or under --ci on a pull request the pull request's head (branchTip). No branch, a
8
- // branch that is not a slice branch, no state file at the tip, no red commit recorded in any version
9
- // of it (a slice before tests-red), or freezeTests set to false in the config (D-10): nothing to judge.
8
+ // branch that is not a slice branch, no red commit recorded in any version of the state file (a slice
9
+ // before tests-red, or one that never had a state file), or freezeTests set to false in the config
10
+ // (D-10): nothing to judge.
11
+ //
12
+ // A tip that has no state file is judged by the versions of the file in its history (issue #100):
13
+ // when one of them recorded a red commit, the removal is one finding naming the state file, and the
14
+ // frozen tests are judged as before. Removing the file does not lift the freeze.
10
15
  //
11
16
  // The red commit and the frozen list are those of the first version of the state file, in the history
12
17
  // of the tip, that records a red commit; frozen paths of later versions are added to that list. A later
@@ -85,8 +90,7 @@ export function run(ctx) {
85
90
  const paths = kitPaths(root, cfg);
86
91
  const stateRel = `${posixRel(root, paths.state)}/${stateFileName(slice)}`;
87
92
  const text = showAt(root, tip, stateRel);
88
- if (text === null) return [];
89
- if (parse(text) === undefined) {
93
+ if (text !== null && parse(text) === undefined) {
90
94
  return [{ file: stateRel, line: 0, message: `state file ${stateRel} is not valid JSON at ${tip}` }];
91
95
  }
92
96
  // The first recorded red commit; every frozen path listed from then on.
@@ -102,14 +106,19 @@ export function run(ctx) {
102
106
  if (Array.isArray(state?.frozenTests)) listed.push(...state.frozenTests);
103
107
  }
104
108
  if (red === null) return [];
109
+ // The tip holds no state file, and an earlier version of it recorded a red commit.
110
+ const removed =
111
+ text === null
112
+ ? [{ file: stateRel, line: 0, message: `state file ${stateRel} was removed after it recorded the red commit ${red.slice(0, 7)}; only the CLI writes it, and removing it does not lift the freeze` }]
113
+ : [];
105
114
  if (!/^[0-9a-f]{7,40}$/.test(red) || !resolveCommit(root, red)) {
106
- return [{ file: stateRel, line: 0, message: `red commit ${red} of ${slice} is not in this repository` }];
115
+ return [...removed, { file: stateRel, line: 0, message: `red commit ${red} of ${slice} is not in this repository` }];
107
116
  }
108
117
 
109
118
  const tests = [...new Set(listed)];
110
119
  const bad = tests.filter((t) => !validTest(t));
111
- if (bad.length > 0) return [{ file: stateRel, line: 0, message: `frozen tests of ${slice} name a path that is not a repository path: ${bad.map(String).join(', ')}` }];
112
- if (tests.length === 0) return [];
120
+ if (bad.length > 0) return [...removed, { file: stateRel, line: 0, message: `frozen tests of ${slice} name a path that is not a repository path: ${bad.map(String).join(', ')}` }];
121
+ if (tests.length === 0) return removed;
113
122
 
114
123
  // An amendment of the slice file after the red commit lifts the freeze (REQ-3.3). Only the slice
115
124
  // branch's own commits count: --first-parent --no-merges leaves out a change to the slice file made on
@@ -117,11 +126,11 @@ export function run(ctx) {
117
126
  const sliceFiles = sliceFilesAt(root, tip, posixRel(root, paths.phases), addr);
118
127
  if (sliceFiles.length > 0) {
119
128
  const amended = git(root, ['--literal-pathspecs', 'log', '--first-parent', '--no-merges', '--format=%H', `${red}..${tip}`, '--', ...sliceFiles]);
120
- if (amended !== '') return [];
129
+ if (amended !== '') return removed;
121
130
  }
122
131
 
123
132
  const changed = new Set(lines(git(root, ['--literal-pathspecs', 'diff', '--name-only', '--no-renames', red, tip, '--', ...tests])));
124
- return tests.filter((t) => changed.has(t)).map((t) => ({ file: t, line: 0, message: `frozen test changed after red: ${t}` }));
133
+ return [...removed, ...tests.filter((t) => changed.has(t)).map((t) => ({ file: t, line: 0, message: `frozen test changed after red: ${t}` }))];
125
134
  }
126
135
 
127
136
  export default { id, blocking, ratchet, run };
@@ -6,7 +6,10 @@
6
6
  // section, and a rendered file only to its fresh render at that version. The rendered files of each
7
7
  // folder under examples/ that holds them are judged the same way (D-95): the sync step renders each
8
8
  // example at that version, so an example file is accepted only where it equals that render. One
9
- // finding per file that differs, naming it. A sync branch whose merge the checkout cannot resolve is the journal rule's
9
+ // finding per file that differs, naming it. The version is computed by the function the sync step
10
+ // runs, so the rule of D-96 holds here too: a phase whose line a CHANGELOG.md section at the merge
11
+ // holds has had its minor version, and a sync pull request that carries a second one for it is one
12
+ // finding on package.json and one on CHANGELOG.md (issue #174). A sync branch whose merge the checkout cannot resolve is the journal rule's
10
13
  // finding. Silent outside CI and on any other branch, and when the config has no release.auto and the
11
14
  // branch changes none of those files.
12
15
  import { execFileSync } from 'node:child_process';
package/src/cli/branch.js CHANGED
@@ -14,9 +14,12 @@
14
14
  // may be on one of them, taken after `release/<slug>` was closed unmerged (issue #152). A slug
15
15
  // given numbered, `<base>-<n>` with <n> 2 or more (the numbers the command itself names), belongs
16
16
  // to the family of `release/<base>`: the host is asked about that branch and each
17
- // `release/<base>-<n>` too, so an open release pull request on any of them refuses.
17
+ // `release/<base>-<n>` too, so an open release pull request on any of them refuses. The next free
18
+ // slug is the family's too: `<base>-<n+1>` or the first number after it that no branch here or on
19
+ // origin has, never `<base>-<n>-2` (issue #170).
18
20
  import { getHost } from '../adapters/githost/index.js';
19
21
  import { GitHostError } from '../adapters/githost/errors.js';
22
+ import { execFileSync } from 'node:child_process';
20
23
  import fs from 'node:fs';
21
24
  import path from 'node:path';
22
25
  import { CONFIG_PATH, ConfigError, loadConfig, migrateConfig } from '../config.js';
@@ -69,6 +72,15 @@ function configAt(root, ref) {
69
72
  }
70
73
  }
71
74
 
75
+ // The bytes of the config the commit `ref` holds, or null when it holds none.
76
+ function configBytesAt(root, ref) {
77
+ try {
78
+ return execFileSync('git', ['cat-file', 'blob', `${ref}:${CONFIG_FILE}`], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
72
84
  const plain = (text) => text.replace(/\r\n/g, '\n').trimEnd();
73
85
  const sameText = (a, b) => a !== null && b !== null && plain(a) === plain(b);
74
86
 
@@ -148,9 +160,11 @@ async function run(args, io) {
148
160
  const dirty = changed && !migrated;
149
161
  // Moves the session to the commit `ref` with `go`. The migrated config is carried, dropped
150
162
  // first where `ref` holds it already, or the move is refused. -> false when refused, with the
151
- // line printed. A dropped copy is put back when the move fails. After the move the file holds
152
- // the bytes the migration wrote: a checkout that converts line endings writes the same config
153
- // with other ones, which git reads as no change.
163
+ // line printed. A dropped copy is put back when the move fails. After the move of a dropped copy
164
+ // the file holds the bytes the branch's commit holds (issue #171): the commit may hold the same
165
+ // config with other line endings or other whitespace at its end than the migration writes, and
166
+ // a checkout that converts line endings writes other bytes again. Writing the migration's bytes
167
+ // back would leave a change behind in the first case.
154
168
  const move = (ref, label, go) => {
155
169
  const file = path.join(root, CONFIG_PATH);
156
170
  let kept = null;
@@ -172,12 +186,16 @@ async function run(args, io) {
172
186
  throw e;
173
187
  }
174
188
  if (kept !== null) {
175
- const now = fs.readFileSync(file);
176
- if (!now.equals(kept) && sameText(now.toString('utf8'), kept.toString('utf8'))) {
177
- fs.writeFileSync(file, kept);
189
+ const committed = configBytesAt(root, 'HEAD');
190
+ if (committed !== null && !fs.readFileSync(file).equals(committed)) {
191
+ fs.writeFileSync(file, committed);
178
192
  // The file's size changed, which git takes for a change until the index entry is read
179
- // again; the add stages nothing, since the content is the commit's.
180
- git(root, ['--literal-pathspecs', 'add', '--', CONFIG_FILE]);
193
+ // again. The refresh stages nothing: it reads the file, which is the commit's.
194
+ try {
195
+ git(root, ['--literal-pathspecs', 'update-index', '-q', '--refresh', '--', CONFIG_FILE]);
196
+ } catch (e) {
197
+ if (!(e instanceof GitError)) throw e;
198
+ }
181
199
  }
182
200
  }
183
201
  return true;
@@ -261,9 +279,13 @@ async function run(args, io) {
261
279
  }
262
280
  }
263
281
  if (own) {
264
- let n = 2;
265
- while (resolves(root, `refs/heads/${target}-${n}`) || resolves(root, `refs/remotes/origin/${target}-${n}`)) n += 1;
266
- io.stderr(`slicekit: ${target} holds commits ${base} lacks, so no release runs on it; run slicekit branch release ${slug}-${n}\n`);
282
+ // The next free number of the family: after the slug's own number when it has one, from 2
283
+ // when it has none; the first that no branch here or on origin has.
284
+ const numbered = family !== target;
285
+ const stem = numbered ? numberedSlug[1] : slug;
286
+ let n = numbered ? Number(numberedSlug[2]) + 1 : 2;
287
+ while (resolves(root, `refs/heads/${kind}/${stem}-${n}`) || resolves(root, `refs/remotes/origin/${kind}/${stem}-${n}`)) n += 1;
288
+ io.stderr(`slicekit: ${target} holds commits ${base} lacks, so no release runs on it; run slicekit branch release ${stem}-${n}\n`);
267
289
  return 1;
268
290
  }
269
291
  if (onTarget && stale.length === 0) {
package/src/config.js CHANGED
@@ -2,6 +2,7 @@ import { execFileSync } from 'node:child_process';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { denyPatternError } from './hooks/paths.js';
5
6
 
6
7
  export const CONFIG_VERSION = 2;
7
8
  export const SHAPES = ['backend', 'fullstack', 'data'];
@@ -307,7 +308,13 @@ function agentsErrors(agents) {
307
308
  const list = agents.denyPaths;
308
309
  if (list === undefined) return [];
309
310
  if (!(isStringArray(list) && list.every((s) => s !== ''))) return ['agents.denyPaths: must be an array of non-empty strings'];
310
- return [];
311
+ // Each pattern is compiled with the code the guards match with (issue #120).
312
+ const errors = [];
313
+ list.forEach((pattern, i) => {
314
+ const why = denyPatternError(pattern);
315
+ if (why !== null) errors.push(`agents.denyPaths[${i}]: ${why}`);
316
+ });
317
+ return errors;
311
318
  }
312
319
 
313
320
  // D-46: testFiles is optional; when present, regular expressions over the repository-relative POSIX