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
@@ -0,0 +1,133 @@
1
+ import { redact } from '../../redact.js';
2
+ import { TrackerError, assertFinding, assertIssueId, assertIssueTitle, assertLabels, assertSlice, findingTitlePrefix, pickFinding } from './errors.js';
3
+
4
+ // C-2 for Jira Cloud through its REST API v3 (D-74). The base URL, project key and issue type come from
5
+ // config (`tracker.baseUrl`, `tracker.project`, `tracker.issueType`); the email and API token come from
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.
9
+ const SEARCH_LIMIT = 50;
10
+
11
+ // Throws a TrackerError naming the first config key that is missing or wrong.
12
+ export function validate(cfg) {
13
+ const t = cfg?.tracker ?? {};
14
+ for (const key of ['baseUrl', 'project', 'issueType']) {
15
+ if (typeof t[key] !== 'string' || t[key].trim() === '') {
16
+ throw new TrackerError(`tracker.${key}: required for a jira tracker, as a non-empty string`);
17
+ }
18
+ }
19
+ let url;
20
+ try {
21
+ url = new URL(t.baseUrl);
22
+ } catch {
23
+ throw new TrackerError(`tracker.baseUrl: not a URL: ${JSON.stringify(t.baseUrl)}`);
24
+ }
25
+ if (url.protocol !== 'https:') throw new TrackerError(`tracker.baseUrl: must be an https URL, got ${url.protocol.replace(/:$/, '')}`);
26
+ if (url.username || url.password) throw new TrackerError('tracker.baseUrl: must not carry credentials');
27
+ return { base: url.href.replace(/\/+$/, ''), project: t.project.trim(), issueType: t.issueType.trim() };
28
+ }
29
+
30
+ // Atlassian Document Format: one paragraph per non-empty line.
31
+ function adf(text) {
32
+ const content = String(text ?? '')
33
+ .split(/\r?\n/)
34
+ .filter((l) => l !== '')
35
+ .map((l) => ({ type: 'paragraph', content: [{ type: 'text', text: l }] }));
36
+ return { type: 'doc', version: 1, content };
37
+ }
38
+
39
+ // A JQL string literal: backslash and double quote escaped.
40
+ const jqlString = (s) => `"${String(s).replace(/[\\"]/g, (c) => `\\${c}`)}"`;
41
+
42
+ export function jiraTracker(cfg, env = process.env, fetchImpl = (...a) => fetch(...a)) {
43
+ const { base, project, issueType } = validate(cfg);
44
+
45
+ function credentials() {
46
+ for (const name of ['JIRA_EMAIL', 'JIRA_API_TOKEN']) {
47
+ 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
+ }
49
+ 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);
57
+ }
58
+
59
+ async function call(op, method, path, body) {
60
+ const secret = credentials();
61
+ const init = { method, headers: { Authorization: secret.header, Accept: 'application/json' } };
62
+ if (body !== undefined) {
63
+ init.headers['Content-Type'] = 'application/json';
64
+ init.body = JSON.stringify(body);
65
+ }
66
+ let res;
67
+ try {
68
+ res = await fetchImpl(`${base}${path}`, init);
69
+ } catch (e) {
70
+ throw new TrackerError(`jira ${op} failed: ${scrub(e?.message ?? e, secret)}`);
71
+ }
72
+ let text = '';
73
+ try {
74
+ text = await res.text();
75
+ } catch {
76
+ text = '';
77
+ }
78
+ if (!res.ok) {
79
+ let detail = text;
80
+ try {
81
+ const j = JSON.parse(text);
82
+ const parts = [...(Array.isArray(j.errorMessages) ? j.errorMessages : []), ...Object.entries(j.errors ?? {}).map(([k, v]) => `${k}: ${v}`)];
83
+ if (parts.length > 0) detail = parts.join('; ');
84
+ } catch {
85
+ // not JSON: keep the text
86
+ }
87
+ throw new TrackerError(`jira ${op} failed: HTTP ${res.status}${detail ? `: ${scrub(detail, secret).slice(0, 500)}` : ''}`);
88
+ }
89
+ if (text === '') return {};
90
+ try {
91
+ return JSON.parse(text);
92
+ } catch (e) {
93
+ throw new TrackerError(`jira ${op} answered with something that is not JSON: ${scrub(e.message, secret)}`);
94
+ }
95
+ }
96
+
97
+ const browse = (key) => `${base}/browse/${key}`;
98
+
99
+ return {
100
+ kind: 'jira',
101
+ async open({ title, body, labels = [], slice }) {
102
+ assertIssueTitle(title);
103
+ assertLabels(labels);
104
+ assertSlice(slice);
105
+ const fields = { project: { key: project }, issuetype: { name: issueType }, summary: title, description: adf(body), labels: [...labels] };
106
+ const made = await call('open', 'POST', '/rest/api/3/issue', { fields });
107
+ const id = Number(made.id);
108
+ if (!Number.isInteger(id) || id < 1 || typeof made.key !== 'string') throw new TrackerError('jira open answered with no issue id and key');
109
+ return { id, url: browse(made.key) };
110
+ },
111
+ async comment(id, body) {
112
+ assertIssueId(id);
113
+ await call('comment', 'POST', `/rest/api/3/issue/${id}/comment`, { body: adf(body) });
114
+ },
115
+ // 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) {
118
+ assertSlice(slice);
119
+ assertFinding(finding);
120
+ 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
+ },
132
+ };
133
+ }
@@ -2,16 +2,17 @@
2
2
  // test run that went with it, never touching a frozen test; a frozen test changes only after the
3
3
  // human has amended the slice file, and then only that one test.
4
4
  import fs from 'node:fs';
5
+ import os from 'node:os';
5
6
  import path from 'node:path';
6
7
  import { buildTestCommand } from '../config.js';
7
- import { GitError, assertRef, commitPaths, git, hasRemote, parseTrailers } from '../git.js';
8
+ import { GitError, assertRef, checkoutIndexTo, commitPaths, commitStaged, git, hasRemote, parseTrailers, stagedChanges } from '../git.js';
8
9
  import { configSubject, namesConfigAt } from './config.js';
9
10
  import { freshAt, renderPathsOnly, renderSubject } from './render.js';
10
11
  import { stateFileName, verdictFilePattern } from '../ids.js';
11
12
  import { kitPaths } from '../paths.js';
12
13
  import { TransitionError, readSlice, unfreeze } from '../state/index.js';
13
14
  import { isKitFile, posixRel, runCommand, sliceIn, toWorktreePath, unusableRun } from './red.js';
14
- import { commitState } from './record.js';
15
+ import { commitState, recordAmendment } from './record.js';
15
16
  import { BuildError, findWorktree } from './worktree.js';
16
17
 
17
18
  const short = (sha) => sha.slice(0, 7);
@@ -202,6 +203,28 @@ function forgedKitChange(wt, cfg, id, current, slice) {
202
203
  return null;
203
204
  }
204
205
 
206
+ // 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.
209
+ function runOnIndex(wt, command) {
210
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'slicekit-index-'));
211
+ const modules = path.join(dir, 'node_modules');
212
+ try {
213
+ checkoutIndexTo(wt, dir);
214
+ const installed = path.join(wt, 'node_modules');
215
+ if (fs.existsSync(installed) && !fs.existsSync(modules)) fs.symlinkSync(installed, modules, 'junction');
216
+ return runCommand(dir, command);
217
+ } 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
223
+ }
224
+ fs.rmSync(dir, { recursive: true, force: true });
225
+ }
226
+ }
227
+
205
228
  export function commitWork(root, cfg, id, { message, requireGreen = false, worktree, env = process.env } = {}) {
206
229
  if (typeof message !== 'string' || message.trim() === '') throw new BuildError('--message is required', 2);
207
230
  const wt = findWorktree(root, id, { worktree }).path;
@@ -211,7 +234,9 @@ export function commitWork(root, cfg, id, { message, requireGreen = false, workt
211
234
  if (forged) throw new BuildError(forged);
212
235
  const frozen = frozenProblem(wt, current);
213
236
  if (frozen) throw new BuildError(frozen);
214
- const paths = changedPaths(wt);
237
+ // Paths staged: those alone are committed, as staged. Nothing staged: every changed path.
238
+ const staged = stagedChanges(wt).map((c) => c.file);
239
+ const paths = staged.length > 0 ? staged : changedPaths(wt);
215
240
  const kit = paths.find((p) => isKitFile(wt, cfg, slice, p));
216
241
  if (kit) {
217
242
  const config = kit === posixRel(wt, kitPaths(wt, cfg).config) ? `; run slicekit build config ${id}` : '';
@@ -220,14 +245,16 @@ export function commitWork(root, cfg, id, { message, requireGreen = false, workt
220
245
  const { command, local } = buildTestCommand(root, cfg, env);
221
246
  if (command.trim() === '') throw new BuildError('commands.test is not declared in .slicekit/config.json');
222
247
  const ranLocal = local ? command : null;
223
-
224
- const run = runCommand(wt, command);
248
+ // With paths staged the commit holds the index, so the tests run on the index (issue #69): a
249
+ // tracked path changed but not staged stays in the worktree, out of the run and out of the commit.
250
+ const run = staged.length > 0 ? runOnIndex(wt, command) : runCommand(wt, command);
225
251
  const unusable = unusableRun(command, run);
226
252
  if (unusable) throw unusable;
227
253
  if (requireGreen && run.exit !== 0) throw new BuildError(`tests fail (exit ${run.exit}): ${run.summary}`);
228
254
  if (paths.length === 0) return { sha: null, exit: run.exit, local: ranLocal };
229
255
  // Only the paths the status named: the developer's work, never the kit's files.
230
- const sha = commitPaths(wt, paths, `${message.trim()}\n\nran: ${command} → exit ${run.exit}\n\nSlice: ${id}`);
256
+ const body = `${message.trim()}\n\nran: ${command} → exit ${run.exit}\n\nSlice: ${id}`;
257
+ const sha = staged.length > 0 ? commitStaged(wt, body) : commitPaths(wt, paths, body);
231
258
  return { sha, exit: run.exit, local: ranLocal };
232
259
  }
233
260
 
@@ -287,17 +314,68 @@ function pendingUnfreeze(wt, id, stateRel, sliceRel, file) {
287
314
  );
288
315
  }
289
316
 
317
+ // The state file on disk differs from HEAD's copy only by one history entry that records an
318
+ // amendment commit on HEAD's history and leaves the state where it was, and HEAD's history does not
319
+ // hold that commit yet: a slice-file-only amend wrote its record and stopped before committing it.
320
+ // -> the amendment commit's SHA, or null.
321
+ function pendingAmendment(wt, id, stateRel, sliceRel) {
322
+ const committed = committedState(wt, stateRel);
323
+ if (!committed || !AMEND_FROM.includes(committed.state)) return null;
324
+ const now = JSON.parse(fs.readFileSync(path.join(wt, ...stateRel.split('/')), 'utf8'));
325
+ const added = now.history.at(-1);
326
+ const sha = added?.evidence?.amendCommit;
327
+ const strip = (s) => JSON.stringify({ ...s, history: null, handoff: null });
328
+ const pending =
329
+ strip(now) === strip(committed) &&
330
+ now.history.length === committed.history.length + 1 &&
331
+ JSON.stringify(now.history.slice(0, -1)) === JSON.stringify(committed.history) &&
332
+ added?.evidence?.unfreeze === undefined &&
333
+ !committed.history.some((h) => h.evidence?.amendCommit === sha) &&
334
+ isAmendment(wt, id, sliceRel, sha);
335
+ return pending ? sha : null;
336
+ }
337
+
338
+ // `build amend` with no test named (issue #72): the slice file alone is amended and committed, and
339
+ // the reason recorded in the state file. Refused while any test the slice file names is still
340
+ // frozen: a frozen test changes only when amend names it. A run that stopped after the slice file's
341
+ // commit, or after the record was written but before it was committed, is finished.
342
+ function amendSliceOnly(wt, cfg, id, current, reason, stateRel) {
343
+ const frozen = current.frozenTests.filter((t) => !current.unfrozen.includes(t));
344
+ if (frozen.length > 0) {
345
+ throw new BuildError(`${frozen.join(', ')} ${frozen.length === 1 ? 'is' : 'are'} frozen; name the test amend changes with --test`);
346
+ }
347
+ const sliceRel = posixRel(wt, sliceIn(wt, cfg, id).path);
348
+ const sliceChanged = git(wt, ['--literal-pathspecs', 'status', '--porcelain', '--', sliceRel]) !== '';
349
+ const recorded = sliceChanged ? null : pendingAmendment(wt, id, stateRel, sliceRel);
350
+ if (recorded) {
351
+ // The record is written; only its bookkeeping commit is left.
352
+ commitState(wt, cfg, id, 'amend');
353
+ return { sha: recorded, test: null };
354
+ }
355
+ let sha;
356
+ if (sliceChanged) {
357
+ sha = commitPaths(wt, [sliceRel], `docs(${id}): amend evaluation set\n\n${reason}\n\nSlice: ${id}`);
358
+ } else if (headIsAmendment(wt, id, sliceRel) && !current.history.some((h) => h.evidence?.amendCommit === git(wt, ['rev-parse', 'HEAD']))) {
359
+ // A run that committed the slice file and stopped before its record is finished.
360
+ sha = git(wt, ['rev-parse', 'HEAD']);
361
+ } else {
362
+ throw new BuildError('amend the slice file first; it has no change');
363
+ }
364
+ recordAmendment(wt, cfg, id, { amendCommit: sha, reason });
365
+ return { sha, test: null };
366
+ }
367
+
290
368
  // -> { sha, test }: the slice file's amendment commit, and the test as stored. A run that stopped part
291
369
  // way (the slice file committed, or the state written but not committed) is finished, not refused.
292
370
  export function amend(root, cfg, id, { test, reason, worktree } = {}) {
293
371
  if (typeof reason !== 'string' || reason.trim() === '') throw new BuildError('--reason is required', 2);
294
- if (typeof test !== 'string' || test.trim() === '') throw new BuildError('--test is required', 2);
295
372
  const wt = findWorktree(root, id, { worktree }).path;
296
373
  const current = readSlice(wt, cfg, id);
297
374
  const stateRel = posixRel(wt, path.join(kitPaths(wt, cfg).state, stateFileName(id)));
298
375
  // Where amend runs from is read from HEAD's state file, never the copy on disk.
299
376
  const committed = committedState(wt, stateRel) ?? current;
300
377
  if (!AMEND_FROM.includes(committed.state)) throw new BuildError(`${id} is ${committed.state}; amend runs from ${AMEND_FROM.join(', ')}`);
378
+ if (test === undefined || (typeof test === 'string' && test.trim() === '')) return amendSliceOnly(wt, cfg, id, current, reason.trim(), stateRel);
301
379
  const file = toWorktreePath(wt, test);
302
380
  // Checked before the slice file is committed; the words are unfreeze's own TransitionError reason.
303
381
  if (!current.frozenTests.includes(file)) throw new BuildError(`${file} is not a frozen test of ${id}`);
@@ -53,6 +53,7 @@ function withUrl(current, url) {
53
53
  }
54
54
 
55
55
  // -> {url, created, state}: state is the filed issue's, `open` or `closed`; a new issue is open.
56
+ // A promise of the same when the tracker answers with promises.
56
57
  export function declineFinding(root, cfg, host, tracker, id, finding, { worktree } = {}) {
57
58
  const wt = findWorktree(root, id, { worktree }).path;
58
59
  const state = readSlice(wt, cfg, id);
@@ -69,13 +70,21 @@ export function declineFinding(root, cfg, host, tracker, id, finding, { worktree
69
70
  const number = state.pr?.number;
70
71
  if (!Number.isInteger(number)) throw new BuildError(`${id} has no pull request to list the declined should-have on`);
71
72
 
72
- const filed = tracker.find(id, finding);
73
- const issue = filed ?? tracker.open({ title: issueTitle(`[${id}] ${finding}: `, quoteMentions(f.wrong)), body: issueBody(f, v), slice: id });
73
+ const open = () => tracker.open({ title: issueTitle(`[${id}] ${finding}: `, quoteMentions(f.wrong)), body: issueBody(f, v), slice: id });
74
+ return after(tracker.find(id, finding), (filed) =>
75
+ after(filed ?? open(), (issue) => {
76
+ const body = host.getPullRequest(number).body;
77
+ const current = getSection(body, SECTION);
78
+ if (!(current ?? '').split(/\s+/).includes(issue.url)) {
79
+ host.updatePullRequestBody(number, setSection(body, SECTION, withUrl(current, issue.url)));
80
+ }
81
+ return { url: issue.url, created: filed === null, state: filed?.state ?? 'open' };
82
+ }),
83
+ );
84
+ }
74
85
 
75
- const body = host.getPullRequest(number).body;
76
- const current = getSection(body, SECTION);
77
- if (!(current ?? '').split(/\s+/).includes(issue.url)) {
78
- host.updatePullRequestBody(number, setSection(body, SECTION, withUrl(current, issue.url)));
79
- }
80
- return { url: issue.url, created: filed === null, state: filed?.state ?? 'open' };
86
+ // `fn(value)`, after `value` settles when it is a promise. A synchronous tracker (GitHub Issues, the
87
+ // fixture) keeps declineFinding synchronous; an asynchronous one (Jira) makes it return a promise.
88
+ function after(value, fn) {
89
+ return value !== null && typeof value?.then === 'function' ? value.then(fn) : fn(value);
81
90
  }
@@ -6,7 +6,7 @@ import { commitPaths } from '../git.js';
6
6
  import { stateFileName } from '../ids.js';
7
7
  import { kitPaths } from '../paths.js';
8
8
  import { renderBuild } from '../state/build.js';
9
- import { setState } from '../state/index.js';
9
+ import { appendHistory, setState } from '../state/index.js';
10
10
 
11
11
  const posixRel = (wt, abs) => path.relative(wt, abs).split(path.sep).join('/');
12
12
 
@@ -21,6 +21,16 @@ export function recordState(wt, cfg, id, to, evidence) {
21
21
  return state;
22
22
  }
23
23
 
24
+ // An amendment of the slice file alone (build amend with no test named, issue #72): one history
25
+ // entry that leaves the state where it is, with the amendment commit and the reason, then one
26
+ // bookkeeping commit.
27
+ // The entry is written under the slice lock (appendHistory), as setState writes its own.
28
+ export function recordAmendment(wt, cfg, id, evidence) {
29
+ const entry = appendHistory(wt, cfg, id, evidence);
30
+ commitState(wt, cfg, id, 'amend');
31
+ return entry;
32
+ }
33
+
24
34
  // BUILD.md rendered again from the state files, then one bookkeeping commit of the slice's state file
25
35
  // and BUILD.md: `chore(slicekit): <id> <what>`.
26
36
  export function commitState(wt, cfg, id, what) {
@@ -1,7 +1,11 @@
1
1
  // The pull request a `slicekit check --ci` run judges (03 REQ-3.11). In GitHub Actions it is read
2
- // from the event file `GITHUB_EVENT_PATH` names; any other event (a push) has no pull request.
2
+ // from the event file `GITHUB_EVENT_PATH` names. A workflow_dispatch run (D-80: the sync job starts
3
+ // the workflow on its sync branch that way) has no pull request in its event, so the open pull
4
+ // request for the run's branch is read through C-1 pullRequestForBranch. Any other event (a push)
5
+ // has no pull request.
3
6
  // Locally, with no event file, `SLICEKIT_PR_TITLE` / `SLICEKIT_PR_BODY` stand in for one.
4
7
  import fs from 'node:fs';
8
+ import { getHost } from '../adapters/githost/index.js';
5
9
  import { DEFAULT_BOT_ACTORS } from '../config.js';
6
10
  import { resolveCommit } from '../git.js';
7
11
 
@@ -11,9 +15,32 @@ export const PR_FILE = '.github/pull_request';
11
15
 
12
16
  const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
13
17
 
14
- // `{title, body, number, headSha, labels, author}` or null when there is no pull request. An event file
18
+ // The open pull request of a workflow_dispatch run's branch, read from the host, or null when the run
19
+ // is not on a branch or the branch has none. A host that cannot answer throws, as a broken event does.
20
+ function dispatchedPullRequest(env, event, { cfg, root } = {}) {
21
+ const ref = typeof env.GITHUB_REF === 'string' && env.GITHUB_REF !== '' ? env.GITHUB_REF : event.ref;
22
+ if (typeof ref !== 'string' || !ref.startsWith('refs/heads/')) return null;
23
+ const branch = ref.slice('refs/heads/'.length);
24
+ const host = getHost(cfg, env, root ?? process.cwd());
25
+ const open = host.pullRequestForBranch(branch, { base: cfg?.defaultBranch });
26
+ if (!open) return null;
27
+ const pr = host.getPullRequest(open.number);
28
+ if (typeof pr.title !== 'string') throw new Error(`pull request ${open.number} of ${branch} has no title`);
29
+ return {
30
+ title: pr.title,
31
+ body: typeof pr.body === 'string' ? pr.body : '',
32
+ number: open.number,
33
+ branch,
34
+ headSha: typeof pr.headSha === 'string' ? pr.headSha : null,
35
+ labels: Array.isArray(pr.labels) ? pr.labels.filter((n) => typeof n === 'string') : [],
36
+ author: null,
37
+ };
38
+ }
39
+
40
+ // `{title, body, number, branch, headSha, labels, author}` or null when there is no pull request. An event file
15
41
  // that is named but missing, unreadable or invalid throws: CI must never pass on a broken event.
16
- export function readCiEvent(env = process.env) {
42
+ // `ctx` ({cfg, root}) names the host a workflow_dispatch run asks.
43
+ export function readCiEvent(env = process.env, ctx = {}) {
17
44
  const file = env.GITHUB_EVENT_PATH;
18
45
  if (typeof file === 'string' && file !== '') {
19
46
  let event;
@@ -24,7 +51,7 @@ export function readCiEvent(env = process.env) {
24
51
  }
25
52
  if (!isObject(event)) throw new Error(`the GitHub event at ${file} is not an object`);
26
53
  const pr = event.pull_request;
27
- if (pr === undefined || pr === null) return null;
54
+ if (pr === undefined || pr === null) return env.GITHUB_EVENT_NAME === 'workflow_dispatch' ? dispatchedPullRequest(env, event, ctx) : null;
28
55
  if (!isObject(pr)) throw new Error(`the GitHub event at ${file} has a pull_request that is not an object`);
29
56
  if (typeof pr.title !== 'string') throw new Error(`the pull request in ${file} has no title`);
30
57
  if (pr.body !== undefined && pr.body !== null && typeof pr.body !== 'string') throw new Error(`the pull request in ${file} has a body that is not text`);
@@ -32,6 +59,7 @@ export function readCiEvent(env = process.env) {
32
59
  title: pr.title,
33
60
  body: pr.body ?? '',
34
61
  number: Number.isInteger(pr.number) ? pr.number : null,
62
+ branch: typeof pr.head?.ref === 'string' ? pr.head.ref : null,
35
63
  headSha: typeof pr.head?.sha === 'string' ? pr.head.sha : null,
36
64
  labels: Array.isArray(pr.labels) ? pr.labels.map((l) => l?.name).filter((n) => typeof n === 'string') : [],
37
65
  author: typeof pr.user?.login === 'string' ? pr.user.login : null,
@@ -49,8 +77,12 @@ export function isBotAuthor(cfg, pr) {
49
77
  return typeof pr?.author === 'string' && bots.includes(pr.author);
50
78
  }
51
79
 
52
- // A `[spec] ` or `[plan] ` title: a spec or plan pull request, not a slice's.
53
- export const EXEMPT_TITLE = /^\[(spec|plan)\] /;
80
+ // A `[spec] `, `[plan] ` or `[sync] ` title: a spec, plan or state sync pull request, not a slice's.
81
+ export const EXEMPT_TITLE = /^\[(spec|plan|sync)\] /;
82
+
83
+ // A `[sync] ` title: the state sync pull request, which belongs on a `sync/<short sha>` branch only.
84
+ export const SYNC_TITLE = /^\[sync\] /;
85
+ export const SYNC_BRANCH = /^sync\/[0-9a-f]{7,40}$/;
54
86
 
55
87
  // The branch a rule judges and the tip it judges it at, or null with no repository, no commits or no
56
88
  // branch (moved from the trailer rule in P3/S-18, so trailer and citations share it). Under --ci on
@@ -81,6 +81,7 @@ export function check(root, { ci = false, env = process.env, rules = ALL_RULES }
81
81
  const counts = {};
82
82
  const lines = [];
83
83
  const ratchetCounts = {};
84
+ const notes = [];
84
85
  const seen = new Map();
85
86
  let over = 0;
86
87
  let blocking = 0;
@@ -103,6 +104,9 @@ export function check(root, { ci = false, env = process.env, rules = ALL_RULES }
103
104
  let found;
104
105
  try {
105
106
  found = runRule(rule, ctx);
107
+ // A note (D-81: host rules not checked outside CI) is printed and never counted or blocking.
108
+ for (const f of found) if (f.note === true) notes.push(`note: ${f.rule} ${f.message}`);
109
+ found = found.filter((f) => f.note !== true);
106
110
  } catch (e) {
107
111
  block({ rule: rule.id, file: '-', line: 0, message: `rule ${rule.id} crashed: ${e?.message ?? e}`, bucket: '-' });
108
112
  continue;
@@ -135,6 +139,7 @@ export function check(root, { ci = false, env = process.env, rules = ALL_RULES }
135
139
  }
136
140
 
137
141
  const ruleCount = rules.filter((r) => !r.synthetic).length;
142
+ lines.push(...notes);
138
143
  lines.push(`check: ${findings.length} findings, ${over} over baseline, ${blocking} blocking, ${ruleCount} rules`);
139
- return { findings, counts, ratchetCounts, exitCode: over > 0 || blocking > 0 ? 1 : 0, lines, rules: ruleCount, over, blocking };
144
+ return { findings, counts, ratchetCounts, notes, exitCode: over > 0 || blocking > 0 ? 1 : 0, lines, rules: ruleCount, over, blocking };
140
145
  }
@@ -14,7 +14,7 @@ export const ratchet = false;
14
14
 
15
15
  export function run(ctx) {
16
16
  if (!ctx.ci) return [];
17
- const pr = readCiEvent(ctx.env);
17
+ const pr = readCiEvent(ctx.env, ctx);
18
18
  if (!pr || isBotAuthor(ctx.cfg, pr)) return [];
19
19
  return prBodyProblems(pr.title, pr.body, ctx.cfg).map((message) => ({ file: PR_FILE, line: 0, message }));
20
20
  }
@@ -1,8 +1,9 @@
1
1
  // ci-title (03 REQ-3.11, REQ-3.7): with --ci, the pull request's title begins with the slice it
2
2
  // delivers, `[P<n>/S-<nn>]`, and that slice has a slice file, a state file and a state of at least
3
3
  // `draft-pr` and before `merged`: a pull request opened by hand, outside the build loop, fails, and
4
- // so does one for a slice already merged or released (a later change needs its own slice). A `[spec] ` or
5
- // `[plan] ` title is not a slice's and is exempt. Draft and closed pull requests are judged alike.
4
+ // so does one for a slice already merged or released (a later change needs its own slice). A `[spec] `,
5
+ // `[plan] ` or `[sync] ` title is not a slice's and is exempt; a `[sync] ` title only on a `sync/<short sha>`
6
+ // branch (the head of the pull request event, or the branch of a dispatched run). Draft and closed pull requests are judged alike.
6
7
  // A pull request opened by an actor in ci.botActors is exempt (D-37). Without --ci, or with no pull
7
8
  // request in the event (a push), there is nothing to judge.
8
9
  import fs from 'node:fs';
@@ -10,7 +11,7 @@ import path from 'node:path';
10
11
  import { ID, stateFileName } from '../../ids.js';
11
12
  import { readSlice } from '../../state/index.js';
12
13
  import { STATES } from '../../state/transitions.js';
13
- import { EXEMPT_TITLE, PR_FILE, isBotAuthor, readCiEvent } from '../ci-event.js';
14
+ import { EXEMPT_TITLE, PR_FILE, SYNC_BRANCH, SYNC_TITLE, isBotAuthor, readCiEvent } from '../ci-event.js';
14
15
 
15
16
  export const id = 'ci-title';
16
17
  export const blocking = true;
@@ -25,9 +26,14 @@ export const titleSlice = (title) => TITLE.exec(title)?.[1] ?? null;
25
26
 
26
27
  export function run(ctx) {
27
28
  if (!ctx.ci) return [];
28
- const pr = readCiEvent(ctx.env);
29
+ const pr = readCiEvent(ctx.env, ctx);
29
30
  if (!pr || isBotAuthor(ctx.cfg, pr)) return [];
30
31
  const at = (message) => [{ file: PR_FILE, line: 0, message }];
32
+ if (SYNC_TITLE.test(pr.title)) {
33
+ const branch = pr.branch ?? (ctx.env?.GITHUB_HEAD_REF || ctx.git?.branch || null);
34
+ if (typeof branch !== 'string' || !SYNC_BRANCH.test(branch)) return at(`a [sync] title belongs to a sync/<short sha> branch, not ${branch ?? 'an unknown branch'}`);
35
+ return [];
36
+ }
31
37
  if (EXEMPT_TITLE.test(pr.title)) return [];
32
38
  const slice = titleSlice(pr.title);
33
39
  if (!slice) return at('title must begin with [P<n>/S-<nn>]');
@@ -0,0 +1,127 @@
1
+ // frozen (03 REQ-3.15, D-10): on a slice branch, a test of the slice's evaluation set stays as it was at
2
+ // the red commit recorded in the slice's state file, unless the slice file was changed in a commit
3
+ // after the red commit (as `build amend` does). The state file, the red commit, the slice file and
4
+ // the tests are all read from git objects of the tip judged, never the working tree: a file hidden
5
+ // with `assume-unchanged` or `skip-worktree` is judged by its committed content (issue #71).
6
+ //
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.
10
+ //
11
+ // The red commit and the frozen list are those of the first version of the state file, in the history
12
+ // of the tip, that records a red commit; frozen paths of later versions are added to that list. A later
13
+ // commit that sets redCommit to null or a new sha, or empties frozenTests, does not change what is
14
+ // judged: tests-red is entered once, from todo, and only the CLI writes the state file.
15
+ import path from 'node:path';
16
+ import { GitError, git, resolveCommit } from '../../git.js';
17
+ import { branchTip } from '../ci-event.js';
18
+ import { parseSliceAddr, sliceFromBranch, stateFileName } from '../../ids.js';
19
+ import { kitPaths } from '../../paths.js';
20
+ import { phaseOfDir } from '../../slicefile.js';
21
+
22
+ export const id = 'frozen';
23
+ export const blocking = true;
24
+ export const ratchet = false;
25
+
26
+ const posixRel = (root, abs) => path.relative(root, abs).split(path.sep).join('/');
27
+ const lines = (out) => out.split('\n').filter((l) => l !== '');
28
+
29
+ // The file's content at `rev`, or null when the commit has no such file.
30
+ function showAt(root, rev, rel) {
31
+ try {
32
+ return git(root, ['show', `${rev}:${rel}`]);
33
+ } catch (e) {
34
+ if (e instanceof GitError) return null;
35
+ throw e;
36
+ }
37
+ }
38
+
39
+ // The slice's file(s) at `rev`: `<phases>/P<n>[-name]/S-<nn>*.md`, matched as findSliceFiles does.
40
+ function sliceFilesAt(root, rev, phasesRel, addr) {
41
+ let listed;
42
+ try {
43
+ listed = git(root, ['--literal-pathspecs', 'ls-tree', '-r', '--name-only', rev, '--', phasesRel]);
44
+ } catch (e) {
45
+ if (e instanceof GitError) return [];
46
+ throw e;
47
+ }
48
+ const prefix = phasesRel === '' || phasesRel === '.' ? '' : `${phasesRel}/`;
49
+ return lines(listed).filter((f) => {
50
+ if (!f.startsWith(prefix)) return false;
51
+ const parts = f.slice(prefix.length).split('/');
52
+ if (parts.length !== 2) return false;
53
+ const phase = phaseOfDir(parts[0]);
54
+ const m = /^S-(\d+).*\.md$/.exec(parts[1]);
55
+ return phase !== null && m !== null && phase.n === addr.phase && Number(m[1]) === addr.slice;
56
+ });
57
+ }
58
+
59
+ const validTest = (t) => typeof t === 'string' && t !== '' && !t.startsWith('-') && !t.startsWith('/') && !t.split('/').includes('..');
60
+
61
+ // Each version of the state file in the history of `tip`, oldest first: [{sha, text}].
62
+ function stateVersions(root, tip, stateRel) {
63
+ const shas = lines(git(root, ['--literal-pathspecs', 'log', '--full-history', '--topo-order', '--reverse', '--format=%H', tip, '--', stateRel]));
64
+ return shas.map((sha) => ({ sha, text: showAt(root, sha, stateRel) })).filter((v) => v.text !== null);
65
+ }
66
+
67
+ const parse = (text) => {
68
+ try {
69
+ return JSON.parse(text);
70
+ } catch {
71
+ return undefined;
72
+ }
73
+ };
74
+
75
+ export function run(ctx) {
76
+ const { root, cfg } = ctx;
77
+ if (cfg?.freezeTests === false) return [];
78
+ const at = branchTip(ctx);
79
+ if (!at) return [];
80
+ const { tip } = at;
81
+ const slice = sliceFromBranch(at.branch);
82
+ if (!slice) return [];
83
+ const addr = parseSliceAddr(slice);
84
+
85
+ const paths = kitPaths(root, cfg);
86
+ const stateRel = `${posixRel(root, paths.state)}/${stateFileName(slice)}`;
87
+ const text = showAt(root, tip, stateRel);
88
+ if (text === null) return [];
89
+ if (parse(text) === undefined) {
90
+ return [{ file: stateRel, line: 0, message: `state file ${stateRel} is not valid JSON at ${tip}` }];
91
+ }
92
+ // The first recorded red commit; every frozen path listed from then on.
93
+ let red = null;
94
+ const listed = [];
95
+ for (const v of stateVersions(root, tip, stateRel)) {
96
+ const state = parse(v.text);
97
+ if (red === null) {
98
+ const r = state?.redCommit;
99
+ if (typeof r !== 'string' || r === '') continue;
100
+ red = r;
101
+ }
102
+ if (Array.isArray(state?.frozenTests)) listed.push(...state.frozenTests);
103
+ }
104
+ if (red === null) return [];
105
+ 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` }];
107
+ }
108
+
109
+ const tests = [...new Set(listed)];
110
+ 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 [];
113
+
114
+ // An amendment of the slice file after the red commit lifts the freeze (REQ-3.3). Only the slice
115
+ // branch's own commits count: --first-parent --no-merges leaves out a change to the slice file made on
116
+ // the default branch and merged into the slice branch.
117
+ const sliceFiles = sliceFilesAt(root, tip, posixRel(root, paths.phases), addr);
118
+ if (sliceFiles.length > 0) {
119
+ const amended = git(root, ['--literal-pathspecs', 'log', '--first-parent', '--no-merges', '--format=%H', `${red}..${tip}`, '--', ...sliceFiles]);
120
+ if (amended !== '') return [];
121
+ }
122
+
123
+ 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}` }));
125
+ }
126
+
127
+ export default { id, blocking, ratchet, run };