@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.
@@ -22,6 +22,7 @@ import { globToRegExp } from './glob.mjs';
22
22
  import { projectWorktrees } from './rules.mjs';
23
23
  import { readQueue, settle, waiting } from './queue.mjs';
24
24
  import { sessions } from './sessions.mjs';
25
+ import { isSecurityReviewer } from './security.mjs';
25
26
 
26
27
  export const EVENTS_DIR = '.claude/state/events';
27
28
  const OPEN_DIR = `${EVENTS_DIR}/.open`;
@@ -253,9 +254,55 @@ function base(ctx, now) {
253
254
  target: ctx.target ?? null,
254
255
  branch: ctx.branch ?? null,
255
256
  head: ctx.head ?? null,
257
+ // The agent type an Agent call starts, for the security review's record (HUBR-2).
258
+ ...(ctx.agentType ? { agentType: ctx.agentType } : {}),
256
259
  };
257
260
  }
258
261
 
262
+ /** An agent's id in a tool's response (a background agent's launch names it), or null. */
263
+ export function agentIdOf(response, depth = 0) {
264
+ if (!response || typeof response !== 'object' || depth > 4) return null;
265
+ for (const [k, v] of Object.entries(response)) {
266
+ if ((k === 'agentId' || k === 'agent_id') && typeof v === 'string' && v) return v;
267
+ const found = agentIdOf(v, depth + 1);
268
+ if (found) return found;
269
+ }
270
+ return null;
271
+ }
272
+
273
+ /**
274
+ * HUBR-2: the security review a stopping security reviewer was started for: the Agent call's end that
275
+ * named `agentId` (one run in the background), else the latest call starting a security reviewer that
276
+ * hasn't ended (one the lead waits on). Each review is recorded once; null when none is open.
277
+ */
278
+ export function securityReviewFor(root, agentId) {
279
+ let open = null;
280
+ for (const story of loggedStories(root)) {
281
+ const events = readEvents(root, story);
282
+ const done = new Set(events.filter((e) => e.kind === 'security-review').map((e) => e.act));
283
+ const ended = new Set(events.filter((e) => e.phase === 'end').map((e) => e.act));
284
+ for (const e of events) {
285
+ if (!isSecurityReviewer(e.agentType) || !e.act || done.has(e.act)) continue;
286
+ if (e.phase === 'end' && agentId && e.result?.agent === agentId) return e;
287
+ if (e.phase === 'start' && !ended.has(e.act) && (!open || e.at > open.at)) open = e;
288
+ }
289
+ }
290
+ return open;
291
+ }
292
+
293
+ /**
294
+ * HUBR-2: each story's last security review, from its log: { at, findings, blockers } or { at, unread }
295
+ * when the reviewer's report had no findings block that reads. Map(story → review).
296
+ */
297
+ export function securityReviews(root) {
298
+ const found = new Map();
299
+ for (const story of loggedStories(root))
300
+ for (const e of readEvents(root, story))
301
+ if (e.kind === 'security-review' && e.phase === 'note')
302
+ found.set(story, { at: e.at, branch: e.branch ?? null, ...(e.result ?? {}) });
303
+ return found;
304
+ }
305
+
259
306
  /** The commit a checkout is at, short; null outside git. */
260
307
  export const headOf = (cwd) => out(git(cwd, 'rev-parse', '--short', 'HEAD')) || null;
261
308
 
@@ -334,6 +381,8 @@ export function replay(events) {
334
381
  state.phase = 'stopped';
335
382
  continue;
336
383
  }
384
+ // What the security reviewer found is a record of its review, not the end of an act.
385
+ if (e.kind === 'security-review') continue;
337
386
  if (!e.act) continue;
338
387
  const act = acts.get(e.act) ?? { start: null, end: null, reconciled: null };
339
388
  acts.set(e.act, act);
@@ -18,7 +18,7 @@ export function start() {
18
18
  if (!config && !error) process.exit(0);
19
19
  // SESS-1: the session acting is still there; one code-kit hadn't seen starts here.
20
20
  try {
21
- seeSession(project, input.session_id);
21
+ seeSession(project, input.session_id, Date.now(), () => ({ model: modelOf(input) }));
22
22
  } catch {
23
23
  // a read-only checkout: the session goes unrecorded
24
24
  }
@@ -36,6 +36,24 @@ const TAIL_BYTES = 64 * 1024;
36
36
  export function apiStopOf(input) {
37
37
  // A lane agent's own transcript: the session's ends where the lead is, not where the agent stopped.
38
38
  const path = input?.agent_id ? input.agent_transcript_path : input?.transcript_path;
39
+ const entry = lastAssistant(path);
40
+ return entry?.isApiErrorMessage ? (entry.error ?? 'unknown') : null;
41
+ }
42
+
43
+ /**
44
+ * The model the session runs on: the one SessionStart names, or the one its transcript's last reply
45
+ * came from (Claude Code writes it on each), or null. Never a lane agent's: that's the session's lead.
46
+ */
47
+ export function modelOf(input) {
48
+ if (typeof input?.model === 'string' && input.model) return input.model.slice(0, 120);
49
+ // A reply Claude Code made up itself (an error, a cut-off turn) names `<synthetic>`: not a model.
50
+ const named = (e) =>
51
+ !e.isApiErrorMessage && typeof e.message?.model === 'string' && /^[^<\s]/.test(e.message.model);
52
+ return lastAssistant(input?.transcript_path, named)?.message.model.slice(0, 120) ?? null;
53
+ }
54
+
55
+ /** The last of the model's entries in a transcript's end that `keep` accepts, or null. */
56
+ function lastAssistant(path, keep = () => true) {
39
57
  if (!path) return null;
40
58
  let fd;
41
59
  try {
@@ -45,19 +63,20 @@ export function apiStopOf(input) {
45
63
  const buffer = Buffer.alloc(length);
46
64
  readSync(fd, buffer, 0, length, size - length);
47
65
  // The last of the model's entries: what Claude Code adds after it (a hook's note) says nothing.
48
- const entry = buffer
49
- .toString('utf8')
50
- .split('\n')
51
- .reverse()
52
- .map((line) => {
53
- try {
54
- return JSON.parse(line);
55
- } catch {
56
- return null;
57
- }
58
- })
59
- .find((e) => e?.type === 'assistant');
60
- return entry?.isApiErrorMessage ? (entry.error ?? 'unknown') : null;
66
+ return (
67
+ buffer
68
+ .toString('utf8')
69
+ .split('\n')
70
+ .reverse()
71
+ .map((line) => {
72
+ try {
73
+ return JSON.parse(line);
74
+ } catch {
75
+ return null;
76
+ }
77
+ })
78
+ .find((e) => e?.type === 'assistant' && keep(e)) ?? null
79
+ );
61
80
  } catch {
62
81
  return null;
63
82
  } finally {
@@ -19,6 +19,8 @@ import { ciFindings } from './ci.mjs';
19
19
  import { storyModels } from './dispatches.mjs';
20
20
  import { pickPerLane } from './schedule.mjs';
21
21
  import { reconcileAll } from './events.mjs';
22
+ import { readCache, teamOf } from './team.mjs';
23
+ import { driftHoldWords, driftHolds, driftUnchecked } from './teamfacts.mjs';
22
24
 
23
25
  export const DRAFT_FILE = '.claude/code-kit.draft.json';
24
26
  export const BRIEF_STATES = ['framed', 'explored', 'scoped', 'specified', 'planned', 'ready'];
@@ -276,9 +278,26 @@ export function nextStep(root, base) {
276
278
  // A branch already in the merge queue has passed its review: it isn't reviewed again.
277
279
  const entries = readQueue(root);
278
280
  const inQueue = waiting(entries);
281
+ // HUBR-9: the team provider's drift findings, as last read, hold the branches they're on.
282
+ const team = teamOf(config);
283
+ const teamState = team && team.provider !== 'github' && inQueue.length ? readCache(root) : null;
284
+ const drift = teamState
285
+ ? driftHolds(
286
+ teamState,
287
+ inQueue.map((e) => e.branch),
288
+ )
289
+ : new Map();
279
290
  // MQ-7: what can merge next; a branch queued with partners waits until they're queued too.
280
- const { head: mergeHead, held: heldGroups } = nextToMerge(entries);
291
+ const { head: mergeHead, held: heldGroups, drifting } = nextToMerge(entries, drift);
281
292
  const queued = inQueue.map((e) => e.branch);
293
+ const driftWords = drifting.map((d) =>
294
+ driftHoldWords(d.branch, d.findings, {
295
+ techLead: team?.techLead,
296
+ provider: teamState?.provider?.name ?? team?.provider?.name ?? null,
297
+ }),
298
+ );
299
+ const driftNote = teamState ? driftUnchecked(teamState) : null;
300
+ const heldByDrift = new Set(drifting.map((d) => d.branch));
282
301
  // MQ-1: a queue merge running now (its verify takes minutes) isn't asked for again.
283
302
  const merging = mergingNow(inQueue[0]) ? inQueue[0].branch : null;
284
303
  const ids = (state) =>
@@ -374,10 +393,13 @@ export function nextStep(root, base) {
374
393
  `${queued[0]} passed review and is next to merge, but ${delegation.into} has no code-kit rules committed yet. Put the rules the person approved onto it (code-kit queue rules); then the queue merges under them.`,
375
394
  { args: delegation.into },
376
395
  );
377
- if (queued.length && !leadMerges)
396
+ const mergeable = queued.filter((b) => !heldByDrift.has(b));
397
+ if (mergeable.length && !leadMerges)
378
398
  attention.push(
379
- `${queued.join(', ')} passed review and ${queued.length === 1 ? 'waits' : 'wait'} for the person to merge (code-kit queue merge --person, or Merge in the code-kit band).`,
399
+ `${mergeable.join(', ')} passed review and ${mergeable.length === 1 ? 'waits' : 'wait'} for the person to merge (code-kit queue merge --person, or Merge in the code-kit band).`,
380
400
  );
401
+ attention.push(...driftWords);
402
+ if (driftNote) attention.push(driftNote);
381
403
  if (merging)
382
404
  attention.push(
383
405
  `${merging} is being merged now (queue merge is running); it says when it's done.`,
@@ -485,11 +507,15 @@ export function nextStep(root, base) {
485
507
  'wait',
486
508
  `${building.join(', ')} ${building.length === 1 ? 'is' : 'are'} being built; nothing else can start until one finishes. A lane that stopped without finishing is dispatched again.`,
487
509
  );
488
- // Stories waiting on branches in the merge queue wait for the merge, not on a broken plan.
510
+ // Stories waiting on branches in the merge queue wait for the merge, not on a broken plan. HUBR-9: a
511
+ // queue that only drift findings hold says which, and how each clears.
512
+ const heldOnly = !mergeHead && driftWords.length ? driftWords.join(' ') : null;
489
513
  if (queued.length)
490
514
  return result(
491
515
  'wait',
492
- `${queued.join(', ')} passed review and ${queued.length === 1 ? 'waits' : 'wait'} to be merged; the stories that depend on ${queued.length === 1 ? 'it' : 'them'} start after.`,
516
+ heldOnly
517
+ ? `${heldOnly} The stories that depend on ${queued.length === 1 ? 'it' : 'them'} start after.`
518
+ : `${queued.join(', ')} passed review and ${queued.length === 1 ? 'waits' : 'wait'} to be merged; the stories that depend on ${queued.length === 1 ? 'it' : 'them'} start after.`,
493
519
  );
494
520
  if (unbuildable.length)
495
521
  return result(
@@ -510,7 +536,7 @@ export function nextStep(root, base) {
510
536
  if (queued.length)
511
537
  return result(
512
538
  'wait',
513
- `${queued.join(', ')} ${queued.length === 1 ? 'waits' : 'wait'} to be merged.`,
539
+ heldOnly ?? `${queued.join(', ')} ${queued.length === 1 ? 'waits' : 'wait'} to be merged.`,
514
540
  );
515
541
  return result(
516
542
  'done',
@@ -56,6 +56,35 @@ const field = (lines, name) =>
56
56
  .find(Boolean)?.[1]
57
57
  .trim() ?? '';
58
58
 
59
+ /**
60
+ * Every spec in the specs (code-kit's spec template): [{ id, file, title, outcome, requirements }]. `id`
61
+ * is the number its `# ` heading starts with ("# 21. The hub adapter" → "21"), or else the file's name;
62
+ * `title` the rest of that heading; `outcome` its `**Outcome:**` line, or null; `requirements` the ids of
63
+ * the requirements it holds (removed ones left out). A file with neither an outcome nor a requirement
64
+ * (principles, architecture) isn't a spec. `plan` is the plan, left out where it sits among the specs.
65
+ */
66
+ export function readSpecs(root, specsPath, plan = null) {
67
+ const requirements = readRequirements(root, specsPath);
68
+ const found = [];
69
+ for (const file of markdownFiles(root, specsPath)) {
70
+ if (file === plan) continue;
71
+ const lines = readFileSync(join(root, file), 'utf8').split('\n');
72
+ const heading = lines.map((l) => l.match(/^#\s+(.+?)\s*$/)).find(Boolean)?.[1] ?? null;
73
+ const numbered = heading?.match(/^(\d+[A-Za-z]?)[.:)]?\s+(.+)$/);
74
+ const outcome = field(lines, 'Outcome') || null;
75
+ const ids = requirements.filter((r) => r.file === file && !r.removed).map((r) => r.id);
76
+ if (!outcome && !ids.length) continue;
77
+ found.push({
78
+ id: numbered ? numbered[1] : file.split('/').pop().replace(/\.md$/, ''),
79
+ file,
80
+ title: numbered ? numbered[2] : heading,
81
+ outcome,
82
+ requirements: ids,
83
+ });
84
+ }
85
+ return found;
86
+ }
87
+
59
88
  /** The first paragraph under a story's `**Field:**` lines, on one line, or null. */
60
89
  function summaryOf(body) {
61
90
  const start = body.findIndex((l) => l.trim() && !/^\*\*[^*]+:\*\*/.test(l.trim()));
@@ -121,10 +121,12 @@ export function mergingNow(entry) {
121
121
  /**
122
122
  * MQ-7: what the queue merges next. A branch queued `with` others merges only together with them, once
123
123
  * each is queued too: verified as one tree, merged one after another. Until then it waits, and the
124
- * queue goes on with the next. `{ head, partners, held }`: `head` null when nothing can merge yet;
125
- * `held` lists each waiting branch with the partners it still needs queued.
124
+ * queue goes on with the next. HUBR-9: a branch the team provider's drift findings hold (`drift`,
125
+ * Map(branch → findings), from `driftHolds`) waits too, with its group, until they clear. `{ head,
126
+ * partners, held, drifting }`: `head` null when nothing can merge yet; `held` lists each waiting branch
127
+ * with the partners it still needs queued; `drifting` each one waiting on findings, with them.
126
128
  */
127
- export function nextToMerge(entries) {
129
+ export function nextToMerge(entries, drift = new Map()) {
128
130
  const queue = waiting(entries);
129
131
  const queued = new Set(queue.map((e) => e.branch));
130
132
  // A partner already merged on its own is no longer waited for.
@@ -148,8 +150,15 @@ export function nextToMerge(entries) {
148
150
  return group;
149
151
  };
150
152
  const held = [];
153
+ const drifting = [];
154
+ let head = null;
155
+ let partners = [];
151
156
  for (const e of queue) {
152
157
  const group = groupOf(e);
158
+ // A group lands as one, so a finding on any of its branches holds them all.
159
+ const findings = [...group].flatMap((b) => drift.get(b) ?? []);
160
+ if (findings.length) drifting.push({ branch: e.branch, findings });
161
+ if (head) continue;
153
162
  const missing = [...group]
154
163
  .flatMap((b) => queue.find((y) => y.branch === b)?.with ?? [])
155
164
  .filter((b) => !queued.has(b) && !merged.has(b));
@@ -157,10 +166,11 @@ export function nextToMerge(entries) {
157
166
  held.push({ branch: e.branch, missing: [...new Set(missing)] });
158
167
  continue;
159
168
  }
160
- const partners = queue.filter((x) => x.branch !== e.branch && group.has(x.branch));
161
- return { head: e, partners, held };
169
+ if (findings.length) continue;
170
+ head = e;
171
+ partners = queue.filter((x) => x.branch !== e.branch && group.has(x.branch));
162
172
  }
163
- return { head: null, partners: [], held };
173
+ return { head, partners, held, drifting };
164
174
  }
165
175
 
166
176
  /** MQ-7: a queued branch's partners, which it merges together with. */
@@ -13,6 +13,34 @@ import { storyOfBranch } from './teamfacts.mjs';
13
13
  export const SECURITY_AGENT = 'security-reviewer';
14
14
  export const SECURITY_AGENT_FILE = `.claude/agents/${SECURITY_AGENT}.md`;
15
15
 
16
+ /** Whether an agent type is the security reviewer: the project's, or a plugin's (`<plugin>:security-reviewer`). */
17
+ export const isSecurityReviewer = (type) =>
18
+ new RegExp(`(^|:)${SECURITY_AGENT}$`).test(String(type ?? ''));
19
+
20
+ const GRADES = ['blocker', 'concern', 'nit'];
21
+
22
+ /**
23
+ * HUBR-2: what the security reviewer's report found, from its last fenced json block (its template's
24
+ * `{"findings": [...]}`): { findings, blockers }, the findings graded blocker, concern or nit counted, or
25
+ * null when the report has no block that reads.
26
+ */
27
+ export function securityOutcome(report) {
28
+ const blocks = [...String(report ?? '').matchAll(/```json\s*\n([\s\S]*?)```/g)];
29
+ if (!blocks.length) return null;
30
+ let data;
31
+ try {
32
+ data = JSON.parse(blocks.at(-1)[1]);
33
+ } catch {
34
+ return null;
35
+ }
36
+ if (!Array.isArray(data?.findings)) return null;
37
+ const graded = data.findings.filter((f) => GRADES.includes(f?.severity));
38
+ return {
39
+ findings: graded.length,
40
+ blockers: graded.filter((f) => f.severity === 'blocker').length,
41
+ };
42
+ }
43
+
16
44
  // Tests, docs and design files describe the change; the review looks at the code that ships.
17
45
  const NOT_SHIPPED =
18
46
  /(^|\/)(tests?|__tests__|e2e|docs?|design)\/|\.(test|spec|stories)\.[^/]+$|_test\.(go|py)$|(^|\/)test_[^/]+\.py$|\.(md|mdx|txt|png|jpe?g|gif|svg|webp)$/i;
@@ -142,6 +170,26 @@ export function securityReasons({ files = [], added = [], cites = [], security =
142
170
  return reasons;
143
171
  }
144
172
 
173
+ /** Every kind of reason a change gets the security review for: the sensitive kinds, then the rest. */
174
+ export const SECURITY_KINDS = [...SENSITIVE.map((s) => s.kind), 'dependencies', 'requirements'];
175
+
176
+ /**
177
+ * The security review's rules for a project: whether it has the reviewer agent, the kinds of change
178
+ * that get the review, and the ids of its specs' security requirements, a story citing any of which
179
+ * gets it too. { reviewer, kinds, requirements }.
180
+ */
181
+ export function securityRules(root, config) {
182
+ const specs = config.docs?.specs;
183
+ const texts = specs
184
+ ? markdownFiles(root, specs).map((f) => readFileSync(join(root, f), 'utf8'))
185
+ : [];
186
+ return {
187
+ reviewer: existsSync(join(root, SECURITY_AGENT_FILE)),
188
+ kinds: SECURITY_KINDS,
189
+ requirements: [...securityRequirementIds(texts)],
190
+ };
191
+ }
192
+
145
193
  /** The reasons as one sentence: "sign-in or sessions (src/auth/login.ts), dependencies (package.json)". */
146
194
  export const reasonsInWords = (reasons) =>
147
195
  reasons.map((r) => `${r.why} (${examples(r.where)})`).join('; ');
@@ -11,6 +11,7 @@ import { join } from 'node:path';
11
11
  import { matchesAny } from './glob.mjs';
12
12
  import { CLI, projectWorktrees } from './rules.mjs';
13
13
  import { shortSession } from './laneclaims.mjs';
14
+ import { isHandle } from './teamfacts.mjs';
14
15
 
15
16
  export { shortSession };
16
17
  export const SESSIONS_DIR = '.claude/state/sessions';
@@ -20,20 +21,37 @@ export const SESSION_LIVE_MS = 15 * 60_000;
20
21
  const SEEN_EVERY_MS = 60_000;
21
22
  /** The uncommitted files a session wrote, kept for SESS-5: at most this many. */
22
23
  const WROTE_KEPT = 500;
24
+ /** The file a session edits is noted again at most this often, unless it's another file. */
25
+ const EDITING_EVERY_MS = 30_000;
26
+ /** The code-kit a session runs, as it starts: the plugin can be updated while other sessions run. */
27
+ const KIT_VERSION = (() => {
28
+ try {
29
+ return JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
30
+ } catch {
31
+ return null;
32
+ }
33
+ })();
23
34
 
24
35
  const main = (root) => projectWorktrees(root)[0] ?? root;
25
36
  const dirOf = (root) => join(main(root), SESSIONS_DIR);
26
37
  const safe = (id) => String(id).replace(/[^\w.-]/g, '_');
27
38
  const fileOf = (root, id) => join(dirOf(root), `${safe(id)}.json`);
28
39
 
29
- /** The person at this machine: their GitHub login if code-kit has it cached, or the OS user. */
30
- export function personHere(root) {
40
+ /** The person at this machine by their GitHub login, when code-kit has it cached, or null. */
41
+ export function loginHere(root) {
31
42
  try {
32
43
  const cached = JSON.parse(readFileSync(join(main(root), '.claude/state/whoami.json'), 'utf8'));
33
- if (cached?.login) return cached.login;
44
+ if (isHandle(cached?.login)) return cached.login;
34
45
  } catch {
35
- // not cached: the OS user
46
+ // not cached
36
47
  }
48
+ return null;
49
+ }
50
+
51
+ /** The person at this machine: their GitHub login if code-kit has it cached, or the OS user. */
52
+ export function personHere(root) {
53
+ const login = loginHere(root);
54
+ if (login) return login;
37
55
  try {
38
56
  return userInfo().username || null;
39
57
  } catch {
@@ -89,40 +107,62 @@ export const leadSession = (root, now = Date.now()) =>
89
107
  /**
90
108
  * SESS-2: a session starting (or resumed). It's the lead when no other live session is; otherwise a
91
109
  * working session. A resumed session keeps the role it had, unless it was the lead and another session
92
- * has led since.
110
+ * has led since. `model` is the model it runs on, when Claude Code says (SessionStart's `model`); the
111
+ * session also keeps its person's GitHub login, when code-kit knows it, and the code-kit it runs.
93
112
  */
94
- export function startSession(root, id, now = Date.now()) {
113
+ export function startSession(root, id, now = Date.now(), { model = null } = {}) {
95
114
  const at = new Date(now).toISOString();
96
115
  const had = readSession(root, id);
97
116
  const lead = leadSession(root, now);
98
117
  return write(root, {
99
118
  id,
100
119
  person: had?.person ?? personHere(root),
120
+ login: loginHere(root) ?? had?.login ?? null,
101
121
  role: lead && lead.id !== id ? 'working' : 'lead',
102
122
  started: had?.started ?? at,
103
123
  seen: at,
104
124
  ended: null,
105
125
  task: had?.task ?? null,
106
126
  wrote: had?.wrote ?? [],
127
+ model: model ?? had?.model ?? null,
128
+ codeKit: KIT_VERSION,
129
+ editing: had?.editing ?? null,
107
130
  });
108
131
  }
109
132
 
110
- /** A hook saw the session act: it's still there. A session code-kit hadn't seen starts here. */
111
- export function seeSession(root, id, now = Date.now()) {
133
+ /**
134
+ * A hook saw the session act: it's still there. A session code-kit hadn't seen starts here. `facts()`
135
+ * gives what's read only when the record is written (the model it runs on now), at most once a minute.
136
+ */
137
+ export function seeSession(root, id, now = Date.now(), facts = () => ({})) {
112
138
  if (!id) return null;
113
139
  const had = readSession(root, id);
114
- if (!had || had.ended) return startSession(root, id, now);
140
+ if (!had || had.ended) return startSession(root, id, now, facts());
115
141
  // A lead that went quiet past SESSION_LIVE_MS, while another session took the lead, works now.
116
142
  const lead = had.role === 'lead' ? leadSession(root, now) : null;
117
143
  const demoted = lead && lead.id !== id;
118
144
  if (!demoted && now - Date.parse(had.seen) < SEEN_EVERY_MS) return had;
145
+ const { model } = facts();
119
146
  return write(root, {
120
147
  ...had,
121
148
  seen: new Date(now).toISOString(),
122
149
  ...(demoted ? { role: 'working' } : {}),
150
+ ...(model ? { model } : {}),
123
151
  });
124
152
  }
125
153
 
154
+ /**
155
+ * The file the session last edited, in any of the project's checkouts: { path, at }, for the team
156
+ * provider's presence and the report. `rel` is relative to the checkout it's in.
157
+ */
158
+ export function noteEditing(root, id, rel, now = Date.now()) {
159
+ if (!id || !rel) return;
160
+ const had = readSession(root, id) ?? startSession(root, id, now);
161
+ const was = had.editing;
162
+ if (was?.path === rel && now - Date.parse(was.at) < EDITING_EVERY_MS) return;
163
+ write(root, { ...had, editing: { path: rel, at: new Date(now).toISOString() } });
164
+ }
165
+
126
166
  /** The session ended: it's no longer live, and leads nothing. Its task stays, stale, for SESS-4. */
127
167
  export function endSession(root, id, now = Date.now()) {
128
168
  const had = readSession(root, id);