import { join } from 'node:path' import { ARTIFACT_LAYOUT, type ActivityKind } from '@basementstudio/qa-schema' import { recordActivity, redactForActivity, trackActivity } from '@basementstudio/qa-engine/run' import type { ToolContext } from './tools' /** * Recording a tool call, for **every** way a tool can be called. * * ## Why this is its own module * * It lived inside `createServer`, closed over that function's `ctx`, and was reachable only through the * `registerTool` wrapper. So `qa mcp ` — which `SKILL.md` §4 presents as the equivalent fallback * *"if you are not registered with the server"*, and which calls the `tools.*` functions directly — * recorded nothing at all. Reported from a real review: 28 issues written and `global/activity/` never * created, which makes the whole timeline invisible to the path the instructions tell an agent to take. * * The fix is the same shape as the original decision. `registerTool` was wrapped once rather than editing * sixteen handlers because a per-handler call is a thing sixteen future registrations can forget; a * recorder that only one of two *call paths* reaches is that bug one level up. One module, imported by * both, so a new host has to opt out rather than remember to opt in. * * ## It returns a promise, and **whether you await it is the difference between the two hosts** * * The server does not: a diagnostic that can slow down or fail the call it describes has inverted its own * priority, and it is a long-lived process where the write lands whenever it lands. * * `qa mcp ` **must**. It is one process per call, and it exits as soon as it has printed the result * — so a fire-and-forget write is simply abandoned. Measured while fixing the bug above: wiring the * recorder into the CLI and not awaiting it still produced **no `global/activity/` at all**, which looks * exactly like not having wired it in. Same class as `clearProgress` racing a progress write, one process * boundary further out. * * It never rejects either way, so awaiting it cannot fail a call that otherwise worked. It returns without * writing when there is no run to attribute the call to — an event with no run has nowhere to go, which is * why `qa_runs` with no `--run` records nothing and should not. */ /** * What each tool is *for*, in the run's vocabulary. See `ActivityKind`. * * An explicit map rather than a prefix rule, because `qa_findings` and `qa_issue_write` share a * namespace and mean opposite things — and because a tool missing from here is `other`, which is * honest, where a clever rule would guess. */ export const KIND_OF_TOOL: Record = { qa_runs: 'orient', qa_run: 'orient', qa_projects: 'orient', qa_schema: 'orient', qa_findings: 'reading', qa_findings_md: 'reading', qa_facts: 'reading', qa_issues: 'reading', qa_screenshot: 'looking', qa_screenshots: 'looking', /** * `reading`, and **not a new `verifying` kind**, however much it wants to be one. * * `ActivityKind` is a closed set on purpose, and `activity.ts::isReading` enumerates three of its * members by hand — so a new member would classify every fetch-to-fetch gap as `other` instead of * `investigating` and quietly change the run timeline, which is the enumerated-renderer trap * `CLAUDE.md` records for `kind`. Nothing is lost: the count that matters for this tool is *how many * fetches replaced a shell-out*, and that comes off the `tool` field, not the kind. */ qa_fetch: 'reading', qa_issue_write: 'authoring', qa_issue_delete: 'authoring', qa_waive: 'waiving', qa_set_finished: 'publishing', } /** * Who the caller is, for the whole of its life. * * `QA_ACTOR` where an orchestrator spawns shards and wants them told apart; otherwise one id per * process, which groups a single-agent run correctly with nothing configured. Deliberately not a tool * parameter: a field an agent has to pass is a field it will forget, and then two reviewers merge into * one row. * * **The prefix names the call path, not the transport's importance.** A shell-driven review is one actor * per invocation, so a fourteen-call review from the shell is fourteen actors — and `ActorActivity` is * per actor. That is a real limitation of driving tools from a shell and the reason `QA_ACTOR` is worth * exporting to a reviewer that runs more than one command: `export QA_ACTOR=reviewer-careers` makes the * whole shard one actor. */ export const actorId = (): string => process.env.QA_ACTOR?.trim() || `qa-${process.pid}` export interface CallRecord { tool: string /** The tool's own arguments. Only `runId`, `route` and `askedOf`'s closed vocabulary are read off it. */ input: unknown ok: boolean ms: number error?: string } /** Filter keys worth recording, per tool. Closed sets, so a typo'd key records nothing rather than itself. */ const FILTER_KEYS: Record = { qa_findings: ['route', 'siteOnly', 'severity', 'category', 'kind', 'defectsOnly', 'notesOnly', 'search', 'excludeWaived'], qa_issues: ['route', 'siteOnly', 'unreviewedOnly', 'titlesOnly', 'fields', 'ids'], } /** * What a call asked for, as closed-vocabulary tokens — **never the arguments**. * * ## Why this projection is narrow on purpose * * `ActivityEvent` forbids prose, and `qa_issue_write`'s input is almost entirely prose a reader sees. So * nothing here reads a title, a `problem`, a `why` or a reason: each tool contributes only values from a * set that was closed before the call — a section name, a filter key, a check id, a file extension. * `activity-record.test.ts` pins that a title never reaches the log. * * ## What each token is for * * The whole point is ranking **digest gaps** by what reviewers actually go and fetch. `qa_facts`' * `sections` is the load-bearing one: a section appearing there repeatedly is a question the brief did * not answer, and that is the list nobody has ever had. `qa_fetch`'s extension says the same thing for * the network — *"reviewers keep fetching `.md` endpoints"* is a sentence the corpus should be able to * produce on its own. */ export function askedOf(tool: string, input: unknown): string[] { const args = (input ?? {}) as Record if (tool === 'qa_facts') { const sections = Array.isArray(args.sections) ? args.sections.filter((s) => typeof s === 'string') : [] /* No sections is the default call, and it is a different ask from any named one. */ return sections.length === 0 ? ['summary'] : (sections as string[]).map((s) => s.slice(0, 60)) } if (tool === 'qa_fetch') { const out = [args.body ? 'body' : 'headers'] /* * The extension only. A URL path is caller data and could be anything; an extension is bounded and * is the half that aggregates — it answers "what kind of thing do reviewers go and fetch". */ if (typeof args.url === 'string') { const ext = /\.([a-z0-9]{1,8})(?:[?#]|$)/i.exec(args.url)?.[1] if (ext) out.push(`.${ext.toLowerCase()}`) } return out } const keys = FILTER_KEYS[tool] if (keys) { const used = keys.filter((k) => { const v = args[k] if (v === undefined || v === null) return false /* An explicit `false` or an empty array narrows nothing, and recording it would overstate the ask. */ if (typeof v === 'boolean') return v if (Array.isArray(v)) return v.length > 0 return true }) /* A check id is an id from a closed catalogue, not prose, and it is the most useful single token here. */ if (tool === 'qa_findings' && typeof args.checkId === 'string') used.push(`checkId:${args.checkId.slice(0, 60)}`) return used } return [] } /** * A recorder bound to one store and default run. * * **Await it from a process that is about to exit; do not from a server.** See the module header — the * returned promise is the whole reason a one-shot CLI call can record anything at all. It resolves rather * than rejects on failure, so awaiting is always safe. */ export function makeRecorder(ctx: ToolContext): (call: CallRecord) => Promise { /* * `trackActivity` because the body awaits before `recordActivity` registers its chain, and a drain in * that gap would silently lose the record — see the note on `pending` in `activity.ts`. */ return (call) => trackActivity(record(ctx, call)) } async function record(ctx: ToolContext, { tool, input, ok, ms, error }: CallRecord): Promise { const given = (input as { runId?: string } | undefined)?.runId ?? ctx.defaultRunId if (!given) return /** * **Resolved, never taken verbatim.** * * `latest` is a legal `runId` on every read tool and on `issueWrite`, so a caller passing it is doing * nothing wrong — but unresolved it builds `runs/latest/global/activity/` and writes the whole * session's telemetry into a directory no reader of that run ever opens. Measured on a five-reviewer * experiment: every call any of them made was recorded, and every one of them was invisible. * * Falls back to the literal on failure because a recorder that throws loses the call it was * recording, and a mislocated record still beats no record. */ const runId = await ctx.store.resolveRunId(given).catch(() => given) await recordActivity( { at: new Date().toISOString(), actor: actorId(), route: (input as { route?: string } | undefined)?.route ?? '', tool, kind: KIND_OF_TOOL[tool] ?? 'other', /* * The one thing `kind` cannot express, because it is derived from the tool name. See the field * note on `ActivityEvent.dryRun`: without this, a validation and a write are the same record, * and the batch contract makes reviewers do both for every issue. */ ...((input as { dryRun?: boolean } | undefined)?.dryRun ? { dryRun: true } : {}), ms: Math.round(ms), ok, ...(() => { const asked = askedOf(tool, input) return asked.length > 0 ? { asked } : {} })(), ...(error ? { error: redactForActivity(error).slice(0, 300) } : {}), }, join(ctx.store.runDir(runId), ARTIFACT_LAYOUT.activityDir), ctx.store.storage, ) }