slicekit 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +7 -2
  2. package/bin/slicekit.js +0 -0
  3. package/package.json +1 -1
  4. package/src/adapters/githost/fixture.js +106 -0
  5. package/src/adapters/githost/gh-json.js +201 -0
  6. package/src/adapters/githost/github.js +141 -0
  7. package/src/adapters/tracker/index.js +5 -1
  8. package/src/adapters/tracker/jira.js +133 -0
  9. package/src/build/commit.js +85 -7
  10. package/src/build/decline.js +17 -8
  11. package/src/build/record.js +11 -1
  12. package/src/check/ci-event.js +38 -6
  13. package/src/check/index.js +6 -1
  14. package/src/check/rules/ci-body.js +1 -1
  15. package/src/check/rules/ci-title.js +10 -4
  16. package/src/check/rules/frozen.js +127 -0
  17. package/src/check/rules/host-rules.js +149 -0
  18. package/src/check/rules/journal.js +130 -3
  19. package/src/check/rules/references.js +31 -0
  20. package/src/check/rules/sync-release.js +94 -0
  21. package/src/cli/build.js +8 -7
  22. package/src/cli/index.js +13 -0
  23. package/src/cli/init.js +29 -2
  24. package/src/cli/journal.js +44 -2
  25. package/src/cli/status.js +14 -2
  26. package/src/cli/sync.js +52 -0
  27. package/src/config.js +77 -3
  28. package/src/git.js +65 -1
  29. package/src/hooks/paths.js +103 -0
  30. package/src/hooks/pre-bash.js +642 -43
  31. package/src/hooks/pre-edit.js +23 -3
  32. package/src/init.js +136 -7
  33. package/src/journal.js +153 -12
  34. package/src/pr.js +1 -1
  35. package/src/prbody.js +1 -1
  36. package/src/release-version.js +196 -0
  37. package/src/render/settings.js +26 -2
  38. package/src/render/update.js +1 -1
  39. package/src/state/index.js +11 -0
  40. package/src/state/sync.js +182 -0
  41. package/src/workflow.js +141 -29
  42. package/templates/instructions/commands/build.md +12 -2
  43. package/templates/workflow/pins.json +2 -1
  44. package/templates/workflow/slicekit.yml +46 -11
package/README.md CHANGED
@@ -10,8 +10,9 @@ agent finishes a turn and again in CI, not because anyone remembers to update it
10
10
  Phases 1 to 3 work. Phases 1 and 2 are intake, specify, the gap scan, plan, the build from red
11
11
  tests to green, the review loop, the independent review and `/slicekit build --parallel`. Phase 3
12
12
  is the traceability graph (`graph`), its queries (`trace`, `impact`, `history`, `uncovered` and
13
- `shipped`), its views (`visualize`), and workspaces that span several repositories. Phase 4
14
- (release, ops, audit and the other examples) is not built yet. [CHANGELOG.md](https://github.com/adityapandya1/agentic-slicekit/blob/main/CHANGELOG.md) lists what each
13
+ `shipped`), its views (`visualize`), and workspaces that let the graph span several repositories;
14
+ a slice is still built in one repository. Phase 4 (hardening: host rules, guards, the journal, Jira)
15
+ and Phase 5 (release, ops, audit and the other examples) are not built yet. [CHANGELOG.md](https://github.com/adityapandya1/agentic-slicekit/blob/main/CHANGELOG.md) lists what each
15
16
  version changed.
16
17
 
17
18
  The kit is on npm as a preview from 0.1.1. It needs Node 22 or later and git, and it has no
@@ -26,6 +27,10 @@ Each change to the kit ships as the next 0.x version, and a 0.x version may chan
26
27
  works. After an upgrade, `npx slicekit update` shows what would change in each of the kit's files,
27
28
  and `npx slicekit update --yes` writes the changes.
28
29
 
30
+ The [user guide](https://github.com/adityapandya1/agentic-slicekit/blob/main/docs/guide/README.md)
31
+ explains the stages and the slash commands, and gives every command's syntax, options, exit codes
32
+ and an example.
33
+
29
34
  The walkthrough below runs from a clone instead, because it copies files only the repository
30
35
  holds (`examples/backend` and `examples/walkthrough`):
31
36
 
package/bin/slicekit.js CHANGED
File without changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slicekit",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Spec-driven agentic workflow kit",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -9,12 +9,23 @@ import {
9
9
  assertLabelColor,
10
10
  assertPrNumber,
11
11
  assertTitle,
12
+ assertWorkflowFile,
13
+ assertComment,
14
+ mapOpenPullRequests,
15
+ mapWorkflowPermissions,
16
+ mapCommit,
17
+ mapRun,
18
+ assertRunId,
12
19
  decidedSlicekitRun,
13
20
  filterMergedSince,
21
+ mapBranchRules,
14
22
  mapJobs,
15
23
  mapPullRequest,
16
24
  pickBranchPullRequest,
17
25
  reduceRuns,
26
+ RULESET_NAME,
27
+ rulesetRules,
28
+ pruneRulesetChecks,
18
29
  } from './gh-json.js';
19
30
 
20
31
  // The test seam for C-1 (05 REQ-5.2): a directory of gh-shaped JSON files.
@@ -26,6 +37,23 @@ import {
26
37
  // label-calls.jsonl written: one line per label call, in order
27
38
  // pr-create-error.txt gh refusing `pr create`
28
39
  // pr-calls.jsonl written: `{op, ...input}` per pull request write (open, update, ready, draft)
40
+ // and per workflow dispatch (`{op: 'dispatchWorkflow', file, ref}`), in order
41
+ // dispatch-error.txt gh refusing `workflow run`
42
+ // pr-close-error.txt gh refusing `pr close`; closePullRequest records `{op: 'closePullRequest', number, comment}`
43
+ // in pr-calls.jsonl and sets the pull request's state to CLOSED
44
+ // workflow-permissions.json what `gh api repos/{o}/{r}/actions/permissions/workflow` prints (missing:
45
+ // readWorkflowPermissions returns null, the setting not known)
46
+ // workflow-permissions-error.txt gh refusing that read (a token without administration read)
47
+ // branch-rules-<branch>.json what `gh api repos/{o}/{r}/rules/branches/<branch>` prints (an array,
48
+ // `[]` for no rules; missing: the rules cannot be read); `/` is written `%2F`
49
+ // branch-<branch>.json what `gh api repos/{o}/{r}/branches/<branch>` prints (missing: no classic protection)
50
+ // branch-rules-error.txt gh refusing the rules read (no token, no network)
51
+ // codeowners.json `{path, text}`, the CODEOWNERS file GitHub reads (missing: none)
52
+ // commit-<sha>.json what `gh api repos/{o}/{r}/commits/<sha>` prints, for getCommit (missing: not found)
53
+ // run-<id>.json what `gh api repos/{o}/{r}/actions/runs/<id>` prints, for getRun (missing: not found)
54
+ // ruleset-apply-error.txt gh refusing the ruleset write
55
+ // ruleset-calls.jsonl written: `{branch, rules}` per ruleset write; the rules are also added to
56
+ // branch-rules-<branch>.json, so a later read sees them
29
57
  // openPullRequest writes pr-<n>.json (n one above the highest there, else 1); updatePullRequestBody,
30
58
  // markReady and markDraft rewrite it, so a later getPullRequest or pullRequestForBranch sees the change.
31
59
  // A missing file is what the real host says for "not there"; an unreadable one is a host failure.
@@ -75,9 +103,70 @@ function readPr(dir, n) {
75
103
  return raw;
76
104
  }
77
105
 
106
+ const branchFile = (dir, kind, branch) => path.join(dir, `${kind}-${branch.replace(/\//g, '%2F')}.json`);
107
+
78
108
  export function fixtureHost(dir) {
79
109
  return {
80
110
  kind: 'fixture',
111
+ readBranchRules(branch) {
112
+ assertBranch(branch);
113
+ refuse(dir, 'branch-rules-error.txt', 'gh api');
114
+ const rules = readJson(branchFile(dir, 'branch-rules', branch));
115
+ if (rules === undefined) throw new GitHostError(`git host fixture ${dir}: no branch-rules-${branch}.json`);
116
+ return mapBranchRules(rules, readJson(branchFile(dir, 'branch', branch)) ?? null);
117
+ },
118
+ readWorkflowPermissions() {
119
+ refuse(dir, 'workflow-permissions-error.txt', 'gh api');
120
+ const raw = readJson(path.join(dir, 'workflow-permissions.json'));
121
+ if (raw === undefined) return null;
122
+ const got = mapWorkflowPermissions(raw);
123
+ if (got === null) throw new GitHostError('git host fixture workflow-permissions.json: needs can_approve_pull_request_reviews');
124
+ return got;
125
+ },
126
+ // As the GitHub host: commit-<sha>.json mapped by mapCommit; a missing file is a commit the host
127
+ // does not have.
128
+ getCommit(sha) {
129
+ assertSha(sha);
130
+ const raw = readJson(path.join(dir, `commit-${sha}.json`));
131
+ if (raw === undefined) throw new GitHostNotFound(`gh api commits/${sha}: not found`);
132
+ const got = mapCommit(raw);
133
+ if (got === null) throw new GitHostError(`git host fixture commit-${sha}.json: needs commit.verification.verified`);
134
+ return got;
135
+ },
136
+ // As the GitHub host: run-<id>.json mapped by mapRun; a missing file is a run the host does not have.
137
+ getRun(id) {
138
+ const run = assertRunId(id);
139
+ const raw = readJson(path.join(dir, `run-${run}.json`));
140
+ if (raw === undefined) throw new GitHostNotFound(`gh api actions/runs/${run}: not found`);
141
+ const got = mapRun(raw);
142
+ if (got === null) throw new GitHostError(`git host fixture run-${run}.json: needs name and head_sha`);
143
+ return got;
144
+ },
145
+ readCodeowners() {
146
+ const got = readJson(path.join(dir, 'codeowners.json'));
147
+ if (got === undefined) return null;
148
+ if (typeof got?.path !== 'string' || typeof got?.text !== 'string') throw new GitHostError('git host fixture codeowners.json: needs {path, text}');
149
+ return { path: got.path, text: got.text };
150
+ },
151
+ // As the GitHub host: the rules of branch-rules-<branch>.json whose ruleset_id is "slicekit" are
152
+ // the slicekit ruleset; only they lose a check not in rules.kitChecks. Nothing changed, nothing written.
153
+ applyBranchRules(branch, rules) {
154
+ assertBranch(branch);
155
+ refuse(dir, 'ruleset-apply-error.txt', 'gh api');
156
+ const file = branchFile(dir, 'branch-rules', branch);
157
+ const now = readJson(file) ?? [];
158
+ const mine = now.filter((r) => r?.ruleset_id === RULESET_NAME);
159
+ const others = now.filter((r) => r?.ruleset_id !== RULESET_NAME);
160
+ const { rules: pruned, removed } = pruneRulesetChecks(mine, rules.kitChecks);
161
+ const added = rulesetRules(rules).map((r) => ({ ...r, ruleset_source_type: 'Repository', ruleset_source: 'fixture', ruleset_id: RULESET_NAME }));
162
+ if (added.length === 0 && removed.length === 0) return { id: null, name: RULESET_NAME, created: false, removedChecks: [] };
163
+ const { kitChecks, ...set } = rules;
164
+ fs.appendFileSync(path.join(dir, 'ruleset-calls.jsonl'), `${JSON.stringify({ branch, rules: set, ...(removed.length > 0 ? { removedChecks: removed } : {}) })}
165
+ `);
166
+ fs.writeFileSync(file, `${JSON.stringify([...others, ...pruned, ...added], null, 2)}
167
+ `);
168
+ return { id: null, name: RULESET_NAME, created: mine.length === 0, removedChecks: removed };
169
+ },
81
170
  getPullRequest(n) {
82
171
  assertPrNumber(n);
83
172
  const raw = readJson(path.join(dir, `pr-${n}.json`));
@@ -147,6 +236,23 @@ export function fixtureHost(dir) {
147
236
  writePr(dir, { ...raw, isDraft: true });
148
237
  recordPr(dir, { op: 'markDraft', number: n });
149
238
  },
239
+ dispatchWorkflow(file, ref) {
240
+ assertWorkflowFile(file);
241
+ assertBranch(ref);
242
+ refuse(dir, 'dispatch-error.txt', 'gh workflow run');
243
+ recordPr(dir, { op: 'dispatchWorkflow', file, ref });
244
+ },
245
+ listOpenPullRequests() {
246
+ return mapOpenPullRequests(prNumbers(dir).map((n) => readJson(prFile(dir, n))).filter((raw) => raw?.state === 'OPEN'));
247
+ },
248
+ closePullRequest(n, comment) {
249
+ assertPrNumber(n);
250
+ assertComment(comment);
251
+ refuse(dir, 'pr-close-error.txt', 'gh pr close');
252
+ const raw = readPr(dir, n);
253
+ writePr(dir, { ...raw, state: 'CLOSED' });
254
+ recordPr(dir, { op: 'closePullRequest', number: n, comment });
255
+ },
150
256
  // As the GitHub host: the open pull requests with that head, a fork's (isCrossRepository) dropped.
151
257
  pullRequestForBranch(branch, { base } = {}) {
152
258
  assertBranch(branch);
@@ -32,6 +32,14 @@ export function assertBranch(name) {
32
32
  return name;
33
33
  }
34
34
 
35
+ // A workflow as `gh workflow run` takes it: a file name under .github/workflows/, nothing else.
36
+ export function assertWorkflowFile(file) {
37
+ if (typeof file !== 'string' || !/^[A-Za-z0-9_][A-Za-z0-9._-]*\.ya?ml$/.test(file)) {
38
+ throw new Error(`workflow must be a .yml file name, got ${JSON.stringify(file)}`);
39
+ }
40
+ return file;
41
+ }
42
+
35
43
  // A pull request title as gh takes it: one non-empty line.
36
44
  export function assertTitle(title) {
37
45
  if (typeof title !== 'string' || title.trim() === '' || /[\r\n]/.test(title)) {
@@ -164,3 +172,196 @@ export function commandJobsVerdict(run, jobs) {
164
172
  if (commands.length > 0 && commands.every((j) => j.status === 'completed' && j.conclusion === 'success')) return 'passed';
165
173
  return 'other';
166
174
  }
175
+
176
+ // REQ-3.14, D-84: the rules of the repository rulesets that apply to a branch, as
177
+ // `GET repos/{owner}/{repo}/rules/branches/{branch}` prints them (one entry per rule per ruleset),
178
+ // folded into one view: the strictest value any ruleset sets. `branch` is what
179
+ // `GET repos/{owner}/{repo}/branches/{branch}` prints, or null; its `protection.enabled` is true when
180
+ // classic branch protection is on, which the kit does not read beyond that flag.
181
+ export function mapBranchRules(rules, branch = null) {
182
+ if (!Array.isArray(rules)) throw new Error('branch rules: expected an array of rules');
183
+ const of = (type) => rules.filter((r) => r?.type === type);
184
+ const pr = of('pull_request').map((r) => r.parameters ?? {});
185
+ const counts = pr.map((p) => (Number.isInteger(p.required_approving_review_count) ? p.required_approving_review_count : 0));
186
+ const checks = of('required_status_checks').flatMap((r) => r.parameters?.required_status_checks ?? []);
187
+ return {
188
+ pullRequest: pr.length > 0,
189
+ approvals: counts.length > 0 ? Math.max(...counts) : 0,
190
+ codeOwnerReview: pr.some((p) => p.require_code_owner_review === true),
191
+ requiredChecks: [...new Set(checks.map((c) => c?.context).filter((c) => typeof c === 'string' && c !== ''))],
192
+ refuseForcePush: of('non_fast_forward').length > 0,
193
+ classic: branch?.protection?.enabled === true,
194
+ ruleCount: rules.length,
195
+ };
196
+ }
197
+
198
+ // The name of the one ruleset `slicekit init --protect` writes.
199
+ export const RULESET_NAME = 'slicekit';
200
+
201
+ // The rules to set, in the shape mapBranchRules reads, as GitHub ruleset rules. `set` holds only the
202
+ // keys to set: pullRequest, approvals and codeOwnerReview (any of them gives one pull_request rule,
203
+ // with at least one approval), requiredChecks (names) and refuseForcePush.
204
+ export function rulesetRules(set) {
205
+ const out = [];
206
+ if (set.pullRequest || set.approvals !== undefined || set.codeOwnerReview) {
207
+ out.push({
208
+ type: 'pull_request',
209
+ parameters: {
210
+ required_approving_review_count: Math.max(1, Number.isInteger(set.approvals) ? set.approvals : 1),
211
+ dismiss_stale_reviews_on_push: false,
212
+ require_code_owner_review: set.codeOwnerReview === true,
213
+ require_last_push_approval: false,
214
+ required_review_thread_resolution: false,
215
+ },
216
+ });
217
+ }
218
+ if (Array.isArray(set.requiredChecks) && set.requiredChecks.length > 0) {
219
+ out.push({
220
+ type: 'required_status_checks',
221
+ parameters: { strict_required_status_checks_policy: false, required_status_checks: set.requiredChecks.map((context) => ({ context })) },
222
+ });
223
+ }
224
+ if (set.refuseForcePush) out.push({ type: 'non_fast_forward' });
225
+ return out;
226
+ }
227
+
228
+ // An existing slicekit ruleset's rules with `add` folded in: the strictest pull_request rule, the union
229
+ // of required checks, and any other rule type kept once.
230
+ export function mergeRulesetRules(existing, add) {
231
+ const byType = new Map();
232
+ for (const r of [...(existing ?? []), ...add]) {
233
+ const prev = byType.get(r.type);
234
+ if (!prev) {
235
+ byType.set(r.type, { type: r.type, ...(r.parameters ? { parameters: { ...r.parameters } } : {}) });
236
+ } else if (r.type === 'pull_request') {
237
+ const a = prev.parameters;
238
+ const b = r.parameters ?? {};
239
+ a.required_approving_review_count = Math.max(a.required_approving_review_count ?? 0, b.required_approving_review_count ?? 0);
240
+ a.require_code_owner_review = a.require_code_owner_review === true || b.require_code_owner_review === true;
241
+ } else if (r.type === 'required_status_checks') {
242
+ const seen = new Set(prev.parameters.required_status_checks.map((c) => c.context));
243
+ for (const c of r.parameters?.required_status_checks ?? []) if (!seen.has(c.context)) prev.parameters.required_status_checks.push(c);
244
+ }
245
+ }
246
+ return [...byType.values()];
247
+ }
248
+
249
+ // The ruleset body for `branch`: one active branch ruleset named slicekit.
250
+ export function rulesetBody(branch, rules) {
251
+ return {
252
+ name: RULESET_NAME,
253
+ target: 'branch',
254
+ enforcement: 'active',
255
+ conditions: { ref_name: { include: [`refs/heads/${branch}`], exclude: [] } },
256
+ rules,
257
+ };
258
+ }
259
+
260
+ // The paths GitHub reads CODEOWNERS from, in the order it looks; the first one present counts.
261
+ export const CODEOWNERS_PATHS = ['.github/CODEOWNERS', 'CODEOWNERS', 'docs/CODEOWNERS'];
262
+
263
+ // A remote URL as { host, owner, repo }, or null when it names no host (a local path, file://).
264
+ // Takes https://host[:port]/owner/repo(.git), ssh://[user@]host[:port]/owner/repo(.git) and
265
+ // [user@]host:owner/repo(.git).
266
+ export function parseRemoteUrl(url) {
267
+ const text = String(url ?? '').trim();
268
+ let host;
269
+ let rest;
270
+ let m = /^(?:https?):\/\/(?:[^@/]+@)?([^/]+)\/(.+)$/i.exec(text);
271
+ if (m) [, host, rest] = m;
272
+ else if ((m = /^ssh:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/i.exec(text))) [, host, rest] = m;
273
+ else if ((m = /^(?:[^@/]+@)?([A-Za-z0-9.-]+):(?!\/)(.+)$/.exec(text)) && m[1].includes('.')) [, host, rest] = m;
274
+ else return null;
275
+ const parts = rest.replace(/\/+$/, '').replace(/\.git$/i, '').split('/');
276
+ const name = /^[A-Za-z0-9_.-]+$/;
277
+ if (parts.length !== 2 || !parts.every((p) => name.test(p) && p !== '.' && p !== '..')) return null;
278
+ if (!/^[A-Za-z0-9.-]+(?::\d+)?$/.test(host)) return null;
279
+ return { host: host.toLowerCase(), owner: parts[0], repo: parts[1] };
280
+ }
281
+
282
+ // The slicekit ruleset's rules with every required check not in `kitChecks` taken out (03 REQ-3.14):
283
+ // a check the generated workflow no longer writes would hold every pull request waiting. A
284
+ // required_status_checks rule left with no check is dropped. Returns { rules, removed }.
285
+ export function pruneRulesetChecks(rules, kitChecks) {
286
+ if (!Array.isArray(kitChecks)) return { rules, removed: [] };
287
+ const keep = new Set(kitChecks);
288
+ const removed = [];
289
+ const out = [];
290
+ for (const r of rules ?? []) {
291
+ if (r.type !== 'required_status_checks') {
292
+ out.push(r);
293
+ continue;
294
+ }
295
+ const checks = (r.parameters?.required_status_checks ?? []).filter((c) => {
296
+ if (keep.has(c.context)) return true;
297
+ removed.push(c.context);
298
+ return false;
299
+ });
300
+ if (checks.length > 0) out.push({ ...r, parameters: { ...r.parameters, required_status_checks: checks } });
301
+ }
302
+ return { rules: out, removed };
303
+ }
304
+
305
+ // The fields `gh pr list` prints for listOpenPullRequests.
306
+ export const OPEN_PR_FIELDS = 'number,url,title,isCrossRepository,baseRefName,headRefName';
307
+
308
+ // listOpenPullRequests's answer from what `gh pr list --state open --json OPEN_PR_FIELDS` prints:
309
+ // [{ number, url, title, head, base }], this repository's own branches only (a fork's dropped).
310
+ export function mapOpenPullRequests(list) {
311
+ return (Array.isArray(list) ? list : [])
312
+ .filter((p) => p && p.isCrossRepository !== true && Number.isInteger(p.number) && typeof p.headRefName === 'string')
313
+ .map((p) => ({ number: p.number, url: p.url ?? null, title: typeof p.title === 'string' ? p.title : '', head: p.headRefName, base: p.baseRefName ?? null }))
314
+ .sort((a, b) => a.number - b.number);
315
+ }
316
+
317
+ // A comment as `gh pr close --comment` takes it: non-empty text.
318
+ export function assertComment(text) {
319
+ if (typeof text !== 'string' || text.trim() === '') throw new Error(`comment must be non-empty text, got ${JSON.stringify(text)}`);
320
+ return text;
321
+ }
322
+
323
+ // readWorkflowPermissions's answer from what `gh api repos/{o}/{r}/actions/permissions/workflow`
324
+ // prints: { canCreatePullRequests, defaultPermissions }. `can_approve_pull_request_reviews` is the
325
+ // repository setting "Allow GitHub Actions to create and approve pull requests". Returns null for an
326
+ // answer without it, which the caller reports as not read.
327
+ export function mapWorkflowPermissions(raw) {
328
+ if (raw === null || typeof raw !== 'object' || typeof raw.can_approve_pull_request_reviews !== 'boolean') return null;
329
+ return {
330
+ canCreatePullRequests: raw.can_approve_pull_request_reviews,
331
+ defaultPermissions: typeof raw.default_workflow_permissions === 'string' ? raw.default_workflow_permissions : null,
332
+ };
333
+ }
334
+
335
+ // A run id as the host numbers it: a positive whole number, given as a number or its digits.
336
+ export function assertRunId(id) {
337
+ const s = String(id ?? '');
338
+ if (!/^[1-9][0-9]{0,19}$/.test(s)) throw new Error(`run id must be a positive whole number, got '${id}'`);
339
+ return s;
340
+ }
341
+
342
+ const login = (u) => (typeof u?.login === 'string' && u.login !== '' ? u.login : null);
343
+
344
+ // getCommit's answer from what `gh api repos/{o}/{r}/commits/<sha>` prints: { verified, signer }.
345
+ // `verified` is the host's own `commit.verification.verified`, true only when the host checked the
346
+ // signature against a key on the signer's account (03 REQ-3.8, D-71). `signer` is the committer's
347
+ // login when verified (the account the key belongs to), else null. Returns null for an answer without
348
+ // a verification block, which the caller reports as not read.
349
+ export function mapCommit(raw) {
350
+ const v = raw?.commit?.verification;
351
+ if (v === null || typeof v !== 'object' || typeof v.verified !== 'boolean') return null;
352
+ return { verified: v.verified, signer: v.verified ? (login(raw.committer) ?? login(raw.author)) : null };
353
+ }
354
+
355
+ // getRun's answer from what `gh api repos/{o}/{r}/actions/runs/<id>` prints:
356
+ // { workflow, headSha, actor, conclusion }. `workflow` is the run's name (the workflow's `name:`, which
357
+ // GITHUB_WORKFLOW carries), `actor` the actor who started the run (GITHUB_ACTOR), never the
358
+ // triggering actor, which a re-run changes, `conclusion` null while the run is in progress. Returns null for an answer without a name or head sha.
359
+ export function mapRun(raw) {
360
+ if (raw === null || typeof raw !== 'object' || typeof raw.name !== 'string' || typeof raw.head_sha !== 'string') return null;
361
+ return {
362
+ workflow: raw.name,
363
+ headSha: raw.head_sha,
364
+ actor: login(raw.actor),
365
+ conclusion: typeof raw.conclusion === 'string' ? raw.conclusion : null,
366
+ };
367
+ }
@@ -8,8 +8,24 @@ import {
8
8
  assertLabelColor,
9
9
  assertPrNumber,
10
10
  assertTitle,
11
+ assertWorkflowFile,
12
+ assertComment,
13
+ mapOpenPullRequests,
14
+ mapWorkflowPermissions,
15
+ mapCommit,
16
+ mapRun,
17
+ assertRunId,
18
+ OPEN_PR_FIELDS,
11
19
  BRANCH_PR_FIELDS,
20
+ CODEOWNERS_PATHS,
12
21
  filterMergedSince,
22
+ mapBranchRules,
23
+ mergeRulesetRules,
24
+ parseRemoteUrl,
25
+ pruneRulesetChecks,
26
+ RULESET_NAME,
27
+ rulesetBody,
28
+ rulesetRules,
13
29
  mapPullRequest,
14
30
  parsePullRequestUrl,
15
31
  pickBranchPullRequest,
@@ -34,6 +50,9 @@ export function ghExitError(args, stderr) {
34
50
  if (args[0] === 'pr' && args[1] === 'view' && /Could not resolve to a PullRequest/i.test(stderr)) {
35
51
  return new GitHostNotFound(`pull request ${args[2]} not found`, { stderr });
36
52
  }
53
+ if (args[0] === 'api' && /\(HTTP 404\)/.test(stderr)) {
54
+ return new GitHostNotFound(`gh api ${args.at(-1)}: not found`, { stderr });
55
+ }
37
56
  const first = stderr.split(/\r?\n/).find((l) => l.trim() !== '')?.trim() ?? '';
38
57
  return new GitHostError(`gh ${args.slice(0, 2).join(' ')} failed: ${redact(first)}`, { stderr });
39
58
  }
@@ -62,8 +81,112 @@ export function githubHost(env = process.env, root = process.cwd(), exec = execF
62
81
  throw new GitHostError(`gh ${args.slice(0, 2).join(' ')} printed something that is not JSON: ${e.message}`);
63
82
  }
64
83
  };
84
+ // REQ-3.14, D-70: `gh api` takes the host from --hostname, never from the remote, so the host and
85
+ // the repository are read from the origin remote here, once, and passed on every call.
86
+ let remote;
87
+ const origin = () => {
88
+ if (remote) return remote;
89
+ let url;
90
+ try {
91
+ url = String(exec('git', ['remote', 'get-url', 'origin'], { encoding: 'utf8', cwd: root, env, stdio: ['ignore', 'pipe', 'pipe'] })).trim();
92
+ } catch (e) {
93
+ throw new GitHostError(`the origin remote could not be read: ${redact(String(e.stderr ?? e.message).trim())}`);
94
+ }
95
+ const parsed = parseRemoteUrl(url);
96
+ if (parsed === null) throw new GitHostError(`the origin remote names no git host: ${redact(url)}`);
97
+ remote = parsed;
98
+ return remote;
99
+ };
100
+ const api = (endpoint, { method, body } = {}) => {
101
+ const { host } = origin();
102
+ const args = ['api', '--hostname', host, ...(method ? ['--method', method, '--input', '-'] : []), endpoint];
103
+ const out = gh(exec, args, { env, cwd: root, ...(method ? { input: JSON.stringify(body) } : {}) });
104
+ try {
105
+ return JSON.parse(out);
106
+ } catch (e) {
107
+ throw new GitHostError(`gh api ${endpoint} printed something that is not JSON: ${e.message}`);
108
+ }
109
+ };
110
+ const repoPath = () => `repos/${origin().owner}/${origin().repo}`;
111
+ const branchPath = (branch) => branch.split('/').map(encodeURIComponent).join('/');
65
112
  return {
66
113
  kind: 'github',
114
+ // The rules of the repository rulesets that apply to `branch` (D-84), and whether classic branch
115
+ // protection is on, which only decides the message.
116
+ readBranchRules(branch) {
117
+ assertBranch(branch);
118
+ const rules = api(`${repoPath()}/rules/branches/${branchPath(branch)}?per_page=100`);
119
+ return mapBranchRules(rules, api(`${repoPath()}/branches/${branchPath(branch)}`));
120
+ },
121
+ // The CODEOWNERS file GitHub reads on the default branch, as { path, text }, or null.
122
+ // The repository's Actions workflow permissions (REQ-3.11, REQ-3.14): whether "Allow GitHub Actions
123
+ // to create and approve pull requests" is on, which the sync job's `gh pr create` needs. Reading it
124
+ // needs a token with the repository's administration read; the workflow's own token has none, so in
125
+ // CI this is a GitHostError the caller reports as not read.
126
+ readWorkflowPermissions() {
127
+ const got = mapWorkflowPermissions(api(`${repoPath()}/actions/permissions/workflow`));
128
+ if (got === null) throw new GitHostError('the Actions workflow permissions answer has no can_approve_pull_request_reviews');
129
+ return got;
130
+ },
131
+ // Whether the host verified the signature of commit `sha` (03 REQ-3.8, D-71): { verified, signer }
132
+ // from `GET repos/{owner}/{repo}/commits/{sha}`. The journal rule calls it under --ci for each
133
+ // commit of the pull request that changes a journal file. The kit manages no keys; the host checks
134
+ // the signature against the keys on the signer's account.
135
+ getCommit(sha) {
136
+ assertSha(sha);
137
+ const got = mapCommit(api(`${repoPath()}/commits/${sha}`));
138
+ if (got === null) throw new GitHostError(`gh api printed commit ${sha} with no verification`);
139
+ return got;
140
+ },
141
+ // The CI run `id` as the host reports it (03 REQ-3.8, D-89): { workflow, headSha, actor, conclusion }
142
+ // from `GET repos/{owner}/{repo}/actions/runs/{id}`. The journal rule recomputes each line the
143
+ // journal-heads file gains from it.
144
+ getRun(id) {
145
+ const run = assertRunId(id);
146
+ const got = mapRun(api(`${repoPath()}/actions/runs/${run}`));
147
+ if (got === null) throw new GitHostError(`gh api printed run ${run} with no name or head sha`);
148
+ return got;
149
+ },
150
+ readCodeowners() {
151
+ for (const file of CODEOWNERS_PATHS) {
152
+ let got;
153
+ try {
154
+ got = api(`${repoPath()}/contents/${file}`);
155
+ } catch (e) {
156
+ if (e instanceof GitHostNotFound) continue;
157
+ throw e;
158
+ }
159
+ if (got?.type !== 'file' || typeof got.content !== 'string') continue;
160
+ return { path: file, text: Buffer.from(got.content, got.encoding === 'base64' ? 'base64' : 'utf8').toString('utf8') };
161
+ }
162
+ return null;
163
+ },
164
+ // Sets `rules` (rulesetRules' input) on `branch` as the one repository ruleset named slicekit:
165
+ // created, or, when the repository has one, updated with the rules folded in. With
166
+ // `rules.kitChecks`, a required check of the slicekit ruleset that is not in that list is taken
167
+ // out; no other ruleset is touched. Writes nothing when nothing changes. Returns
168
+ // { id, name, created, removedChecks }. The only host write of a rule; `slicekit init --protect`
169
+ // is its one caller (REQ-3.14).
170
+ applyBranchRules(branch, rules) {
171
+ assertBranch(branch);
172
+ const add = rulesetRules(rules);
173
+ const list = api(`${repoPath()}/rulesets?includes_parents=false&per_page=100`);
174
+ const mine = (Array.isArray(list) ? list : []).find((r) => r?.name === RULESET_NAME && r?.source_type !== 'Organization');
175
+ if (!mine) {
176
+ if (add.length === 0) return { id: null, name: RULESET_NAME, created: false, removedChecks: [] };
177
+ const made = api(`${repoPath()}/rulesets`, { method: 'POST', body: rulesetBody(branch, add) });
178
+ return { id: made?.id ?? null, name: RULESET_NAME, created: true, removedChecks: [] };
179
+ }
180
+ if (!Number.isInteger(mine.id)) throw new GitHostError('gh api printed a ruleset with no id');
181
+ const full = api(`${repoPath()}/rulesets/${mine.id}`);
182
+ const { rules: pruned, removed } = pruneRulesetChecks(mergeRulesetRules(full?.rules, add), rules.kitChecks);
183
+ if (add.length === 0 && removed.length === 0) return { id: mine.id, name: RULESET_NAME, created: false, removedChecks: [] };
184
+ const include = [...new Set([...(full?.conditions?.ref_name?.include ?? []), `refs/heads/${branch}`])];
185
+ const body = { ...rulesetBody(branch, pruned), conditions: { ref_name: { include, exclude: full?.conditions?.ref_name?.exclude ?? [] } } };
186
+ if (Array.isArray(full?.bypass_actors)) body.bypass_actors = full.bypass_actors;
187
+ api(`${repoPath()}/rulesets/${mine.id}`, { method: 'PUT', body });
188
+ return { id: mine.id, name: RULESET_NAME, created: false, removedChecks: removed };
189
+ },
67
190
  getPullRequest(n) {
68
191
  assertPrNumber(n);
69
192
  return mapPullRequest(ghJson(['pr', 'view', String(n), '--json', PR_FIELDS]));
@@ -131,6 +254,24 @@ export function githubHost(env = process.env, root = process.cwd(), exec = execF
131
254
  const list = ghJson(['pr', 'list', '--head', branch, '--state', 'open', '--json', BRANCH_PR_FIELDS]);
132
255
  return pickBranchPullRequest(list, branch, base);
133
256
  },
257
+ // Every open pull request of this repository, as [{ number, url, title, head, base }] (a fork's
258
+ // dropped), oldest first. The sync job reads it to close the [sync] pull requests a newer one replaces.
259
+ listOpenPullRequests() {
260
+ return mapOpenPullRequests(ghJson(['pr', 'list', '--state', 'open', '--limit', '200', '--json', OPEN_PR_FIELDS]));
261
+ },
262
+ // Closes pull request `n` with a comment saying why; the branch stays. Needs pull-requests: write.
263
+ closePullRequest(n, comment) {
264
+ assertPrNumber(n);
265
+ assertComment(comment);
266
+ gh(exec, ['pr', 'close', String(n), `--comment=${comment}`], { env, cwd: root });
267
+ },
268
+ // Starts the workflow `file` on branch `ref` with workflow_dispatch (D-80): a pull request opened
269
+ // with the workflow's own token starts no run, and this is how its checks run. Needs actions: write.
270
+ dispatchWorkflow(file, ref) {
271
+ assertWorkflowFile(file);
272
+ assertBranch(ref);
273
+ gh(exec, ['workflow', 'run', file, `--ref=${ref}`], { env, cwd: root });
274
+ },
134
275
  // Creates the label, or with --force updates its colour and description: safe to run every time.
135
276
  ensureLabel(name, { color, description }) {
136
277
  assertLabel(name);
@@ -1,14 +1,18 @@
1
1
  import { TrackerError } from './errors.js';
2
2
  import { fixtureTracker } from './fixture.js';
3
3
  import { githubIssues } from './github-issues.js';
4
+ import { jiraTracker } from './jira.js';
4
5
 
5
6
  export { TrackerError };
6
7
 
7
- // C-2: the only door to a tracker. A second tracker (Jira) is a second file and one more branch here.
8
+ // C-2: the only door to a tracker. Each tracker is one file and one branch here; Jira validates its
9
+ // own config keys (D-74), so src/config.js checks only that tracker.kind is a string.
8
10
  // `root` is the project the tracker is asked about; gh reads the repository from it.
11
+ // GitHub Issues answers synchronously; Jira answers with promises, so a caller awaits each answer.
9
12
  export function getTracker(cfg, env = process.env, root = process.cwd()) {
10
13
  if (env.SLICEKIT_TRACKER_FIXTURE) return fixtureTracker(env.SLICEKIT_TRACKER_FIXTURE);
11
14
  const kind = cfg?.tracker?.kind;
12
15
  if (kind === 'github-issues') return githubIssues(env, root);
16
+ if (kind === 'jira') return jiraTracker(cfg, env);
13
17
  throw new TrackerError(`unsupported tracker: ${kind}`);
14
18
  }