Tells the delivery lead's session when a team agent is waiting for input, and nudges it when team agents have been idle 15 minutes or more

A Claude Code mod that tells the delivery lead when a team agent is stuck waiting for input, such as a permission prompt, so nobody has to watch every pane, and nudges the delivery lead when team agents have been idle for fifteen minutes, so the team stays active.
It loads in every session on the machine and acts only in the one whose identity the roster gives the delivery-lead role. A session whose root holds no agents/roster.json (the house assistant's, or one started outside a checkout), or whose identity is not the delivery lead's, has nothing to watch: it shows no status line at all and logs nothing. The line exists only in the session that watches. Every ten seconds it reads each live session's ~/.claude/sessions/<pid>.json. Where /proc exists, a file whose process has gone, or whose pid now belongs to another process, is skipped, and each session is named by the GIT_AUTHOR_EMAIL its launch line set, looked up in agents/roster.json, or failing that by its session name. On a platform without /proc (macOS) a session counts as live while the socket its own record names (messagingSocketPath) still exists, and goes by its session name. An active agent of any other role that has been waiting for 25 seconds is reported once, e.g. Wren waiting: permission prompt (proj:@1.%2), in a message marked as coming from the mod and not the owner; it is reported again only after it has moved on and starts waiting afresh. Nothing is sent while the delivery lead is mid-turn, so a wait that ends meanwhile is never reported. The delivery lead's status bar shows watching N, M waiting (the engine prefixes every mod's line with the mod's name).
It is also the nudger. Every five minutes, in the delivery lead's session, it reads the rows the context publisher writes (docs/context-publisher.md: CONTEXT_DIR, else ~/.local/state/<HARNESS_PROJECT>/context, resolved from the environment and harness.env as scripts/lib/harness-env.sh does, the project defaulting to the name of the MAIN checkout even when the lead's session root is a linked worktree such as acme-carl; ignoring any row older than two minutes). When that directory does not exist the status bar says context dir missing: <path> beside the watch count and the debug log names the two settings to check, because a silent hold on a wrong path looks exactly like a quiet team. When active agents of any other role have been idle for fifteen minutes or more (LEAD_NUDGE_THRESHOLD_S in harness.env or the environment), it queues one prompt into the delivery lead's session, e.g. [Automated nudge 1 of 2 from the waiting-agents mod, not from the owner; it assigns nothing.] Team agents idle for 15 minutes or more: Wren, developer idle 19m. As delivery lead, check each one and keep the team active. A queued prompt runs as a turn of its own once the session is idle and never touches the prompt box, so nothing the owner is typing there is disturbed. The same set of idle agents is nudged at most twice, a full threshold apart; the count survives a restart through the mod's store and is cleared once nobody is idle, so the bound covers one idle spell and the next starts afresh; a different set is a new state. It never prods the idle agents and assigns nothing. Only developers, testers, the code reviewer and process improvement are nudged (NUDGE_ROLES in hooks/nudge.ts): the head of testing defines what is true rather than working a ticket, and assistants are not on the team. Every verdict, holds included, is appended to lead-nudge.log beside the context directory.
Pausing it. While the file waiting-agents.paused exists beside that log (one level above the context directory: ~/.local/state/<HARNESS_PROJECT>/waiting-agents.paused by default), the mod sends nothing at all, neither waiting alerts nor nudges, and the status bar says paused. Touch it before an evening or a weekend; remove it to resume. A wait that ends during the pause is forgotten, so one that starts during the pause and outlasts it is reported once the file is gone.
Install it for every session on the machine by naming the mods folder in the env block of ~/.claude/settings.json (each subfolder holding .claude-plugin/plugin.json loads as a mod, so every mod in this repo installs with the one line; naming this mod's own folder still works):
{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/harness/claude-code" } }
It takes effect in sessions started after that. The session files are read from Claude Code's config directory, $CLAUDE_CONFIG_DIR when set and ~/.claude otherwise, so the mod's folder can live anywhere; a poll that cannot find them logs the error once per poll in the delivery lead's session and sends nothing.
hooks/watch.ts reads the roster and the session files and decides who is due a report; hooks/nudge.ts decides who is idle and whether a nudge may go; hooks/register.ts polls and sends; hooks/waiting.test.ts and hooks/nudge.test.ts hold the tests.claude plugin validate claude-code/waiting-agents and claude plugin test claude-code/waiting-agents check it. scripts/verify.sh runs the tests on every PR through scripts/check-mods-tests-pass.sh. .claude-plugin/types/, which tsconfig.json extends, is written by Claude Code when it loads the mod and is not committed.hooks/register.ts 220 lines1import type { EngineInterface, Register } from 'claude-code'
2import { type ContextRow, DEFAULT_THRESHOLD_S, MAX_NUDGES, NUDGE_ROLES, decide, describe, envFileValue, freshRows, idleAgents, type NudgeState, nudgeText, stateKey, statePaths } from './nudge.ts'
3import { authorEmailOf, current, dueWaiting, forget, parseRoster, procStartOf, type Roster, type SessionFile } from './watch.ts'
4
5const POLL_MS = 10_000
6// How often the nudger looks at the team, in the delivery lead's session.
7const NUDGE_EVERY_MS = 300_000
8// The store key holding the NudgeState, so the two-nudge bound survives a session restart.
9const NUDGE_STATE = 'nudgeState'
10
11// Where Claude Code writes `<pid>.json` for every live session: under its config directory, which is
12// `$CLAUDE_CONFIG_DIR` when set and `~/.claude` otherwise.
13//
14// ⚠ NOT RELATIVE TO THE PLUGIN'S OWN DIRECTORY. The first version used `${$.plugin.root}/../../sessions`,
15// which reaches ~/.claude/sessions only when the mod sits two levels under ~/.claude. Installed the way
16// the README says (CLAUDE_CODE_PLUGIN_DIRS=/path/to/harness/mods/waiting-agents) it resolved to
17// /path/to/harness/sessions and every poll in the delivery lead's session logged
18// `$.fs.list(...) failed: ENOENT` (2026-10-15). The tests passed because their fake filesystem answered
19// any path ending in /sessions; they now answer only the real one.
20export async function sessionsDir($: EngineInterface): Promise<string> {
21 const config = await $.env.get('CLAUDE_CONFIG_DIR')
22 if (config) return `${config}/sessions`
23 const home = await $.env.get('HOME')
24 if (!home) throw new Error('neither CLAUDE_CONFIG_DIR nor HOME is set, so the sessions directory cannot be found')
25 return `${home}/.claude/sessions`
26}
27
28// The socket paths that exist now, from one listing of each directory the records name.
29async function socketsPresent($: EngineInterface, files: readonly SessionFile[]): Promise<Set<string>> {
30 const dirs = new Set(
31 files
32 .map(f => f.messagingSocketPath)
33 .filter((path): path is string => typeof path === 'string' && path.includes('/'))
34 .map(path => path.slice(0, path.lastIndexOf('/'))),
35 )
36 const present = new Set<string>()
37 for (const dir of dirs) {
38 for (const entry of await $.fs.list(dir).catch(() => [])) present.add(`${dir}/${entry.name}`)
39 }
40 return present
41}
42
43// The session files of live Claude processes: a file whose session has gone is left out. Each is
44// named by its launch line's GIT_AUTHOR_EMAIL in the roster, or failing that by the session's own name.
45//
46// Where /proc exists the process's start time is read from it and compared with the `procStart` the
47// record carries, so a pid since given to another process is not taken for the session, and the
48// identity is read from the process's environment. A platform without /proc (macOS) publishes
49// neither, so there a session counts as live while the socket named in its own record is still
50// present: Claude Code writes both the record and the socket when a session starts and removes both
51// when it exits. A session killed outright leaves both behind and is reported once more, until the
52// files are cleared.
53async function sessionFiles($: EngineInterface, roster: Roster): Promise<SessionFile[]> {
54 const dir = await sessionsDir($)
55 const hasProc = typeof (await $.fs.read('/proc/self/stat').catch(() => undefined)) === 'string'
56 const found: { pid: string; file: SessionFile }[] = []
57 for (const entry of await $.fs.list(dir)) {
58 if (!/^\d+\.json$/.test(entry.name)) continue
59 const text = await $.fs.read(`${dir}/${entry.name}`).catch(() => undefined)
60 if (typeof text !== 'string') continue
61 try { found.push({ pid: entry.name.slice(0, -5), file: JSON.parse(text) as SessionFile }) } catch { continue }
62 }
63 const sockets = hasProc ? new Set<string>() : await socketsPresent($, found.map(f => f.file))
64 const live: SessionFile[] = []
65 for (const { pid, file } of found) {
66 let name = file.name
67 if (hasProc) {
68 const stat = await $.fs.read(`/proc/${pid}/stat`).catch(() => undefined)
69 if (typeof stat !== 'string' || file.procStart !== procStartOf(stat)) continue
70 const environ = await $.fs.read(`/proc/${pid}/environ`).catch(() => undefined)
71 const email = typeof environ === 'string' ? authorEmailOf(environ) : undefined
72 name = (email && roster.byEmail.get(email)) || file.name
73 } else if (!file.messagingSocketPath || !sockets.has(file.messagingSocketPath)) {
74 continue
75 }
76 live.push({ ...file, name })
77 }
78 return live
79}
80
81// Where the publisher writes the rows, where the nudger logs and where the pause file sits, from the
82// same settings the harness scripts read (statePaths), with the checkout's harness.env text for the
83// threshold. The pause file sits beside the log, one level above the context directory.
84type Where = { contextDir: string; log: string; pause: string; envFile?: string }
85
86async function whereOf($: EngineInterface): Promise<Where> {
87 const root = await $.session.root()
88 const envFileText = await $.fs.read(`${root}/harness.env`).catch(() => undefined)
89 const envFile = typeof envFileText === 'string' ? envFileText : undefined
90 // A linked worktree's `.git` is a one-line file naming the main checkout; a main checkout's is a
91 // directory, and the read fails.
92 const gitFileText = await $.fs.read(`${root}/.git`).catch(() => undefined)
93 const home = (await $.env.get('HOME')) ?? ''
94 const paths = statePaths(home, root, {
95 CONTEXT_DIR: (await $.env.get('CONTEXT_DIR')) || undefined,
96 HARNESS_PROJECT: (await $.env.get('HARNESS_PROJECT')) || undefined,
97 }, envFile, typeof gitFileText === 'string' ? gitFileText : undefined)
98 return { ...paths, pause: `${paths.log.slice(0, paths.log.lastIndexOf('/'))}/waiting-agents.paused`, envFile }
99}
100
101// One poll: does nothing unless this session is the delivery lead's. Alerts
102// are sent only while that session is not mid-turn, so a message is never
103// queued behind a long turn: each poll re-reads the files, and an agent that
104// stopped waiting in the meantime is simply not reported.
105type Nudger = { nextAt: number; problem?: string }
106
107async function poll($: EngineInterface, told: Set<string>, nudger: Nudger): Promise<void> {
108 // The mod loads in EVERY session on the machine (CLAUDE_CODE_PLUGIN_DIRS names the mods folder),
109 // including ones whose root is not a checkout of the project: the house assistant's, or a developer's
110 // started in ~/dev. There is no roster to read there, so there is nothing to watch, and nothing
111 // is shown: the status line exists only in the session that actually watches (owner, 2026-10-16;
112 // the first fix said so in the status bar, with a ⚠ the owner did not want). No ENOENT is logged
113 // either (2026-10-16).
114 const rosterPath = `${await $.session.root()}/agents/roster.json`
115 const rosterText = await $.fs.read(rosterPath).catch(() => undefined)
116 if (typeof rosterText !== 'string') { $.ui.status(undefined); return }
117 const roster = parseRoster(rosterText)
118 const files = await sessionFiles($, roster)
119 const id = await $.session.id()
120 const mine = files.find(f => f.sessionId === id)
121 if (!mine?.name || !roster.lead.has(mine.name)) { $.ui.status(undefined); return }
122 const agents = current(files)
123 // An agent that has stopped waiting is forgotten even while paused, so a wait it starts during a
124 // pause is reported once the pause ends.
125 forget(agents, told)
126 const where = await whereOf($)
127 // While this file exists (e.g. overnight) the mod sends nothing: no waiting alerts and no nudges.
128 if (typeof (await $.fs.read(where.pause).catch(() => undefined)) === 'string') { $.ui.status('paused'); return }
129 const isFree = mine.status !== 'busy' && mine.status !== 'waiting'
130 const lines = isFree ? dueWaiting(agents, roster.team, told, await $.clock.now()) : []
131 const waiting = [...roster.team].filter(n => agents.get(n)?.status === 'waiting').length
132 // The nudger's standing problem, when it has one, rides on the same line so it is never silent.
133 $.ui.status(`watching ${roster.team.size}, ${waiting} waiting${nudger.problem ? `; ${nudger.problem}` : ''}`)
134 if (lines.length > 0) {
135 await $.prompt.submit({
136 text: ['[waiting-agents mod, not the owner] A team agent is waiting for input:', ...lines].join('\n'),
137 })
138 return
139 }
140 const now = await $.clock.now()
141 if (now < nudger.nextAt) return
142 nudger.nextAt = now + NUDGE_EVERY_MS
143 nudger.problem = await nudge($, roster, isFree, now, where)
144}
145
146// One line, prefixed with the local time, appended to the nudger's log. Every verdict is logged,
147// holds included, so "did the nudger fire" is answered from the file.
148async function logVerdict($: EngineInterface, path: string, nowMs: number, text: string): Promise<void> {
149 const d = new Date(nowMs)
150 const p = (n: number) => String(n).padStart(2, '0')
151 const stamp = `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
152 const before = await $.fs.read(path).catch(() => '')
153 await $.fs.write(path, `${typeof before === 'string' ? before : ''}${stamp} ${text}\n`)
154}
155
156// The nudger: tells the delivery lead, as a queued prompt of its own, which team agents have been idle
157// for the threshold or more. A queued prompt never touches the prompt box, so nothing the owner is
158// typing in this session is disturbed. Idleness comes from the rows the context publisher writes
159// (docs/context-publisher.md); where they live, and the threshold, come from the environment or
160// harness.env as the harness scripts read them (`paths`, resolved once per poll).
161//
162// Returns the problem that stops it reading the rows at all (the context directory is missing), so
163// the status line can show it; a silent hold on a misconfigured path looks exactly like a quiet team.
164async function nudge($: EngineInterface, roster: Roster, isFree: boolean, now: number, paths: Where): Promise<string | undefined> {
165 const thresholdS = Number((await $.env.get('LEAD_NUDGE_THRESHOLD_S')) || envFileValue(paths.envFile, 'LEAD_NUDGE_THRESHOLD_S')) || DEFAULT_THRESHOLD_S
166 const entries = await $.fs.list(paths.contextDir).catch(() => undefined)
167 if (entries === undefined) {
168 const problem = `context dir missing: ${paths.contextDir}`
169 $.ui.log(`${problem} (set CONTEXT_DIR or HARNESS_PROJECT; see docs/context-publisher.md)`)
170 return problem
171 }
172 const rows: ContextRow[] = []
173 for (const entry of entries) {
174 if (!entry.name.endsWith('.json')) continue
175 const text = await $.fs.read(`${paths.contextDir}/${entry.name}`).catch(() => undefined)
176 try { if (typeof text === 'string') rows.push(JSON.parse(text) as ContextRow) } catch { continue }
177 }
178 // Only the roles the nudger reports: the head of testing and the assistants are never nudged.
179 const team = new Map([...roster.roleOf].filter(([, role]) => NUDGE_ROLES.includes(role)))
180 const idle = idleAgents(team, freshRows(rows, now), thresholdS)
181 if (idle.length === 0) {
182 // The team is active, so the bound has covered one idle spell: the next spell, of the same agents
183 // or others, starts afresh. Without this a set nudged twice stayed held for good.
184 if ((await $.store.get(NUDGE_STATE)) !== undefined) await $.store.delete(NUDGE_STATE)
185 await logVerdict($, paths.log, now, `hold: no team agent idle for ${thresholdS}s or more`)
186 return
187 }
188 if (!isFree) { await logVerdict($, paths.log, now, `hold: delivery lead is mid-turn; idle: ${describe(idle)}`); return }
189 const key = stateKey(idle)
190 const prev = (await $.store.get(NUDGE_STATE)) as NudgeState | undefined
191 const verdict = decide(key, prev, now, thresholdS)
192 if (!verdict.send) { await logVerdict($, paths.log, now, `hold: ${verdict.why}; idle: ${describe(idle)}`); return }
193 await $.prompt.submit({ text: nudgeText(verdict.count, idle, thresholdS) })
194 await $.store.set(NUDGE_STATE, { key, count: verdict.count, lastMs: now } satisfies NudgeState)
195 await logVerdict($, paths.log, now, `sent nudge ${verdict.count} of ${MAX_NUDGES}; idle: ${describe(idle)}`)
196 return
197}
198
199// Loaded into every session, it acts only in the one the roster names as the
200// delivery lead, polling ~/.claude/sessions every ten seconds and looking for
201// idle team agents every five minutes.
202export const register: Register = on => {
203 const told = new Set<string>()
204 const nudger: Nudger = { nextAt: 0 }
205 let timer: { cancel: () => void } | undefined
206 let busy = false
207
208 on('session.start', async ($, e, next) => {
209 timer?.cancel()
210 timer = $.clock.every(POLL_MS, () => {
211 if (busy) return
212 busy = true
213 poll($, told, nudger)
214 .catch(err => $.ui.log(String(err)))
215 .finally(() => { busy = false })
216 })
217 return next(e)
218 })
219}
220hooks/nudge.ts 131 lines1// The pure part of the nudger: which team agents have been idle long enough to wake the delivery lead
2// for, and whether this state has already been nudged as often as it may be.
3//
4// An agent runs one turn per prompt and then stops; nothing inside its session restarts it. The
5// nudger tells the delivery lead, who decides what each one should do. It never talks to the idle
6// agents and it assigns nothing. The owner, 2026-10-02: "I only want you to have a nudger so you
7// ensure the team remain active".
8
9export const DEFAULT_THRESHOLD_S = 900
10// A context row older than this says nothing about what the agent is doing now.
11export const STALE_S = 120
12// At most this many nudges for one state (the same agents idle).
13export const MAX_NUDGES = 2
14// The roles the nudger reports, by their roster ids. The delivery lead is the one told; the head of
15// testing defines what is true rather than working a ticket; assistants are not on the team.
16export const NUDGE_ROLES: readonly string[] = ['developer', 'tester', 'code-reviewer', 'process-improvement']
17
18// One row of the context directory (docs/context-publisher.md), published by each session's status line.
19export type ContextRow = { agent?: string; ts?: string; activity?: string; idle_s?: number | null }
20
21export type Idle = { name: string; role: string; idleS: number }
22
23// What has been sent for the current state: the state's key, how many nudges, and when the last went.
24export type NudgeState = { key: string; count: number; lastMs: number }
25
26// The value of `KEY=value` in harness.env, which scripts/lib/harness-env.sh sources: an optional
27// `export`, quotes around the value and a trailing comment are allowed; an empty value is no value.
28export function envFileValue(text: string | undefined, key: string): string | undefined {
29 for (const line of (text ?? '').split('\n')) {
30 const m = line.match(new RegExp(`^\\s*(?:export\\s+)?${key}=(.*)$`))
31 if (!m) continue
32 let value = m[1]!.trim()
33 const quoted = value.match(/^"([^"]*)"|^'([^']*)'/)
34 value = quoted ? (quoted[1] ?? quoted[2] ?? '') : value.replace(/(^|\s+)#.*$/, '').trim()
35 return value === '' ? undefined : value
36 }
37 return undefined
38}
39
40// The main checkout a linked worktree belongs to, from the one-line `.git` FILE git leaves in the
41// worktree (`gitdir: /path/to/project/.git/worktrees/<name>`); undefined for a main checkout, where
42// `.git` is a directory and there is no such text.
43export function mainCheckoutOf(gitFile: string | undefined): string | undefined {
44 const m = (gitFile ?? '').match(/^\s*gitdir:\s*(.+?)\/\.git\/worktrees\/[^/\s]+\/?\s*$/m)
45 return m?.[1]
46}
47
48// Where the publisher writes the rows and where the nudger logs, from the same settings the harness
49// scripts read: `CONTEXT_DIR`, else `~/.local/state/<HARNESS_PROJECT>/context` with the project
50// defaulting to the checkout's directory name. The log sits beside the context directory.
51//
52// ⚠ The checkout is the MAIN one, not the session's worktree. The delivery lead works in a linked
53// worktree named after themself (AGENTS.md rule 0: `../<project>-<you>`), so the session root's
54// basename is `acme-carl` while the publisher writes under `acme`. The first version took
55// the root's basename, found no rows, and logged "hold: no team agent idle" on every tick, in a log
56// directory that did not exist either (review, 2026-10-16). `gitFile` is the text of
57// `<root>/.git` when the root is a linked worktree.
58export function statePaths(
59 home: string,
60 root: string,
61 vars: { CONTEXT_DIR?: string; HARNESS_PROJECT?: string },
62 envFile: string | undefined,
63 gitFile?: string,
64): { contextDir: string; log: string } {
65 const checkout = mainCheckoutOf(gitFile) ?? root
66 const project = vars.HARNESS_PROJECT ?? envFileValue(envFile, 'HARNESS_PROJECT') ?? checkout.slice(checkout.lastIndexOf('/') + 1)
67 const contextDir = vars.CONTEXT_DIR ?? envFileValue(envFile, 'CONTEXT_DIR') ?? `${home}/.local/state/${project}/context`
68 return { contextDir, log: `${contextDir.slice(0, contextDir.lastIndexOf('/'))}/lead-nudge.log` }
69}
70
71// The freshest row per agent, leaving out rows older than STALE_S.
72export function freshRows(rows: readonly ContextRow[], nowMs: number): Map<string, ContextRow & { ageS: number }> {
73 const best = new Map<string, ContextRow & { ageS: number }>()
74 for (const row of rows) {
75 if (!row.agent) continue
76 const ts = Date.parse(row.ts ?? '')
77 if (Number.isNaN(ts)) continue
78 const ageS = (nowMs - ts) / 1000
79 if (ageS > STALE_S) continue
80 const held = best.get(row.agent)
81 if (!held || ageS < held.ageS) best.set(row.agent, { ...row, ageS })
82 }
83 return best
84}
85
86// The role id of agents/roster.json as the message says it: `head-of-testing` reads "head of testing".
87export function roleWords(role: string): string {
88 return role.replace(/-/g, ' ')
89}
90
91// The team agents (name to role) idle for `thresholdS` or more, in roster order.
92export function idleAgents(team: ReadonlyMap<string, string>, rows: ReadonlyMap<string, ContextRow>, thresholdS: number): Idle[] {
93 const idle: Idle[] = []
94 for (const [name, role] of team) {
95 const row = rows.get(name)
96 if (row?.activity !== 'idle' || (row.idle_s ?? 0) < thresholdS) continue
97 idle.push({ name, role, idleS: Math.floor(row.idle_s ?? 0) })
98 }
99 return idle
100}
101
102// The state a nudge is about: the same agents idle is the same state, however long they stay idle.
103export function stateKey(idle: readonly Idle[]): string {
104 return idle.map(i => i.name).sort().join('\n')
105}
106
107export function describe(idle: readonly Idle[]): string {
108 return idle.map(i => `${i.name}, ${roleWords(i.role)} idle ${Math.floor(i.idleS / 60)}m`).join('; ')
109}
110
111// Whether a nudge may go now: a new state may always be nudged; the same state at most MAX_NUDGES
112// times, a full threshold apart. A bound, not a cadence: no amount of time produces a third.
113export function decide(
114 key: string,
115 prev: NudgeState | undefined,
116 nowMs: number,
117 thresholdS: number,
118): { send: true; count: number } | { send: false; why: string } {
119 const sent = prev?.key === key ? prev : undefined
120 if (!sent) return { send: true, count: 1 }
121 if (sent.count >= MAX_NUDGES) return { send: false, why: `already nudged ${MAX_NUDGES} times for this exact state` }
122 if (nowMs - sent.lastMs < thresholdS * 1000) return { send: false, why: `${thresholdS}s not yet passed since nudge ${sent.count} for this state` }
123 return { send: true, count: sent.count + 1 }
124}
125
126export function nudgeText(count: number, idle: readonly Idle[], thresholdS: number): string {
127 return `[Automated nudge ${count} of ${MAX_NUDGES} from the waiting-agents mod, not from the owner; it assigns nothing.] `
128 + `Team agents idle for ${Math.floor(thresholdS / 60)} minutes or more: ${describe(idle)}. `
129 + 'As delivery lead, check each one and keep the team active.'
130}
131hooks/watch.ts 100 lines1// The pure part of the watcher: reading the roster and the session files,
2// and deciding who has just started waiting.
3
4export type Roster = {
5 lead: ReadonlySet<string>
6 team: ReadonlySet<string>
7 // GIT_AUTHOR_EMAIL -> name: the launch line's identity, as agents/roster.json records it.
8 byEmail: ReadonlyMap<string, string>
9 // name -> role id, for every team agent (the roles the nudger names), in roster order.
10 roleOf: ReadonlyMap<string, string>
11}
12
13export type SessionFile = {
14 pid: number
15 procStart?: string
16 sessionId?: string
17 name?: string | null
18 status?: string | null
19 waitingFor?: string | null
20 tmux?: string | null
21 messagingSocketPath?: string | null
22 updatedAt?: number | null
23 statusUpdatedAt?: number | null
24}
25
26// agents/roster.json: the active rows of `agents`. The delivery lead watches; every other active role
27// is watched. Assistants are kept apart in `assistants` and are never watched.
28export function parseRoster(json: string): Roster {
29 const lead = new Set<string>()
30 const team = new Set<string>()
31 const byEmail = new Map<string, string>()
32 const roleOf = new Map<string, string>()
33 const doc = JSON.parse(json) as { agents?: { name?: string; email?: string; role?: string; status?: string }[] }
34 for (const a of doc.agents ?? []) {
35 if (a.status !== 'active' || !a.name) continue
36 if (a.email) byEmail.set(a.email, a.name)
37 if (a.role === 'delivery-lead') lead.add(a.name)
38 else { team.add(a.name); roleOf.set(a.name, a.role ?? 'agent') }
39 }
40 return { lead, team, byEmail, roleOf }
41}
42
43// The GIT_AUTHOR_EMAIL in a process's NUL-separated /proc/<pid>/environ, if it has one.
44export function authorEmailOf(environ: string): string | undefined {
45 for (const kv of environ.split('\0')) {
46 if (kv.startsWith('GIT_AUTHOR_EMAIL=')) return kv.slice('GIT_AUTHOR_EMAIL='.length)
47 }
48 return undefined
49}
50
51// Field 22 of /proc/<pid>/stat, the process's start time: the session file's
52// `procStart`, so a pid reused by another process is not taken for the session.
53export function procStartOf(stat: string): string | undefined {
54 return stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19]
55}
56
57// Several files can name one agent (old ones stay behind): the live one with
58// the newest `updatedAt` stands for it.
59export function current(files: readonly SessionFile[]): Map<string, SessionFile> {
60 const byName = new Map<string, SessionFile>()
61 for (const f of files) {
62 if (!f.name) continue
63 const held = byName.get(f.name)
64 if (!held || (f.updatedAt ?? 0) > (held.updatedAt ?? 0)) byName.set(f.name, f)
65 }
66 return byName
67}
68
69// An agent counts as waiting once it has been waiting this long: a prompt
70// answered within seconds is not worth waking the delivery lead for.
71export const GRACE_MS = 25_000
72
73// Drops from `told` every agent that is no longer waiting, so its next wait is
74// reported afresh.
75export function forget(agents: ReadonlyMap<string, SessionFile>, told: Set<string>): void {
76 for (const name of [...told]) {
77 if (agents.get(name)?.status !== 'waiting') told.delete(name)
78 }
79}
80
81// The lines for team agents waiting for at least GRACE_MS and not yet reported,
82// each added to `told` as it is reported.
83export function dueWaiting(
84 agents: ReadonlyMap<string, SessionFile>,
85 team: ReadonlySet<string>,
86 told: Set<string>,
87 now: number,
88): string[] {
89 const lines: string[] = []
90 for (const name of team) {
91 const f = agents.get(name)
92 if (f?.status !== 'waiting' || told.has(name)) continue
93 const since = f.statusUpdatedAt ?? f.updatedAt ?? now
94 if (now - since < GRACE_MS) continue
95 told.add(name)
96 lines.push(`${name} waiting: ${f.waitingFor || 'input'} (${f.tmux || 'no pane'})`)
97 }
98 return lines
99}
100