:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(qa-team): prompt-cache-aware agent launch protocol (#71617)
Robbie87f6ea131847
diff --git a/.agents/skills/qa-team/SKILL.md b/.agents/skills/qa-team/SKILL.mdindex 365977954fca..5a0e2e38cbfc 100644--- a/.agents/skills/qa-team/SKILL.md+++ b/.agents/skills/qa-team/SKILL.md@@ -28,15 +28,21 @@ analysis will be performed. This ensures findings are fully independent.Determine the base branch. If the user provided `$ARGUMENTS`, use that as the base branch.Otherwise, default to `master`.-Run these commands to collect context:+Create a run directory **outside the repository** (session scratchpad or `mktemp -d` — never+inside the repo), then collect context into it:```bash-git diff <base>...HEAD --name-only-git diff <base>...HEAD-git log <base>...HEAD --oneline+RUN_DIR="$(mktemp -d "${TMPDIR:-/tmp}/qa-team-XXXXXX")"+mkdir -p "$RUN_DIR/personas" "$RUN_DIR/claimed"+git diff <base>...HEAD --name-only > "$RUN_DIR/files.txt"+git log <base>...HEAD --oneline > "$RUN_DIR/commits.txt"+git diff <base>...HEAD > "$RUN_DIR/diff.patch"```-Store the full diff, changed file list, and commit messages. These will be passed to each agent.+The run directory holds the persona queue, the claim script, and the generated launch+scripts (Step 3); the diff is baked into the shared agent prompt by the build script,+without passing through the model (see Step 3 for why). Keep `diff.patch` on disk — the+build script reads it, and oversized diffs fall back to it at review time.If there are no changes, inform the user and stop.@@ -65,15 +71,35 @@ compatibility) until at least 4 specialists are active.**Always launch both generalist agents** (`generalist-a` and `generalist-b`) regardless offile classification. They review all changes.-### Step 3: Launch parallel review agents--Launch all relevant agents **simultaneously** using the Agent tool.--**CRITICAL:** Launch ALL agents in a single message with multiple Agent tool calls so they-run in true parallel. Do NOT launch them sequentially.+### Step 3: Launch the review agents (cache-aware protocol)++**Why this protocol exists:** every agent request carries a large fixed prefix (system+prompt, tools, project context, and the user prompt) that is prompt-cached **only when the+prompt is byte-identical across agents**. Prompt caching is strict-prefix based: one+divergent character anywhere in the prompt forces the entire prefix — tens of thousands of+tokens — to be re-ingested at full price by every agent. Four rules follow:++1. **Every agent gets the same prompt, byte for byte — including the full diff.** The+ diff inside the identical prompt is part of the shared cached prefix, so followers+ ingest it at cache-read prices instead of each re-paying write prices for a+ file-read tool result.+2. **The launch scripts are built by a shipped build tool, never typed by the+ orchestrator.** `scripts/build_launch_scripts.js` JSON-encodes the prompt (diff+ included) into two Workflow script files, so the diff never passes through the model+ as output tokens and the two scripts' prompts cannot drift apart by a stray byte.+3. **Per-agent divergence (the persona) arrives via a tool result, not the prompt.** Each+ agent's first action is to run a claim script that atomically assigns it a persona.+ Tool results come after the shared prefix, so they don't break the cache. Never deliver+ the persona as a follow-up message to a completed agent — resuming a finished agent+ rebuilds its request from scratch and misses the cache entirely.+4. **Stagger the launch.** The first reviewer launches alone; its persona claim appearing+ in `claimed/` is the signal that its first request finished and the shared prefix is+ cached. Only then do the remaining reviewers launch in parallel and read it. A+ simultaneous cold launch makes every agent write the prefix instead of reading it+ (measured: two agents launched together each wrote the full ~42k tokens).**CRITICAL — Agent independence:** Each agent must operate in total isolation. Do NOT-include any of the following in any agent's prompt:+include any of the following in the shared prompt or in any persona file:- Names, codenames, or descriptions of other agents- The number of agents being launched@@ -82,76 +108,39 @@ include any of the following in any agent's prompt:- Any reference to a "team" of reviewersEach agent believes it is the sole reviewer. This ensures fully independent findings.+(The persona queue on disk necessarily contains the other personas; the shared prompt+forbids agents from inspecting the run directory, which preserves independence in+practice.)-#### Specialist agent prompt template+#### 3a. Write the persona files-For each specialist agent (security, database, reliability, performance, frontend,-compatibility, data-integrity, copy), build the prompt from these parts:+Write one file per selected agent to `$RUN_DIR/personas/`, named with a numeric prefix so+claim order is deterministic (`01-generalist-a.md`, `02-generalist-b.md`, `03-security.md`,+`04-database.md`, ...). The generalists come first because they run in every review, so+reviewer 1 — the agent that warms the shared cache — is always the same persona+regardless of which specialists the diff selects. The number of persona files must equal+the number of reviewers you will launch — the build script derives the launch count from+this directory.-1. **Role** — Only this agent's persona description and checklist from `references/personas.md`-2. **Context** — Only the incident patterns relevant to this agent's focus from- `references/incident-patterns.md`. Omit for the copy agent.-3. **Diff material** — Changed files, commit messages, and the full diff+For each **specialist** (security, database, reliability, performance, frontend,+compatibility, data-integrity, copy), the file contains:```text-You are a code reviewer specializing in {FOCUS_AREA}.+Your assigned review focus: {FOCUS_AREA}## Your expertise{PERSONA_DESCRIPTION_AND_CHECKLIST from references/personas.md — this agent's section only}## Known failure patterns{RELEVANT_PATTERNS from references/incident-patterns.md — only patterns matching-this agent's focus area. Omit this entire section for the copy agent.}--## Code changes to review--### Changed files-{FILE_LIST}--### Commit messages-{COMMIT_LOG}--### Full diff-{FULL_DIFF}--## Instructions--1. Read the full diff carefully. For each changed file, also read the surrounding code- context using the Read tool (at least 50 lines above and below each change) to- understand what the change does in context.--2. Apply your review checklist systematically. For each item, determine if the change- introduces a risk.--3. Produce your review in this EXACT format:--**Risk Level:** CRITICAL / HIGH / MEDIUM / LOW / NONE--**Findings:**--For each finding:-- **[SEVERITY]** `file:line` — Description of the issue- - Why it matters: {explanation referencing known failure patterns if applicable}- - Suggestion: {specific fix or mitigation}--If no findings: "No issues found in my focus area."--**Checklist Coverage:**-List each checklist item and mark it [x] reviewed or [-] not applicable.--**Summary:**-One paragraph summarizing your overall assessment.+this agent's focus area. Omit this entire section for the copy persona.}```-#### Generalist agent prompt template--Always launch both generalist agents (`generalist-a` and `generalist-b`). Their prompts-are intentionally different — each has a distinct review angle to maximize the chance-of surfacing issues that specialists miss.--**Generalist A** — reviews from a "new team member" perspective:+Always include both **generalist** personas. Generalist A (fresh-eyes senior engineer):```text+Your assigned review focus: general correctness and safety+You are a senior software engineer reviewing this code change for the first time.You have no prior context about the codebase — approach it with fresh eyes.@@ -164,46 +153,14 @@ Focus on things that would concern you if you saw this code in a pull request:- Are there any "that looks wrong" moments?Do NOT focus on style, formatting, or minor nits. Focus on correctness and safety.--## Code changes to review--### Changed files-{FILE_LIST}--### Commit messages-{COMMIT_LOG}--### Full diff-{FULL_DIFF}--## Instructions--1. Read the full diff carefully. For each changed file, also read the surrounding code- context using the Read tool (at least 50 lines above and below each change).--2. Think about what could go wrong. Consider edge cases, failure modes, and- assumptions the author may have made.--3. Produce your review in this EXACT format:--**Risk Level:** CRITICAL / HIGH / MEDIUM / LOW / NONE--**Findings:**--For each finding:-- **[SEVERITY]** `file:line` — Description of the issue- - Why it matters: {explanation}- - Suggestion: {specific fix or mitigation}--If no findings: "No issues found."--**Summary:**-One paragraph summarizing your overall assessment.+This focus has no formal checklist — omit the Checklist Coverage section from your review.```-**Generalist B** — reviews from an "adversarial tester" perspective:+Generalist B (adversarial tester):```text+Your assigned review focus: breakability+You are a QA engineer who tries to break things. Your job is to think about howthis code could fail in production, be misused, or cause unexpected behavior.@@ -217,42 +174,67 @@ edge-case dataset. For each change, ask:- What if a developer misunderstands this code and extends it incorrectly?Do NOT focus on style or readability. Focus on breakability.+This focus has no formal checklist — omit the Checklist Coverage section from your review.+```-## Code changes to review--### Changed files-{FILE_LIST}--### Commit messages-{COMMIT_LOG}--### Full diff-{FULL_DIFF}--## Instructions--1. Read the full diff carefully. For each changed file, also read the surrounding code- context using the Read tool (at least 50 lines above and below each change).--2. Try to find ways to break it. Think adversarially.--3. Produce your review in this EXACT format:--**Risk Level:** CRITICAL / HIGH / MEDIUM / LOW / NONE--**Findings:**--For each finding:-- **[SEVERITY]** `file:line` — Description of the issue- - Why it matters: {explanation}- - Suggestion: {specific fix or mitigation}+#### 3b. Install the claim script and build the launch scripts-If no findings: "No issues found."+Both live in this skill's `scripts/` directory — copy the claim script into the run+directory, then build the two Workflow launch scripts from the run directory's contents:-**Summary:**-One paragraph summarizing your overall assessment.+```bash+SKILL_DIR="<this skill's base directory>"+cp "$SKILL_DIR/scripts/claim_persona.sh" "$RUN_DIR/"+node "$SKILL_DIR/scripts/build_launch_scripts.js" "$RUN_DIR"```+`claim_persona.sh` atomically hands each caller the next unclaimed persona (`mv` is+atomic, so concurrent agents each win a distinct one). `build_launch_scripts.js`+JSON-encodes the shared review prompt — claim instruction, changed files, commit+messages, and the full diff (or a read-from-disk instruction when the diff exceeds+~200 KB) — into `$RUN_DIR/launch_first.js` and `$RUN_DIR/launch_rest.js`, sizing the+parallel fan-out from the persona count. The prompt text itself lives in the build+script; do not re-type or edit the generated files.++#### 3c. Launch in two phases++1. Invoke the Workflow tool with `{scriptPath: "$RUN_DIR/launch_first.js"}`. It launches+ reviewer 1 alone, in the background.+2. Poll for reviewer 1's persona claim — the signal that its **first request** completed+ (~15 seconds in) and the shared prefix (diff included) is cached:++ ```bash+ timeout 120 bash -c 'until [ -n "$(ls -A '"$RUN_DIR"'/claimed)" ]; do sleep 1; done'+ ```++ Do NOT wait for the first workflow run to complete — reviewer 1 keeps reviewing while+ the rest launch, so all reviewers run concurrently apart from this brief warm-up+ window. If the poll times out, first check whether the `launch_first` run errored,+ then continue and note in the final report that the run proceeded uncached — a cache+ miss costs money, not correctness, but it should be attributable.++3. Invoke the Workflow tool with `{scriptPath: "$RUN_DIR/launch_rest.js"}`. It launches+ the remaining reviewers in parallel; each reads the cached prefix reviewer 1 wrote.+4. Both workflow runs return `{ reviews: [...] }` as they complete — collect both for+ Step 4. Failed reviewers appear as explicit `REVIEWER FAILED: ...` sentinel entries,+ never as silently missing reviews.+5. **Reconcile before synthesizing:** `personas/` must be empty and the number of+ collected reviews (sentinels included) must equal the persona count. On a mismatch,+ name the unclaimed or unreviewed personas in the report — or relaunch a single agent+ for the leftovers — rather than presenting partial coverage as a complete review.+ (Known limitation: a claim is not idempotent — an agent that reruns the claim consumes+ a second persona and starves a later reviewer; the reconciliation step is what catches+ this.)++After the report is written, best-effort clean up the run directory (`rm -rf "$RUN_DIR"`)+— it contains the full diff on disk and has no further use.++**Fallback:** if the Workflow tool is unavailable, launch agents directly with the Agent+tool using one shared prompt that references the run-dir files instead of embedding the+diff (`Read $RUN_DIR/diff.patch` etc. — hand-typing the diff N times costs more than the+cache saves). Launch the first agent, run the same `claimed/` poll as above, then launch+the rest in a single message in parallel.+### Step 4: Synthesize the reportAfter all agents complete, compile their findings into a unified report.@@ -375,7 +357,7 @@ in the `Agents` column and carry higher confidence.### Persona Definitions-- **`references/personas.md`** -- Full persona descriptions, context, and review checklists for specialist agents (not used for generalists — they have their own prompts)+- **`references/personas.md`** -- Full persona descriptions, context, and review checklists for specialist agents (not used for generalists — their persona files are defined inline in Step 3a)### Incident Patternsdiff --git a/.agents/skills/qa-team/scripts/build_launch_scripts.js b/.agents/skills/qa-team/scripts/build_launch_scripts.jsnew file mode 100644index 000000000000..100d95edf4b4--- /dev/null+++ b/.agents/skills/qa-team/scripts/build_launch_scripts.js@@ -0,0 +1,148 @@+#!/usr/bin/env node+// Build the qa-team Workflow launch scripts for a review run.+//+// Usage: node build_launch_scripts.js <RUN_DIR>+//+// Reads diff.patch, files.txt, commits.txt, and personas/ from RUN_DIR and writes+// launch_first.js and launch_rest.js next to them, with the shared review prompt+// JSON-encoded into both. Building the scripts with this tool (instead of having+// the orchestrating agent type them) keeps the two prompts byte-identical — the+// prompt-cache invariant the launch protocol depends on — and means the diff never+// passes through the model as output tokens.++const fs = require('fs')+const path = require('path')++// Above this size the diff is not inlined into the prompt: agents read it from+// disk instead (paying per-agent ingestion, but keeping requests well-formed).+const MAX_EMBED_BYTES = 200_000++const PROMPT_TEMPLATE = `You are a code reviewer. Your specific review focus is pre-assigned. Follow these steps exactly:++1. FIRST action — run this exact command with the Bash tool to receive your review focus:++ bash "__RUN_DIR__/claim_persona.sh"++ It prints your assigned focus, expertise, checklist, and known failure patterns. Conduct your entire review through that lens. If the command reports an error, stop immediately and report that error text as your entire review — do not improvise a focus. Do not read, list, or otherwise inspect anything inside __RUN_DIR__ other than running this command and, if step 2 below explicitly instructs it, reading the diff file it names.++2. The code changes to review:++### Changed files++__FILE_LIST__++### Commit messages++__COMMIT_LOG__++### Full diff++__FULL_DIFF__++3. Read the full diff carefully. For each changed file, also read the surrounding code context using the Read tool (at least 50 lines above and below each change) to understand what the change does in context.++4. Apply your assigned review checklist systematically. For each item, determine if the change introduces a risk.++5. Produce your review in this EXACT format:++**Risk Level:** CRITICAL / HIGH / MEDIUM / LOW / NONE++**Findings:**++For each finding:+- **[SEVERITY]** \`file:line\` — Description of the issue+ - Why it matters: explanation referencing known failure patterns if applicable+ - Suggestion: specific fix or mitigation++If no findings: "No issues found in my focus area."++**Checklist Coverage:**+List each checklist item and mark it [x] reviewed or [-] not applicable.+(Omit this section if your assigned focus says it has no formal checklist.)++**Summary:**+One paragraph summarizing your overall assessment.`++const FIRST_TEMPLATE = `export const meta = {+ name: 'qa-team-launch-first',+ description: 'Launch the first QA reviewer to warm the shared prompt prefix',+ phases: [{ title: 'First reviewer' }],+}+const PROMPT = __PROMPT_JSON__+phase('First reviewer')+const review = await agent(PROMPT, { label: 'reviewer-1', phase: 'First reviewer' })+return { reviews: [review || 'REVIEWER FAILED: reviewer-1 returned no review'] }+`++// Failed reviewers must stay visible as explicit sentinels — a silently shorter+// review list reads as complete coverage during synthesis.+const REST_TEMPLATE = `export const meta = {+ name: 'qa-team-launch-rest',+ description: 'Launch the remaining QA reviewers against the warmed prefix',+ phases: [{ title: 'Reviewers' }],+}+const PROMPT = __PROMPT_JSON__+phase('Reviewers')+const results = await parallel(+ Array.from({ length: __REST_COUNT__ }, (_, i) => () =>+ agent(PROMPT, { label: \`reviewer-\${i + 2}\`, phase: 'Reviewers' })+ )+)+const reviews = results.map((r, i) => r || \`REVIEWER FAILED: reviewer-\${i + 2} returned no review\`)+return { reviews }+`++function main() {+ if (process.argv.length !== 3) {+ console.error(`usage: node ${path.basename(process.argv[1])} <RUN_DIR>`)+ process.exit(1)+ }+ const runDir = path.resolve(process.argv[2])++ const fileList = fs.readFileSync(path.join(runDir, 'files.txt'), 'utf8').trim()+ const commitLog = fs.readFileSync(path.join(runDir, 'commits.txt'), 'utf8').trim()+ const reviewerCount = fs.readdirSync(path.join(runDir, 'personas')).filter((f) => f.endsWith('.md')).length+ if (reviewerCount < 2) {+ console.error('need at least 2 persona files in personas/ before building')+ process.exit(1)+ }++ const diffPath = path.join(runDir, 'diff.patch')+ const diffSize = fs.statSync(diffPath).size+ if (diffSize === 0) {+ console.error('diff.patch is empty — nothing to review')+ process.exit(1)+ }+ const fullDiff =+ diffSize > MAX_EMBED_BYTES+ ? `The diff is too large to inline. Read it from "${diffPath}" with the Read tool (in chunks if needed) before reviewing.`+ : fs.readFileSync(diffPath, 'utf8').trim()++ // Single-pass fill: every placeholder is substituted in one scan of the+ // original template, so placeholder-shaped text inside substituted content+ // (a diff that mentions __REST_COUNT__, a commit subject naming+ // __FULL_DIFF__) is never itself rewritten. The function replacement also+ // keeps `$&`-style patterns in diff content literal.+ const fill = (template, vars) =>+ template.replace(/__([A-Z_]+?)__/g, (match, key) => (key in vars ? vars[key] : match))++ const prompt = fill(PROMPT_TEMPLATE, {+ RUN_DIR: runDir,+ FILE_LIST: fileList,+ COMMIT_LOG: commitLog,+ FULL_DIFF: fullDiff,+ })+ // U+2028/U+2029 are valid in JSON strings but only valid in JS string+ // literals under ES2019 JSON-superset parsing — escape them so the+ // generated scripts parse under any dialect.+ const promptJson = JSON.stringify(prompt).replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')++ fs.writeFileSync(path.join(runDir, 'launch_first.js'), fill(FIRST_TEMPLATE, { PROMPT_JSON: promptJson }))+ fs.writeFileSync(+ path.join(runDir, 'launch_rest.js'),+ fill(REST_TEMPLATE, { PROMPT_JSON: promptJson, REST_COUNT: String(reviewerCount - 1) })+ )+ console.info(`built ${runDir}/launch_first.js and ${runDir}/launch_rest.js for ${reviewerCount} reviewers`)+}++main()diff --git a/.agents/skills/qa-team/scripts/claim_persona.sh b/.agents/skills/qa-team/scripts/claim_persona.shnew file mode 100755index 000000000000..d4124040198f--- /dev/null+++ b/.agents/skills/qa-team/scripts/claim_persona.sh@@ -0,0 +1,22 @@+#!/bin/bash+# Atomically claim the next unclaimed persona from the run directory's queue.+# Each review agent runs this as its first action; mv is atomic, so concurrent+# claimers each win exactly one persona file.+dir="$(cd "$(dirname "$0")" && pwd)"+mkdir -p "$dir/claimed"+for f in "$dir"/personas/*.md; do+ [ -e "$f" ] || continue+ name="$(basename "$f")"+ # mv errors are expected noise when losing a claim race; the post-loop check+ # distinguishes a genuinely exhausted queue from a broken run directory.+ if mv "$f" "$dir/claimed/$name" 2>/dev/null; then+ cat "$dir/claimed/$name"+ exit 0+ fi+done+if [ -n "$(ls -A "$dir/personas" 2>/dev/null)" ]; then+ echo "ERROR: claim failed: personas remain in $dir/personas but could not be moved to $dir/claimed (check permissions/mount)" >&2+else+ echo "ERROR: no persona available (queue exhausted — more claimers than personas, or claim retried)" >&2+fi+exit 1