slicekit 0.2.1 → 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 +2 -0
  23. package/src/cli/init.js +29 -2
  24. package/src/cli/journal.js +44 -2
  25. package/src/cli/status.js +14 -2
  26. package/src/cli/sync.js +52 -0
  27. package/src/config.js +72 -0
  28. package/src/git.js +30 -1
  29. package/src/hooks/paths.js +103 -0
  30. package/src/hooks/pre-bash.js +642 -43
  31. package/src/hooks/pre-edit.js +23 -3
  32. package/src/init.js +134 -6
  33. package/src/journal.js +153 -12
  34. package/src/pr.js +1 -1
  35. package/src/prbody.js +1 -1
  36. package/src/release-version.js +196 -0
  37. package/src/render/settings.js +26 -2
  38. package/src/render/update.js +1 -1
  39. package/src/state/index.js +11 -0
  40. package/src/state/sync.js +182 -0
  41. package/src/workflow.js +141 -29
  42. package/templates/instructions/commands/build.md +12 -2
  43. package/templates/workflow/pins.json +2 -1
  44. package/templates/workflow/slicekit.yml +46 -11
package/src/workflow.js CHANGED
@@ -1,13 +1,14 @@
1
1
  // The GitHub Actions workflow init writes (REQ-3.11): a gate, a job per declared team command, a job
2
- // per observability step (D-20), the ready label and the post-merge state sync (D-12). The YAML is
2
+ // per observability step (D-20), the ready label and the post-merge state sync (D-12), which opens a
3
+ // [sync] pull request and starts the workflow on its branch with workflow_dispatch (D-78, D-80). The YAML is
3
4
  // generated as text; every free-text value goes through yamlScalar so a quote, colon or hash in a
4
5
  // team's command cannot change the document's structure.
6
+ import { execFileSync } from 'node:child_process';
5
7
  import fs from 'node:fs';
6
8
  import path from 'node:path';
7
9
  import { fileURLToPath } from 'node:url';
8
- import { DEFAULT_TIMEOUT_MINUTES, GITHUB_EXPRESSION, LINE_SEPARATOR, shardErrors } from './config.js';
10
+ import { DEFAULT_RUNS_ON, DEFAULT_TIMEOUT_MINUTES, GITHUB_EXPRESSION, LINE_SEPARATOR, MATRIX_OS, shardErrors, shardRunnerErrors } from './config.js';
9
11
  import { readText } from './fs.js';
10
- import { kitPaths } from './paths.js';
11
12
  import { substitute } from './render/entry.js';
12
13
 
13
14
  export const WORKFLOW_TEMPLATE = fileURLToPath(new URL('../templates/workflow/slicekit.yml', import.meta.url));
@@ -16,15 +17,14 @@ export const PINS_PATH = fileURLToPath(new URL('../templates/workflow/pins.json'
16
17
  export const WORKFLOW_PATH = '.github/workflows/slicekit.yml';
17
18
  export const WORKFLOW_DRIFT = `${WORKFLOW_PATH} differs from the generator; run slicekit workflow --write to regenerate it`;
18
19
 
19
- const ACTIONS = { checkout: 'actions/checkout', setupNode: 'actions/setup-node', uploadArtifact: 'actions/upload-artifact', cache: 'actions/cache' };
20
+ const ACTIONS = { checkout: 'actions/checkout', setupNode: 'actions/setup-node', uploadArtifact: 'actions/upload-artifact', cache: 'actions/cache', setupJava: 'actions/setup-java' };
20
21
  const COMMAND_ORDER = ['test', 'lint', 'build', 'e2e'];
21
- const MATRIX_OS = ['ubuntu-latest', 'windows-latest', 'macos-latest'];
22
22
  const SHA = /^[0-9a-f]{40}$/;
23
23
  const TAG = /^v\d+\.\d+\.\d+$/;
24
24
  const BLOCK_KEYS = ['gateExtraSteps', 'commandJobs', 'observabilityJobs'];
25
25
  // Filled as written: values the kit computes or validates to a safe shape.
26
26
  const VALUE_KEYS = [
27
- 'checksOk', 'defaultBranchItem', 'readyNeeds', 'syncPaths', 'timeoutMinutes',
27
+ 'checksOk', 'defaultBranchItem', 'readyNeeds', 'runsOn', 'timeoutMinutes',
28
28
  ...Object.keys(ACTIONS).flatMap((k) => [`${k}Sha`, `${k}Tag`]),
29
29
  ];
30
30
  // The team's own text: a mapping value holding one is filled, then quoted as a whole.
@@ -39,6 +39,122 @@ const NO_DEPENDENCIES = [
39
39
  ` node -e "const p = require('./package.json'); const bad = [${DEPENDENCY_FIELDS.map((f) => `'${f}'`).join(', ')}].flatMap((f) => { const v = p[f]; const n = v === true ? ['true'] : Array.isArray(v) ? v : Object.keys(v || {}); return n.length ? [f + ': ' + n.join(', ')] : []; }); if (bad.length) { console.error('package.json has runtime dependencies: ' + bad.join('; ')); process.exit(1) }"`,
40
40
  ];
41
41
 
42
+ // D-67: the runner of every job, ci.runsOn (a label or a list of labels), default ubuntu-latest.
43
+ // A label inside a flow sequence: quoted when a comma or bracket would end it.
44
+ const flowItem = (label) => {
45
+ const out = yamlScalar(label);
46
+ return out.startsWith("'") || !/[,[\]]/.test(out) ? out : `'${label.replace(/'/g, "''")}'`;
47
+ };
48
+ export function runsOnValue(runsOn) {
49
+ if (runsOn === undefined) return DEFAULT_RUNS_ON;
50
+ return Array.isArray(runsOn) ? `[${runsOn.map(flowItem).join(', ')}]` : yamlScalar(runsOn);
51
+ }
52
+
53
+ // D-69, D-85: a repository is a Java repository when it holds a Maven or Gradle build file at its root
54
+ // or a declared command calls mvn, gradle or ./gradlew. The cache is the build tool of the one build
55
+ // file present; with both or neither, the tool the first command calling one names (Maven when none does).
56
+ export const DEFAULT_JAVA = 25;
57
+ const BUILD_FILES = { 'pom.xml': 'maven', 'build.gradle': 'gradle', 'build.gradle.kts': 'gradle' };
58
+ // The tool counts only where a shell runs it: as the first word of a simple command. The command is
59
+ // split at line breaks and at ; & | ( ); in each part, NAME=value assignments and the wrapper words
60
+ // below (with the flags after them) and shell keywords such as then or do are skipped; a shell started with a flag holding c (sh -c,
61
+ // bash -lc) has its script read the same way. A mention such as echo "mvn test" or rg 'gradle' docs
62
+ // is an argument, not a call.
63
+ const JAVA_TOOLS = { mvn: 'maven', gradle: 'gradle', './gradlew': 'gradle' };
64
+ const WRAPPERS = new Set(['env', 'time', 'nice', 'nohup', 'exec', 'command', 'sudo', 'xvfb-run']);
65
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash']);
66
+ // Shell keywords that open a command position: if ...; then mvn verify; fi.
67
+ const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{']);
68
+ const unquote = (word) => word.replace(/^["']+|["']+$/g, '');
69
+ function toolCalled(command) {
70
+ for (const part of String(command).split(/[\n;&|()]+/)) {
71
+ const words = part.trim().split(/\s+/).filter(Boolean);
72
+ let i = 0;
73
+ while (i < words.length) {
74
+ const word = unquote(words[i]);
75
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(word) || KEYWORDS.has(word)) { i += 1; continue; }
76
+ if (WRAPPERS.has(word)) { i += 1; while (i < words.length && words[i].startsWith('-')) i += 1; continue; }
77
+ break;
78
+ }
79
+ if (i >= words.length) continue;
80
+ const first = unquote(words[i]);
81
+ if (JAVA_TOOLS[first]) return JAVA_TOOLS[first];
82
+ if (SHELLS.has(first)) {
83
+ const flag = words.findIndex((w, k) => k > i && /^-[A-Za-z]*c[A-Za-z]*$/.test(w));
84
+ if (flag !== -1) {
85
+ const inner = toolCalled(unquote(words.slice(flag + 1).join(' ')));
86
+ if (inner) return inner;
87
+ }
88
+ }
89
+ }
90
+ return null;
91
+ }
92
+ // A root build file counts only when the CI checkout holds it too: in a git repository, a file git
93
+ // tracks or would add (a gitignored pom.xml is absent from the checkout, as for the cache below).
94
+ function hasBuildFile(root, file, tracked) {
95
+ if (!fs.existsSync(path.join(root, file))) return false;
96
+ return tracked === null || tracked.includes(file);
97
+ }
98
+ export function javaBuildTool(root, commands) {
99
+ const tracked = root ? trackedFiles(root) : null;
100
+ const fromFiles = new Set(root ? Object.entries(BUILD_FILES).filter(([f]) => hasBuildFile(root, f, tracked)).map(([, t]) => t) : []);
101
+ if (fromFiles.size === 1) return [...fromFiles][0];
102
+ const call = commands.map(toolCalled).find(Boolean);
103
+ if (call) return call;
104
+ return fromFiles.size > 0 ? 'maven' : null;
105
+ }
106
+
107
+ // setup-java fails a job whose cache matches no file, so the cache is set only when the checkout holds
108
+ // a file the tool's cache keys on: pom.xml at any depth for Maven; for Gradle a build, settings or
109
+ // wrapper file or versions.properties at any depth, or a *.versions.toml in the gradle folder directly
110
+ // under the checkout root (the action's pattern gradle/*.versions.toml is root-only). In a git
111
+ // repository only the files git tracks or would add count (git ls-files --cached --others
112
+ // --exclude-standard), so a gitignored file the CI checkout lacks turns no cache on; a file not yet
113
+ // committed counts, as init runs before the first commit. Outside a git repository, or when git
114
+ // fails, the folder is walked.
115
+ const CACHE_SKIP = new Set(['.git', 'node_modules', '.worktrees']);
116
+ // name is the file's basename, dir its parent folder relative to root with / separators ('' at the root).
117
+ const CACHE_FILE = {
118
+ maven: (name) => name === 'pom.xml',
119
+ gradle: (name, dir) => /\.gradle/.test(name) || name === 'gradle-wrapper.properties' || name === 'versions.properties'
120
+ || (dir === 'gradle' && name.endsWith('.versions.toml')),
121
+ };
122
+ function trackedFiles(root) {
123
+ try {
124
+ const out = execFileSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 256 * 1024 * 1024 });
125
+ return out.split('\0').filter(Boolean);
126
+ } catch { return null; }
127
+ }
128
+ const parentDir = (p) => { const d = path.posix.dirname(p); return d === '.' ? '' : d; };
129
+ export function hasCacheFile(root, tool) {
130
+ const match = CACHE_FILE[tool];
131
+ if (!root || !match) return false;
132
+ const tracked = trackedFiles(root);
133
+ if (tracked) return tracked.some((p) => match(path.posix.basename(p), parentDir(p)));
134
+ const dirs = [root];
135
+ while (dirs.length > 0) {
136
+ const dir = dirs.pop();
137
+ let entries;
138
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
139
+ for (const e of entries) {
140
+ if (e.isDirectory()) { if (!CACHE_SKIP.has(e.name)) dirs.push(path.join(dir, e.name)); }
141
+ else if (match(e.name, path.relative(root, dir).split(path.sep).join('/'))) return true;
142
+ }
143
+ }
144
+ return false;
145
+ }
146
+
147
+ function setupJavaSteps(v, java, tool, root) {
148
+ if (!tool) return [];
149
+ return [
150
+ ` - uses: actions/setup-java@${v.setupJavaSha} # ${v.setupJavaTag}`,
151
+ ' with:',
152
+ ' distribution: temurin',
153
+ ` java-version: ${yamlScalar(String(java))}`,
154
+ ...(hasCacheFile(root, tool) ? [` cache: ${tool}`] : []),
155
+ ];
156
+ }
157
+
42
158
  export function loadPins() {
43
159
  return JSON.parse(fs.readFileSync(PINS_PATH, 'utf8'));
44
160
  }
@@ -114,7 +230,7 @@ const COMMAND_IF = ' if: ${{ !cancelled() && !(' + BOOKKEEPING + ') }}';
114
230
 
115
231
  // One job per declared team command, run on `systems`. `shards` (the test command only, D-49) maps a
116
232
  // system to its shard count; each shard sets SLICEKIT_SHARD to <k>/<n>, 1/1 on a system not split.
117
- function commandJob(name, command, v, systems, timeout, shards) {
233
+ function commandJob(name, command, v, systems, timeout, shards, jdk) {
118
234
  const strategy = [' strategy:', ' fail-fast: false', ' matrix:'];
119
235
  let head;
120
236
  let env = [];
@@ -131,10 +247,10 @@ function commandJob(name, command, v, systems, timeout, shards) {
131
247
  head = [` runs-on: ${systems[0]}`];
132
248
  }
133
249
  const [stepName, ...rest] = runStep(name, command);
134
- return ['', ` cmd-${name}:`, ' needs: [gate]', COMMAND_IF, ...head, ` timeout-minutes: ${timeout}`, ' steps:', ...setupSteps(v), stepName, ...env, ...rest];
250
+ return ['', ` cmd-${name}:`, ' needs: [gate]', COMMAND_IF, ...head, ` timeout-minutes: ${timeout}`, ' steps:', ...setupSteps(v), ...jdk, stepName, ...env, ...rest];
135
251
  }
136
252
 
137
- // SLICEKIT_CHECKS_OK for ready-label: the gate and every observability job succeeded, and each team
253
+ // SLICEKIT_CHECKS_OK for the checks job, which ready-label reads through its result: the gate and every observability job succeeded, and each team
138
254
  // command job succeeded or was skipped because the gate said bookkeeping. A job that failed, was
139
255
  // cancelled or was skipped for any other reason is not passed.
140
256
  function checksOk(commands, steps) {
@@ -149,8 +265,8 @@ function checksOk(commands, steps) {
149
265
  return '${{ ' + parts.join(' && ') + ' }}';
150
266
  }
151
267
 
152
- function observabilityJob(n, step, v, timeout) {
153
- return ['', ` obs-${n}:`, ` name: ${yamlScalar(step.name, 4)}`, ' runs-on: ubuntu-latest', ` timeout-minutes: ${timeout}`, ' steps:', ...setupSteps(v), ...runStep(step.name, step.run, step.env)];
268
+ function observabilityJob(n, step, v, timeout, runsOn) {
269
+ return ['', ` obs-${n}:`, ` name: ${yamlScalar(step.name, 4)}`, ` runs-on: ${runsOn}`, ` timeout-minutes: ${timeout}`, ' steps:', ...setupSteps(v), ...runStep(step.name, step.run, step.env)];
154
270
  }
155
271
 
156
272
  // One pass over the value, so text inside cli is never itself read as a placeholder.
@@ -161,14 +277,7 @@ function fillFreeText(line, vars) {
161
277
  return m[1] + yamlScalar(substitute(m[2], vars, FREE_TEXT_KEYS));
162
278
  }
163
279
 
164
- // What the sync commit may stage: BUILD.md and the state directory, as repository-relative paths.
165
- function syncPaths(cfg) {
166
- // Neither path depends on docsRoot; the default only keeps a partial config renderable.
167
- const p = kitPaths('.', { docsRoot: 'docs', ...cfg });
168
- return [p.build, p.state].map((f) => path.relative('.', f).split(path.sep).join('/')).join(' ');
169
- }
170
-
171
- export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileSync(WORKFLOW_TEMPLATE, 'utf8') } = {}) {
280
+ export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileSync(WORKFLOW_TEMPLATE, 'utf8'), root = null } = {}) {
172
281
  if (/[\r\n]/.test(cfg.cli)) throw new Error('cli: must be one line to render the workflow');
173
282
  const v = checkPins(pins);
174
283
  const matrix = cfg.ci?.matrix === true;
@@ -176,12 +285,15 @@ export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileS
176
285
  if (!Number.isInteger(timeout) || timeout < 1 || timeout > 360) throw new Error('ci.timeoutMinutes: must be an integer from 1 to 360');
177
286
  const shardProblems = shardErrors(cfg.ci?.shards);
178
287
  if (shardProblems.length > 0) throw new Error(shardProblems.join('; '));
179
- const testSystems = matrix ? MATRIX_OS : ['ubuntu-latest'];
180
- const shards = cfg.ci?.shards && Object.keys(cfg.ci.shards).length > 0 ? cfg.ci.shards : null;
181
- for (const os of Object.keys(shards ?? {})) {
182
- if (!testSystems.includes(os)) throw new Error(`ci.shards.${os}: the test job runs only on ${testSystems.join(', ')}`);
183
- }
288
+ const runnerProblems = shardRunnerErrors(cfg.ci);
289
+ if (runnerProblems.length > 0) throw new Error(runnerProblems.join('; '));
290
+ const runsOn = runsOnValue(cfg.ci?.runsOn);
291
+ const testSystems = matrix ? MATRIX_OS : [runsOn];
292
+ // Without the matrix the one shard key names a label of the runner; the job is keyed by its rendered runs-on.
293
+ const given = cfg.ci?.shards && Object.keys(cfg.ci.shards).length > 0 ? cfg.ci.shards : null;
294
+ const shards = given && (matrix ? given : { [runsOn]: Object.values(given)[0] });
184
295
  const commands = COMMAND_ORDER.filter((name) => typeof cfg.commands[name] === 'string' && cfg.commands[name].trim() !== '');
296
+ const jdk = setupJavaSteps(v, cfg.ci?.java ?? DEFAULT_JAVA, javaBuildTool(root, commands.map((c) => cfg.commands[c])), root);
185
297
  const steps = cfg.ci?.observabilitySteps ?? [];
186
298
  const texts = [cfg.cli, ...commands.map((c) => cfg.commands[c]), ...steps.map((s) => s.run)];
187
299
  if (texts.some((t) => GITHUB_EXPRESSION.test(t))) throw new Error('workflow: a command contains a GitHub expression; pass values through env:');
@@ -189,17 +301,17 @@ export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileS
189
301
  gateExtraSteps: matrix ? NO_DEPENDENCIES : [],
190
302
  commandJobs: commands.flatMap((name) =>
191
303
  name === 'test'
192
- ? commandJob(name, cfg.commands[name], v, testSystems, timeout, shards)
193
- : commandJob(name, cfg.commands[name], v, ['ubuntu-latest'], timeout, null),
304
+ ? commandJob(name, cfg.commands[name], v, testSystems, timeout, shards, jdk)
305
+ : commandJob(name, cfg.commands[name], v, [runsOn], timeout, null, jdk),
194
306
  ),
195
- observabilityJobs: steps.flatMap((step, i) => observabilityJob(i + 1, step, v, timeout)),
307
+ observabilityJobs: steps.flatMap((step, i) => observabilityJob(i + 1, step, v, timeout, runsOn)),
196
308
  };
197
309
  const vars = {
198
310
  ...v,
199
311
  checksOk: checksOk(commands, steps),
200
312
  defaultBranchItem: yamlScalar(cfg.defaultBranch),
201
313
  readyNeeds: ['gate', ...commands.map((c) => `cmd-${c}`), ...steps.map((_s, i) => `obs-${i + 1}`)].join(', '),
202
- syncPaths: syncPaths(cfg),
314
+ runsOn,
203
315
  timeoutMinutes: String(timeout),
204
316
  };
205
317
  const free = { cli: cfg.cli, defaultBranch: cfg.defaultBranch };
@@ -217,7 +329,7 @@ export function renderWorkflow(cfg, pins = loadPins(), { template = fs.readFileS
217
329
 
218
330
  // The rendered workflow and the repository's copy of it (null when absent), line endings normalised.
219
331
  export function workflowState(root, cfg, pins = loadPins()) {
220
- const expected = renderWorkflow(cfg, pins);
332
+ const expected = renderWorkflow(cfg, pins, { root });
221
333
  const file = path.join(root, WORKFLOW_PATH);
222
334
  const current = fs.existsSync(file) ? readText(file) : null;
223
335
  return { file, expected, current };
@@ -72,8 +72,11 @@ stops.
72
72
  After each developer report in which a test newly passes, run
73
73
  `{{cli}} build commit <id> --message "<subject>" --worktree <path>`, with a subject such as
74
74
  `feat(<id>): <what now works>`. It prints `<sha7> exit <n>`, or `nothing to commit` with exit 0,
75
- which is success. A refusal naming a frozen test means the developer changed one: send it back with
76
- the message. While tests still fail, spawn the developer again with what is left.
75
+ which is success. With nothing staged it commits every changed path; with paths staged it commits
76
+ those alone, as staged, and runs the tests on the staged content; a tracked path changed but not
77
+ staged stays in the worktree, out of the commit. A refusal naming
78
+ a frozen test means the developer changed one: send it back with the message. While tests still
79
+ fail, spawn the developer again with what is left.
77
80
 
78
81
  When the developer reports a line `amend: <test path> — <why>`, ask the human whether that test may
79
82
  change. On no, tell the developer the test stands. On yes:
@@ -91,6 +94,13 @@ inside a frozen test: the same three steps, then the slice is back at `building`
91
94
  developer) changes that test, and step 7's `build commit` and `build pr` take the slice back to
92
95
  `draft-pr` on the same pull request.
93
96
 
97
+ When the human changes the slice file and every test it names is already unfrozen, there is no test
98
+ to name: edit the slice file in the worktree as in step 1, then run
99
+ `{{cli}} build amend <id> --reason "<why>" --worktree <path>`. It commits the slice file alone,
100
+ records the reason in the state file, leaves the state as it is, and prints
101
+ `<sha7> amended the slice file`. While a test is still frozen it refuses: name that test with
102
+ `--test`.
103
+
94
104
  ## 5. Green, then the draft pull request
95
105
 
96
106
  When the developer reports every test passing, run
@@ -3,5 +3,6 @@
3
3
  "actions/checkout": { "tag": "v4.2.2", "sha": "11bd71901bbe5b1630ceea73d27597364c9af683" },
4
4
  "actions/setup-node": { "tag": "v4.1.0", "sha": "39370e3970a6d050c480ffad4ff0ed4d3fdee5af" },
5
5
  "actions/upload-artifact": { "tag": "v4.4.3", "sha": "b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882" },
6
- "actions/cache": { "tag": "v4.2.3", "sha": "5a3ec84eff668545956fd18022155c47e93e2684" }
6
+ "actions/cache": { "tag": "v4.2.3", "sha": "5a3ec84eff668545956fd18022155c47e93e2684" },
7
+ "actions/setup-java": { "tag": "v5.7.0", "sha": "b6effb05e454b25005698d916606bdc6ffcbf961" }
7
8
  }
@@ -1,4 +1,6 @@
1
1
  # slicekit: the pull request gate and the state sync (REQ-3.11). Every action is pinned by SHA.
2
+ # A run started with workflow_dispatch (the sync pull request's checks, D-80) runs the gate, the
3
+ # command jobs and checks on the branch's head; check --ci reads the branch's open pull request.
2
4
  name: slicekit
3
5
 
4
6
  on:
@@ -6,6 +8,9 @@ on:
6
8
  types: [opened, synchronize, reopened, edited]
7
9
  push:
8
10
  branches: [{{defaultBranchItem}}]
11
+ # The sync job starts the workflow on its sync branch this way (D-80): a pull request opened with
12
+ # the workflow's own token starts no run, so its checks would never report.
13
+ workflow_dispatch:
9
14
 
10
15
  permissions:
11
16
  contents: read
@@ -20,7 +25,7 @@ defaults:
20
25
 
21
26
  jobs:
22
27
  gate:
23
- runs-on: ubuntu-latest
28
+ runs-on: {{runsOn}}
24
29
  timeout-minutes: {{timeoutMinutes}}
25
30
  permissions:
26
31
  actions: read
@@ -45,6 +50,8 @@ jobs:
45
50
  id: bookkeeping
46
51
  env:
47
52
  GH_TOKEN: ${{ github.token }}
53
+ # With no pull request event (a push, or a dispatched run on a sync branch, D-80) the head is
54
+ # empty and the decision is code, so every team command job runs.
48
55
  SLICEKIT_PR_HEAD: ${{ github.event.pull_request.head.sha }}
49
56
  SLICEKIT_PR_BASE_BRANCH: ${{ github.base_ref }}
50
57
  run: {{cli}} ci bookkeeping --head "$SLICEKIT_PR_HEAD" --base-branch "$SLICEKIT_PR_BASE_BRANCH" --output "$GITHUB_OUTPUT"
@@ -71,6 +78,11 @@ jobs:
71
78
  {{gateExtraSteps}}
72
79
  - name: slicekit check
73
80
  run: {{cli}} check --ci
81
+ # The host-rules rule reads the default branch's rulesets and CODEOWNERS (REQ-3.14). gh reads
82
+ # GH_TOKEN on github.com and GH_ENTERPRISE_TOKEN on a GitHub Enterprise Server host (D-70).
83
+ env:
84
+ GH_TOKEN: ${{ github.token }}
85
+ GH_ENTERPRISE_TOKEN: ${{ github.token }}
74
86
  - name: The workflow matches the generator
75
87
  run: {{cli}} workflow --check
76
88
  - name: Upload the graph
@@ -82,10 +94,25 @@ jobs:
82
94
  {{commandJobs}}
83
95
  {{observabilityJobs}}
84
96
 
97
+ # The one check the default branch's ruleset requires besides the gate (REQ-3.14). A job skipped
98
+ # by its own if, such as a test matrix on a bookkeeping push (D-49), reports no matrix names, so
99
+ # the ruleset names this job instead: it always runs, and passes when every job a merge waits on
100
+ # passed or was skipped because the gate said bookkeeping.
101
+ checks:
102
+ if: ${{ always() }}
103
+ needs: [{{readyNeeds}}]
104
+ runs-on: {{runsOn}}
105
+ timeout-minutes: 10
106
+ steps:
107
+ - name: Every job a merge waits on passed
108
+ env:
109
+ SLICEKIT_CHECKS_OK: {{checksOk}}
110
+ run: test "$SLICEKIT_CHECKS_OK" = true
111
+
85
112
  ready-label:
86
113
  if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && github.actor != 'dependabot[bot]' }}
87
- needs: [{{readyNeeds}}]
88
- runs-on: ubuntu-latest
114
+ needs: [checks]
115
+ runs-on: {{runsOn}}
89
116
  timeout-minutes: 10
90
117
  permissions:
91
118
  contents: read
@@ -105,16 +132,20 @@ jobs:
105
132
  - name: Ready label
106
133
  env:
107
134
  GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
108
- SLICEKIT_CHECKS_OK: {{checksOk}}
135
+ SLICEKIT_CHECKS_OK: ${{ needs.checks.result == 'success' }}
109
136
  run: {{cli}} ready-label
110
137
 
138
+ # After a merge (D-78, D-80): the state change goes up as a [sync] pull request on
139
+ # sync/<short sha>, never onto the default branch, and the workflow is started on that branch so its
140
+ # checks run. sync open pushes only the sync branch; nothing here commits or pushes.
111
141
  sync:
112
142
  if: github.event_name == 'push'
113
- runs-on: ubuntu-latest
143
+ runs-on: {{runsOn}}
114
144
  timeout-minutes: 10
115
145
  permissions:
146
+ actions: write
116
147
  contents: write
117
- pull-requests: read
148
+ pull-requests: write
118
149
  steps:
119
150
  - uses: actions/checkout@{{checkoutSha}} # {{checkoutTag}}
120
151
  with:
@@ -131,11 +162,15 @@ jobs:
131
162
  env:
132
163
  GH_TOKEN: ${{ github.token }}
133
164
  run: {{cli}} status --sync --write
134
- - name: Commit state
135
- env:
136
- ALLOW_PROTECTED_COMMIT: '1'
165
+ # One line per journal file the merge changed, with this run's id, workflow and actor (REQ-3.8);
166
+ # check --ci on the sync pull request recomputes each line from git and the host (D-89).
167
+ - name: Record the journal heads
168
+ run: {{cli}} journal heads "$GITHUB_SHA"
169
+ - name: Commit identity
137
170
  run: |
138
171
  git config user.name 'github-actions[bot]'
139
172
  git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
140
- git add -- {{syncPaths}}
141
- git diff --cached --quiet || { git commit -m 'chore(slicekit): sync state [skip ci]' && git push; }
173
+ - name: Open the sync pull request
174
+ env:
175
+ GH_TOKEN: ${{ github.token }}
176
+ run: {{cli}} sync open