@warren-dean/code-kit 0.27.0 → 0.29.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.
@@ -1,5 +1,5 @@
1
- // Teams (docs/specs/16-teams.md), the pure parts: names, story branches, staleness and what an intent
2
- // touches. Shared by the hooks and CLI (team.mjs) and the mod, which runs without Node.
1
+ // Teams (docs/specs/16-teams.md), the pure parts: names, story branches, staleness, what an intent
2
+ // touches and which drift findings hold a merge (spec 21, HUBR-9). Shared by the hooks and CLI (team.mjs) and the mod, which runs without Node.
3
3
 
4
4
  /** A GitHub handle: letters, digits and single hyphens, at most 39 characters. */
5
5
  export const isHandle = (h) =>
@@ -189,3 +189,81 @@ export const boardValues = (story, claim) => ({
189
189
  /** The fields whose value changed since the last sync: [[field, value]]. */
190
190
  export const boardChanges = (before = {}, now) =>
191
191
  BOARD_FIELDS.filter((f) => (before[f] ?? '') !== now[f]).map((f) => [f, now[f]]);
192
+
193
+ // --- drift holds (spec 21, HUBR-9) ---------------------------------------------------------------------
194
+
195
+ /**
196
+ * What a team provider's "What blocks a merge" setting may say: a finding against a spec or decision,
197
+ * any finding, or nothing. A provider that says none (GitHub, or an older hosted one) holds nothing.
198
+ */
199
+ export const MERGE_HOLDS = ['spec-or-decision', 'any', 'nothing'];
200
+
201
+ /** What a drift finding is against, from its `conflictsWith`: spec, decision, branch or intent. */
202
+ export const findingKind = (f) => String(f?.conflictsWith ?? '').split(/[\s#]/)[0] || null;
203
+
204
+ /** Whether a finding holds a merge at the provider's level. Its severity doesn't change that. */
205
+ export function holdsMerge(finding, level) {
206
+ if (level === 'any') return true;
207
+ if (level === 'spec-or-decision') return ['spec', 'decision'].includes(findingKind(finding));
208
+ return false;
209
+ }
210
+
211
+ /** Whether the team's state came from its provider, not its fallback or a cache it couldn't renew. */
212
+ export const providerAnswered = (state) =>
213
+ Boolean(state) && state.reachable !== false && !state.fallback;
214
+
215
+ /**
216
+ * The open drift findings that hold `branch` in the merge queue, by the provider's state: its level
217
+ * (`mergeHolds`) and its findings. None when the provider didn't answer: code-kit doesn't hold on what
218
+ * it couldn't check (`driftUnchecked` says so).
219
+ */
220
+ export function driftHoldsOf(state, branch) {
221
+ if (!providerAnswered(state)) return [];
222
+ const level = MERGE_HOLDS.includes(state.mergeHolds) ? state.mergeHolds : 'nothing';
223
+ if (level === 'nothing') return [];
224
+ return (Array.isArray(state.findings) ? state.findings : []).filter(
225
+ (f) => f && f.branch === branch && !f.resolved && holdsMerge(f, level),
226
+ );
227
+ }
228
+
229
+ /** Each of `branches` the provider's findings hold: Map(branch → findings). */
230
+ export function driftHolds(state, branches) {
231
+ const held = new Map();
232
+ for (const b of branches) {
233
+ const found = driftHoldsOf(state, b);
234
+ if (found.length) held.set(b, found);
235
+ }
236
+ return held;
237
+ }
238
+
239
+ const against = (f) =>
240
+ findingKind(f) === 'intent' ? f.conflictsWith : `the ${f.conflictsWith ?? 'work in flight'}`;
241
+ const oneLine = (s, max = 200) =>
242
+ String(s ?? '')
243
+ .replace(/\s+/g, ' ')
244
+ .trim()
245
+ .slice(0, max);
246
+
247
+ /**
248
+ * Why a branch is held, in words an agent or person can act on: each finding, who decides, and how it
249
+ * clears. `provider` is the team provider's name as its state gives it; `techLead` the team's.
250
+ */
251
+ export function driftHoldWords(branch, findings, { techLead = null, provider = null } = {}) {
252
+ const where = provider ?? 'the team provider';
253
+ const each = findings.map(
254
+ (f) =>
255
+ `against ${against(f)}${f.severity ? ` (a ${f.severity})` : ''}: ${oneLine(f.title || f.text)}${f.url ? ` (${f.url})` : ''}`,
256
+ );
257
+ const one = each.length === 1;
258
+ const found = one
259
+ ? `the drift check found it ${each[0]}`
260
+ : `the drift check found it ${each.length} times: ${each.join('; ')}`;
261
+ return `${branch} is held from merging: ${found}. ${techLead ? `The tech lead (${techLead})` : 'The tech lead'} decides: if the work still stands, resolve ${one ? 'the finding' : 'the findings'} on ${where}; otherwise push a fix to ${branch}, and the drift check clears ${one ? 'it' : 'each'} once a push no longer conflicts. It merges as soon as nothing holds it.`;
262
+ }
263
+
264
+ /** When the provider didn't answer, that drift findings weren't checked, in words; null when they were. */
265
+ export function driftUnchecked(state) {
266
+ if (providerAnswered(state)) return null;
267
+ const why = oneLine(state?.fallback ?? state?.why ?? "The team provider can't be reached.");
268
+ return `${why.replace(/\.$/, '')}, so drift findings weren't checked: merges don't wait on them until it answers.`;
269
+ }
@@ -226,7 +226,16 @@ const URGENCY = [
226
226
  'report',
227
227
  'worktree',
228
228
  ];
229
- const NOTES = new Set(['usage', 'paused', 'finish', 'done', 'teamDown', 'elsewhere', 'loop']);
229
+ const NOTES = new Set([
230
+ 'usage',
231
+ 'paused',
232
+ 'finish',
233
+ 'done',
234
+ 'teamDown',
235
+ 'elsewhere',
236
+ 'loop',
237
+ 'drift',
238
+ ]);
230
239
 
231
240
  /** What a line is, in a word or two, for the Needs you panel. */
232
241
  const NEED_WORD = {
@@ -1261,11 +1261,12 @@ export function register(on) {
1261
1261
  $.ui.invalidate('ui.render');
1262
1262
  },
1263
1263
  // USE-1: a model request's tokens, put down to the agent that made it and its story and lane.
1264
- measure: async (agentId, usage) => {
1264
+ measure: async (agentId, usage, ranOn = null) => {
1265
1265
  if (agentId && !agentsSeen.has(agentId))
1266
1266
  for (const a of (await $.agent.list().catch(() => [])) ?? []) agentsSeen.set(a.id, a);
1267
1267
  const who = attribution(agentId, agentsSeen.get(agentId) ?? null, model.check, model.state);
1268
- ledger = withUsage(ledger, who, usage);
1268
+ // HUBR-2, report version 6: by the model the request ran on, as the step names it.
1269
+ ledger = withUsage(ledger, who, usage, ranOn);
1269
1270
  $.ui.invalidate('ui.render');
1270
1271
  // LEAN-5: a lane agent past its context limit is told to wrap up; its story goes on fresh.
1271
1272
  const limit = harness().agents.lanes.contextLimit;
@@ -2436,7 +2437,7 @@ export function register(on) {
2436
2437
  on('turn.step', async function* ($, e, next) {
2437
2438
  const res = yield* next(e);
2438
2439
  if (e.agentId) activityOf(e.agentId, 0).at = await $.clock.now();
2439
- if (res?.usage && act) await act.measure(e.agentId, res.usage).catch(() => {});
2440
+ if (res?.usage && act) await act.measure(e.agentId, res.usage, e.model).catch(() => {});
2440
2441
  return res;
2441
2442
  });
2442
2443
  // USE-4: the plan's 5-hour use, as Claude Code measures it.
@@ -455,8 +455,16 @@ export function bandLines({
455
455
  text: `background agents paused: plan at ${plan.percent}%`,
456
456
  actions: [],
457
457
  });
458
- // MQ-2: where the lead doesn't merge, the head of the queue waits for the person's Merge.
459
- const next = queue.find((e) => ['waiting', 'merging'].includes(e.state));
458
+ // MQ-2: where the lead doesn't merge, the head of the queue waits for the person's Merge. HUBR-9: a
459
+ // branch the team provider's drift findings hold (`drift`, from `queue --json`) isn't offered; it's said.
460
+ const inQueue = queue.filter((e) => ['waiting', 'merging'].includes(e.state));
461
+ const next = inQueue.find((e) => !e.drift?.length);
462
+ for (const e of inQueue.filter((x) => x.drift?.length && !working))
463
+ lines.push({
464
+ kind: 'drift',
465
+ text: `${e.branch} is held by the drift check: ${e.drift[0].title || e.drift[0].conflictsWith}`,
466
+ actions: [],
467
+ });
460
468
  const autonomous = (check?.harness?.autonomy ?? 'autonomous') === 'autonomous';
461
469
  // SETUP-2: with no rules on the base yet, the lead puts them there first and then merges.
462
470
  const leadMerges = autonomous && (check?.delegatesMerge || check?.firstMerge);
@@ -1159,11 +1167,15 @@ export function attribution(agentId, agent, check, state) {
1159
1167
  return { key: agentId, lane, story: named ?? laneStory(lane), background: false };
1160
1168
  }
1161
1169
 
1162
- /** The ledger with one request added: entries by agent and story, their tokens summed. */
1163
- export function withUsage(ledger, who, usage) {
1164
- const id = `${who.key}|${who.story ?? ''}`;
1170
+ /**
1171
+ * The ledger with one request added: entries by agent, story and the model the request ran on (as
1172
+ * Claude Code names it on the step), their tokens summed.
1173
+ */
1174
+ export function withUsage(ledger, who, usage, model = null) {
1175
+ const named = typeof model === 'string' && model && !/[\r\n]/.test(model) ? model : null;
1176
+ const id = `${who.key}|${who.story ?? ''}${named ? `|${named}` : ''}`;
1165
1177
  const t = tokensOf(usage);
1166
- const was = ledger[id] ?? { ...who, input: 0, output: 0, cache: 0 };
1178
+ const was = ledger[id] ?? { ...who, model: named, input: 0, output: 0, cache: 0 };
1167
1179
  return {
1168
1180
  ...ledger,
1169
1181
  [id]: {
@@ -1176,9 +1188,9 @@ export function withUsage(ledger, who, usage) {
1176
1188
  }
1177
1189
 
1178
1190
  /**
1179
- * HUBR-2: the ledger as a report carries it: [{ story, kind, input, output, cache }], each entry's kind
1180
- * (lead, lane, reviewer, security-reviewer or background) from who made it and `typeOf(key)`, the agent's
1181
- * type. Tokens only: no prompt, no message.
1191
+ * HUBR-2: the ledger as a report carries it: [{ story, kind, model, input, output, cache }], each entry's
1192
+ * kind (lead, lane, reviewer, security-reviewer or background) from who made it and `typeOf(key)`, the
1193
+ * agent's type, and the model its requests ran on (report version 6). Tokens only: no prompt, no message.
1182
1194
  */
1183
1195
  export function usageForReport(ledger, typeOf = () => null) {
1184
1196
  return Object.fromEntries(
@@ -1196,7 +1208,14 @@ export function usageForReport(ledger, typeOf = () => null) {
1196
1208
  : 'background';
1197
1209
  return [
1198
1210
  id,
1199
- { story: e.story ?? null, kind, input: e.input, output: e.output, cache: e.cache },
1211
+ {
1212
+ story: e.story ?? null,
1213
+ kind,
1214
+ model: e.model ?? null,
1215
+ input: e.input,
1216
+ output: e.output,
1217
+ cache: e.cache,
1218
+ },
1200
1219
  ];
1201
1220
  }),
1202
1221
  );
@@ -10,7 +10,7 @@ import { block, start } from './lib/hook.mjs';
10
10
  import { brokenLayerRule, layerProblems } from './lib/layers.mjs';
11
11
  import { noteFor } from './lib/standards.mjs';
12
12
  import { projectWorktrees, relativeTo, worktreeRoot } from './lib/rules.mjs';
13
- import { noteWrite } from './lib/sessions.mjs';
13
+ import { noteEditing, noteWrite } from './lib/sessions.mjs';
14
14
 
15
15
  const { input, project, config, error } = start();
16
16
  const target = input.tool_input?.file_path;
@@ -23,6 +23,8 @@ const rel = relativeTo(root, target);
23
23
  if (!existsSync(join(root, rel))) process.exit(0);
24
24
  // SESS-5: in the checkout every session shares, which session wrote the file, for a blocked git to name.
25
25
  if (root === projectWorktrees(project)[0]) noteWrite(project, input.session_id, rel);
26
+ // The file the session is editing, in whichever checkout: for the team provider's presence and report.
27
+ noteEditing(project, input.session_id, rel);
26
28
 
27
29
  // Violations recorded in the baseline (brownfield code as it was adopted) don't block; new ones do.
28
30
  const layers = layerProblems(rel, readFileSync(join(root, rel), 'utf8'), config);
package/hooks/session.mjs CHANGED
@@ -9,6 +9,7 @@ import { readFileSync } from 'node:fs';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { loadConfig } from './lib/config.mjs';
11
11
  import { releaseSession } from './lib/laneclaims.mjs';
12
+ import { modelOf } from './lib/hook.mjs';
12
13
  import { endSession, startSession } from './lib/sessions.mjs';
13
14
  import { projectDir } from './lib/rules.mjs';
14
15
 
@@ -22,7 +23,8 @@ const project = projectDir();
22
23
  const { config } = loadConfig(project);
23
24
  const session = input.session_id ?? null;
24
25
  if (config && session && process.argv[2] === 'start') {
25
- startSession(project, session);
26
+ // The model the session starts on, when Claude Code names it, or its transcript's (a resumed one).
27
+ startSession(project, session, Date.now(), { model: modelOf(input) });
26
28
  // LEAN-8: the worktrees left done with since the last session go, in the background: a project with
27
29
  // many of them never holds up a session's start.
28
30
  const cli = fileURLToPath(new URL('../bin/code-kit.mjs', import.meta.url));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warren-dean/code-kit",
3
- "version": "0.27.0",
3
+ "version": "0.29.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",
@@ -46,7 +46,7 @@ Commit everything the lanes need first. Each lane branches from the lead's branc
46
46
  node "${CLAUDE_PLUGIN_ROOT}/bin/code-kit.mjs" team claim ST-<n> --lease "<glob>,<glob>"
47
47
  ```
48
48
 
49
- The lease is the paths the story will create or change: its lane's folders for this feature, and any contract it changes. A claim someone else holds is refused with who holds it; pick another story or ask them. Stories in a lane another person owns are theirs to dispatch. Making the story's branch also claims it, and each commit on it adds what it changed to the lease; merging it ends the claim.
49
+ When the story carries out an intent the team agreed (`code-kit intend`), add `--intent <its number>`, so the team sees which pull request is the intent's. The lease is the paths the story will create or change: its lane's folders for this feature, and any contract it changes. A claim someone else holds is refused with who holds it; pick another story or ask them. Stories in a lane another person owns are theirs to dispatch. Making the story's branch also claims it, and each commit on it adds what it changed to the lease; merging it ends the claim.
50
50
 
51
51
  One agent per story: never send a running lane agent a second story, or a send-back. A story that goes on (sent back, or handed back at its context limit) gets a fresh agent: first run `node "${CLAUDE_PLUGIN_ROOT}/bin/code-kit.mjs" worktrees release <branch>`, which keeps the branch's commits and moves its report to the main checkout, then start the agent as below with the brief, "Read your earlier report first: `.claude/state/reports/<branch with / as _>.md` in the main checkout", and what `node "${CLAUDE_PLUGIN_ROOT}/bin/code-kit.mjs" replay <story> --brief` prints: the story's last commit, the tests last run, what changed since, and what was reconciled, from its event log, which holds them even when the stopped agent wrote no report. A long-lived agent rereads its whole context on every step, which is most of what a build costs.
52
52
 
@@ -54,11 +54,13 @@ Write `.claude/code-kit.draft.json`. Follow `${CLAUDE_PLUGIN_ROOT}/README.md`
54
54
  - `paths`: globs matching where that layer's code really lives;
55
55
  - `mayImport`: the direction the docs set. For brownfield code, the direction most of the code already follows;
56
56
  - `denyPackages`: packages forbidden for that layer, for example `node:*` or a vendor SDK outside its adapter.
57
+ - `label` (optional): what the layer delivers, in a few words ("API contract", "Data", "Service"), when its name doesn't say it.
57
58
  - Also add `importAliases` for path aliases in `tsconfig` `paths` that the graph can't see. Workspace package names are found automatically.
58
59
  - The import check reads JavaScript and TypeScript. For another language, record the layers anyway (agents and spec-check use them), and say the import check doesn't cover that language yet.
59
60
  - **`lanes`:** one per documented or discovered ownership area. Each needs:
60
61
  - `agent`: a kebab-case agent name, for example `api-engineer`;
61
62
  - `paths` and `exclude`: every path must have exactly one owner.
63
+ - `label` (optional): what the lane delivers, in a few words ("Screens", "Tests"), when its name doesn't say it.
62
64
  - **A QA lane:** when lanes own screens, or the plan's journeys cross lanes, a `qa` lane with a `test-engineer` agent owning the end-to-end suites (the plan's work split names them; brownfield: the folders the existing end-to-end tests live in), even if the docs forgot it. Its agent's proving command runs the suites. Add a `checks` entry for them scoped by `files` to the suites, so verify runs them when they change. Unit tests stay with each lane.
63
65
  - **`setup`:** `3`, the version of this setup, so `code-kit next` can tell an older project what re-running init adds.
64
66
  - **`lead.paths`:** contracts, specs, design, root config, and anything the docs reserve for the lead.
@@ -78,7 +78,7 @@ Report the table, `verify`'s result, the security review's findings (or that non
78
78
  node "${CLAUDE_PLUGIN_ROOT}/bin/code-kit.mjs" queue add <branch>
79
79
  ```
80
80
 
81
- Branches merge from the queue one at a time, in the order their reviews passed, each verified against the base as it is then. Where `approvals.delegate.merge` is on and the harness's autonomy is `autonomous`, you merge the head: `code-kit queue merge --delegated` (code-kit's loop asks you when it's its turn). Otherwise the person merges it, with Merge in the code-kit band or `code-kit queue merge --person`. The queue records the commit your review passed and merges exactly that commit. A branch that moves on after your review leaves the queue: review it again, then queue it again. A head that no longer merges cleanly, or fails verify against the moved base, is sent back to its lane on its own; dispatch the fix as for any send-back. When the branch is merged, remove its worktree. Where the base's rules set `branches.publish`, the merge also reaches the remote's base on its own: pushed, or as a pull request code-kit opens from `code-kit/publish-<base>` (and merges, where pushing the base is delegated to you). Never merge a story into another branch to get it there: `code-kit publish --delegated` tries again when GitHub held it back. A branch that breaks the base merged on its own (a new API whose callers another story updates) is queued with the branches it lands with: `queue add <branch> --with <other>`. It waits in the queue, without asking for review again, until they're reviewed and queued too, and then they're verified and merged as one.
81
+ Branches merge from the queue one at a time, in the order their reviews passed, each verified against the base as it is then. Where `approvals.delegate.merge` is on and the harness's autonomy is `autonomous`, you merge the head: `code-kit queue merge --delegated` (code-kit's loop asks you when it's its turn). Otherwise the person merges it, with Merge in the code-kit band or `code-kit queue merge --person`. The queue records the commit your review passed and merges exactly that commit. A branch that moves on after your review leaves the queue: review it again, then queue it again. A head that no longer merges cleanly, or fails verify against the moved base, is sent back to its lane on its own; dispatch the fix as for any send-back. When the branch is merged, remove its worktree. Where the base's rules set `branches.publish`, the merge also reaches the remote's base on its own: pushed, or as a pull request code-kit opens from `code-kit/publish-<base>` (and merges, where pushing the base is delegated to you). Never merge a story into another branch to get it there: `code-kit publish --delegated` tries again when GitHub held it back. A branch that breaks the base merged on its own (a new API whose callers another story updates) is queued with the branches it lands with: `queue add <branch> --with <other>`. It waits in the queue, without asking for review again, until they're reviewed and queued too, and then they're verified and merged as one. In a team whose provider checks pushes for drift, a branch with an open finding at the level the provider's setting names waits in its place too, and the queue goes on with the next: `queue` and `next` say which finding and that the tech lead decides. It clears when the finding is resolved on the provider, or a push fixes what it found; never merge around it.
82
82
 
83
83
  - **Send back.** List each problem, where it is, and what "fixed" looks like, with the requirement or the standard's id it breaks. Record the send-back, so `status` and `next` read the branch as waiting for its fix rather than finished:
84
84