SLOPSHOPPER

pr-review-watch

pr-review / pr-team run tracking: Phase 5 band, engine-measured matrix and agent usage rows, bubble Stop guard

bandguardtoastpromptprocess
A shopper browsing a rack in a slop shop
README

pr-review-watch

Run tracking for the harness plugin's pr-review and pr-team skills, written as a CLI plugin of function hooks. It turns review rules that depended on the model remembering prose, or on a keyword heuristic, into hooks over the structured state the skills already write.

Every hook fails open: an unreadable file, a malformed return block, a missing project root or a refused host call degrades to "no run" or "no row". No hook blocks or fails a tool call, a turn or a stop on its own error. The Stop guard blocks only on the condition below.

Activation and configuration

The watch is active only in a project that holds .claude/harness.json, the harness plugin's per-project configuration. Candidates follow the harness library's project_root: the git top level of the session cwd (a linked worktree, or a subfolder of one), then CLAUDE_PROJECT_DIR, then the cwd itself; the first that holds the file is the project root. Without the file every hook passes straight through. Configured paths are joined to that root unless absolute.

An installed mod lives in its own plugin cache folder and cannot read the harness plugin's config/defaults.json, so hooks/config.ts carries copies of the values it needs and merges the project's harness.json over them (objects key by key, scalars replace; malformed JSON or a wrong-typed value keeps the default):

KeyDefaultUsed for
state_dir.claude/state/harnessPhase 5 sentinels in <state_dir>/pr-review/, pr-team runs in <state_dir>/pr-team/_runtime/
matrix_pathdocs/_harness/pr_review_invocation_test_matrix.jsonlthe invocation matrix rows are appended to
agent_usage_pathdocs/_harness/pr_review_agent_usage.jsonlthe agent usage rows are appended to
artifacts.reviewsdocs/PR_REVIEWSconsolidated review JSON
artifacts.scratchdocs/_scratch/pr_reviewpr-review run folders
base_branchnulldev_commit's merge base; null resolves origin/HEAD, else main

tests/mods/test_pr_review_watch_config_mirror.py fails when defaults.json changes one of these values without config.ts following.

Rules it enforces

#RuleBehavior
R1Phase 5 must close before the session stopsA band above the prompt shows PR #N · <phase> · K bubbled while a run is active or a <state_dir>/pr-review/.phase5_pending_<PR> sentinel is hot (younger than 24 h, the harness check_phase5_sentinel.py rule). A hot sentinel for the run's PR follows the phase rather than replacing it (PR #N · fixers 2/5 · Phase 5 pending · K bubbled). The phase comes from the latest dispatch; for pr-review, the phase in the current run's plan.json wins when it is a known value. K for pr-review counts the review JSON's bubbles[] plus ids bubbled in the run's fixes/*.json that no RESOLVED / CLOSED_NO_ACTION resolution closes. Each prompt also carries PHASE5_PENDING=<ids> while sentinels are hot.
R2Matrix rows carry real tokens / tool_uses / duration_sOne row per reviewer, from engine-measured usage.
R3Rows validate against pr_review_invocation_test_matrix.schema.json before appendValidated in-process; an invalid row is not appended, is kept in failures and raised as a toast.
R4model_family is the family tokenToken search over the resolved model id; an id with no haiku / sonnet / opus token fails R3.
R5dev_commit starts with the merge base against the base branchRun by the mod: git merge-base HEAD <base>, written as <sha> -- <branch> (pr-review-watch auto).
R6Bubbled issues are dispositioned in the review JSON before stoppingTwo triggers, each blocking once (stop_hook_active lets the stop through). State (pr-team runs): every tracked bubbled id must appear in the run's review JSON bubbles[], bubble_up[] or post_review_resolutions[] (the id_handling.disposition_ids rule). Keyword (any active review): when the last assistant message contains "bubble" (any case or inflection), the active review JSON's bubbles[] must be populated unless every issue is already dispositioned.
R7Every returned dispatch of a defined agent gets a usage rowOne row per reviewer, fixer, orchestrator, planner and closer dispatch of a pr-review or pr-team run, and one per dispatch of any other agent the marketplace defines (skill: standalone, role: other). Written when the agent returns and validated against pr_review_agent_usage.schema.json before append; fixer and closer rows add issues_assigned, issues_fixed, issues_bubbled and files_touched (null when unknown). A denied dispatch writes none.

The keyword trigger checks the active review: the tracked run's PR (its review JSON no older than the run), or, with no tracked run, the PR of the first hot Phase 5 sentinel that blocks the stopping session. Line 3 of a sentinel names the session that armed it; another session's sentinel is skipped, and an unowned one (no line 3) counts for every session, the check_phase5_sentinel.py blocks_session rule. A Stop input with no session id (or a blank one) fails closed: any hot sentinel counts. With neither, the keyword checks nothing. The band still lists every hot sentinel. The text comes from the Stop input's last_assistant_message, so no transcript is parsed.

How a run is recognized

DispatchPrompt headerTracked as
pr-team orchestrator / fixer modes`MODE=PLAN\CONSOLIDATE\CLOSEOUT, PR_NUMBER=, RUN_ID=, RUNTIME_DIR=`orchestrator_plan, orchestrator_consolidate, fixer_plan, closer
pr-team reviewers and fixersAGENT_ID:, AGENT_ROLE:, RUN_ID: (canonical_prompt_template.md)the plan's agent id
pr-review reviewers and fixersthe same three lines plus PR: (rows printed by pr_review.py capture / waves)the AGENT_ID
any other defined agentnonea run of its own, standalone_<UTC stamp>_<seq>, agent id the type's name without its plugin prefix (harness:messenger is messenger)

An Agent call without RUN_ID is ignored unless its subagent_type is a defined agent (DEFINED_AGENTS in hooks/contract.ts: every file under a plugin's agents/ folder, spelled <plugin>:<name>); a header that fails to identify a defined agent (an unknown role or MODE) also falls back to a standalone run. Built-in types (Explore, general-purpose, Plan) and other plugins' agents are never tracked. A standalone run feeds only the usage log: it has no PR, no phase, no band entry, no matrix row and no Stop check, and its state entry is dropped as soon as its usage row is attempted. A pr-team slot without OUTPUT_FILE is placed in <state_dir>/pr-team/_runtime/<RUN_ID>. Return blocks are parsed per the pr-team skill's return_contract.md: the last column-1 --- fenced block that has a SIGNAL: line.

Usage comes from the Agent result when it ran in the foreground (totalTokens, totalToolUseCount, totalDurationMs, resolvedModel). For a background launch, the mod counts the subagent loop's tool calls and takes tokens (input + output + cache read + cache write), duration and the report from that loop's turn.complete.

Hooks

HookDoes
tool.call on AgentRecords the dispatch, folds the result, refreshes, and for pr-review reviewers appends the ownership note to the result's context once the run is recorded with a PR.
tool.call (any)Counts tool calls per subagent loop id.
tool.call on Bash / PowerShellAfter a command that names pr_review.py, refreshes, so the band follows the script's phases within a turn.
turn.completeCompletes a background subagent; on every turn end, refreshes and appends rows that became due.
session.startRecovers pr-team runs a previous session claimed but never logged, then refreshes.
prompt.submitScans the sentinels and attaches PHASE5_PENDING=<ids> when the hot set changed since the line last attached.
session.end, session.compactAfter /clear, a resume or a main compaction, the next prompt gets the PHASE5_PENDING= line again.
classic.StopKeeps a settings hook's block as is; otherwise blocks on R6.
ui.render AbovePromptDraws the band above whatever the hooks beneath drew (band-line's banner stays on screen); yields to a survey and passes when there is nothing to show.

A refresh reads the hot sentinels, the active run's review JSON (the newest <artifacts.reviews>/<NNNN>_*.json for its PR, and no older than the run), and bubble_ups.json in the run's runtime dir. For a pr-review run it also reads <artifacts.scratch>/<NNNN>/current; only when that names the run's RUN_ID does it read <RUN_ID>/plan.json (phase: a missing or unknown value is ignored) and every <RUN_ID>/fixes/*.json (bubbled[].id). The latest post_review_resolutions[] status per id decides whether it is closed.

A sentinel is hot by its line-2 unix stamp, else the listed file mtime, else the stat mtime.

PhaseBand text
review / fixreviewers k/n / fixers k/n (tracked agents that returned, of those dispatched)
plan, consolidate, fix-plan, closeoutplanning, consolidating, fix planning, closeout
donethe run is hidden; only a hot sentinel shows, as PR #N · Phase 5 pending

Matrix-row ownership

Rows go to <matrix_path> once the review JSON has a READY TO MERGE / NOT READY TO MERGE verdict and every tracked reviewer has returned. cell is pr<N>_<agentId>, dispatch_shape is parallel, other_count is 0 and phase4_script is null. Each reviewer is attempted once. A matrix file that exists but cannot be read (a lock, an OS refusal, over the 4 MiB read limit) is never rewritten: its rows go to failures as matrix unreadable; not overwritten and are toasted.

  • pr-team. When the orchestrator PLAN returns DONE, the mod writes <runtime_dir>/.matrix_owner with pending. It rewrites the marker to logged <iso time> after the append. The pr-team-orchestrator agent's Step 5 skips when the marker exists. If a session ends between the reviewer returns and the consolidation, the next session.start rebuilds the run from dispatch_plan_review.json and terminals.jsonl under <state_dir>/pr-team/_runtime/. It writes those rows with usage 0 and says so in notes. The rebuilt run starts at the RUN_ID's UTC stamp, so a review JSON older than the run (an earlier review of the same PR) is never taken for its verdict; a RUN_ID without a valid stamp is not recovered.
  • pr-review. Each tracked reviewer's Agent result (AGENT_ROLE: reviewer) carries [pr-review-watch] Matrix rows for this run are recorded by the pr-review-watch mod; ..., and pr-review Phase 3 Step 4 skips when that note was seen. The note is added only when the run was recorded in state with a PR; otherwise the skill's own append runs. Fixer results (AGENT_ROLE: fixer) never carry the note, even though their dispatch rows include the PR: header.

Agent usage rows

Each tracked dispatch that returns appends one row to <agent_usage_path>: who ran (role, agent_id, subagent_type, full model and its model_family, unknown when the id holds no family token), what it cost (tokens, tool_uses, duration_s) and its signal. A standalone dispatch writes the same fields: skill: standalone, role: other, pr: null, no count fields, and signal: NO_BLOCK for an agent that ends without a return block, as most do. A synchronous result is logged when it returns, a background agent when its loop turn ends; nothing waits for the verdict. A retried dispatch is a second row. An errored result logs signal: ERROR with zero usage; a background turn with no usage logs tokens: 0 (the tool calls the mod counted and the turn's duration still land) with usage not measured in notes; a denied dispatch never ran and logs nothing. A background loop that is interrupted or dies on an API error is not told apart from a normal return: it logs the signal of its return block, NO_BLOCK when it left none, never ERROR.

Fixer and closer rows carry outcome counts. A pr-review fixer reads issue_ids in the run's waves.json and fixed / bubbled / the distinct edited files in fixes/<agent_id>.json, falling back to its return block's FIXED / BUBBLED / EDITED; pr-team fixers and the closer count from the block, and their issues_assigned is null. Reviewers a restarted session rebuilds from disk write no usage row. The file follows the matrix's write rules: append-only, and a file that exists but cannot be read is never rewritten (its rows go to failures as usage log unreadable; not overwritten and are toasted). The log takes one row (about 450 bytes) per defined-agent dispatch, so it reaches the 4 MiB read limit well before the matrix does; past it every row fails as unreadable. Move or archive the file when it nears 4 MiB; the next row recreates it.

State

$.state['pr-review-watch'] (contract: types/index.d.ts):

KeyMeaning
runsTracked runs by RUN_ID (a standalone run only while its agent is in flight): skill, PR, phase (dispatch-derived; for pr-review refined by the current run's plan.json), agents (subagent type, background launch model, usage, signal, counts, matrix and usage row attempt times), bubbled set and its source (closer, bubble_ups, or review_json: for pr-review the review JSON plus open fixer bubbles), verdict.
activeThe pr-review or pr-team run dispatched most recently; a standalone dispatch never becomes active.
loopsBackground subagent loop id to [runId, agentId].
failuresThe last 20 rows that failed validation or could not be written.
phase5PR ids of hot Phase 5 sentinels.
missingTracked bubbled ids the active run's review JSON does not disposition.

Known limitations

  • A pr-review run, or a pr-team run whose consolidation already logged, loses its tracker state when the process restarts. The band then shows only hot sentinels until the next dispatch.
  • A background subagent's tool calls made before its launch result registered are not counted.
  • A standalone row never says which skill or command dispatched the agent; only subagent_type and the time identify it.
  • Workflow-run reviews are not tracked. Their agents raise tool.call and turn.complete with loop ids that no dispatch header names.
  • Appends are a read and a whole-file write, serialized within the session. Two sessions appending to the same JSONL (matrix or usage log) at the same moment can lose a row.
  • A git top level, once answered, is cached per cwd for the life of the hooks module; a worktree moved or removed mid-session keeps its old root until a reload. A cwd git fails on is asked again each time.
  • claude plugin test covers Windows path spellings through the host's own C:\... paths; Linux runs only /repo paths.

Checks

claude plugin validate <mod folder>
claude plugin test <mod folder>
tsc -p <tsconfig>   # the tsconfig in the header of the engine's claude-code.d.ts, kept outside this folder

tests/mods/test_pr_review_watch_matrix_contract.py pins MATRIX_REQUIRED, MATRIX_OPTIONAL, DISPATCH_SHAPES, DEV_COMMIT_PATTERN and MODEL_FAMILIES to the harness plugin's schemas/pr_review_invocation_test_matrix.schema.json; tests/mods/test_pr_review_watch_usage_contract.py pins USAGE_REQUIRED, USAGE_COUNT_FIELDS, USAGE_ROLES, USAGE_COUNTED_ROLES, USAGE_SKILLS, USAGE_MODEL_FAMILIES and LOGGED_AT_PATTERN to schemas/pr_review_agent_usage.schema.json, and DEFINED_AGENTS to the agent files under plugins/*/agents/ (a new agent file fails the test until the list follows); tests/mods/test_pr_review_watch_config_mirror.py pins the mirrored defaults. The plugin test sandbox cannot read repository files.

Loading

Install from the operator-straps marketplace:

claude plugin marketplace add t968rs/operator-straps
claude plugin install pr-review-watch@operator-straps

For development, a CLAUDE_CODE_PLUGIN_DIRS entry in the user-level ~/.claude/settings.json env block (or claude --plugin-dir <folder> for one session) loads the folder with hot reload and replaces the marketplace copy of the same-named mod, so it never runs twice. The variable is one string, ;-separated on Windows: append to its existing value rather than replacing it. The engine reads it only from the process environment or the user settings env block, never from a project's settings.

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "C:\\path\\to\\operator-straps\\plugins\\pr-review-watch;C:\\path\\to\\operator-straps\\plugins\\git-status;C:\\path\\to\\operator-straps\\plugins\\session-bookmark"
  }
}

.claude-plugin/types/ is generated by the engine on load and git-ignored; tsconfig.json extends it.

Source 14 files
hooks/register.ts 12 lines
1import type { Register } from 'claude-code'
2
3import { registerBand } from './band'
4import { registerPhase5Context } from './phase5Scan'
5import { registerTracker } from './tracker'
6
7export const register: Register = on => {
8  registerTracker(on)
9  registerPhase5Context(on)
10  registerBand(on)
11}
12
hooks/band.tsx 37 lines
1import type { On } from 'claude-code'
2import { atom, read } from 'claude-code'
3
4import { bandText } from './runs'
5
6/**
7 * The row above the prompt: the active review run and hot Phase 5 sentinels. Reads state only. It wraps what
8 * the hooks beneath drew, so another mod's band (band-line's oStraps banner) stays on screen with it.
9 */
10
11const runsAtom = atom({ plugin: 'pr-review-watch', key: 'runs' } as const, {})
12const activeAtom = atom({ plugin: 'pr-review-watch', key: 'active' } as const, null)
13const phase5Atom = atom({ plugin: 'pr-review-watch', key: 'phase5' } as const, [])
14const missingAtom = atom({ plugin: 'pr-review-watch', key: 'missing' } as const, [])
15
16export const registerBand = (on: On): void => {
17  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
18    if (e.props.hasSurvey) return next(e)
19    const id = await read($, activeAtom)
20    const runs = await read($, runsAtom)
21    const missing = await read($, missingAtom)
22    const run = id === null ? null : (runs[id] ?? null)
23    const text = bandText({ run, phase5: await read($, phase5Atom), missing })
24    if (text === undefined) return next(e)
25    const below = await next(e).catch(() => undefined)
26    const { Box, Text } = $.ui.resolve(e)
27    return (
28      <Box flexDirection="column">
29        <Text color={missing.length > 0 ? 'warning' : 'subtle'}>
30          {text}
31        </Text>
32        {below}
33      </Box>
34    )
35  })
36}
37
hooks/phase5Scan.ts 109 lines
1import type { EngineInterface, FsEntry, On, SessionCompactInput, SessionCompactResult } from 'claude-code'
2import { atom, update } from 'claude-code'
3
4import { sentinelDirOf, under } from './config'
5import { isHot, isSentinelName, parseSentinel, SENTINEL_PREFIX, type SentinelText } from './sentinels'
6import { resolveWatch } from './watch'
7
8/**
9 * Phase 5 sentinels on disk: the scan of `<state_dir>/pr-review` the band, the Stop guard and the
10 * per-prompt `PHASE5_PENDING=` context line share. Every failure degrades to "no sentinel". Functions
11 * taking `$` are function declarations: the engine follows `$` past an import only into one.
12 */
13
14type Dollar = EngineInterface
15
16/** A hot sentinel's PR id and the session that armed it (null when unowned). */
17export type HotSentinel = { pr: string; owner: string | null }
18
19const phase5Atom = atom({ plugin: 'pr-review-watch', key: 'phase5' } as const, [])
20
21const noop = (): undefined => undefined
22const byName = (a: FsEntry, b: FsEntry): number => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
23
24/** Write time of one sentinel in unix seconds: line 2, else the listed mtime, else the stat mtime. */
25async function sentinelBasis(
26  $: Dollar,
27  path: string,
28  entry: FsEntry,
29  text: SentinelText | undefined,
30): Promise<number | undefined> {
31  if (text !== undefined && text.writtenAt !== null) return text.writtenAt
32  const listed = entry.mtimeMs > 0 ? entry.mtimeMs : undefined
33  const mtimeMs = listed ?? (await $.fs.stat(path).catch(noop))?.mtimeMs
34  return mtimeMs !== undefined && mtimeMs > 0 ? Math.floor(mtimeMs / 1000) : undefined
35}
36
37/** One sentinel when hot; undefined when stale or without any usable age. */
38async function hotSentinel($: Dollar, dir: string, entry: FsEntry, now: number): Promise<HotSentinel | undefined> {
39  const path = `${dir}/${entry.name}`
40  const raw = await $.fs.read(path).catch(noop)
41  const text = typeof raw === 'string' ? parseSentinel(raw) : undefined
42  const basis = await sentinelBasis($, path, entry, text)
43  if (basis === undefined || !isHot(basis, now)) return undefined
44  return { pr: text?.pr ?? entry.name.slice(SENTINEL_PREFIX.length), owner: text?.sessionId ?? null }
45}
46
47/** Hot sentinels in `dir` (absolute), sorted by file name; empty when the folder is absent. */
48export async function scanPhase5($: Dollar, dir: string): Promise<HotSentinel[]> {
49  const entries = await $.fs.list(dir).catch(() => [] as FsEntry[])
50  const named = entries.filter(e => e.kind !== 'dir' && isSentinelName(e.name)).sort(byName)
51  if (named.length === 0) return []
52  const now = Math.floor((await $.clock.now()) / 1000)
53  const hot: HotSentinel[] = []
54  for (const entry of named) {
55    const found = await hotSentinel($, dir, entry, now).catch(noop)
56    if (found !== undefined) hot.push(found)
57  }
58  return hot
59}
60
61/** The prompt context line for hot sentinel PR ids. */
62export const phase5Context = (ids: readonly string[]): string => `PHASE5_PENDING=${ids.join(',')}`
63
64// ---------------------------------------------------------------------------
65// Per-prompt context
66
67/** The line last attached in this conversation; '' forces the next non-empty one on. */
68const context = { lastAttached: '' }
69
70/** This prompt's line when hot sentinels exist and it differs from the one last attached. */
71async function promptLine($: Dollar): Promise<string | undefined> {
72  const w = await resolveWatch($)
73  if (w === undefined) return undefined
74  const ids = (await scanPhase5($, under(w.sentinelRoot, sentinelDirOf(w.cfg)))).map(s => s.pr)
75  await update($, phase5Atom, () => ids).catch(noop)
76  if (ids.length === 0) context.lastAttached = ''
77  const line = ids.length === 0 ? undefined : phase5Context(ids)
78  return line === context.lastAttached ? undefined : line
79}
80
81/** Session-end reasons after which the same process goes on with a fresh conversation. */
82const FRESH_CONVERSATION = new Set<string>(['clear', 'resume'])
83
84/** Whether a compaction result replaced the main conversation (its context line may be gone). */
85const isMainCompaction = (e: SessionCompactInput, result: SessionCompactResult): boolean =>
86  result.skip === undefined && e.agentId === undefined && e.trigger !== 'precompute'
87
88/** Attaches `PHASE5_PENDING=<ids>` to a prompt while sentinels are hot, once per change of the set. */
89export const registerPhase5Context = (on: On): void => {
90  on('prompt.submit', async ($, e, next) => {
91    const line = await promptLine($).catch(noop)
92    if (line === undefined || next.signal.aborted) return next(e)
93    const result = await next({ ...e, context: [...(e.context ?? []), line] })
94    if (result.drop === undefined && (result.context ?? []).includes(line)) context.lastAttached = line
95    return result
96  }).catch((_$, e, next) => next(e))
97
98  on('session.end', async ($, e, next) => {
99    if (FRESH_CONVERSATION.has(e.reason)) context.lastAttached = ''
100    return next(e)
101  }).catch((_$, e, next) => next(e))
102
103  on('session.compact', async ($, e, next) => {
104    const result = await next(e)
105    if (isMainCompaction(e, result)) context.lastAttached = ''
106    return result
107  }).catch((_$, e, next) => next(e))
108}
109
hooks/tracker.ts 611 lines
1import type { EngineInterface, FsEntry, On } from 'claude-code'
2import { atom, read, update } from 'claude-code'
3
4import type { AgentRec, LogFailure, Phase, Run } from '../types'
5import {
6  keywordBlock, mentionsBubble, missingFromReview, readReview, reviewFileFor, sidecarIds, stopBlock, verdictPrefix,
7  type ReviewDoc,
8} from './bubbles'
9import { runtimeBaseOf, sentinelDirOf, under } from './config'
10import {
11  identify, identifyStandalone, isDefinedAgent, parseReturnBlock, prOfRunId, standaloneRunId, startedAtOfRunId,
12  type Dispatch,
13} from './contract'
14import { appendRows, buildRow, validateRow, type MatrixRow } from './matrixRow'
15import { scanPhase5, type HotSentinel } from './phase5Scan'
16import {
17  applyCompletion, applyDispatch, currentRunId, fixerBubbledIds, markLogged, markUsageLogged, newAgent, planPhase,
18  recoverReviewers, reviewersSettled, reviewersToLog, settle, usageToLog, withDiskPhase, type Completion,
19} from './runs'
20import { blocksSession } from './sentinels'
21import {
22  blockCounts, buildUsageRow, NO_COUNTS, preferCounts, reportCounts, validateUsageRow, type FixerCounts,
23  type UsageRow,
24} from './usageRow'
25import { resolveWatch, type Watch } from './watch'
26
27/**
28 * Engine glue for pr-review-watch: tracks pr-team / pr-review `Agent` dispatches and the standalone dispatches
29 * of every other defined agent, folds subagent usage, appends invocation-matrix rows (reviewers) and agent
30 * usage rows (every tracked agent), and guards Stop on undispositioned bubbled
31 * ids. Active only in a project holding `.claude/harness.json` (./watch); its paths and base branch
32 * come from that file. Every host
33 * failure degrades to doing nothing; no hook throws into a tool call, a turn or a stop.
34 */
35
36type Dollar = EngineInterface
37type Key = { runId: string; agentId: string }
38/** The fields of an Agent tool result the watch reads; the engine's union is wider. */
39type AgentResult = {
40  status?: string
41  agentId?: string
42  totalTokens?: number
43  totalToolUseCount?: number
44  totalDurationMs?: number
45  resolvedModel?: string
46  content?: readonly { type: string; text?: string }[]
47}
48/** The fields of a tool result the watch reads. */
49type ToolAnswer = { result?: unknown; text?: string; isError?: true; deny?: string }
50type Usage = {
51  input_tokens: number
52  output_tokens: number
53  cache_read_input_tokens: number
54  cache_creation_input_tokens: number
55  model: string
56}
57type TurnEnd = { answer: string; durationMs: number; usage?: Usage }
58
59const runsAtom = atom({ plugin: 'pr-review-watch', key: 'runs' } as const, {})
60const activeAtom = atom({ plugin: 'pr-review-watch', key: 'active' } as const, null)
61const loopsAtom = atom({ plugin: 'pr-review-watch', key: 'loops' } as const, {})
62const failuresAtom = atom({ plugin: 'pr-review-watch', key: 'failures' } as const, [])
63const phase5Atom = atom({ plugin: 'pr-review-watch', key: 'phase5' } as const, [])
64const missingAtom = atom({ plugin: 'pr-review-watch', key: 'missing' } as const, [])
65
66/** A shell command that drives pr-review's script; its result can move a run's phase or bubbles. */
67const PR_REVIEW_SCRIPT = /pr_review\.py/
68const MARKER = '.matrix_owner'
69const GIT_TIMEOUT_MS = 10_000
70const MAX_FAILURES = 20
71export const OWNER_NOTE =
72  '[pr-review-watch] Matrix rows for this run are recorded by the pr-review-watch mod; ' +
73  'skip the manual JSONL append (pr-review Phase 3 Step 4).'
74
75const noop = (): undefined => undefined
76/** Tool calls per subagent loop id, counted for background launches. */
77const toolUses = new Map<string, number>()
78/** Serializes matrix and usage appends: parallel returns never interleave a read-modify-write. */
79let flushTail: Promise<unknown> = Promise.resolve()
80/** Numbers the standalone runs of this process, so same-second dispatches never share a run id. */
81let standaloneSeq = 0
82
83// ---------------------------------------------------------------------------
84// Host access
85
86const readText = async ($: Dollar, path: string): Promise<string | undefined> => {
87  const raw = await $.fs.read(path).catch(noop)
88  return typeof raw === 'string' ? raw : undefined
89}
90
91const listDir = ($: Dollar, path: string): Promise<FsEntry[]> => $.fs.list(path).catch(() => [] as FsEntry[])
92
93const gitLine = async ($: Dollar, root: string, args: readonly string[]): Promise<string | undefined> => {
94  const ran = await $.process.run(['git', '-C', root, ...args], { timeoutMs: GIT_TIMEOUT_MS }).catch(noop)
95  return ran !== undefined && ran.exitCode === 0 ? ran.stdout.trim() : undefined
96}
97
98/** The configured base branch, else the branch `origin/HEAD` names, else `main` (resolve_base_branch). */
99const baseBranchFor = async ($: Dollar, w: Watch): Promise<string> => {
100  if (w.cfg.baseBranch !== null) return w.cfg.baseBranch
101  const head = await gitLine($, w.root, ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'])
102  const slash = head?.indexOf('/') ?? -1
103  return head !== undefined && slash > 0 ? head.slice(slash + 1) : 'main'
104}
105
106/** `<merge-base> -- <branch> (pr-review-watch auto)`; empty (which fails validation) when git fails. */
107const devCommitFor = async ($: Dollar, w: Watch): Promise<string> => {
108  const sha = await gitLine($, w.root, ['merge-base', 'HEAD', await baseBranchFor($, w)])
109  const branch = (await gitLine($, w.root, ['rev-parse', '--abbrev-ref', 'HEAD'])) ?? '?'
110  return sha === undefined ? '' : `${sha} -- ${branch} (pr-review-watch auto)`
111}
112
113// ---------------------------------------------------------------------------
114// Sentinels and review JSON
115
116const scanSentinels = ($: Dollar, w: Watch): Promise<HotSentinel[]> =>
117  scanPhase5($, under(w.sentinelRoot, sentinelDirOf(w.cfg)))
118
119/** The newest review JSON for a PR, unless it is older than `sinceMs`. */
120const loadReviewFor = async ($: Dollar, w: Watch, pr: number, sinceMs: number): Promise<ReviewDoc | undefined> => {
121  const dir = under(w.root, w.cfg.reviewsDir)
122  const hit = reviewFileFor(pr, await listDir($, dir))
123  if (hit === undefined || hit.mtimeMs < sinceMs) return undefined
124  const text = await readText($, `${dir}/${hit.name}`)
125  return text === undefined ? undefined : readReview(text)
126}
127
128/** The run's review JSON: newest for its PR and not older than the run. */
129const loadReview = ($: Dollar, w: Watch, run: Run): Promise<ReviewDoc | undefined> =>
130  run.pr === null ? Promise.resolve(undefined) : loadReviewFor($, w, run.pr, run.startedAt)
131
132const loadSidecar = async ($: Dollar, w: Watch, run: Run): Promise<string[] | null> => {
133  if (run.runtimeDir === null) return null
134  const text = await readText($, `${under(w.root, run.runtimeDir)}/bubble_ups.json`)
135  return text === undefined ? null : sidecarIds(text)
136}
137
138/** What a pr-review run directory says: the `plan.json` phase and the fixer-bubbled ids. */
139type RunDisk = { phase: Phase | undefined; fixerBubbled: string[] }
140const NO_RUN_DISK: RunDisk = { phase: undefined, fixerBubbled: [] }
141
142/**
143 * The pr-review run directory under `artifacts.scratch` (`<NNNN>/current` names the active run,
144 * `<NNNN>/<RUN_ID>/` holds it), only while the PR folder's `current` names this run.
145 */
146const prReviewRunDir = async ($: Dollar, w: Watch, run: Run): Promise<string | undefined> => {
147  if (run.skill !== 'pr-review' || run.pr === null) return undefined
148  const prDir = `${under(w.root, w.cfg.scratchDir)}/${String(run.pr).padStart(4, '0')}`
149  return currentRunId(await readText($, `${prDir}/current`)) === run.runId ? `${prDir}/${run.runId}` : undefined
150}
151
152const fixerReports = async ($: Dollar, dir: string): Promise<string[]> => {
153  const names = (await listDir($, dir)).filter(e => e.kind === 'file' && e.name.endsWith('.json')).map(e => e.name)
154  const texts = await Promise.all(names.sort().map(name => readText($, `${dir}/${name}`)))
155  return texts.filter((t): t is string => t !== undefined)
156}
157
158const loadRunDisk = async ($: Dollar, w: Watch, run: Run): Promise<RunDisk> => {
159  const dir = await prReviewRunDir($, w, run)
160  if (dir === undefined) return NO_RUN_DISK
161  const plan = await readText($, `${dir}/plan.json`)
162  const phase = plan === undefined ? undefined : planPhase(plan)
163  return { phase, fixerBubbled: fixerBubbledIds(await fixerReports($, `${dir}/fixes`)) }
164}
165
166// ---------------------------------------------------------------------------
167// State updates
168
169const runOf = async ($: Dollar, runId: string): Promise<Run | undefined> => (await read($, runsAtom))[runId]
170
171const updateRun = ($: Dollar, runId: string, fn: (run: Run) => Run): Promise<unknown> =>
172  update($, runsAtom, runs => {
173    const cur = runs[runId]
174    return cur === undefined ? runs : { ...runs, [runId]: fn(cur) }
175  })
176
177type DispatchMeta = { model?: string; effort?: string; subagentType?: string }
178
179const recordDispatch = async ($: Dollar, d: Dispatch, meta: DispatchMeta): Promise<void> => {
180  const now = await $.clock.now()
181  await update($, runsAtom, runs => applyDispatch(runs, d, newAgent(d, meta), now))
182  if (d.skill !== 'standalone') await update($, activeAtom, () => d.runId)
183}
184
185/** A standalone run holds one agent; once its usage row is attempted the run is dropped, bounding state. */
186const dropStandalone = ($: Dollar, runId: string): Promise<unknown> =>
187  update($, runsAtom, runs => {
188    if (runs[runId]?.skill !== 'standalone') return runs
189    return Object.fromEntries(Object.entries(runs).filter(([id]) => id !== runId))
190  })
191
192/** Writes the pending ownership marker once the orchestrator's plan is in. */
193const claimMatrix = async ($: Dollar, key: Key, signal: string | undefined): Promise<void> => {
194  if (key.agentId !== 'orchestrator_plan' || signal !== 'DONE') return
195  const run = await runOf($, key.runId)
196  const w = await resolveWatch($)
197  if (run === undefined || run.runtimeDir === null || w === undefined) return
198  await $.fs.write(`${under(w.root, run.runtimeDir)}/${MARKER}`, 'pending\n').catch(noop)
199}
200
201const complete = async ($: Dollar, key: Key, c: Completion): Promise<void> => {
202  await updateRun($, key.runId, run => applyCompletion(run, key.agentId, c))
203  await claimMatrix($, key, c.block?.signal)
204  await logUsage($, key, c)
205  await dropStandalone($, key.runId)
206}
207
208const textOf = (r: AgentResult): string => (r.content ?? []).map(b => b.text ?? '').join('\n')
209
210/** Maps the loop to its agent and keeps the model the engine launched it with. */
211const registerLoop = async ($: Dollar, loopId: string, key: Key, model: string | null): Promise<void> => {
212  await update($, loopsAtom, loops => ({ ...loops, [loopId]: [key.runId, key.agentId] as [string, string] }))
213  await updateRun($, key.runId, run => {
214    const a = run.agents[key.agentId]
215    return a === undefined ? run : { ...run, agents: { ...run.agents, [key.agentId]: { ...a, launchModel: model } } }
216  })
217}
218
219/** Folds an Agent tool result: usage now when synchronous, a loop registration when backgrounded. */
220const recordResult = async ($: Dollar, key: Key, r: ToolAnswer): Promise<void> => {
221  const res = (r.deny === undefined && r.isError !== true ? r.result : undefined) as AgentResult | undefined
222  if (res?.status === 'async_launched' && res.agentId !== undefined) {
223    return registerLoop($, res.agentId, key, res.resolvedModel ?? null)
224  }
225  const isDone = res?.status === 'completed'
226  await complete($, key, {
227    tokens: isDone ? (res.totalTokens ?? 0) : 0,
228    toolUses: isDone ? (res.totalToolUseCount ?? 0) : 0,
229    durationMs: isDone ? (res.totalDurationMs ?? 0) : 0,
230    model: res?.resolvedModel ?? null,
231    block: isDone ? parseReturnBlock(r.text ?? textOf(res)) : undefined,
232    isMeasured: isDone,
233    ending: r.deny !== undefined ? 'denied' : isDone ? 'ok' : 'errored',
234  })
235}
236
237const usageTokens = (u: Usage | undefined): number =>
238  u === undefined ? 0 : u.input_tokens + u.output_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
239
240/** A background subagent's turn ended: its usage, tool count and report complete the agent. */
241const recordLoopEnd = async ($: Dollar, loopId: string, e: TurnEnd): Promise<void> => {
242  const used = toolUses.get(loopId) ?? 0
243  toolUses.delete(loopId)
244  const hit = (await read($, loopsAtom))[loopId]
245  if (hit === undefined) return
246  await update($, loopsAtom, loops => Object.fromEntries(Object.entries(loops).filter(([k]) => k !== loopId)))
247  await complete($, { runId: hit[0], agentId: hit[1] }, {
248    tokens: usageTokens(e.usage), toolUses: used, durationMs: e.durationMs, model: e.usage?.model ?? null,
249    block: parseReturnBlock(e.answer), isMeasured: e.usage !== undefined, ending: 'ok',
250  })
251}
252
253// ---------------------------------------------------------------------------
254// JSONL append (matrix and usage log)
255
256/** Keeps the failures and toasts them; `noun` names the row kind (`matrix`, `usage`). */
257const recordFailures = async ($: Dollar, failures: readonly LogFailure[], noun: string): Promise<void> => {
258  if (failures.length === 0) return
259  await update($, failuresAtom, prev => [...prev, ...failures].slice(-MAX_FAILURES)).catch(noop)
260  const first = failures[0]
261  const text = `pr-review-watch: ${failures.length} ${noun} row(s) not appended (${first?.cell}: ${first?.reason})`
262  await Promise.resolve($.ui.toast(text)).catch(noop)
263}
264
265/**
266 * The JSONL text to append to: '' when the file is missing, undefined when it exists (or its existence
267 * is unknown) but cannot be read, so a whole-file write would drop its rows.
268 */
269const readJsonl = async ($: Dollar, path: string): Promise<string | undefined> => {
270  const isThere = await $.fs.exists(path).catch(() => true)
271  return isThere ? readText($, path) : ''
272}
273
274/** How one JSONL file checks and names its rows; `label` starts the failure reasons. */
275type RowCheck<R> = { label: string; problems: (r: R) => string[]; cellOf: (r: R) => string }
276
277const MATRIX_CHECK: RowCheck<MatrixRow> = { label: 'matrix', problems: validateRow, cellOf: r => r.cell }
278const USAGE_CHECK: RowCheck<UsageRow> = {
279  label: 'usage log', problems: validateUsageRow, cellOf: r => `${r.run_id}/${r.agent_id}`,
280}
281
282/**
283 * Appends valid rows to `path`; returns the failures (invalid rows, or every row when the file cannot be
284 * read or the write is refused). An unreadable file is never overwritten.
285 */
286const appendValid = async <R extends object>(
287  $: Dollar,
288  path: string,
289  rows: readonly R[],
290  check: RowCheck<R>,
291  now: number,
292): Promise<LogFailure[]> => {
293  const checked = rows.map(r => ({ r, why: check.problems(r) }))
294  const good = checked.filter(x => x.why.length === 0).map(x => x.r)
295  const failures = checked.filter(x => x.why.length > 0)
296    .map(x => ({ cell: check.cellOf(x.r), reason: x.why.join('; '), at: now }))
297  if (good.length === 0) return failures
298  const existing = await readJsonl($, path)
299  const isWritten =
300    existing !== undefined && (await $.fs.write(path, appendRows(existing, good)).then(() => true, () => false))
301  if (isWritten) return failures
302  const reason = existing === undefined ? `${check.label} unreadable; not overwritten` : `${check.label} write refused`
303  return [...failures, ...good.map(r => ({ cell: check.cellOf(r), reason, at: now }))]
304}
305
306const writeRows = ($: Dollar, w: Watch, rows: readonly MatrixRow[], now: number): Promise<LogFailure[]> =>
307  appendValid($, under(w.root, w.cfg.matrixPath), rows, MATRIX_CHECK, now)
308
309// ---------------------------------------------------------------------------
310// Usage rows
311
312/** Claims the agent's usage row inside one atom update, so a second fold never appends it again. */
313const claimUsage = async ($: Dollar, key: Key, now: number): Promise<[Run, AgentRec] | undefined> => {
314  const box: { hit?: [Run, AgentRec] } = {}
315  await updateRun($, key.runId, r => {
316    box.hit = undefined
317    const a = usageToLog(r, key.agentId)
318    if (a === undefined) return r
319    box.hit = [r, a]
320    return markUsageLogged(r, key.agentId, now)
321  })
322  return box.hit
323}
324
325/**
326 * Outcome counts: closer and pr-team fixers from the return block; a pr-review fixer from its run's
327 * waves.json and fixes/<id>.json, falling back to the block; other roles none.
328 */
329const countsFor = async (
330  $: Dollar,
331  w: Watch,
332  run: Run,
333  agent: AgentRec,
334  c: Completion,
335): Promise<FixerCounts> => {
336  if (agent.role === 'closer' || (agent.role === 'fixer' && run.skill === 'pr-team')) return blockCounts(c.block)
337  if (agent.role !== 'fixer') return NO_COUNTS
338  const dir = await prReviewRunDir($, w, run).catch(noop)
339  const read = (rel: string): Promise<string | undefined> =>
340    dir === undefined ? Promise.resolve(undefined) : readText($, `${dir}/${rel}`)
341  const [waves, report] = await Promise.all([read('waves.json'), read(`fixes/${agent.id}.json`)])
342  return preferCounts(reportCounts(waves, report, agent.id), blockCounts(c.block))
343}
344
345/** One usage row per returned dispatch; a denied dispatch never ran and writes none. */
346const logUsage = async ($: Dollar, key: Key, c: Completion): Promise<void> => {
347  if (c.ending === 'denied') return
348  const w = await resolveWatch($)
349  if (w === undefined) return
350  const now = await $.clock.now()
351  const hit = await claimUsage($, key, now)
352  if (hit === undefined) return
353  const [run, claimed] = hit
354  const counts = await countsFor($, w, run, claimed, c)
355  // The engine's model: this completion's, else the background launch's, else the requested one.
356  const agent = { ...claimed, model: c.model ?? claimed.launchModel ?? claimed.model }
357  const row = buildUsageRow({
358    runId: run.runId, skill: run.skill, pr: run.pr, agent, ending: c.ending, isMeasured: c.isMeasured,
359    loggedAt: now, counts,
360  })
361  const path = under(w.root, w.cfg.agentUsagePath)
362  flushTail = flushTail
363    .then(async () => recordFailures($, await appendValid($, path, [row], USAGE_CHECK, now), 'usage'))
364    .catch(noop)
365  await flushTail
366}
367
368/**
369 * Claims the run's unlogged reviewers: marks them logged inside one atom update and returns them, so an
370 * overlapping refresh finds nothing left to claim and never appends the same rows again.
371 */
372const claimReviewers = async ($: Dollar, runId: string, now: number): Promise<AgentRec[]> => {
373  let claimed: AgentRec[] = []
374  await updateRun($, runId, r => {
375    claimed = reviewersToLog(r)
376    return claimed.length === 0 ? r : markLogged(r, claimed.map(a => a.id), now)
377  })
378  return claimed
379}
380
381const flushNow = async ($: Dollar, w: Watch, runId: string): Promise<void> => {
382  const run = await runOf($, runId)
383  const prefix = verdictPrefix(run?.verdict ?? null)
384  if (run === undefined || run.pr === null || prefix === undefined || !reviewersSettled(run)) return
385  const now = await $.clock.now()
386  const agents = await claimReviewers($, runId, now)
387  if (agents.length === 0) return
388  const devCommit = await devCommitFor($, w)
389  const pr = run.pr
390  const rows = agents.map(agent => buildRow({ pr, agent, verdictPrefix: prefix, devCommit }))
391  await recordFailures($, await writeRows($, w, rows, now), 'matrix')
392  if (run.runtimeDir === null) return
393  const stamp = `logged ${new Date(now).toISOString()}\n`
394  await $.fs.write(`${under(w.root, run.runtimeDir)}/${MARKER}`, stamp).catch(noop)
395}
396
397const flush = ($: Dollar, w: Watch, runId: string): Promise<unknown> => {
398  flushTail = flushTail.then(() => flushNow($, w, runId)).catch(noop)
399  return flushTail
400}
401
402// ---------------------------------------------------------------------------
403// Refresh, recovery, stop
404
405/** Re-reads disk for the active run: sentinels, verdict, bubbled set, missing ids; flushes rows. */
406const refreshWith = async ($: Dollar, w: Watch): Promise<void> => {
407  const phase5 = (await scanSentinels($, w).catch(() => [] as HotSentinel[])).map(s => s.pr)
408  await update($, phase5Atom, () => phase5)
409  const id = await read($, activeAtom)
410  const run = id === null ? undefined : await runOf($, id)
411  if (run === undefined) {
412    await update($, missingAtom, () => [])
413    return
414  }
415  const review = await loadReview($, w, run)
416  const sidecar = await loadSidecar($, w, run)
417  const disk = await loadRunDisk($, w, run).catch(() => NO_RUN_DISK)
418  await updateRun($, run.runId, r => withDiskPhase(settle(r, review, sidecar, disk.fixerBubbled), disk.phase))
419  const settled = await runOf($, run.runId)
420  const tracked = settled === undefined || settled.bubbledFrom === 'review_json' ? [] : settled.bubbled
421  await update($, missingAtom, () => missingFromReview(tracked, review))
422  if (review !== undefined) await flush($, w, run.runId)
423}
424
425/** `refreshWith` for the session's project; nothing outside a harness project. */
426const refresh = async ($: Dollar): Promise<void> => {
427  const w = await resolveWatch($)
428  if (w !== undefined) await refreshWith($, w)
429}
430
431/**
432 * A run rebuilt from its runtime dir: plan reviewers joined with terminals rows. Its start is the run id's
433 * stamp, so an older review JSON for the same PR is never taken for its verdict; no stamp, no recovery.
434 */
435const recoveredRun = async ($: Dollar, w: Watch, runId: string): Promise<Run | undefined> => {
436  const runtimeDir = `${runtimeBaseOf(w.cfg)}/${runId}`
437  const dir = under(w.root, runtimeDir)
438  const plan = await readText($, `${dir}/dispatch_plan_review.json`)
439  const pr = prOfRunId(runId)
440  const startedAt = startedAtOfRunId(runId)
441  if (plan === undefined || pr === null || startedAt === null) return undefined
442  const agents = recoverReviewers(plan, (await readText($, `${dir}/terminals.jsonl`)) ?? '')
443  return {
444    runId, skill: 'pr-team', pr, phase: 'consolidate', runtimeDir,
445    agents: Object.fromEntries(agents.map(a => [a.id, a])), bubbled: [], bubbledFrom: 'none', verdict: null,
446    startedAt,
447  }
448}
449
450/** Rows for a pr-team run a previous session claimed but never logged. */
451const recoverRun = async ($: Dollar, w: Watch, runId: string): Promise<void> => {
452  const run = await recoveredRun($, w, runId)
453  if (run === undefined) return
454  await update($, runsAtom, runs => (runs[runId] === undefined ? { ...runs, [runId]: run } : runs))
455  const review = await loadReview($, w, run)
456  if (review === undefined) return
457  await updateRun($, runId, r => settle(r, review, null))
458  await flush($, w, runId)
459}
460
461const recoverPending = async ($: Dollar): Promise<void> => {
462  const w = await resolveWatch($)
463  if (w === undefined) return
464  const known = await read($, runsAtom)
465  const base = under(w.root, runtimeBaseOf(w.cfg))
466  for (const entry of await listDir($, base)) {
467    if (entry.kind !== 'dir' || known[entry.name] !== undefined) continue
468    const marker = await readText($, `${base}/${entry.name}/${MARKER}`)
469    if (marker?.startsWith('pending')) await recoverRun($, w, entry.name).catch(noop)
470  }
471}
472
473const activeRun = async ($: Dollar): Promise<Run | undefined> => {
474  const id = await read($, activeAtom)
475  return id === null ? undefined : runOf($, id)
476}
477
478type PrReview = [number, ReviewDoc | undefined]
479
480/**
481 * The active review for the keyword check: the tracked run's PR, else that of the first hot sentinel
482 * blocking the stopping session (`blocksSession`; another session's sentinel is not this one's review).
483 */
484const keywordReview = async (
485  $: Dollar,
486  w: Watch,
487  run: Run | undefined,
488  sessionId: string | undefined,
489): Promise<PrReview | undefined> => {
490  if (run !== undefined && run.pr !== null) return [run.pr, await loadReview($, w, run)]
491  const hot = await scanSentinels($, w).catch(() => [] as HotSentinel[])
492  const pr = Number(hot.find(s => blocksSession(s.owner, sessionId))?.pr)
493  return Number.isInteger(pr) && pr >= 1 ? [pr, await loadReviewFor($, w, pr, 0)] : undefined
494}
495
496type StopInput = { stop_hook_active: boolean; last_assistant_message?: string; session_id?: string }
497
498/** Tracked bubbled ids out of the review JSON (pr-team), then the "bubble" keyword rule (any review). */
499const stopReason = async ($: Dollar, w: Watch, e: StopInput): Promise<string | undefined> => {
500  const run = await activeRun($)
501  const missing = await read($, missingAtom)
502  const tracked =
503    run?.skill === 'pr-team' ? stopBlock(run.pr, missing, run.bubbledFrom, e.stop_hook_active) : undefined
504  if (tracked !== undefined || !mentionsBubble(e.last_assistant_message)) return tracked
505  const hit = await keywordReview($, w, run, e.session_id)
506  return hit === undefined ? undefined : keywordBlock(hit[0], e.last_assistant_message, hit[1], e.stop_hook_active)
507}
508
509/** The Stop block the watch owes, or undefined; nothing outside a harness project. */
510const stopBlockFor = async ($: Dollar, e: StopInput): Promise<string | undefined> => {
511  const w = await resolveWatch($)
512  if (w === undefined) return undefined
513  await refreshWith($, w).catch(noop)
514  return stopReason($, w, e)
515}
516
517// ---------------------------------------------------------------------------
518// Hooks
519
520/** A shell call that ran pr-review's script refreshes, so the band moves within a turn. */
521const afterShell = async ($: Dollar, command: string | undefined): Promise<void> => {
522  if (PR_REVIEW_SCRIPT.test(command ?? '')) await refresh($).catch(noop)
523}
524
525/** Whether the mod holds a run it can log rows for: recorded in state, with a PR. */
526const ownsRows = async ($: Dollar, runId: string): Promise<boolean> =>
527  ((await runOf($, runId).catch(noop))?.pr ?? null) !== null
528
529/** A defined agent that carries no run header gets a run of its own, under a fresh id. */
530const standaloneFor = async ($: Dollar, subagentType: string | undefined): Promise<Dispatch | undefined> =>
531  identifyStandalone(subagentType, standaloneRunId(await $.clock.now(), ++standaloneSeq))
532
533/**
534 * The tracked identity of a dispatch in a harness project, with that project; else undefined. A run header
535 * names the run; a defined agent without one is a standalone run.
536 */
537const trackedDispatch = async (
538  $: Dollar,
539  subagentType: string | undefined,
540  prompt: string,
541): Promise<[Dispatch, Watch] | undefined> => {
542  if (identify(subagentType, prompt, '') === undefined && !isDefinedAgent(subagentType)) return undefined
543  const w = await resolveWatch($).catch(noop)
544  if (w === undefined) return undefined
545  const d = identify(subagentType, prompt, runtimeBaseOf(w.cfg)) ?? (await standaloneFor($, subagentType))
546  return d === undefined ? undefined : [d, w]
547}
548
549/** Tool-call hooks: tracked Agent dispatches, per-loop tool counts and shell refreshes. */
550const registerToolHooks = (on: On): void => {
551  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
552    const hit = await trackedDispatch($, e.subagent_type, e.prompt)
553    if (hit === undefined) return next(e)
554    const [d, w] = hit
555    await recordDispatch($, d, { model: e.model, effort: e.effort, subagentType: e.subagent_type }).catch(noop)
556    const r = await next(e)
557    await recordResult($, { runId: d.runId, agentId: d.agentId }, r).catch(noop)
558    if (d.skill !== 'standalone') await refreshWith($, w).catch(noop)
559    // Refusals inline (not a helper) so the checker narrows `r` to a result that takes context.
560    if (d.skill !== 'pr-review' || d.role !== 'reviewer' || r.deny !== undefined || r.isError === true) return r
561    if (!(await ownsRows($, d.runId))) return r
562    return { ...r, context: [...(r.context ?? []), OWNER_NOTE] }
563  })
564
565  on('tool.call', ($, e, next) => {
566    if (e.agentId !== undefined) toolUses.set(e.agentId, (toolUses.get(e.agentId) ?? 0) + 1)
567    return next(e)
568  })
569
570  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
571    const r = await next(e)
572    await afterShell($, e.command)
573    return r
574  })
575
576  on('tool.call', { tool: 'PowerShell' }, async ($, e, next) => {
577    const r = await next(e)
578    await afterShell($, e.command)
579    return r
580  })
581}
582
583/** Turn, session and Stop hooks: loop usage, recovery, refreshes and the Stop guard. */
584const registerLifecycleHooks = (on: On): void => {
585  on('turn.complete', async ($, e, next) => {
586    const r = await next(e)
587    if (e.agentId !== undefined) await recordLoopEnd($, e.agentId, e).catch(noop)
588    await refresh($).catch(noop)
589    return r
590  })
591
592  on('session.start', async ($, e, next) => {
593    const r = await next(e)
594    await recoverPending($).catch(noop)
595    await refresh($).catch(noop)
596    return r
597  })
598
599  on('classic.Stop', async ($, e, next) => {
600    const r = await next(e)
601    if (r.block !== undefined) return r
602    const block = await stopBlockFor($, e).catch(noop)
603    return block === undefined ? r : { ...r, block }
604  })
605}
606
607export const registerTracker = (on: On): void => {
608  registerToolHooks(on)
609  registerLifecycleHooks(on)
610}
611
hooks/runs.ts 234 lines
1import type { AgentRec, Counts, Phase, Run } from '../types'
2import { allDispositioned, type ReviewDoc } from './bubbles'
3import type { Dispatch, ReturnBlock } from './contract'
4
5/** Pure state transitions over tracked runs, plus the band text. No `$`. */
6
7/** What one subagent turn (or a synchronous Agent result) contributes. */
8export type Completion = {
9  tokens: number
10  toolUses: number
11  durationMs: number
12  model: string | null
13  block: ReturnBlock | undefined
14  isMeasured: boolean
15  /** `ok`: a result the engine reported; `errored`: an error or unfinished Agent result; `denied`: never ran. */
16  ending: 'ok' | 'errored' | 'denied'
17}
18
19const PHASE_LABEL: Readonly<Record<Phase, string>> = {
20  plan: 'planning', review: 'reviewers', consolidate: 'consolidating', 'fix-plan': 'fix planning',
21  fix: 'fixers', closeout: 'closeout', done: 'done',
22}
23
24export const newAgent = (
25  d: Dispatch,
26  meta: { model?: string; effort?: string; subagentType?: string },
27): AgentRec => ({
28  id: d.agentId, role: d.role, model: meta.model ?? null, effort: meta.effort ?? null,
29  tokens: 0, toolUses: 0, durationMs: 0, isMeasured: false, signal: null, counts: null, loggedAt: null,
30  subagentType: meta.subagentType ?? null, usageLoggedAt: null, launchModel: null,
31})
32
33const newRun = (d: Dispatch, now: number): Run => ({
34  runId: d.runId, skill: d.skill, pr: d.pr, phase: d.phase, runtimeDir: d.runtimeDir,
35  agents: {}, bubbled: [], bubbledFrom: 'none', verdict: null, startedAt: now,
36})
37
38/** Records a dispatch: the run is created on first sight, the phase follows the dispatch. */
39export const applyDispatch = (
40  runs: Readonly<Record<string, Run>>,
41  d: Dispatch,
42  rec: AgentRec,
43  now: number,
44): Record<string, Run> => {
45  const run = runs[d.runId] ?? newRun(d, now)
46  const agents = { ...run.agents, [d.agentId]: rec }
47  const next: Run = { ...run, pr: run.pr ?? d.pr, runtimeDir: run.runtimeDir ?? d.runtimeDir, phase: d.phase, agents }
48  return { ...runs, [d.runId]: next }
49}
50
51const foldAgent = (a: AgentRec, c: Completion): AgentRec => ({
52  ...a,
53  tokens: a.tokens + c.tokens,
54  toolUses: a.toolUses + c.toolUses,
55  durationMs: a.durationMs + c.durationMs,
56  model: c.model ?? a.model,
57  isMeasured: a.isMeasured || c.isMeasured,
58  signal: c.block?.signal ?? 'NO_BLOCK',
59  counts: c.block?.counts ?? a.counts,
60})
61
62/** The closer's DONE ends the run; its BUBBLED list becomes the run's bubbled set. */
63const applyCloser = (run: Run, block: ReturnBlock): Run => {
64  const closed: Run = block.signal === 'DONE' ? { ...run, phase: 'done' } : run
65  return block.bubbled === null ? closed : { ...closed, bubbled: block.bubbled, bubbledFrom: 'closer' }
66}
67
68export const applyCompletion = (run: Run, agentId: string, c: Completion): Run => {
69  const prev = run.agents[agentId]
70  if (prev === undefined) return run
71  const next: Run = { ...run, agents: { ...run.agents, [agentId]: foldAgent(prev, c) } }
72  return agentId === 'closer' && c.block !== undefined ? applyCloser(next, c.block) : next
73}
74
75const withBubbled = (run: Run, ids: string[], from: 'bubble_ups' | 'review_json'): Run =>
76  run.bubbledFrom === 'closer' ? run : { ...run, bubbled: ids, bubbledFrom: from }
77
78/** pr-review's bubbled set: the review's `bubbles`, plus fixer-bubbled ids no resolution has closed. */
79export const prReviewBubbled = (review: ReviewDoc | undefined, fixerBubbled: readonly string[]): string[] => {
80  const closed = review?.closed ?? []
81  return [...new Set([...(review?.bubbles ?? []), ...fixerBubbled.filter(id => !closed.includes(id))])]
82}
83
84/**
85 * Folds what disk says: verdict, bubbled set (closer > sidecar > pr-review's review JSON and fixer
86 * reports), completion. `fixerBubbled`: ids bubbled in a pr-review run's `fixes/*.json`.
87 */
88export const settle = (
89  run: Run,
90  review: ReviewDoc | undefined,
91  sidecar: string[] | null,
92  fixerBubbled: readonly string[] = [],
93): Run => {
94  const isPrReview = run.skill === 'pr-review'
95  if (review === undefined && sidecar === null && !(isPrReview && fixerBubbled.length > 0)) return run
96  const base: Run = review === undefined ? run : { ...run, verdict: review.verdict }
97  const bubbled =
98    sidecar !== null ? withBubbled(base, sidecar, 'bubble_ups')
99      : isPrReview ? withBubbled(base, prReviewBubbled(review, fixerBubbled), 'review_json')
100        : base
101  return review !== undefined && allDispositioned(review) ? { ...bubbled, phase: 'done' } : bubbled
102}
103
104/** The phase a pr-review run's `plan.json` records wins over the dispatch-derived one; none keeps it. */
105export const withDiskPhase = (run: Run, phase: Phase | undefined): Run =>
106  phase === undefined || phase === run.phase ? run : { ...run, phase }
107
108const reviewers = (run: Run): AgentRec[] => Object.values(run.agents).filter(a => a.role === 'reviewer')
109
110export const reviewersSettled = (run: Run): boolean => reviewers(run).every(a => a.signal !== null)
111
112export const reviewersToLog = (run: Run): AgentRec[] =>
113  reviewers(run).filter(a => a.signal !== null && a.loggedAt === null)
114
115export const markLogged = (run: Run, ids: readonly string[], now: number): Run => ({
116  ...run,
117  agents: Object.fromEntries(
118    Object.entries(run.agents).map(([k, a]) => [k, ids.includes(k) ? { ...a, loggedAt: now } : a]),
119  ),
120})
121
122/** The agent when it has returned and its usage row is not yet attempted; else undefined. */
123export const usageToLog = (run: Run, agentId: string): AgentRec | undefined => {
124  const a = run.agents[agentId]
125  return a !== undefined && a.signal !== null && a.usageLoggedAt === null ? a : undefined
126}
127
128export const markUsageLogged = (run: Run, agentId: string, now: number): Run => {
129  const a = run.agents[agentId]
130  return a === undefined ? run : { ...run, agents: { ...run.agents, [agentId]: { ...a, usageLoggedAt: now } } }
131}
132
133const isRecord = (v: unknown): v is Record<string, unknown> =>
134  typeof v === 'object' && v !== null && !Array.isArray(v)
135const str = (v: unknown): string | null => (typeof v === 'string' ? v : null)
136
137const parseJson = (text: string): unknown => {
138  try {
139    return JSON.parse(text)
140  } catch {
141    return undefined
142  }
143}
144
145/** Reviewer terminals rows by agent id. */
146const terminalsByAgent = (text: string): Map<string, Record<string, unknown>> => {
147  const out = new Map<string, Record<string, unknown>>()
148  for (const line of text.split(/\r?\n/)) {
149    const row = parseJson(line)
150    if (isRecord(row) && row.agent_role === 'reviewer' && typeof row.agent_id === 'string') out.set(row.agent_id, row)
151  }
152  return out
153}
154
155const countsOf = (v: unknown): Counts | null => {
156  if (!isRecord(v)) return null
157  const n = (k: string): number => (typeof v[k] === 'number' ? (v[k] as number) : 0)
158  return { findings: n('findings'), critical: n('critical'), important: n('important'), minor: n('minor') }
159}
160
161const recovered = (agent: Record<string, unknown>, row: Record<string, unknown>): AgentRec => ({
162  id: String(agent.id), role: 'reviewer', model: str(agent.model), effort: str(agent.effort),
163  tokens: 0, toolUses: 0, durationMs: 0, isMeasured: false,
164  signal: str(row.signal) ?? 'NO_BLOCK', counts: countsOf(row.counts), loggedAt: null,
165  subagentType: null, usageLoggedAt: null, launchModel: null,
166})
167
168/** Reviewers rebuilt after a restart: plan `agents[]` that have a reviewer terminals row. */
169export const recoverReviewers = (planText: string, terminalsText: string): AgentRec[] => {
170  const plan = parseJson(planText)
171  const agents = isRecord(plan) && Array.isArray(plan.agents) ? plan.agents.filter(isRecord) : []
172  const rows = terminalsByAgent(terminalsText)
173  return agents.flatMap(a => {
174    const row = typeof a.id === 'string' ? rows.get(a.id) : undefined
175    return row === undefined ? [] : [recovered(a, row)]
176  })
177}
178
179const isPhase = (v: unknown): v is Phase => typeof v === 'string' && Object.hasOwn(PHASE_LABEL, v)
180
181/** A pr-review `plan.json`'s `phase`; undefined when absent, unknown or the text is not JSON. */
182export const planPhase = (planText: string): Phase | undefined => {
183  const plan = parseJson(planText)
184  return isRecord(plan) && isPhase(plan.phase) ? plan.phase : undefined
185}
186
187/** The `current` run id of a pr-review PR folder: its first line, trimmed; undefined when blank. */
188export const currentRunId = (text: string | undefined): string | undefined =>
189  text?.split(/\r?\n/)[0]?.trim() || undefined
190
191/** Ids bubbled across pr-review fixer reports (`fixes/*.json` `bubbled[].id`), first-seen order. */
192export const fixerBubbledIds = (reportTexts: readonly string[]): string[] => {
193  const ids = reportTexts.flatMap(text => {
194    const doc = parseJson(text)
195    const bubbled = isRecord(doc) && Array.isArray(doc.bubbled) ? doc.bubbled : []
196    return bubbled.flatMap(b => (isRecord(b) && typeof b.id === 'string' ? [b.id] : []))
197  })
198  return [...new Set(ids)]
199}
200
201const progress = (run: Run, role: string): string => {
202  const agents = Object.values(run.agents).filter(a => a.role === role)
203  return `${agents.filter(a => a.signal !== null).length}/${agents.length}`
204}
205
206const phaseLabel = (run: Run): string => {
207  if (run.phase === 'review') return `reviewers ${progress(run, 'reviewer')}`
208  if (run.phase === 'fix') return `fixers ${progress(run, 'fixer')}`
209  return PHASE_LABEL[run.phase]
210}
211
212/** The run's phase, then the Phase 5 marker when its PR's sentinel is hot. */
213const phaseText = (run: Run, isPhase5: boolean): string =>
214  isPhase5 ? `${phaseLabel(run)} · Phase 5 pending` : phaseLabel(run)
215
216const runText = (run: Run, phase5: readonly string[], missing: readonly string[]): string => {
217  const parts = [`PR #${run.pr ?? '?'}`, phaseText(run, phase5.includes(String(run.pr)))]
218  if (run.bubbled.length > 0) parts.push(`${run.bubbled.length} bubbled`)
219  if (missing.length > 0) parts.push(`bubbles[] missing ${missing.join(',')}`)
220  return parts.join(' · ')
221}
222
223export type BandInput = { run: Run | null; phase5: readonly string[]; missing: readonly string[] }
224
225/** One band line: the active run (unless done), then any other hot sentinel; undefined when empty. */
226export const bandText = (b: BandInput): string | undefined => {
227  const run = b.run !== null && b.run.phase !== 'done' ? b.run : null
228  const others = b.phase5
229    .filter(pr => run === null || pr !== String(run.pr))
230    .map(pr => `PR #${pr} · Phase 5 pending`)
231  const lines = run === null ? others : [runText(run, b.phase5, b.missing), ...others]
232  return lines.length === 0 ? undefined : lines.join(' | ')
233}
234
hooks/config.ts 73 lines
1/**
2 * The harness keys the watch reads from `<project>/.claude/harness.json`, merged over copies of the harness
3 * plugin's `config/defaults.json` values: an installed mod sits in its own plugin cache folder and cannot
4 * read that file. `tests/mods/test_pr_review_watch_config_mirror.py` pins the copies. Pure: no `$`.
5 */
6
7export const DEFAULT_STATE_DIR = '.claude/state/harness'
8export const DEFAULT_MATRIX_PATH = 'docs/_harness/pr_review_invocation_test_matrix.jsonl'
9export const DEFAULT_AGENT_USAGE_PATH = 'docs/_harness/pr_review_agent_usage.jsonl'
10export const DEFAULT_REVIEWS = 'docs/PR_REVIEWS'
11export const DEFAULT_SCRATCH = 'docs/_scratch/pr_review'
12export const DEFAULT_BASE_BRANCH: string | null = null
13
14/** Project-relative POSIX paths and the configured base branch (null: resolve it from git). */
15export type WatchConfig = {
16  stateDir: string
17  matrixPath: string
18  agentUsagePath: string
19  reviewsDir: string
20  scratchDir: string
21  baseBranch: string | null
22}
23
24type Json = Readonly<Record<string, unknown>>
25
26const isObject = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
27
28const clean = (p: string): string => p.trim().replace(/\\/g, '/').replace(/\/+$/, '')
29
30/** A non-blank string value, cleaned; else the fallback. */
31const pathOr = (v: unknown, fallback: string): string =>
32  typeof v === 'string' && clean(v) !== '' ? clean(v) : fallback
33
34const parse = (text: string): Json => {
35  try {
36    const data: unknown = JSON.parse(text)
37    return isObject(data) ? data : {}
38  } catch {
39    return {}
40  }
41}
42
43/**
44 * The watch's view of a `harness.json` text: each key it reads replaces its default, `artifacts` merges
45 * key by key. Malformed JSON or a wrong-typed value keeps the default (the harness hooks report it).
46 */
47export const readConfig = (text: string): WatchConfig => {
48  const data = parse(text)
49  const artifacts = isObject(data.artifacts) ? data.artifacts : {}
50  const base = data.base_branch
51  return {
52    stateDir: pathOr(data.state_dir, DEFAULT_STATE_DIR),
53    matrixPath: pathOr(data.matrix_path, DEFAULT_MATRIX_PATH),
54    agentUsagePath: pathOr(data.agent_usage_path, DEFAULT_AGENT_USAGE_PATH),
55    reviewsDir: pathOr(artifacts.reviews, DEFAULT_REVIEWS),
56    scratchDir: pathOr(artifacts.scratch, DEFAULT_SCRATCH),
57    baseBranch: typeof base === 'string' && base.trim() !== '' ? base.trim() : DEFAULT_BASE_BRANCH,
58  }
59}
60
61/**
62 * A configured path against the project root: a relative one is joined to it, an absolute one (POSIX,
63 * drive or UNC) is kept, as harness_lib's `cfg.path()` does.
64 */
65export const under = (root: string, path: string): string =>
66  /^([A-Za-z]:)?[\\/]/.test(path) ? path : `${root}/${path}`
67
68/** `<state_dir>/pr-review`: where Phase 5 sentinels live. */
69export const sentinelDirOf = (c: WatchConfig): string => `${c.stateDir}/pr-review`
70
71/** `<state_dir>/pr-team/_runtime`: the pr-team run folders. */
72export const runtimeBaseOf = (c: WatchConfig): string => `${c.stateDir}/pr-team/_runtime`
73
hooks/sentinels.ts 39 lines
1/** The Phase 5 sentinel rule of the harness plugin's `hooks/check_phase5_sentinel.py`. Pure: no `$`. */
2
3/** Mirrors `MAX_AGE_SECONDS` in check_phase5_sentinel.py. */
4export const MAX_AGE_SECONDS = 86400
5export const SENTINEL_PREFIX = '.phase5_pending_'
6
7export type SentinelText = { pr: string | null; writtenAt: number | null; sessionId: string | null }
8
9const orNull = (s: string): string | null => (s === '' ? null : s)
10
11/**
12 * Line 1 the PR id, line 2 an optional unix-int write time, line 3 the optional id of the session
13 * that armed it (CRLF tolerated).
14 */
15export const parseSentinel = (text: string): SentinelText => {
16  const lines = text.split(/\r?\n/)
17  const stamp = (lines[1] ?? '').trim()
18  return {
19    pr: orNull((lines[0] ?? '').trim()),
20    writtenAt: /^\d+$/.test(stamp) ? Number(stamp) : null,
21    sessionId: orNull((lines[2] ?? '').trim()),
22  }
23}
24
25export const isHot = (basisSeconds: number, nowSeconds: number): boolean =>
26  nowSeconds - basisSeconds < MAX_AGE_SECONDS
27
28/**
29 * Mirrors `blocks_session`: a hot sentinel spares a session only when both ids are known and differ.
30 * A blank session id (after trimming, as the Python hook strips it) counts as unknown.
31 */
32export const blocksSession = (owner: string | null, sessionId: string | null | undefined): boolean => {
33  const id = sessionId?.trim() ?? ''
34  return owner === null || id === '' || owner === id
35}
36
37export const isSentinelName = (name: string): boolean =>
38  name.startsWith(SENTINEL_PREFIX) && name.length > SENTINEL_PREFIX.length
39
hooks/watch.ts 55 lines
1import type { EngineInterface } from 'claude-code'
2
3import { readConfig, type WatchConfig } from './config'
4import { HARNESS_CONFIG_REL, rootCandidates } from './root'
5
6/**
7 * The project the watch serves: its root (forward slashes), its harness configuration, and the main
8 * checkout per-repository state (Phase 5 sentinels) lives under; the root itself outside a linked worktree.
9 */
10export type Watch = { root: string; cfg: WatchConfig; sentinelRoot: string }
11
12const GIT_TIMEOUT_MS = 10_000
13
14const noop = (): undefined => undefined
15
16/** Top levels already answered, by start folder (a reload starts afresh). */
17const toplevels = new Map<string, string>()
18
19/** `git rev-parse --show-toplevel` from `start`; undefined on any failure. */
20async function toplevelOf($: EngineInterface, start: string | undefined): Promise<string | undefined> {
21  if (start === undefined || start.trim() === '') return undefined
22  const known = toplevels.get(start)
23  if (known !== undefined) return known
24  const argv = ['git', '-C', start, 'rev-parse', '--show-toplevel']
25  const ran = await $.process.run(argv, { timeoutMs: GIT_TIMEOUT_MS }).catch(noop)
26  const top = ran === undefined || ran.exitCode !== 0 ? '' : ran.stdout.trim()
27  if (top === '') return undefined
28  toplevels.set(start, top)
29  return top
30}
31
32/** Main checkout of `root`'s repository (`git rev-parse --git-common-dir` minus `/.git`); else `root`. */
33async function mainCheckoutOf($: EngineInterface, root: string): Promise<string> {
34  const argv = ['git', '-C', root, 'rev-parse', '--path-format=absolute', '--git-common-dir']
35  const ran = await $.process.run(argv, { timeoutMs: GIT_TIMEOUT_MS }).catch(noop)
36  const common = ran === undefined || ran.exitCode !== 0 ? '' : ran.stdout.trim().replace(/\\/g, '/')
37  return common.endsWith('/.git') ? common.slice(0, -'/.git'.length) : root
38}
39
40/**
41 * The first candidate root (./root) whose `.claude/harness.json` reads, with that file's configuration;
42 * undefined when none does, which leaves the watch inactive. Never throws. Function declarations: the
43 * engine follows `$` past an import only into one.
44 */
45export async function resolveWatch($: EngineInterface): Promise<Watch | undefined> {
46  const env = await $.env.get('CLAUDE_PROJECT_DIR').catch(noop)
47  const cwd = await $.session.cwd().catch(noop)
48  const top = await toplevelOf($, cwd).catch(noop)
49  for (const root of rootCandidates(env, cwd, top)) {
50    const text = await $.fs.read(`${root}/${HARNESS_CONFIG_REL}`).catch(noop)
51    if (typeof text === 'string') return { root, cfg: readConfig(text), sentinelRoot: await mainCheckoutOf($, root) }
52  }
53  return undefined
54}
55
hooks/bubbles.ts 143 lines
1/**
2 * Review-JSON reading for the bubble guard: a port of the harness library's `validation/id_handling.py`
3 * (`issue_ids`, `disposition_ids`, `all_issues_dispositioned`) plus file selection. Pure: no `$`.
4 */
5
6/**
7 * The parts of a consolidated review JSON (`<artifacts.reviews>/*.json`) the watch reads. `closed`: ids
8 * whose latest `post_review_resolutions[]` status is `RESOLVED` or `CLOSED_NO_ACTION`.
9 */
10export type ReviewDoc = {
11  verdict: string | null
12  issueIds: string[]
13  dispositioned: string[]
14  bubbles: string[]
15  closed: string[]
16}
17
18/** A directory entry, as `$.fs.list` reports one. */
19export type Listed = { name: string; mtimeMs: number; kind: string }
20
21const VERDICT_PREFIX = /^(NOT READY TO MERGE|READY TO MERGE)/
22
23const isRecord = (v: unknown): v is Record<string, unknown> =>
24  typeof v === 'object' && v !== null && !Array.isArray(v)
25const list = (v: unknown): unknown[] => (Array.isArray(v) ? v : [])
26const idOf = (v: unknown): string | undefined => (isRecord(v) && typeof v.id === 'string' ? v.id : undefined)
27const isDefined = <T>(v: T | undefined): v is T => v !== undefined
28const uniq = (ids: readonly string[]): string[] => [...new Set(ids)]
29
30/** Issue ids in C, I, M order, then by number. */
31const byId = (a: string, b: string): number =>
32  a[0] === b[0] ? Number(a.slice(1)) - Number(b.slice(1)) : a < b ? -1 : 1
33
34const parseObject = (text: string): Record<string, unknown> | undefined => {
35  try {
36    const doc: unknown = JSON.parse(text)
37    return isRecord(doc) ? doc : undefined
38  } catch {
39    return undefined
40  }
41}
42
43const issueIdsOf = (doc: Record<string, unknown>): string[] => {
44  const issues = isRecord(doc.issues) ? doc.issues : {}
45  return Object.values(issues).flatMap(bucket => list(bucket).map(idOf).filter(isDefined))
46}
47
48const bubblesOf = (doc: Record<string, unknown>): string[] =>
49  list(doc.bubbles).filter((b): b is string => typeof b === 'string')
50
51const dispositionedOf = (doc: Record<string, unknown>): string[] => [
52  ...list(doc.post_review_resolutions).map(idOf).filter(isDefined),
53  ...bubblesOf(doc),
54  ...list(doc.bubble_up).map(idOf).filter(isDefined),
55]
56
57const CLOSING_STATUSES: readonly unknown[] = ['RESOLVED', 'CLOSED_NO_ACTION']
58
59/** Ids whose last resolution entry carries a closing status; a later non-closing entry reopens. */
60const closedOf = (doc: Record<string, unknown>): string[] => {
61  const latest = new Map<string, unknown>()
62  for (const entry of list(doc.post_review_resolutions)) {
63    const id = idOf(entry)
64    if (id !== undefined && isRecord(entry)) latest.set(id, entry.status)
65  }
66  return [...latest].filter(([, status]) => CLOSING_STATUSES.includes(status)).map(([id]) => id)
67}
68
69/** The review parts, or undefined when the text is not a JSON object. */
70export const readReview = (text: string): ReviewDoc | undefined => {
71  const doc = parseObject(text)
72  if (doc === undefined) return undefined
73  return {
74    verdict: typeof doc.verdict === 'string' ? doc.verdict : null,
75    issueIds: uniq(issueIdsOf(doc)),
76    dispositioned: uniq(dispositionedOf(doc)),
77    bubbles: uniq(bubblesOf(doc)),
78    closed: closedOf(doc),
79  }
80}
81
82/** `bubble_ups.json` `items[].id`, or null when the text is not a JSON object. */
83export const sidecarIds = (text: string): string[] | null => {
84  const doc = parseObject(text)
85  return doc === undefined ? null : uniq(list(doc.items).map(idOf).filter(isDefined))
86}
87
88/** At least one issue, and every issue dispositioned. */
89export const allDispositioned = (r: ReviewDoc): boolean =>
90  r.issueIds.length > 0 && r.issueIds.every(id => r.dispositioned.includes(id))
91
92/** Tracked bubbled ids the review does not disposition, sorted; none without a review. */
93export const missingFromReview = (tracked: readonly string[], r: ReviewDoc | undefined): string[] =>
94  r === undefined ? [] : uniq(tracked.filter(id => !r.dispositioned.includes(id))).sort(byId)
95
96export const verdictPrefix = (verdict: string | null): string | undefined => verdict?.match(VERDICT_PREFIX)?.[1]
97
98/** The newest `<NNNN>_*.json` file entry for a PR, or undefined. */
99export const reviewFileFor = (pr: number, entries: readonly Listed[]): Listed | undefined => {
100  const prefix = `${String(pr).padStart(4, '0')}_`
101  const hits = entries.filter(e => e.kind === 'file' && e.name.startsWith(prefix) && e.name.endsWith('.json'))
102  return [...hits].sort((a, b) => b.mtimeMs - a.mtimeMs)[0]
103}
104
105const BUBBLE_WORD = /bubble/i
106
107/** The message talks about bubbles: the trigger `BUBBLE-watch.sh` used, any case and inflection. */
108export const mentionsBubble = (text: string | undefined): boolean => BUBBLE_WORD.test(text ?? '')
109
110/**
111 * The keyword-triggered Stop block (the `has_bubbles.py` rule): a message that mentions bubbles needs a
112 * populated `bubbles[]`, unless every issue is already dispositioned. Undefined to let the stop through.
113 */
114export const keywordBlock = (
115  pr: number,
116  text: string | undefined,
117  r: ReviewDoc | undefined,
118  isLoopBreak: boolean,
119): string | undefined => {
120  if (isLoopBreak || r === undefined || !mentionsBubble(text) || r.bubbles.length > 0) return undefined
121  const open = r.issueIds.filter(id => !r.dispositioned.includes(id)).sort(byId)
122  if (open.length === 0) return undefined
123  return (
124    `PR #${pr}: the last message discusses bubbles, but the review JSON's bubbles[] is empty while ` +
125    `${open.join(', ')} remain undispositioned. Populate bubbles[] before discussing bubbles, unless all ` +
126    'issues are already resolved.'
127  )
128}
129
130/** The state-triggered Stop block text, or undefined to let the stop through. */
131export const stopBlock = (
132  pr: number | null,
133  missing: readonly string[],
134  from: string,
135  isLoopBreak: boolean,
136): string | undefined => {
137  if (isLoopBreak || missing.length === 0) return undefined
138  return (
139    `PR #${pr ?? '?'}: the review JSON does not disposition bubbled ${missing.join(', ')} ` +
140    `(tracked from ${from}). Add them to bubbles[] (or bubble_up[] / post_review_resolutions[]) before stopping.`
141  )
142}
143
hooks/contract.ts 201 lines
1import type { Counts, Phase, Skill } from '../types'
2
3/**
4 * Parsers for pr-team / pr-review `Agent` prompts and return-contract blocks (the harness pr-team skill's
5 * `return_contract.md` and `canonical_prompt_template.md`). Pure: no `$`.
6 */
7
8/** Header fields of an `Agent` prompt: `KEY=value` and `KEY: value` lines at column 1. */
9export type Header = Readonly<Record<string, string>>
10
11/** Who a tracked `Agent` dispatch is. */
12export type Dispatch = {
13  runId: string
14  skill: Skill
15  agentId: string
16  role: string
17  pr: number | null
18  runtimeDir: string | null
19  phase: Phase
20}
21
22/**
23 * A parsed return-contract block; `fixed` / `bubbled` are null when the block has no `FIXED:` / `BUBBLED:`
24 * line, `edited` when `EDITED:` is absent or not a count.
25 */
26export type ReturnBlock = {
27  signal: string
28  role: string | null
29  counts: Counts | null
30  fixed: string[] | null
31  bubbled: string[] | null
32  edited: number | null
33  output: string | null
34  notes: string | null
35}
36
37export const MODEL_FAMILIES = ['haiku', 'sonnet', 'opus'] as const
38export type ModelFamily = (typeof MODEL_FAMILIES)[number]
39
40const HEADER_LINE = /^([A-Z][A-Z_]*)(?:=|: )(.*)$/
41const BLOCK_LINE = /^([A-Z][A-Z_]*):(?: (.*))?$/
42const COUNTS_VALUE = /^findings=(\d+) critical=(\d+) important=(\d+) minor=(\d+)$/
43const ISSUE_ID = /^[CIM]\d+$/
44const RUN_ID_PR = /^pr(\d{1,7})_\d{8}T\d{6}Z$/
45const RUN_ID_STAMP = /^pr\d{1,7}_(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/
46
47/** Phase, agent id and role per pr-team agent family and MODE. */
48const MODES: Readonly<Record<string, Readonly<Record<string, readonly [Phase, string, string]>>>> = {
49  orchestrator: {
50    PLAN: ['plan', 'orchestrator_plan', 'orchestrator'],
51    CONSOLIDATE: ['consolidate', 'orchestrator_consolidate', 'orchestrator'],
52  },
53  fixer: { PLAN: ['fix-plan', 'fixer_plan', 'planner'], CLOSEOUT: ['closeout', 'closer', 'closer'] },
54}
55
56/** Key/value lines matching `pattern`; the first occurrence of a key wins. */
57const fieldsOf = (lines: readonly string[], pattern: RegExp): Record<string, string> => {
58  const out: Record<string, string> = {}
59  for (const line of lines) {
60    const m = line.trimEnd().match(pattern)
61    const key = m?.[1]
62    if (key !== undefined && !(key in out)) out[key] = (m?.[2] ?? '').trim()
63  }
64  return out
65}
66
67export const parseHeader = (prompt: string): Header => fieldsOf(prompt.split(/\r?\n/), HEADER_LINE)
68
69/** A positive integer PR number, or null. */
70export const toPr = (raw: string | undefined): number | null =>
71  raw !== undefined && /^\d+$/.test(raw) && Number(raw) >= 1 ? Number(raw) : null
72
73/** The PR a run id names (`pr1122_20260518T060416Z`), or null. */
74export const prOfRunId = (runId: string): number | null => toPr(runId.match(RUN_ID_PR)?.[1])
75
76/** Epoch ms of the UTC stamp a run id carries (`pr1122_20260518T060416Z`), or null when absent or invalid. */
77export const startedAtOfRunId = (runId: string): number | null => {
78  const m = runId.match(RUN_ID_STAMP)
79  if (m === null) return null
80  const [y, mo, d, h, mi, s] = m.slice(1).map(Number) as [number, number, number, number, number, number]
81  const ms = Date.UTC(y, mo - 1, d, h, mi, s)
82  const back = new Date(ms)
83  return back.getUTCMonth() === mo - 1 && back.getUTCDate() === d && h < 24 && mi < 60 && s < 60 ? ms : null
84}
85
86/** The agent family a pr-team subagent type names, or undefined. */
87const familyOf = (subagentType: string): string | undefined =>
88  /orchestrator/.test(subagentType) ? 'orchestrator' : /fixer/.test(subagentType) ? 'fixer' : undefined
89
90/** A pr-team `MODE=` dispatch to the orchestrator or fixer agent. */
91const modeDispatch = (subagentType: string, h: Header, runId: string): Dispatch | undefined => {
92  const family = familyOf(subagentType)
93  const hit = family === undefined ? undefined : MODES[family]?.[h.MODE ?? '']
94  if (hit === undefined) return undefined
95  const [phase, agentId, role] = hit
96  const pr = toPr(h.PR_NUMBER) ?? prOfRunId(runId)
97  return { runId, skill: 'pr-team', agentId, role, pr, runtimeDir: h.RUNTIME_DIR ?? null, phase }
98}
99
100/** The runtime dir an OUTPUT_FILE slot sits in, else `<runtimeBase>/<runId>`. */
101const runtimeDirOf = (h: Header, runId: string, runtimeBase: string): string => {
102  const m = (h.OUTPUT_FILE ?? '').match(/^(.*)[\\/]outputs[\\/][^\\/]+$/)
103  return m?.[1] ?? `${runtimeBase}/${runId}`
104}
105
106/** A slot dispatch (`AGENT_ID:` / `AGENT_ROLE:`): pr-review when a `PR:` line is present. */
107const slotDispatch = (h: Header, runId: string, runtimeBase: string): Dispatch | undefined => {
108  const { AGENT_ID: agentId, AGENT_ROLE: role } = h
109  if (!agentId || (role !== 'reviewer' && role !== 'fixer')) return undefined
110  const isReview = h.PR !== undefined
111  const pr = (isReview ? toPr(h.PR) : null) ?? prOfRunId(runId)
112  const skill: Skill = isReview ? 'pr-review' : 'pr-team'
113  const runtimeDir = isReview ? null : runtimeDirOf(h, runId, runtimeBase)
114  return { runId, skill, agentId, role, pr, runtimeDir, phase: role === 'reviewer' ? 'review' : 'fix' }
115}
116
117/**
118 * Every agent the marketplace defines, as Claude Code names the type: `<plugin>:<file stem>` for each file in a
119 * plugin's `agents` folder. `tests/mods/test_pr_review_watch_usage_contract.py` pins the list to those files.
120 */
121export const DEFINED_AGENTS = [
122  'harness:messenger', 'harness:pr-fixer', 'harness:pr-reviewer', 'harness:pr-team-fixer',
123  'harness:pr-team-orchestrator', 'harness:roast-my-code', 'harness:todo-editor',
124] as const
125
126export const isDefinedAgent = (subagentType: string | undefined): boolean =>
127  (DEFINED_AGENTS as readonly (string | undefined)[]).includes(subagentType)
128
129/** `standalone_<UTC yyyymmddTHHMMSSZ>_<seq>`: one run per dispatch; `seq` tells same-second dispatches apart. */
130export const standaloneRunId = (now: number, seq: number): string =>
131  `standalone_${new Date(now).toISOString().replace(/\.\d+Z$/, 'Z').replace(/[-:]/g, '')}_${seq}`
132
133/**
134 * A defined agent dispatched outside any run header: its own run, its agent id the type's name after the
135 * plugin prefix, role `other`. Undefined for any other agent type.
136 */
137export const identifyStandalone = (subagentType: string | undefined, runId: string): Dispatch | undefined =>
138  subagentType === undefined || !isDefinedAgent(subagentType)
139    ? undefined
140    : {
141      runId, skill: 'standalone', agentId: subagentType.slice(subagentType.indexOf(':') + 1), role: 'other', pr: null,
142      runtimeDir: null, phase: 'done',
143    }
144
145/**
146 * The tracked identity of an `Agent` call, or undefined for any other dispatch. `runtimeBase` is the
147 * project's pr-team runtime folder, used when a pr-team slot names no OUTPUT_FILE.
148 */
149export const identify = (
150  subagentType: string | undefined,
151  prompt: string,
152  runtimeBase: string,
153): Dispatch | undefined => {
154  const h = parseHeader(prompt)
155  const runId = h.RUN_ID
156  if (runId === undefined || runId === '') return undefined
157  return h.MODE !== undefined ? modeDispatch(subagentType ?? '', h, runId) : slotDispatch(h, runId, runtimeBase)
158}
159
160/** Comma-separated issue ids; malformed entries dropped. */
161export const idList = (raw: string): string[] =>
162  raw.split(',').map(s => s.trim()).filter(s => ISSUE_ID.test(s))
163
164/** A COUNTS value, or null when absent or malformed. */
165export const parseCounts = (raw: string | undefined): Counts | null => {
166  const m = raw?.match(COUNTS_VALUE)
167  if (!m) return null
168  return { findings: Number(m[1]), critical: Number(m[2]), important: Number(m[3]), minor: Number(m[4]) }
169}
170
171/** Indexes of column-1 `---` fence lines. */
172const fences = (lines: readonly string[]): number[] => lines.flatMap((l, i) => (l.trimEnd() === '---' ? [i] : []))
173
174const toBlock = (f: Readonly<Record<string, string>>): ReturnBlock => ({
175  signal: f.SIGNAL ?? '',
176  role: f.AGENT_ROLE ?? null,
177  counts: parseCounts(f.COUNTS),
178  fixed: f.FIXED === undefined ? null : idList(f.FIXED),
179  bubbled: f.BUBBLED === undefined ? null : idList(f.BUBBLED),
180  edited: /^\d+$/.test(f.EDITED ?? '') ? Number(f.EDITED) : null,
181  output: f.OUTPUT ?? null,
182  notes: f.NOTES ?? null,
183})
184
185/** The last fenced block that carries a SIGNAL line; undefined when there is none. */
186export const parseReturnBlock = (text: string): ReturnBlock | undefined => {
187  const lines = text.split(/\r?\n/)
188  const at = fences(lines)
189  for (let i = at.length - 1; i >= 1; i--) {
190    const f = fieldsOf(lines.slice((at[i - 1] ?? 0) + 1, at[i]), BLOCK_LINE)
191    if (f.SIGNAL) return toBlock(f)
192  }
193  return undefined
194}
195
196/** The family token in a model id, case-insensitive; undefined when none appears. */
197export const modelFamily = (raw: string | null | undefined): ModelFamily | undefined => {
198  const id = (raw ?? '').toLowerCase()
199  return MODEL_FAMILIES.find(t => id.includes(t))
200}
201
hooks/matrixRow.ts 116 lines
1import type { AgentRec } from '../types'
2import { MODEL_FAMILIES, modelFamily } from './contract'
3
4/**
5 * Rows for the project's invocation matrix (harness `matrix_path`), validated against the rules of the
6 * harness plugin's `schemas/pr_review_invocation_test_matrix.schema.json`. The constants below are pinned
7 * to that schema by `tests/mods/test_pr_review_watch_matrix_contract.py`. Pure: no `$`.
8 */
9
10export const MATRIX_REQUIRED = [
11  'cell', 'pr', 'model_family', 'effort', 'dev_commit', 'dispatch_shape', 'tokens', 'tool_uses', 'duration_s',
12  'findings_count', 'C_count', 'I_count', 'M_count', 'other_count', 'verdict_prefix', 'notes',
13] as const
14export const MATRIX_OPTIONAL = ['phase4_script', 'legacy'] as const
15export const DISPATCH_SHAPES = ['parallel', 'inline'] as const
16export const DEV_COMMIT_PATTERN = '^[0-9a-f]{40}( -- .*)?$'
17
18export type MatrixRow = {
19  cell: string
20  pr: number
21  model_family: string
22  effort: string
23  dev_commit: string
24  dispatch_shape: 'parallel'
25  tokens: number
26  tool_uses: number
27  duration_s: number
28  phase4_script: null
29  findings_count: number
30  C_count: number
31  I_count: number
32  M_count: number
33  other_count: number
34  verdict_prefix: string
35  notes: string
36}
37
38export type RowInput = { pr: number; agent: AgentRec; verdictPrefix: string; devCommit: string }
39
40const STRING_FIELDS = [
41  'cell', 'model_family', 'effort', 'dev_commit', 'dispatch_shape', 'verdict_prefix', 'notes',
42] as const
43const COUNT_FIELDS = [
44  'tokens', 'tool_uses', 'findings_count', 'C_count', 'I_count', 'M_count', 'other_count',
45] as const
46const ALLOWED = new Set<string>([...MATRIX_REQUIRED, ...MATRIX_OPTIONAL])
47const DEV_COMMIT = new RegExp(DEV_COMMIT_PATTERN)
48
49const notesFor = (a: AgentRec): string => {
50  const base = `pr-review-watch auto row; ${a.role} ${a.signal ?? 'pending'}`
51  return a.isMeasured ? base : `${base}; usage not measured (session restarted mid-run)`
52}
53
54const whole = (n: number): number => Math.max(0, Math.round(n))
55
56export const buildRow = (i: RowInput): MatrixRow => {
57  const { agent: a } = i
58  const c = a.counts
59  return {
60    cell: `pr${i.pr}_${a.id}`, pr: i.pr, model_family: modelFamily(a.model) ?? a.model ?? 'unknown',
61    effort: a.effort ?? 'default', dev_commit: i.devCommit, dispatch_shape: 'parallel',
62    tokens: whole(a.tokens), tool_uses: whole(a.toolUses), duration_s: whole(a.durationMs) / 1000,
63    phase4_script: null, findings_count: c?.findings ?? 0, C_count: c?.critical ?? 0, I_count: c?.important ?? 0,
64    M_count: c?.minor ?? 0, other_count: 0, verdict_prefix: i.verdictPrefix, notes: notesFor(a),
65  }
66}
67
68const isCount = (v: unknown): boolean => Number.isInteger(v) && (v as number) >= 0
69const isOneOf = (v: string, options: readonly string[]): boolean => options.includes(v)
70
71/** Range checks on numeric fields that are present. */
72const numberProblems = (row: Readonly<Record<string, unknown>>): string[] => {
73  const out: string[] = []
74  if ('pr' in row && !(Number.isInteger(row.pr) && (row.pr as number) >= 1)) out.push('pr: not a positive integer')
75  const d = row.duration_s
76  const isDuration = typeof d === 'number' && Number.isFinite(d) && d >= 0
77  if ('duration_s' in row && !isDuration) out.push('duration_s: not a non-negative number')
78  return out
79}
80
81/** Enum, pattern and optional-field checks on fields that are present with the right primitive type. */
82const valueProblems = (row: Readonly<Record<string, unknown>>): string[] => {
83  const out = numberProblems(row)
84  const m = row.model_family
85  if (typeof m === 'string' && !isOneOf(m, MODEL_FAMILIES)) {
86    out.push(`model_family: '${m}' is not one of ${MODEL_FAMILIES.join('/')}`)
87  }
88  const s = row.dispatch_shape
89  if (typeof s === 'string' && !isOneOf(s, DISPATCH_SHAPES)) {
90    out.push(`dispatch_shape: '${s}' is not one of ${DISPATCH_SHAPES.join('/')}`)
91  }
92  if (row.legacy !== true && typeof row.dev_commit === 'string' && !DEV_COMMIT.test(row.dev_commit)) {
93    out.push('dev_commit: does not start with a 40-char merge-base SHA')
94  }
95  const p4 = row.phase4_script
96  if ('phase4_script' in row && p4 !== null && typeof p4 !== 'string') out.push('phase4_script: not a string or null')
97  if ('legacy' in row && typeof row.legacy !== 'boolean') out.push('legacy: not a boolean')
98  return out
99}
100
101/** Every way the row breaks the schema; empty when it validates. */
102export const validateRow = (row: Readonly<Record<string, unknown>>): string[] => [
103  ...Object.keys(row).filter(k => !ALLOWED.has(k)).map(k => `${k}: not in the schema`),
104  ...MATRIX_REQUIRED.filter(k => !(k in row)).map(k => `${k}: missing`),
105  ...STRING_FIELDS.filter(k => k in row && typeof row[k] !== 'string').map(k => `${k}: not a string`),
106  ...COUNT_FIELDS.filter(k => k in row && !isCount(row[k])).map(k => `${k}: not a non-negative integer`),
107  ...valueProblems(row),
108]
109
110/** The JSONL text with rows appended, one compact object per line. */
111export const appendRows = (existing: string, rows: readonly object[]): string => {
112  if (rows.length === 0) return existing
113  const head = existing === '' || existing.endsWith('\n') ? existing : `${existing}\n`
114  return head + rows.map(r => `${JSON.stringify(r)}\n`).join('')
115}
116
hooks/usageRow.ts 210 lines
1import type { AgentRec, Skill } from '../types'
2import { modelFamily, type ReturnBlock } from './contract'
3
4/**
5 * Rows for the project's agent usage log (harness `agent_usage_path`), validated against the rules of the
6 * harness plugin's `schemas/pr_review_agent_usage.schema.json`. The constants below are pinned to that
7 * schema by `tests/mods/test_pr_review_watch_usage_contract.py`. Pure: no `$`.
8 */
9
10export const USAGE_REQUIRED = [
11  'logged_at', 'run_id', 'pr', 'skill', 'role', 'agent_id', 'subagent_type', 'model', 'model_family', 'effort',
12  'tokens', 'tool_uses', 'duration_s', 'signal', 'notes',
13] as const
14export const USAGE_COUNT_FIELDS = ['issues_assigned', 'issues_fixed', 'issues_bubbled', 'files_touched'] as const
15export const USAGE_ROLES = ['reviewer', 'fixer', 'orchestrator', 'planner', 'closer', 'other'] as const
16export const USAGE_COUNTED_ROLES = ['fixer', 'closer'] as const
17export const USAGE_SKILLS = ['pr-review', 'pr-team', 'standalone'] as const
18export const USAGE_MODEL_FAMILIES = ['haiku', 'sonnet', 'opus', 'unknown'] as const
19export const LOGGED_AT_PATTERN = '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}([.][0-9]+)?Z$'
20
21/** Fixer outcome counts; null means unknown, never zero. */
22export type FixerCounts = {
23  issues_assigned: number | null
24  issues_fixed: number | null
25  issues_bubbled: number | null
26  files_touched: number | null
27}
28export const NO_COUNTS: FixerCounts = {
29  issues_assigned: null, issues_fixed: null, issues_bubbled: null, files_touched: null,
30}
31
32/** How the dispatch ended: a result the engine reported, or an errored Agent result. */
33export type Ending = 'ok' | 'errored'
34
35export type UsageInput = {
36  runId: string
37  skill: Skill
38  pr: number | null
39  agent: AgentRec
40  ending: Ending
41  isMeasured: boolean
42  loggedAt: number
43  counts: FixerCounts
44}
45
46export type UsageRow = {
47  logged_at: string
48  run_id: string
49  pr: number | null
50  skill: Skill
51  role: string
52  agent_id: string
53  subagent_type: string | null
54  model: string | null
55  model_family: string
56  effort: string
57  tokens: number
58  tool_uses: number
59  duration_s: number
60  signal: string
61  notes: string
62} & Partial<FixerCounts>
63
64const isCountedRole = (role: unknown): boolean => (USAGE_COUNTED_ROLES as readonly unknown[]).includes(role)
65const whole = (n: number): number => Math.max(0, Math.round(n))
66
67const notesFor = (role: string, signal: string, i: UsageInput): string => {
68  const base = `pr-review-watch auto row; ${role} ${signal}`
69  if (i.ending === 'errored') return `${base}; usage not measured; agent errored`
70  return i.isMeasured ? base : `${base}; usage not measured`
71}
72
73export const buildUsageRow = (i: UsageInput): UsageRow => {
74  const a = i.agent
75  const signal = i.ending === 'errored' ? 'ERROR' : (a.signal ?? 'NO_BLOCK')
76  const row: UsageRow = {
77    logged_at: new Date(i.loggedAt).toISOString(), run_id: i.runId, pr: i.pr, skill: i.skill, role: a.role,
78    agent_id: a.id, subagent_type: a.subagentType, model: a.model, model_family: modelFamily(a.model) ?? 'unknown',
79    effort: a.effort ?? 'default', tokens: whole(a.tokens), tool_uses: whole(a.toolUses),
80    duration_s: whole(a.durationMs) / 1000, signal, notes: notesFor(a.role, signal, i),
81  }
82  return isCountedRole(a.role) ? { ...row, ...i.counts } : row
83}
84
85// ---------------------------------------------------------------------------
86// Validation
87
88type Row = Readonly<Record<string, unknown>>
89
90const ALLOWED = new Set<string>([...USAGE_REQUIRED, ...USAGE_COUNT_FIELDS])
91const LOGGED_AT = new RegExp(LOGGED_AT_PATTERN)
92export const NON_EMPTY = ['run_id', 'agent_id', 'effort', 'signal'] as const
93const STRINGS = ['logged_at', 'skill', 'role', 'model_family', 'notes', ...NON_EMPTY] as const
94export const NULLABLE_STRINGS = ['subagent_type', 'model'] as const
95const ENUMS: readonly [string, readonly string[]][] = [
96  ['skill', USAGE_SKILLS], ['role', USAGE_ROLES], ['model_family', USAGE_MODEL_FAMILIES],
97]
98
99const isCount = (v: unknown): boolean => Number.isInteger(v) && (v as number) >= 0
100
101/** Type checks on the string fields that are present. */
102const stringProblems = (row: Row): string[] => [
103  ...STRINGS.filter(k => k in row && typeof row[k] !== 'string').map(k => `${k}: not a string`),
104  ...NON_EMPTY.filter(k => row[k] === '').map(k => `${k}: empty`),
105  ...NULLABLE_STRINGS.filter(k => k in row && row[k] !== null && typeof row[k] !== 'string')
106    .map(k => `${k}: not a string or null`),
107]
108
109/** Enum and pattern checks on string fields that are present. */
110const valueProblems = (row: Row): string[] => {
111  const out = ENUMS.flatMap(([k, options]) =>
112    typeof row[k] === 'string' && !options.includes(row[k] as string)
113      ? [`${k}: '${String(row[k])}' is not one of ${options.join('/')}`] : [])
114  if (typeof row.logged_at === 'string' && !LOGGED_AT.test(row.logged_at)) out.push('logged_at: not an ISO UTC time')
115  return out
116}
117
118/** Range checks on the numeric fields that are present. */
119const numberProblems = (row: Row): string[] => {
120  const out = (['tokens', 'tool_uses'] as const).filter(k => k in row && !isCount(row[k]))
121    .map(k => `${k}: not a non-negative integer`)
122  const pr = row.pr
123  const isPr = Number.isInteger(pr) && (pr as number) >= 1
124  if ('pr' in row && pr !== null && !isPr) out.push('pr: not a positive integer or null')
125  const d = row.duration_s
126  if ('duration_s' in row && !(typeof d === 'number' && Number.isFinite(d) && d >= 0)) {
127    out.push('duration_s: not a non-negative number')
128  }
129  return out
130}
131
132/** Count fields: required (count or null) on fixer and closer rows, absent on every other role. */
133const countProblems = (row: Row): string[] => {
134  if (!isCountedRole(row.role)) {
135    return USAGE_COUNT_FIELDS.filter(k => k in row).map(k => `${k}: only on fixer and closer rows`)
136  }
137  return USAGE_COUNT_FIELDS.flatMap(k =>
138    !(k in row) ? [`${k}: missing`] : row[k] !== null && !isCount(row[k]) ? [`${k}: not a count or null`] : [])
139}
140
141/** Every way the row breaks the schema; empty when it validates. */
142export const validateUsageRow = (row: Row): string[] => [
143  ...Object.keys(row).filter(k => !ALLOWED.has(k)).map(k => `${k}: not in the schema`),
144  ...USAGE_REQUIRED.filter(k => !(k in row)).map(k => `${k}: missing`),
145  ...stringProblems(row),
146  ...valueProblems(row),
147  ...numberProblems(row),
148  ...countProblems(row),
149]
150
151// ---------------------------------------------------------------------------
152// Fixer counts
153
154/** Counts from a fixer or closer return block; `issues_assigned` is never in a block. */
155export const blockCounts = (b: ReturnBlock | undefined): FixerCounts => ({
156  issues_assigned: null,
157  issues_fixed: b?.fixed?.length ?? null,
158  issues_bubbled: b?.bubbled?.length ?? null,
159  files_touched: b?.edited ?? null,
160})
161
162const isRecord = (v: unknown): v is Record<string, unknown> =>
163  typeof v === 'object' && v !== null && !Array.isArray(v)
164
165const parseJson = (text: string | undefined): unknown => {
166  if (text === undefined) return undefined
167  try {
168    return JSON.parse(text)
169  } catch {
170    return undefined
171  }
172}
173
174/** The length of a fixer's `issue_ids` in a pr-review `waves.json`; null when absent or malformed. */
175const assignedIn = (wavesText: string | undefined, agentId: string): number | null => {
176  const doc = parseJson(wavesText)
177  const waves = isRecord(doc) && Array.isArray(doc.waves) ? doc.waves : []
178  const fixer = waves.flatMap(w => (Array.isArray(w) ? w : [])).find(f => isRecord(f) && f.id === agentId)
179  return isRecord(fixer) && Array.isArray(fixer.issue_ids) ? fixer.issue_ids.length : null
180}
181
182/** Distinct `files` across a report's `fixed` entries. */
183const editedFiles = (fixed: readonly unknown[]): number =>
184  new Set(fixed.flatMap(e => (isRecord(e) && Array.isArray(e.files) ? e.files : []))).size
185
186/** Counts from a pr-review fixer's `waves.json` entry and its `fixes/<agentId>.json` report. */
187export const reportCounts = (
188  wavesText: string | undefined,
189  reportText: string | undefined,
190  agentId: string,
191): FixerCounts => {
192  const report = parseJson(reportText)
193  const fixed = isRecord(report) && Array.isArray(report.fixed) ? report.fixed : null
194  const bubbled = isRecord(report) && Array.isArray(report.bubbled) ? report.bubbled : null
195  return {
196    issues_assigned: assignedIn(wavesText, agentId),
197    issues_fixed: fixed?.length ?? null,
198    issues_bubbled: bubbled?.length ?? null,
199    files_touched: fixed === null ? null : editedFiles(fixed),
200  }
201}
202
203/** `primary`, with each null field taken from `fallback`. */
204export const preferCounts = (primary: FixerCounts, fallback: FixerCounts): FixerCounts => ({
205  issues_assigned: primary.issues_assigned ?? fallback.issues_assigned,
206  issues_fixed: primary.issues_fixed ?? fallback.issues_fixed,
207  issues_bubbled: primary.issues_bubbled ?? fallback.issues_bubbled,
208  files_touched: primary.files_touched ?? fallback.files_touched,
209})
210