0009 - Agent Context Reuse¶
Status¶
Accepted 2026-10-03 by the owner, as written (session reuse across runs was considered and left out, keeping ADR-0006's fresh sessions). Builds on ADR-0005, ADR-0006, ADR-0007, and ADR-0008.
Date¶
2026-10-02
Context¶
ADR-0006 gives every run a fresh process and workspace. Taskbase supplies the task and persona; the repository supplies current instructions and code. A revision, review, or follow-up must rediscover information that another run may have found. We want to reuse findings without resuming a model conversation, treating a prior agent's assertions as truth, or moving provider-specific data into Taskbase.
Measured baseline¶
The following is a snapshot of Taskbase MCP get_usage(organization_id=2, from=2026-09-01, to=2026-10-02, group_by=persona), taken on 2026-10-02. It includes all projects, not only epic 27. Five of 178 runs have unknown usage; denominators for token and turn averages use runs with usage. Input excludes cache reads, as defined by ADR-0008. A run may have many turns, so total cache reads count repeated context sent to the model, not distinct documents.
| Role | Runs with usage / all | Turns / measured run | Fresh input | Cache write | Cache read | Output |
|---|---|---|---|---|---|---|
| Implementation | 90 / 93 | 27.5 | 61.12m | 4.09m | 248.98m | 1.54m |
| Review | 83 / 85 | 18.5 | 29.34m | 2.53m | 95.09m | 0.84m |
| Both | 173 / 178 | 23.2 | 90.46m | 6.62m | 344.07m | 2.38m |
The 54 implemented tasks had 93 implementation and 85 review runs: 3.30 runs per task, including 1.57 review rounds per task. The 443.52m raw tokens contain 344.07m cache reads (77.6%). At the epic 26 definition of effective tokens, input + output + cache_write + 0.1 × cache_read, this is 133.86m effective tokens, or 2.48m per implemented task. These totals are a baseline, not a claim that all cached tokens are waste. By persona, the measured implementation runs were: developer 58 measured of 59 runs / 1,925 turns / 45.12m fresh input / 200.55m cache reads; junior-developer 10 / 92 / 4.95m / 7.24m; senior-developer 6 measured of 7 / 216 / 4.52m / 19.53m; project-manager 3 / 34 / 0.08m / 0.99m. Reviewer persona had 83 measured review runs / 1,536 turns / 29.34m fresh input / 95.09m cache reads; seven additional implementation runs were assigned to that persona in this historical period. Compare by role and persona so that anomaly is visible.
The readable local runner logs contain 49 Claude stream-json runs; 47 have a final result. The other local logs use different formats, so this tool-call sample is Claude-only. Deduplicating stream updates by assistant message ID, total input context per model turn (input + cache creation + cache read) has a median of 26,441 tokens on turn one (49 runs; range 10,598–39,385), 28,396 on turn two (49), and 64,357 on turns two onward (1,782 nonzero turns, including the 49 turn-two observations; middle half 43,644–102,488). One message in the latter group reports zero usage and is excluded. This total grows with conversation and tool results; it is not the stable base prompt. On the first turn, 39 of 49 runs reported exactly 11,723 cache-read tokens, evidence of a commonly reused prefix, but the stream does not identify which instructions or tools occupy that prefix or separate a fixed base from task content on later turns. The first-turn 26,441 is therefore an observed total, not a fixed base size.
Across the 49 logs there are 1,358 Bash, 294 Read, 54 Grep, 47 ToolSearch, 164 Edit, and 53 Write tool calls. For a conservative re-read measure, count only the 292 distinct Read tool calls with a parsed, explicit file path, normalize each run's workspace prefix, and classify docs/ plus AGENTS.md, CLAUDE.md, and README.md as documentation. Within a run, 57 of 228 source/configuration Read calls and 9 of 64 documentation Read calls revisit a path already read in that run. Their logged tool results returned 137,908 and 35,619 bytes, respectively, on those repeat calls; one failed source/configuration Read is excluded from byte totals. These are returned bytes, not model tokens or avoidable spend: partial reads, edits between reads, and verification can make repetition necessary. Bash commands can also read files, but path mentions alone do not prove a read, so they are excluded. The stream has no reliable per-tool token accounting.
For a concrete repeat round, local runs 165 and 166 both fetched Taskbase task #289. Run 165 took 116 turns and run 166 took 62. Both explicit source/configuration Read calls in run 166 (api/internal/runner/match.go and api/internal/runner/store_pg.go) had already occurred in run 165; their results returned 12,293 bytes. In another pair, runs 169 and 170 for task #295, 9 of the later run's 11 explicit source/configuration Reads repeated paths read in the earlier run, returning 10,330 bytes. Neither later run repeated an explicit documentation Read from its earlier run. These are observed overlap counts, not a percentage of run tokens saved by a digest; the later run still needs to check current code. The Taskbase MCP list_task_runs tool returns forbidden: not available to agents acting for a run, so this analysis cannot independently join all API run records to the local log sample. Future measurement should use an authorized offline export rather than granting a working agent broader run-history access.
We already reduce some repetition in agent-runner: pre-fetched PR facts and scoped re-reviews (4440605, 0029b37), plus a trimmed tool set. This decision measures and extends those controls rather than counting their benefit twice.
Options considered¶
| Option | Expected saving and evidence | Cost and risk | Runtime boundary |
|---|---|---|---|
Task links alone: relates to, depends on, follow-up of, duplicates |
Allows a claim to identify the relevant predecessor; no token saving until selected context is imported. Most relevant to a follow-up; the 3.30 runs per task show same-task reuse is also needed. | Schema, API/MCP/UI, permissions, and link maintenance. Importing full linked task descriptions or histories can overwhelm a prompt and propagate stale or unrelated claims. | Taskbase stores typed task IDs and provenance; it does not build a provider prompt. |
| Short structured handoff digest per finished run | Targets the demonstrated repeat rounds: 2 of 2 later explicit Reads overlap in task #289 and 9 of 11 in task #295. The testable expectation is fewer navigation turns in revisions; no exact token saving can be projected from present logs. | A digest costs output tokens and storage; an incorrect or old digest can misdirect the next agent. It must identify source run, files, PR/head, verification, and open questions, and remain untrusted. | Neutral fields live on the run; the runner adapter renders them into the next prompt. |
| Repository instructions and docs first | Can avoid rediscovery across unrelated tasks. Nine of 64 explicit documentation Reads revisited a path within a run, but that does not measure the saving from any one document. | Repository changes require normal review; broad or stale instructions can harm every run. Keep task-specific facts out of permanent instructions. | Repo content remains in git; Taskbase stores at most references. Agents propose doc updates in their PRs. |
| Stable prompt prefix: persona and instructions before task-specific data | Could improve cache hits across consecutive runs. Cache reads are already 77.6% of raw tokens, so benefit must be measured as lower effective tokens and cost, not raw token count. | Adapter-specific cache behavior and prefix invalidation; no guaranteed hit. Changing order must preserve instruction priority and review isolation. | Runner controls ordering per adapter; Taskbase sends neutral claim fields. |
| Full transcript or free-form summary import | Might avoid more rereading in one run. | Largest prompt cost, privacy exposure, stale conclusions, and prompt injection; hard to bound or compare. | Would couple Taskbase to provider conversation formats. Reject. |
Choice: combine typed links, run-scoped handoff digests, repository-first navigation, and stable prompt ordering in that order of dependency. Start with same-task digests, which need no links; add linked-task selection after permissions and freshness checks exist. A link is a discovery hint, not a dependency scheduler or authority to copy the linked task's whole context. People and the project-manager persona may create and edit any permitted link. Other agents may propose or create a link for a concrete follow-up they make, subject to the same organization/project access checks; they cannot silently mark unrelated work as duplicate or use a link to change task priority. depends on is directional and records a planning relationship only. follow-up of is directional from new task to predecessor. relates to and duplicates are symmetric. Cross-organization links are rejected; cross-project links within one organization are permitted only when the caller can read both tasks. A linked task's context is never imported solely because its ID appears in text.
Taskbase stores one immutable digest on each completed run, including unsuccessful runs when the adapter can produce a useful handoff. Fields are: changed files and PR reference/head, decisions with reasons, verification with result, open questions or blockers, and source run/time. The runner can select the latest same-task implementation digest and the latest relevant review digest for a revision or review round. For a linked task it selects only a permitted, explicit predecessor digest; duplicates and relates to do not cause automatic import. Taskbase returns neutral fields and provenance in the claim. The adapter renders a compact, clearly labeled prior-run note after current persona and repository instructions and before the current task details. The agent checks the current repository, task, PR, and review comments before acting. The digest never overrides those sources.
Budget and freshness¶
The imported handoff budget is 2,000 model-input tokens per claim, measured by the adapter's tokenizer when available, otherwise a conservative character bound and truncation with an explicit marker. This is incremental to the current task, persona, and current repository instructions. Reserve up to 900 for the latest same-task digest, 700 for one explicit follow-up of or depends on predecessor, and 400 for provenance, freshness status, and a second short open question when useful. Unused space may be reassigned within the 2,000 total. Never include transcripts, full prior summaries, full diffs, or arbitrary linked task descriptions. Keep source run IDs, PR URLs, commit IDs, and file paths before prose. Cut older related digests first, then repeated verification detail, then lower-priority decisions; retain an explicit truncated marker. If the latest digest itself exceeds the budget, compact it at write time and preserve its open questions and provenance.
At claim time, Taskbase checks that the link still exists, both tasks are readable, the source run belongs to that task, and the digest is the latest eligible one. The runner compares the recorded source PR/head and touched file paths with the freshly cloned repository and current PR facts. If a PR merged, closed, or gained commits, or relevant files changed since the recorded head, it labels the digest stale with the reason and commit references. A stale digest can supply file pointers and open questions, but its decisions and verification are omitted from automatic import; the agent fetches current facts. If freshness cannot be checked, the digest is labeled unverified and reduced to provenance and file pointers. Do not silently reuse a digest from a different branch. The current task, current review comments, and repository state always win.
Measurement and consequences¶
Before each implementation stage, retain the same 30-day Taskbase get_usage baseline by role and persona, excluding runs with unknown usage from token averages while reporting their count. After release, compare a complete 30-day window and matched task classes: first implementations, revisions, first reviews, later reviews, and linked follow-ups. Record per claim the number of candidate/selected/stale/truncated digests, imported token count, cache-prefix hit when the adapter exposes it, and whether a linked task was consulted. Compare median turns per run, fresh input, cache write/read, effective tokens per completed task, and review rounds; report distributions by persona, model tier, project, and task complexity rather than only a global mean. The epic 26 effectiveness index is delivered complexity points per million effective tokens, with completed tasks and all their implementation and review runs attributed on completion day. Compare that index on the same cohorts, watching for more reopens, blocked reviews, or failed runs: fewer tokens with worse delivery is not success. Use task #289's repeated reads as a qualitative regression sample, not a savings target. An A/B holdout or staggered rollout is preferable where volume permits; otherwise label before/after differences as observational.
This keeps ADR-0006's fresh sessions and ADR-0005's runtime boundary. It adds metadata, authorization checks, digest generation, and a small prompt cost. It does not guarantee a token reduction: repository verification remains necessary, and current cache reads are already discounted. Accepted on 2026-10-03; the implementation tasks below are tracked under epic 27.
What we deferred (and what would trigger adding it)¶
| Concept | Trigger to add |
|---|---|
| Full transcript or long summary import | Short digests repeatedly omit facts needed in measured revision failures, and a bounded/redacted format is demonstrated safe |
| Automatic semantic linking or retrieval over all tasks | Explicit links miss a substantial measured share of useful follow-ups |
Dependency scheduling from depends on |
Project management explicitly asks for dependency enforcement rather than documentation |
| Persisting repository knowledge in Taskbase | Repositories cannot maintain the needed shared guidance under normal review |
| Provider-specific cache controls in Taskbase | More than one adapter demonstrates a common neutral control that materially improves effective tokens |
| Exact per-file token attribution | Adapters expose trustworthy tool-result usage rather than only run totals |
Proposed implementation tasks¶
Create these under epic 27 after owner acceptance; sizes use the repository's small/medium/large persona tiers. Each is a reviewable change in its own repository.
- Taskbase — developer / medium: add authorized typed task links (schema, API/MCP, UI), including direction, symmetry, duplicate handling, and cross-project permissions; add tests for missing/deleted and forbidden targets.
- Taskbase — developer / medium: store immutable neutral handoff digests on runs and return eligible same-task and explicitly linked candidates with claim provenance; test role/round selection, latest-run ordering, access, and stale references.
- agent-runner — senior-developer / medium: produce bounded structured digests at finish, render selected context in claims, check PR/head and file freshness, and enforce the 2,000-token budget; test revisions, linked follow-ups, stale/missing PRs, and truncation for Claude and Codex adapters.
- agent-runner — developer / small: order stable persona/instructions before task-specific claim content without changing instruction precedence; measure cache behavior on both adapters.
- Platform — senior-developer / small: update agent workflow guidance so repository instructions and relevant docs are the first stop, and agents propose durable knowledge changes in their PRs; document the shipped implementation and revise this ADR if its boundaries change.
- Taskbase — developer / medium: expose context reuse counters and before/after cohorts beside epic 26 effective-token and effectiveness measures; validate missing-usage handling and persona/role breakdowns.
The Taskbase and agent-runner documentation lives in this platform repository, so task 5 covers it after the code lands; no separate documentation-repository task is needed today.