@warren-dean/code-kit 0.24.0 → 0.25.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.
@@ -9,7 +9,7 @@
9
9
  "name": "code-kit",
10
10
  "source": "./",
11
11
  "description": "Keeps AI coding agents inside your project's rules, from idea to merged code: spec design, lanes, layer rules, protected paths with an approval log, spec-check and design gates, proof-before-finish checks, dispatch, review, build status and CI verification, configured per project from its docs",
12
- "version": "0.24.0",
12
+ "version": "0.25.0",
13
13
  "category": "development",
14
14
  "tags": ["guardrails", "architecture", "lanes", "layers", "spec-driven", "ci", "multi-agent"],
15
15
  "license": "MIT"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "code-kit",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Keeps AI coding agents inside your project's rules, from idea to merged code: spec design, lanes, layer rules, protected paths with an approval log, spec-check and design gates, proof-before-finish checks, dispatch, review, build status and CI verification, configured per project from its docs",
5
5
  "author": {
6
6
  "name": "Warren Langeveldt"
package/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  What changed in each release of code-kit, newest first. Versions follow the plugin manifest and the npm package `@warren-dean/code-kit`. Each release is also on [GitHub Releases](https://github.com/warrendeanlangeveldt/code-kit/releases).
4
4
 
5
+ ## 0.25.0 (2026-10-25)
6
+
7
+ code-kit spends far fewer GitHub Actions minutes: a project's full CI runs once per release instead of once per story, and you can see what it costs.
8
+
9
+ - code-kit's own workflow now checks the rules only (`verify --no-checks`): ownership, layers, approvals, the design gate and the standards, which take seconds. The project's checks already ran in the merge queue before each story merged. The job stops after 10 minutes, and a new push cancels the run it replaces. A project whose workflow was written before this keeps it until you approve the change.
10
+ - `code-kit ci check` reads the project's workflows and lists what costs most with code-kit's way of working, with the fix for each: a workflow that runs on every push to the base branch, a slow workflow on every pull request, a job with no time limit, a pull request workflow that doesn't cancel the run a new push replaces, and code-kit's older workflow running the checks again. init runs it and proposes the changes, applied only as you approve them (approval `ci`), and `code-kit next` mentions them.
11
+ - `code-kit release <version>` cuts `release/<version>` from the base branch's head and pushes it, so the project's full CI runs there once. It names the stories merged since the last release branch, and refuses a branch that already exists. Releasing stays your decision: the lead never cuts one unasked.
12
+ - `code-kit ci usage [--days 7]` lists the project's Actions runs by workflow and trigger, with their minutes and how many were cancelled or failed. It says plainly when GitHub has stopped starting jobs for the account's billing.
13
+
5
14
  ## 0.24.0 (2026-10-25)
6
15
 
7
16
  Each lane agent can run on the model its story needs, instead of one model for every lane.
package/README.md CHANGED
@@ -418,7 +418,7 @@ It's a preview: it's tested end to end against a stand-in for GitHub, and has be
418
418
 
419
419
  ## Enforce it in CI
420
420
 
421
- The hooks only see Claude Code sessions. For everything else, init offers `.github/workflows/code-kit.yml` (from `templates/github-workflow.yml`). It runs `verify` on every pull request, through `npx @warren-dean/code-kit@<version>`, pinned so CI doesn't change under you. It needs no secret. Two settings to make: mark the `code-kit` check as required on the protected branches, and make sure the workflow installs what the project's checks run, since a check whose tool is missing is skipped, and listed as not run, unless it sets `ifMissing: "fail"`. Add gitleaks to the workflow for the secret scan of commits' content.
421
+ The hooks only see Claude Code sessions. For everything else, init offers `.github/workflows/code-kit.yml` (from `templates/github-workflow.yml`). It runs `verify --no-checks` on every pull request, through `npx @warren-dean/code-kit@<version>`, pinned so CI doesn't change under you: the rules, in seconds, with a 10-minute limit, and a new push cancels the run it replaces. The project's checks aren't run again there, because the merge queue ran them before each merge; the project's full CI runs on its release branches instead, once per release (`code-kit release <version>` cuts one). `code-kit ci check` says what in the project's own workflows still runs once per story, and `code-kit ci usage` what the project spent. The workflow needs no secret. Mark the `code-kit` check as required on the protected branches, and keep its install step: a fix story's test is run without its fix (REG-1). Add gitleaks to the workflow for the secret scan of commits' content.
422
422
 
423
423
  `verify` can't see spec-check reports, because `.claude/state/` isn't committed. Review covers those.
424
424
 
@@ -466,6 +466,9 @@ code-kit report "<title>" --what "…" [--expected …] [--command …] [--refus
466
466
  code-kit report [--json] | report send|discard <id> # the drafts; sending files it on code-kit's GitHub with your gh, which only you do
467
467
  code-kit stops [--session id] [--json] # finish checks that refused an agent's last stop and still fail
468
468
  code-kit sent-back <branch> [--reason "…"] # record a review's send-back: status shows the story as sent back until the branch moves on
469
+ code-kit ci check [--json] # what in the project's workflows runs once per story, or without a time limit, and the fix
470
+ code-kit ci usage [--days N] [--json] # the project's GitHub Actions runs and minutes, by workflow and trigger
471
+ code-kit release <version> # cut release/<version> from the base and push it: the project's full CI runs there once
469
472
  code-kit decisions [--json] [--all] # what waits on you in this session, and a count in each other one; --all lists every session's
470
473
  code-kit who # which session this is, whether it leads the project, and its task
471
474
  code-kit sessions [--json] # the sessions working the project, which one leads, and each one's task
package/bin/code-kit.mjs CHANGED
@@ -41,6 +41,9 @@
41
41
  // a working session's ad hoc task and the paths it leases
42
42
  // lanes [--json] | lanes release <lane>
43
43
  // the lanes running a story now, one each across sessions (spec 23)
44
+ // ci check [--json] | ci usage [--days N] [--json]
45
+ // what the project's CI spends and what multiplies it (spec 25)
46
+ // release <version> cut release/<version> from the base and push it: the full CI runs there
44
47
  // --config <file> reads a draft (.claude/code-kit.draft.json) instead of .claude/code-kit.json.
45
48
  import { execFileSync, spawnSync } from 'node:child_process';
46
49
  import {
@@ -169,6 +172,7 @@ import {
169
172
  worktrees,
170
173
  } from '../hooks/lib/worktrees.mjs';
171
174
  import { decisionsFor, openDecisions } from '../hooks/lib/decisionstore.mjs';
175
+ import { WORKFLOWS_DIR, ciFindings, ciUsage, releaseBranch } from '../hooks/lib/ci.mjs';
172
176
  import {
173
177
  appliesTo,
174
178
  projectStandards,
@@ -207,6 +211,7 @@ const callerSession = sessionId ?? process.env.CLAUDE_CODE_SESSION_ID ?? null;
207
211
  // A provider's command hears which session is calling, for that session's own live link.
208
212
  if (callerSession) process.env.CODE_KIT_SESSION = callerSession;
209
213
  const minutesGiven = option('--minutes');
214
+ const daysGiven = option('--days');
210
215
  const answerGiven = option('--answer');
211
216
  const leaseGiven = option('--lease');
212
217
  const touchesGiven = option('--touches');
@@ -1329,6 +1334,73 @@ function settings() {
1329
1334
  );
1330
1335
  }
1331
1336
 
1337
+ /**
1338
+ * CIC-2, CIC-4: `ci check` lists what in the project's workflows multiplies their cost with a story per
1339
+ * branch; `ci usage` sums the Actions runs of the last days, by workflow and trigger.
1340
+ */
1341
+ function ciCommand() {
1342
+ const { config } = load();
1343
+ const root = resolve('.');
1344
+ const [sub] = rest;
1345
+ if (sub === 'check') {
1346
+ const found = ciFindings(root, config.branches.protected[0]);
1347
+ if (flag('--json')) return out(JSON.stringify(found, null, 2));
1348
+ if (!found.length)
1349
+ return out(
1350
+ existsSync(join(root, WORKFLOWS_DIR))
1351
+ ? "Nothing in the project's workflows multiplies their cost: no full run per merge or pull request, every job has a time limit."
1352
+ : `No workflows in ${WORKFLOWS_DIR}.`,
1353
+ );
1354
+ let last = null;
1355
+ for (const f of found) {
1356
+ if (f.file !== last) out(`${last ? '\n' : ''}${f.file}`);
1357
+ last = f.file;
1358
+ out(` ${f.kind}: ${f.what}.\n Fix: ${f.fix}.`);
1359
+ }
1360
+ out(
1361
+ "\nChanging CI is the person's to approve (approval ci). A release then runs the full suite once: code-kit release <version>.",
1362
+ );
1363
+ return;
1364
+ }
1365
+ if (sub === 'usage') {
1366
+ const days = Number(daysGiven ?? 7);
1367
+ if (!Number.isFinite(days) || days <= 0) die('--days takes a number of days, such as 7.');
1368
+ const u = ciUsage(root, { days });
1369
+ if (u.error) die(u.error);
1370
+ if (flag('--json')) return out(JSON.stringify(u, null, 2));
1371
+ out(
1372
+ `${u.repo}, the last ${days} day${days === 1 ? '' : 's'}: ${u.runs} run${u.runs === 1 ? '' : 's'}, about ${u.minutes} minutes of wall-clock time (GitHub bills each job, rounded up to the minute, so the bill is at least this).`,
1373
+ );
1374
+ for (const r of u.rows)
1375
+ out(
1376
+ ` ${String(r.minutes).padStart(6)} min ${String(r.runs).padStart(4)} runs ${r.workflow} (${r.event})${r.cancelled ? `, ${r.cancelled} cancelled` : ''}${r.failed ? `, ${r.failed} failed` : ''}`,
1377
+ );
1378
+ if (u.refused)
1379
+ out(
1380
+ `\nGitHub isn't starting this project's jobs: ${u.refused} The project's CI isn't running at all until that's resolved in the account's Billing settings.`,
1381
+ );
1382
+ return;
1383
+ }
1384
+ usage();
1385
+ }
1386
+
1387
+ /** CIC-3: the release branch, cut from the base as committed and pushed, where the full CI runs once. */
1388
+ function releaseCommand(version) {
1389
+ const { config } = load();
1390
+ const from = base(config, false);
1391
+ const r = releaseBranch(resolve('.'), version, { base: from });
1392
+ if (!r.ok) die(`Not released: ${r.why}`);
1393
+ if (flag('--json')) return out(JSON.stringify(r, null, 2));
1394
+ out(
1395
+ `Cut ${r.branch} from ${from} at ${r.commit.slice(0, 7)} and pushed it: the project's full CI runs on it now.`,
1396
+ );
1397
+ out(
1398
+ r.stories.length
1399
+ ? `Stories in it since ${r.since ?? 'the start'}: ${r.stories.join(', ')}.`
1400
+ : `No story ids in its commits since ${r.since ?? 'the start'}.`,
1401
+ );
1402
+ }
1403
+
1332
1404
  /** Records the review's send-back of `branch` at its current commit (lib/reviews.mjs). */
1333
1405
  function sentBackCommand(branch) {
1334
1406
  load();
@@ -2534,6 +2606,8 @@ const commands = {
2534
2606
  journal: journalCommand,
2535
2607
  timeline,
2536
2608
  'sent-back': () => (rest.length === 1 ? sentBackCommand(rest[0]) : usage()),
2609
+ ci: ciCommand,
2610
+ release: () => (rest.length === 1 ? releaseCommand(rest[0]) : usage()),
2537
2611
  trace: () => (rest.length ? trace(rest) : usage()),
2538
2612
  adapters,
2539
2613
  next,
@@ -2566,6 +2640,7 @@ function usage() {
2566
2640
  ' | lanes [--json] | lanes release <lane> | sessions [--json] | sessions lead\n' +
2567
2641
  ' | who | task "<what>" --touches globs | task done | task take <session>\n' +
2568
2642
  ' | decisions [--json] [--all]\n' +
2643
+ ' | ci check [--json] | ci usage [--days N] [--json] | release <version>\n' +
2569
2644
  ' | hold <id> [--minutes N] | hold <id> --answer approved|refused\n' +
2570
2645
  ' | queue [--json] | queue add|drop <branch> | queue rules | queue merge --delegated|--person\n' +
2571
2646
  ' | loop [--json] | loop pause|resume | loop lead|release --session id [--take]\n' +
@@ -0,0 +1,407 @@
1
+ // What a project's CI costs (docs/specs/25-what-ci-costs.md). code-kit builds each story on its own branch
2
+ // and merges it on its own, so whatever CI runs per pull request or per merge runs once per story; the
3
+ // merge queue already ran the checks before each merge. `ciFindings` reads the workflows for what
4
+ // multiplies that cost (CIC-2), `usageSummary` sums what the project spent (CIC-4), and `releaseBranch`
5
+ // cuts the branch the full CI runs on instead (CIC-3).
6
+ import { execFileSync, spawnSync } from 'node:child_process';
7
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+
10
+ export const WORKFLOWS_DIR = '.github/workflows';
11
+ export const RELEASE_PREFIX = 'release/';
12
+ /** GitHub's own limit for a job without one: six hours. */
13
+ const GITHUB_LIMIT_MINUTES = 360;
14
+
15
+ // --- a YAML subset ---------------------------------------------------------------------------------
16
+
17
+ const unquote = (v) => {
18
+ const t = v.trim();
19
+ if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")))
20
+ return t.slice(1, -1);
21
+ return t;
22
+ };
23
+ const stripComment = (line) => {
24
+ let quote = null;
25
+ for (let i = 0; i < line.length; i++) {
26
+ const c = line[i];
27
+ if (quote) {
28
+ if (c === quote) quote = null;
29
+ } else if (c === '"' || c === "'") quote = c;
30
+ else if (c === '#' && (i === 0 || /\s/.test(line[i - 1]))) return line.slice(0, i);
31
+ }
32
+ return line;
33
+ };
34
+ const scalar = (v) => {
35
+ const t = v.trim();
36
+ if (t === '') return null;
37
+ if (t.startsWith('[') && t.endsWith(']'))
38
+ return t
39
+ .slice(1, -1)
40
+ .split(',')
41
+ .map((x) => unquote(x))
42
+ .filter(Boolean);
43
+ if (t.startsWith('{') && t.endsWith('}')) return {};
44
+ if (t === 'true') return true;
45
+ if (t === 'false') return false;
46
+ if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
47
+ return unquote(t);
48
+ };
49
+
50
+ /**
51
+ * The block maps, block lists and flow lists GitHub workflows are written in, as plain objects. Block
52
+ * scalars (`run: |`) are kept as their text. Anchors, tags and multi-document files aren't read.
53
+ */
54
+ export function parseYaml(text) {
55
+ const lines = String(text ?? '')
56
+ .split('\n')
57
+ .map((raw) => ({ raw, indent: raw.length - raw.trimStart().length }));
58
+ let i = 0;
59
+ const skipBlank = () => {
60
+ while (i < lines.length && !stripComment(lines[i].raw).trim()) i += 1;
61
+ };
62
+ const blockScalar = (indent) => {
63
+ const out = [];
64
+ while (i < lines.length && (!lines[i].raw.trim() || lines[i].indent > indent)) {
65
+ out.push(lines[i].raw.trim());
66
+ i += 1;
67
+ }
68
+ return out.join('\n').trim();
69
+ };
70
+ const node = (indent) => {
71
+ skipBlank();
72
+ if (i >= lines.length || lines[i].indent < indent) return null;
73
+ const first = stripComment(lines[i].raw).trim();
74
+ return first.startsWith('- ') || first === '-' ? list(lines[i].indent) : map(lines[i].indent);
75
+ };
76
+ const value = (rest, indent) => {
77
+ const r = rest.trim();
78
+ if (r === '|' || r === '>' || /^[|>][+-]?$/.test(r)) return blockScalar(indent);
79
+ if (r !== '') return scalar(r);
80
+ skipBlank();
81
+ if (i < lines.length && lines[i].indent > indent) return node(lines[i].indent);
82
+ // A list may sit at its key's own indentation.
83
+ if (i < lines.length && lines[i].indent === indent && /^-(\s|$)/.test(lines[i].raw.trim()))
84
+ return list(indent);
85
+ return null;
86
+ };
87
+ const map = (indent) => {
88
+ const out = {};
89
+ while (true) {
90
+ skipBlank();
91
+ if (i >= lines.length || lines[i].indent !== indent) break;
92
+ const line = stripComment(lines[i].raw).trim();
93
+ if (line.startsWith('- ')) break;
94
+ const m = /^("[^"]*"|'[^']*'|[^:]+?):(\s+|$)(.*)$/.exec(line);
95
+ i += 1;
96
+ if (!m) continue;
97
+ out[unquote(m[1])] = value(m[3], indent);
98
+ }
99
+ return out;
100
+ };
101
+ const list = (indent) => {
102
+ const out = [];
103
+ while (true) {
104
+ skipBlank();
105
+ if (i >= lines.length || lines[i].indent !== indent) break;
106
+ const line = stripComment(lines[i].raw).trim();
107
+ if (!/^-(\s|$)/.test(line)) break;
108
+ const rest = line.replace(/^-\s?/, '');
109
+ const kv = /^("[^"]*"|'[^']*'|[^:\s][^:]*?):(\s+|$)(.*)$/.exec(rest);
110
+ if (kv && !rest.startsWith('"') && !rest.startsWith("'")) {
111
+ // A map in a list: its first key is on the dash's line, the rest under it, past the dash.
112
+ const inner =
113
+ indent +
114
+ (lines[i].raw.slice(indent).length -
115
+ lines[i].raw.slice(indent).replace(/^-\s*/, '').length);
116
+ lines[i] = { raw: `${' '.repeat(inner)}${rest}`, indent: inner };
117
+ out.push(map(inner));
118
+ } else {
119
+ i += 1;
120
+ out.push(rest === '' ? node(indent + 1) : scalar(rest));
121
+ }
122
+ }
123
+ return out;
124
+ };
125
+ return node(0) ?? {};
126
+ }
127
+
128
+ // --- what costs most -------------------------------------------------------------------------------
129
+
130
+ /** A workflow's triggers as { event: config }, whichever way `on:` is written. */
131
+ export function triggersOf(doc) {
132
+ const on = doc?.on ?? doc?.true ?? null; // a bare `on` key can read as a boolean elsewhere
133
+ if (typeof on === 'string') return { [on]: null };
134
+ if (Array.isArray(on)) return Object.fromEntries(on.map((e) => [e, null]));
135
+ return on && typeof on === 'object' ? on : {};
136
+ }
137
+
138
+ const listOf = (v) => (Array.isArray(v) ? v : v === null || v === undefined ? [] : [v]);
139
+ const globMatch = (pattern, name) =>
140
+ new RegExp(
141
+ `^${String(pattern)
142
+ .replace(/[.+^${}()|[\]\\]/g, '\\$&')
143
+ .replace(/\*\*/g, '\u0000')
144
+ .replace(/\*/g, '[^/]*')
145
+ .replace(/\u0000/g, '.*')}$`,
146
+ ).test(name);
147
+
148
+ /** Whether a push trigger runs when `base` moves. */
149
+ function pushRunsOnBase(push, base) {
150
+ if (push === null || push === undefined) return true;
151
+ const branches = listOf(push.branches);
152
+ const ignored = listOf(push['branches-ignore']);
153
+ if (branches.length) return branches.some((b) => globMatch(b, base));
154
+ if (ignored.length) return !ignored.some((b) => globMatch(b, base));
155
+ // Tags (or paths) alone: a push of tags only isn't a merge.
156
+ return !(push.tags || push['tags-ignore']) || Boolean(push.paths);
157
+ }
158
+
159
+ const TESTING = /\b(test|tests|e2e|playwright|cypress|integration|pytest|vitest|jest)\b/i;
160
+ const runsCodeKitVerify = (step) =>
161
+ typeof step?.run === 'string' && /code-kit(@\S+)?\s+verify\b/.test(step.run.replace(/\n/g, ' '));
162
+
163
+ /**
164
+ * CIC-2: what in one workflow multiplies its cost with a story per branch: [{ file, kind, what, fix }].
165
+ * `base` is the branch lanes merge into.
166
+ */
167
+ export function workflowFindings(file, text, base) {
168
+ let doc;
169
+ try {
170
+ doc = parseYaml(text);
171
+ } catch {
172
+ return [];
173
+ }
174
+ const on = triggersOf(doc);
175
+ const jobs = doc.jobs && typeof doc.jobs === 'object' ? doc.jobs : {};
176
+ const steps = Object.values(jobs).flatMap((j) => (Array.isArray(j?.steps) ? j.steps : []));
177
+ const ours = steps.some(runsCodeKitVerify);
178
+ const out = [];
179
+ const add = (kind, what, fix) => out.push({ file, kind, what, fix });
180
+ if ('push' in on && pushRunsOnBase(on.push, base))
181
+ add(
182
+ 'every-merge',
183
+ `runs on every push to ${base}, so once per story merged; the merge queue already checked each one`,
184
+ `run it on the release branches instead: on: push: branches: ['${RELEASE_PREFIX}**']`,
185
+ );
186
+ const onPr = 'pull_request' in on || 'pull_request_target' in on;
187
+ const pr = on.pull_request ?? on.pull_request_target ?? null;
188
+ const filtered = Boolean(pr?.paths || pr?.['paths-ignore']);
189
+ if (
190
+ onPr &&
191
+ !ours &&
192
+ !filtered &&
193
+ steps.some((s) => TESTING.test(`${s?.name ?? ''} ${s?.run ?? ''} ${s?.uses ?? ''}`))
194
+ )
195
+ add(
196
+ 'every-pr',
197
+ 'runs its tests on every pull request, so once per story, after the merge queue ran them',
198
+ `run it on the release branches instead (on: push: branches: ['${RELEASE_PREFIX}**']), keeping a fast check on pull requests if the project wants one`,
199
+ );
200
+ const untimed = Object.entries(jobs)
201
+ .filter(([, j]) => j && typeof j === 'object' && !('timeout-minutes' in j) && !j.uses)
202
+ .map(([id]) => id);
203
+ if (untimed.length)
204
+ add(
205
+ 'no-timeout',
206
+ `${untimed.length === 1 ? 'job' : 'jobs'} ${untimed.join(', ')} ${untimed.length === 1 ? 'has' : 'have'} no timeout-minutes, so a hung step runs up to GitHub's ${GITHUB_LIMIT_MINUTES / 60} hours`,
207
+ 'give each job a timeout-minutes a little over its usual run',
208
+ );
209
+ const cancels = (c) => c && typeof c === 'object' && c['cancel-in-progress'] === true;
210
+ if (
211
+ onPr &&
212
+ !cancels(doc.concurrency) &&
213
+ !Object.values(jobs).every((j) => cancels(j?.concurrency))
214
+ )
215
+ add(
216
+ 'no-concurrency',
217
+ 'has no concurrency with cancel-in-progress, so every push to a pull request runs to the end',
218
+ 'add concurrency: { group: <workflow>-${{ github.head_ref || github.ref }}, cancel-in-progress: true }',
219
+ );
220
+ if (steps.some((s) => runsCodeKitVerify(s) && !/--no-checks\b/.test(s.run)))
221
+ add(
222
+ 'code-kit-checks',
223
+ "code-kit's verify runs the project's checks again on every pull request, after the merge queue ran them",
224
+ 'add --no-checks to its verify step',
225
+ );
226
+ return out;
227
+ }
228
+
229
+ /** CIC-2: every workflow's findings, in file order. */
230
+ export function ciFindings(root, base) {
231
+ const dir = join(root, WORKFLOWS_DIR);
232
+ if (!existsSync(dir)) return [];
233
+ return readdirSync(dir)
234
+ .filter((f) => /\.ya?ml$/.test(f))
235
+ .sort()
236
+ .flatMap((f) =>
237
+ workflowFindings(`${WORKFLOWS_DIR}/${f}`, readFileSync(join(dir, f), 'utf8'), base),
238
+ );
239
+ }
240
+
241
+ // --- what it spent ---------------------------------------------------------------------------------
242
+
243
+ /** GitHub refusing to start jobs for the account's billing, from a job's annotations. */
244
+ export const BILLING_REFUSAL = /spending limit|payments have failed|billing/i;
245
+
246
+ /**
247
+ * CIC-4: runs summed by workflow and trigger: { rows: [{ workflow, event, runs, minutes, cancelled,
248
+ * failed }], runs, minutes }, most minutes first. A run's minutes are its wall-clock time.
249
+ */
250
+ export function usageSummary(runs) {
251
+ const by = new Map();
252
+ let minutes = 0;
253
+ for (const r of runs) {
254
+ const start = Date.parse(r.run_started_at ?? r.created_at);
255
+ const end = Date.parse(r.updated_at);
256
+ const m =
257
+ Number.isFinite(start) && Number.isFinite(end) && end > start ? (end - start) / 60000 : 0;
258
+ const key = `${r.name}\u0000${r.event}`;
259
+ const row = by.get(key) ?? {
260
+ workflow: r.name,
261
+ event: r.event,
262
+ runs: 0,
263
+ minutes: 0,
264
+ cancelled: 0,
265
+ failed: 0,
266
+ };
267
+ row.runs += 1;
268
+ row.minutes += m;
269
+ if (r.conclusion === 'cancelled') row.cancelled += 1;
270
+ if (r.conclusion === 'failure' || r.conclusion === 'timed_out') row.failed += 1;
271
+ by.set(key, row);
272
+ minutes += m;
273
+ }
274
+ const rows = [...by.values()]
275
+ .map((r) => ({ ...r, minutes: Math.round(r.minutes) }))
276
+ .sort((a, b) => b.minutes - a.minutes || a.workflow.localeCompare(b.workflow));
277
+ return { rows, runs: runs.length, minutes: Math.round(minutes) };
278
+ }
279
+
280
+ const gh = (root, args) =>
281
+ spawnSync('gh', args, { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
282
+
283
+ /**
284
+ * CIC-4: the project's Actions runs over the last `days`, summed, and whether GitHub refused to start the
285
+ * latest run's jobs for billing: { repo, days, ...usageSummary, refused } or { error }.
286
+ */
287
+ export function ciUsage(root, { days = 7, now = Date.now() } = {}) {
288
+ const repo = gh(root, ['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']);
289
+ if (repo.error || repo.status !== 0)
290
+ return {
291
+ error: `GitHub's CLI couldn't say which repository this is${repo.stderr ? `: ${repo.stderr.trim().split('\n')[0]}` : ''}. Run it in a clone with a GitHub remote, signed in with gh auth login.`,
292
+ };
293
+ const name = repo.stdout.trim();
294
+ const since = new Date(now - days * 86_400_000).toISOString().slice(0, 10);
295
+ const listed = gh(root, [
296
+ 'api',
297
+ '--paginate',
298
+ `repos/${name}/actions/runs?created=%3E%3D${since}&per_page=100`,
299
+ '-q',
300
+ '.workflow_runs[] | {name, event, conclusion, run_started_at, created_at, updated_at, id}',
301
+ ]);
302
+ if (listed.status !== 0)
303
+ return { error: `GitHub didn't list the runs: ${listed.stderr.trim().split('\n')[0]}` };
304
+ const runs = listed.stdout
305
+ .split('\n')
306
+ .filter(Boolean)
307
+ .map((l) => JSON.parse(l));
308
+ let refused = null;
309
+ const latest = runs.find((r) => r.conclusion === 'failure');
310
+ if (latest && latest === runs[0]) {
311
+ const jobs = gh(root, [
312
+ 'api',
313
+ `repos/${name}/actions/runs/${latest.id}/jobs`,
314
+ '-q',
315
+ '.jobs[].id',
316
+ ]);
317
+ for (const id of jobs.stdout.split('\n').filter(Boolean).slice(0, 3)) {
318
+ const notes = gh(root, [
319
+ 'api',
320
+ `repos/${name}/check-runs/${id}/annotations`,
321
+ '-q',
322
+ '.[].message',
323
+ ]);
324
+ const hit = notes.stdout.split('\n').find((m) => BILLING_REFUSAL.test(m));
325
+ if (hit) {
326
+ refused = hit.trim();
327
+ break;
328
+ }
329
+ }
330
+ }
331
+ return { repo: name, days, ...usageSummary(runs), refused };
332
+ }
333
+
334
+ // --- the release branch ----------------------------------------------------------------------------
335
+
336
+ const git = (root, ...args) => {
337
+ try {
338
+ return execFileSync('git', ['-C', root, ...args], {
339
+ encoding: 'utf8',
340
+ stdio: ['ignore', 'pipe', 'pipe'],
341
+ }).trim();
342
+ } catch {
343
+ return null;
344
+ }
345
+ };
346
+
347
+ /** Version-aware order of release branches: release/0.10.0 after release/0.9.0. */
348
+ const byVersion = (a, b) => a.localeCompare(b, undefined, { numeric: true });
349
+
350
+ /**
351
+ * CIC-3: cuts `release/<version>` from `base` as committed and pushes it to `remote`, so the project's
352
+ * full CI runs once on it: { ok, branch, commit, stories, since } or { ok: false, why }.
353
+ */
354
+ export function releaseBranch(root, version, { base, remote = 'origin', push = true } = {}) {
355
+ const branch = `${RELEASE_PREFIX}${String(version).replace(/^release\//, '')}`;
356
+ if (!version || git(root, 'check-ref-format', '--branch', branch) === null)
357
+ return {
358
+ ok: false,
359
+ why: `${branch} isn't a branch name git accepts. Give a version such as 0.4.0.`,
360
+ };
361
+ const commit = git(root, 'rev-parse', '--verify', '--quiet', `${base}^{commit}`);
362
+ if (!commit) return { ok: false, why: `There's no ${base} here to release from.` };
363
+ const here = git(root, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}`);
364
+ const there = push ? git(root, 'ls-remote', '--heads', remote, branch) : '';
365
+ if (here || there)
366
+ return {
367
+ ok: false,
368
+ why: `${branch} already exists${here ? `, at ${here.slice(0, 7)}` : ` on ${remote}`}. A release branch is cut once; give the next version.`,
369
+ };
370
+ // The stories merged since the last release branch, by the ids their commits name.
371
+ const earlier = (
372
+ git(
373
+ root,
374
+ 'for-each-ref',
375
+ '--format=%(refname:short)',
376
+ `refs/heads/${RELEASE_PREFIX}`,
377
+ `refs/remotes/${remote}/${RELEASE_PREFIX}`,
378
+ ) ?? ''
379
+ )
380
+ .split('\n')
381
+ .filter(Boolean)
382
+ .sort(byVersion);
383
+ const since = earlier.at(-1) ?? null;
384
+ const log = git(root, 'log', '--format=%s%n%b', since ? `${since}..${commit}` : commit) ?? '';
385
+ const stories = [...new Set(log.match(/\bST-\d+\b/g) ?? [])].sort(
386
+ (a, b) => a.slice(3) - b.slice(3),
387
+ );
388
+ if (git(root, 'branch', branch, commit) === null)
389
+ return { ok: false, why: `git couldn't make ${branch} at ${commit.slice(0, 7)}.` };
390
+ if (push) {
391
+ const pushed = spawnSync(
392
+ 'git',
393
+ ['-C', root, 'push', remote, `refs/heads/${branch}:refs/heads/${branch}`],
394
+ {
395
+ encoding: 'utf8',
396
+ },
397
+ );
398
+ if (pushed.status !== 0) {
399
+ git(root, 'branch', '-D', branch);
400
+ return {
401
+ ok: false,
402
+ why: `Pushing ${branch} to ${remote} failed: ${(pushed.stderr || '').trim().split('\n').at(-1)}`,
403
+ };
404
+ }
405
+ }
406
+ return { ok: true, branch, commit, stories, since: since?.replace(`${remote}/`, '') ?? null };
407
+ }
@@ -14,7 +14,7 @@ import {
14
14
  } from './standards.mjs';
15
15
 
16
16
  /** The version of code-kit's instructions: raised whenever the templates' rules change. */
17
- export const INSTRUCTIONS_VERSION = 7;
17
+ export const INSTRUCTIONS_VERSION = 8;
18
18
 
19
19
  const TEMPLATES = fileURLToPath(new URL('../../templates/', import.meta.url));
20
20
  const BEGIN = (v) => `<!-- code-kit:begin v${v} -->`;
@@ -14,6 +14,7 @@ import { instructionsState } from './instructions.mjs';
14
14
  import { SECURITY_AGENT_FILE } from './security.mjs';
15
15
  import { laneClaims } from './laneclaims.mjs';
16
16
  import { keptBecause, worktrees } from './worktrees.mjs';
17
+ import { ciFindings } from './ci.mjs';
17
18
  import { storyModels } from './dispatches.mjs';
18
19
  import { pickPerLane } from './schedule.mjs';
19
20
 
@@ -288,6 +289,14 @@ export function nextStep(root, base) {
288
289
  );
289
290
  // ONB-8: code-kit's own instructions to the lead and the lanes, brought up to date before the next step:
290
291
  // a newer code-kit's rules reach the agents only through them.
292
+ // CIC-2: what in the project's workflows runs per story, or with no time limit.
293
+ const ci = ciFindings(root, config.branches.protected[0]);
294
+ if (ci.length) {
295
+ const files = [...new Set(ci.map((f) => f.file))];
296
+ attention.push(
297
+ `${ci.length} thing${ci.length === 1 ? '' : 's'} in the project's CI (${files.join(', ')}) ${ci.length === 1 ? 'runs' : 'run'} once per story or without a time limit; \`code-kit ci check\` says what, and the fix for the person to approve.`,
298
+ );
299
+ }
291
300
  const instructions = instructionsState(root, config);
292
301
  const behind = instructions.filter((f) => ['stale', 'legacy'].includes(f.state));
293
302
  // A file with no code-kit part may be one the project keeps without it: said, not insisted on.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warren-dean/code-kit",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "description": "Keeps AI coding agents inside your project's rules: lanes, layer rules, protected paths and proof before finish, enforced by Claude Code hooks and in CI",
5
5
  "license": "MIT",
6
6
  "author": "Warren Langeveldt",
@@ -150,9 +150,10 @@ Once they approve (with any changes):
150
150
  6. Offer CI enforcement, since the hooks only see Claude Code sessions. On yes:
151
151
  - write `.github/workflows/code-kit.yml` from `${CLAUDE_PLUGIN_ROOT}/templates/github-workflow.yml`;
152
152
  - set the version from `${CLAUDE_PLUGIN_ROOT}/.claude-plugin/plugin.json`;
153
- - fill in the install steps the project's checks need, from its existing CI or package manager;
153
+ - fill in the steps that install the project's dependencies, from its existing CI or package manager (a fix story's test is run without its fix, REG-1). The job runs `verify --no-checks`: the merge queue already ran the checks before each merge. Ask whether people open pull requests from outside Claude Code and want those proven at once; only if they do, take `--no-checks` out;
154
154
  - make sure the lead owns the workflow file, and add it to `protected` (approval `ci`, why "the CI that enforces the rules"), so a lane can't switch it off;
155
- - tell the person to make the `code-kit` check required on the protected branches.
155
+ - tell the person to make the `code-kit` check required on the protected branches;
156
+ - run `code-kit ci check` on the project's own workflows. Each story is its own branch, pull request and merge, so a workflow that runs its full suite on every push to the base or every pull request runs once per story, after the merge queue has already run the checks. Show the person what it found and the changes you propose: the full suite on `release/**` instead (`code-kit release <version>` cuts one when they release), a `timeout-minutes` on each job, and `concurrency` with `cancel-in-progress` on pull requests. Changing CI is theirs to approve (approval `ci`); make only the changes they approve.
156
157
  7. Run `check` and `unowned` again, without `--config`.
157
158
  8. Commit the setup straight onto the base branch (usually `main`), not a branch: while the base has no `.claude/code-kit.json` committed, the hooks let the lead make that one commit, so the rules the person just approved are in force on `main` and the lead can merge reviewed work from the start, with no first merge for anyone to make. The kit records the protected files in `.claude/approval-log.jsonl`. If the base already has rules (an update, section 4), commit on a branch as usual.
158
159
  9. **A team, only if there is one.** Not every developer works in a team. Ask once: "Do other developers work in this repository with their own Claude Code sessions?" If yes, run `/code-kit:team-init` now (it asks who the tech lead is and who owns which lanes, and writes the `team` section). If no, or not yet, leave it out and say `/code-kit:team-init` sets it up any time.
@@ -30,4 +30,6 @@ The build runs from the specs in `{{docs.specs}}` and the stories in `{{docs.pla
30
30
 
31
31
  {{if ci}}Pull requests run `code-kit verify`, and it must pass before a person merges to a protected branch.{{end}}
32
32
 
33
+ The merge queue checks each story before it merges, so the project's full CI runs on its release branches, not on every merge. Releasing is the person's decision: when they ask for a release, cut it with `code-kit release <version>`, which branches `release/<version>` from the base and pushes it, and the full CI runs there once. Never cut one unasked. `code-kit ci check` says what in the project's workflows still runs per story, and `code-kit ci usage` what the project spent on GitHub Actions.
34
+
33
35
  Changing the rules means editing `.claude/code-kit.json` (the lead only), then running the `code-kit:check` skill.
@@ -1,12 +1,19 @@
1
1
  # code-kit verify: the project's rules for every pull request, including work done outside Claude Code.
2
+ # It checks the rules only (--no-checks): the merge queue ran the project's checks before each merge, and
3
+ # the project's full CI runs on its release branches (docs/specs/25-what-ci-costs.md, CIC-1).
2
4
  name: code-kit
3
5
 
4
6
  on:
5
7
  pull_request:
6
8
 
9
+ concurrency:
10
+ group: code-kit-${{ github.head_ref }}
11
+ cancel-in-progress: true
12
+
7
13
  jobs:
8
14
  verify:
9
15
  runs-on: ubuntu-latest
16
+ timeout-minutes: 10
10
17
  steps:
11
18
  - uses: actions/checkout@v4
12
19
  with:
@@ -14,10 +21,10 @@ jobs:
14
21
  - uses: actions/setup-node@v4
15
22
  with:
16
23
  node-version: 22
17
- # {{init replaces this line with the steps that install what the project's checks need,
18
- # e.g. pnpm/action-setup and `pnpm install --frozen-lockfile`}}
24
+ # {{init replaces this line with the steps that install the project's dependencies, e.g.
25
+ # pnpm/action-setup and `pnpm install --frozen-lockfile`: a fix story's test is run without its fix (REG-1)}}
19
26
  - name: Verify
20
27
  run: >
21
- npx --yes @warren-dean/code-kit@{{code-kit version}} verify
28
+ npx --yes @warren-dean/code-kit@{{code-kit version}} verify --no-checks
22
29
  --base origin/${{ github.base_ref }}
23
30
  --branch ${{ github.head_ref }}