Repository navigation
Description
Problem Statement
The sequential MultiAgentPipeline.run (src/devops_cli/ai/agents/pipeline.py:160-206) carries every earlier stage's full reply into the next stage's prompt with no cap, and re-appends the whole scratchpad summary once per stage (pipeline.py:203-206), so stage k's prompt holds k-1 copies of it. Nothing measures or records what each stage received.
Measured at the release/v0.2.25 tip (8271385) with a fake client (/tmp/refine/out/measure_859.py, offline: MagicMock(spec=LLMClient), investigate_rag_context patched, count_tokens on the prompt each stage was sent):
| stages | reply size | stage-5 prompt | scratchpad copies in stage 5 | prompt tokens summed over stages |
|---|---|---|---|---|
| 5 | 1,000 chars | 1,210 tokens | 4 | 2,804 |
| 5 | 4,000 chars | 3,186 tokens | 4 | 7,744 |
| 5 | 8,000 chars | 5,786 tokens | 4 | 14,244 |
| 3 | 4,000 chars | 1,502 tokens (stage 3) | 2 | 2,239 |
Growth is linear in reply size: stage k's prompt is the initial prompt plus k-1 full replies plus k-1 scratchpad summaries. The roadmap's "~20K tokens of bloat" is reached only with replies near 5K tokens each (the review persona reply cap is 8,192 tokens, src/devops_cli/config/defaults.py:395; the pipeline command sets no cap). The scratchpad repetition is a few hundred tokens of it; the carried replies are the cost, and a late stage reads the stage-1 reply ahead of the stage-4 reply it most needs.
Only devops ai pipeline (src/devops_cli/commands/ai.py:1146-1255; default personas devsecops,architect,qa, defaults.py:365) and library callers use the sequential path. The review pipeline runs parallel=True with message_history=[] (src/devops_cli/ai/review/pipeline.py:938-945), which carries no inter-stage context, so it is unaffected.
Two neighbouring defects sit in the same lines: run accepts skip_rag (pipeline.py:130) and drops it (agent.run at :170-175 is called without it; run_async at :312-318 forwards it to run, where it is lost), and devops ai pipeline --no-rag only skips the command-level prefix (commands/ai.py:1232-1235); pipeline_engine.run at :1237-1241 passes no skip_rag, so every stage still performs a RAG lookup (agent.py:827-840; failures are swallowed).
What the original body claimed that is not so:
ContextPackeris an AST packer for Python source (src/devops_cli/ai/context_packer.py:293-331,396-424). Prose stage output would hit_handle_syntax_fallback, whose line pruner drops every line starting with#, which in markdown is a heading (context_packer.py:205-216). The right primitives arecount_tokensandtruncate_to_token_limitinsrc/devops_cli/ai/context_budget.py:37,65(tiktoken 0.14.0,pyproject.toml:36, with a chars/4 fallback when the encoding is unavailable, so the network guard intests/conftest.py:99never matters).AgentMemorysummarization does not touch invariants placed in a system prompt:PydanticAgent.runrebuilds the system prompt verbatim fromself.system_prompton every run (src/devops_cli/ai/agents/agent.py:590,825), and the pipeline's ownAgentMemory(pipeline.py:93,157-158,191-192,218) is recorded on the result and never sent to a model. The pinned-invariant store matters for multi-turn conversations (devops ai chatresends all of memory,commands/ai.py:940), which is feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985's change with feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985's dependency (docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840). It is split off to feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 (owner decision, 2026-10-02).
Proposed Solution
In MultiAgentPipeline.run (sequential only):
- Add
stage_context_tokens: inttoMultiAgentPipeline.__init__(pipeline.py:79-88), defaultDEFAULT_PIPELINE_STAGE_CONTEXT_TOKENS = 4096insrc/devops_cli/config/defaults.py.0disables the cut (the once-appended scratchpad in step 3 applies regardless). - Replace the growing
accumulated_contextstring with a list of per-stage outputs. Before each stage, allocate the budget newest-first: the latest stage's output is kept whole when it fits; each older output then gets what remains, cut withtruncate_to_token_limit(text, budget_left, suffix="\n...[stage output truncated to the stage context budget]"); an older stage that gets no budget is listed by name only (### Stage 1 (DevSecOps) Output: omitted, over budget). The block is rendered in stage order (oldest first, as today) so it still reads as a transcript under the existing## Pipeline Context from Previous Stagesheader. Counting usescount_tokens, the same function the budget test uses, so the heuristic fallback and tiktoken both satisfy the assertions. - Append
self.scratchpad.render_context_summary()(src/devops_cli/models/ai.py:174-185) once, after the carried outputs, outside the budget (it is already capped byScratchpadBuffer.max_chars=4000,models/ai.py:104). - Record on
PipelineStepResult(pipeline.py:39-48):context_tokens: int(tokens of carried context the stage received) andcontext_truncated: bool. devops ai pipelinegains--stage-context-tokens(help text as a newAICommandHelpfield insrc/devops_cli/lang/en/help.py:79-226, covered bytests/test_language_catalogs.py:63), passed to the constructor; the dry-rundetailsdict (commands/ai.py:1193-1203) lists it.- Forward
skip_ragfromruntoagent.run(pipeline.py:170-175), and passskip_rag=not ragfrom the command (commands/ai.py:1237-1241). Two lines, both inside the blocks this item already edits.
No new dependency. No change to run_parallel, run_async, AgentMemory, or the review pipeline. The AgentMemory invariant partition, head re-injection and SystemReminders cadence are #985's.
Scope
src/devops_cli/ai/agents/pipeline.py: carried-context assembly,PipelineStepResultfields, constructor option,skip_ragforwarding.src/devops_cli/config/defaults.py:DEFAULT_PIPELINE_STAGE_CONTEXT_TOKENS.src/devops_cli/commands/ai.py,src/devops_cli/lang/en/help.py:--stage-context-tokens,skip_rag=not rag.tests/test_agent.py(or a newtests/test_pipeline_context_budget.py),tests/test_ai_cmd.py.changelog.d/859.md,docs/agent/tasks/task-859-pipeline-stage-context-budgets.mdwith the measurement table before and after.
Effort: medium after the split (the original three deliverables were high).
Key Questions
- How much context does a 5-stage pipeline accumulate today? Answered by measurement (table above): stage k carries k-1 full replies plus k-1 scratchpad copies; 1,210 / 3,186 / 5,786 tokens at stage 5 for 1K / 4K / 8K-char replies.
- Which packer applies to inter-stage context? Answered: not
ContextPacker(Python AST, markdown-hostile fallback).count_tokensandtruncate_to_token_limitfromcontext_budget.py. - Does the review pipeline need the budget? Answered: no. It runs
parallel=True, message_history=[](review/pipeline.py:938-945); no inter-stage context exists there. - What is the default per-stage budget, and is it fixed or a fraction of the model's window? Answered (owner decision, 2026-10-02): a fixed default of 4,096 tokens,
DEFAULT_PIPELINE_STAGE_CONTEXT_TOKENS, overridable perMultiAgentPipelineand viadevops ai pipeline --stage-context-tokens;0disables the cut. The measurement shows 4,096 leaves 1K-token replies untouched over five stages and first cuts the 8K-char case at stage 4 (4,269 tokens); the default 3-persona command never reaches it with 4K-char replies (1,502 tokens). A fraction ofLLMClient.get_context_window()(src/devops_cli/ai/client/unified.py:308) depends on a per-task lookup that fake clients in tests do not have; it is out of scope and can be added later without changing the API. - How is the carried context fit into the budget? Answered (owner decision, 2026-10-02): newest-first allocation. The latest stage is kept whole when it fits; older stages are cut with
truncate_to_token_limit(visible truncation marker) or omitted by name; the block is rendered in stage order; the scratchpad is appended once outside the budget. It is deterministic, favours the stage the next agent builds on, and needs no model call. Tail-truncating the whole block (keeps the oldest, cuts the newest) and an LLM summary of older stages (an extra nondeterministic call per stage, a fake in every test) are rejected. - Is the pinned-invariant store and cadenced reminder its own item? Answered (owner decision, 2026-10-02, global Q2): yes, split. feat(ai): sequential pipeline stages carry a budgeted context, with the scratchpad appended once #859 keeps the stage budget plus the two-line
skip_ragfix; feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 holds theAgentMemoryinvariant partition, head re-injection andSystemReminderscadence, depends on docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840 and lands after fix(ai): streameddevops ai chatturns send the user's message #874. The budget is pipeline-only, measured and dependency-free; the invariant store changesagent.pyandmemory.pyand does nothing for the pipeline. Which invariants are pinned, where they are injected and on what cadence are feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985's key questions, answered there.
Acceptance Criteria
- Budget holds: a test runs a 5-stage
MultiAgentPipeline(stage_context_tokens=2048)with a fakeLLMClientwhosechat_messagesrecords each prompt and returns a 4,000-char reply that names its stage (a 4,000-char carried block is 661 tokens with tiktoken and 1,008 with the chars/4 fallback, so the newest stage always fits whole); for every stage,count_tokens(carried block)is at most 2,048, the stage-4 reply appears verbatim in the stage-5 prompt, the stage-1 reply does not, and the truncation suffix or theomitted, over budgetline is present. Fails today: the stage-5 carried block is 3,186 tokens (measurement).uv run pytest tests/test_agent.py -k stage_context_budget -n 0. - Scratchpad once: in the same run, every stage prompt from stage 2 on contains
### Scratchpad Reasoning Contextexactly once. Fails today: stage 5 contains it four times. Same test module. - Budget off:
stage_context_tokens=0carries every earlier reply verbatim in stage order (a 5-stage run with 4,000-char replies sends all four replies to stage 5), andtest_multi_agent_pipeline(tests/test_agent.py:99) andtest_multi_agent_pipeline_with_memory(tests/test_agent_memory.py:109) pass unchanged with the default constructor. - Default is 4,096: a test asserts
DEFAULT_PIPELINE_STAGE_CONTEXT_TOKENS == 4096and thatMultiAgentPipeline()without the argument setsstage_context_tokensto it; a 5-stage run with 1,000-char replies under the default cuts nothing (context_truncatedisFalsefor every step, matching the measurement's 1,210-token stage-5 prompt). - Recorded:
PipelineStepResult.context_tokensequalscount_tokensof the carried block the stage was sent, andcontext_truncatedisTrueonly for stages whose block was cut; asserted as a tuple over the five steps. Stages 1-3 areFalseand stage 5 isTrueunder both counting modes (four 4,000-char blocks are 2,644 tokens with tiktoken and 4,032 with the chars/4 fallback, over 2,048); stage 4 sits on the boundary (1,983 or 3,024), so the test derives its expected flag fromcount_tokensof the three carried outputs rather than hard-coding it, and the result is the same with tiktoken cached or absent. - CLI:
devops ai pipeline Review --stage-context-tokens 512 --no-ragwithMultiAgentPipeline.runpatched (patterntests/test_ai_cmd.py:121-143) exits 0, constructs the pipeline withstage_context_tokens=512and callsrunwithskip_rag=True;--dry-run(patterntests/test_ai_cmd.py:538-543) output listsstage_context_tokens. -
skip_ragforwarded: a test withdevops_cli.ai.rag.investigator.investigate_rag_contextpatched asserts it is not called whenrun(..., skip_rag=True)and is called once per stage whenskip_rag=False; fails today (pipeline.py:170-175). - Parallel untouched:
test_multi_agent_pipeline_empty_history_sends_only_current_prompt(tests/test_agent.py:166) andtest_multi_agent_pipeline_parallel_and_skip_rag(tests/test_pydantic_agent.py:200) pass unchanged. - Tests use fake clients only, open no socket (
tests/conftest.py:99guard stays silent), and each new test runs in under 1 s;uv run devops cipasses. -
changelog.d/859.mdwritten;docs/agent/tasks/task-859-pipeline-stage-context-budgets.mdrecords the before and after measurement table from/tmp/refine/out/measure_859.pyre-run against the branch.CHANGELOG.mdanddocs/ROADMAP.mdare not edited.
Out of Scope
- Pinned invariants, head re-injection and the cadenced reminder: feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 (depends on docs(agents): instruction surfaces state only what is true, and
devops ai agentsnever overwrites AGENTS.md #840, lands after fix(ai): streameddevops ai chatturns send the user's message #874). - LLM summarization of older stages, and budgets derived from the model's context window.
- The review pipeline (parallel, no carried context).
- The roadmap's "Context Carry Audit" (
docs/ROADMAP.md:1025, no issue) and "One Tokenizer-Backed Token Estimator" (docs/ROADMAP.md:977, no issue): the audit's baseline is supplied by the measurement above, so this item does not wait for it; the estimator is not needed becausecount_tokenswith tiktoken 0.14.0 (pyproject.toml:36) already exists. - Any
ContextPackerchange (tests/test_context_packer.py:296is fix(cli): cli start-up imports no telemetry when the bridge is off, and timing tests stop asserting host speed #858's).
Dependencies
- None blocking. This item is pipeline-only and dependency-free; it is Ready and lands in v0.2.27 in any order among the items that do not share its files.
- feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 — child split from this issue on 2026-10-02; takes the
#840 -> pinned invariantsordering, lands after docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840 and fix(ai): streameddevops ai chatturns send the user's message #874, and joins epic Release Epic: v0.2.27 — Binding Quality Gates, Verdict Evidence, Context Budgets & Cluster Doctor #907's checklist. - docs(agents): instruction surfaces state only what is true, and
devops ai agentsnever overwrites AGENTS.md #840 — binds feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 only (its AGENTS.md-derived invariant set waits for docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840 to make the rules true); the budget half here does not depend on it, although epic Release Epic: v0.2.27 — Binding Quality Gates, Verdict Evidence, Context Budgets & Cluster Doctor #907 orders docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840 before feat(ai): sequential pipeline stages carry a budgeted context, with the scratchpad appended once #859. docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840 also rewrites theagentscommand insrc/devops_cli/commands/ai.py:849-920, a different function from the pipeline command; the cross-check orders fix(ai): streameddevops ai chatturns send the user's message #874, then docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840, then feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 on that file, and this item rebases on whichever lands first. - fix(ai): streamed
devops ai chatturns send the user's message #874 — same file, different functions: fix(ai): streameddevops ai chatturns send the user's message #874 edits the chat path insrc/devops_cli/commands/ai.py:926-953,1106-1110, this item the pipeline command (:1146-1241); fix(ai): streameddevops ai chatturns send the user's message #874 lands first (low effort, nearly ready) and this item rebases, no conflict. fix(ai): streameddevops ai chatturns send the user's message #874's closer overlap on the chat memory path is with feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985. - fix(cli): cli start-up imports no telemetry when the bridge is off, and timing tests stop asserting host speed #858 — re-derives the timing ceiling in
tests/test_context_packer.py:296; this item touches neitherContextPackernor that test (it usescontext_budget.py), so no conflict while scope holds. - Release Epic: v0.2.27 — Binding Quality Gates, Verdict Evidence, Context Budgets & Cluster Doctor #907 — the v0.2.27 epic lists this item and says docs(agents): instruction surfaces state only what is true, and
devops ai agentsnever overwrites AGENTS.md #840 lands before it; with the split that ordering binds feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985, and the epic's checklist gains feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985. Release Epic: v0.2.26 — Roadmap Closure, Refinement & Automatic Release Cut #906 and Release Epic: v0.2.27 — Binding Quality Gates, Verdict Evidence, Context Budgets & Cluster Doctor #907 both say a Ready P0 goes first into v0.2.26 when that release starts; the cross-check notes the measurement (1,210-5,786 prompt tokens at stage 5) does not read as critical, a label call left to the epic. - Release Epic: v0.2.25 — Multi-IDE MCP Scaffolding, Context Budgeting & Invariant Pinning #300 — the epic that first named this deliverable; filed from
docs/ROADMAP.md:809at 308a71f (now:1172). The roadmap table row (docs/ROADMAP.md:1512) still says v0.2.25; GitHub is the roadmap's source of truth (ADR 0001) and the file is not edited here.
Readiness check (2026-10-04)
Checked against release/v0.2.26 at b61e5a0. The pipeline.py anchors hold:
runis at:123, andskip_ragis still dropped at:170-175.- The scratchpad is still re-appended at
:203-206. PipelineStepResultis at:39-48and the constructor at:79-93.run_asyncstill forwardsskip_ragat:307,318.
Corrections:
src/devops_cli/commands/ai.py(+9): thepipelinecommand starts at:1155(was:1146); the dry-rundetailsdict is at:1205-1210, inside:1200-1212(was:1193-1203); the--no-ragprefix is at:1241-1244(was:1232-1235);pipeline_engine.runis at:1246-1250(was:1237-1241); the chat resend is at:949(was:940).src/devops_cli/config/defaults.py: the review persona reply cap is at:407(was:395), andDEFAULT_AI_PIPELINE_PERSONASat:377(was:365).src/devops_cli/ai/review/pipeline.py:parallel=True, skip_rag=True, message_history=[]is at:955-962(was:938-945).src/devops_cli/ai/agents/agent.py: the system build is at:612,847(was:590,825), and the RAG step at:849-862(was:827-840).AICommandHelpis atsrc/devops_cli/lang/en/help.py:82-240(was:79-226);get_context_windowatsrc/devops_cli/ai/client/unified.py:298(was:308);test_multi_agent_pipeline_parallel_and_skip_ragattests/test_pydantic_agent.py:201(was:200).- Since v0.2.25 (feat(release): v0.2.25 #1089),
docs/ROADMAP.mdis a generated GitHub view of 305 lines. The citations to:977,:1025,:1172and:1512refer to 8271385. The file is still not edited. - Release epics are retired: Release Epic: v0.2.26 — Roadmap Closure, Refinement & Automatic Release Cut #906 and Release Epic: v0.2.27 — Binding Quality Gates, Verdict Evidence, Context Budgets & Cluster Doctor #907 were closed as not planned on 2026-10-03, and a release is its milestone. The "Release Epic: v0.2.27 — Binding Quality Gates, Verdict Evidence, Context Budgets & Cluster Doctor #907 orders docs(agents): instruction surfaces state only what is true, and
devops ai agentsnever overwrites AGENTS.md #840 before feat(ai): sequential pipeline stages carry a budgeted context, with the scratchpad appended once #859" line no longer binds. This item has no ordering constraint; docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840's ordering binds feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 only.
Rule alignment:
devops ai pipeline --dry-runstill returnsCommandDryRunResultand does so beforeload_settings(commands/ai.py:1200-1212), so it makes no request. This item only adds thestage_context_tokenskey.- Moving that dry run to the command's real result type with planned requests (feat(cli): reachable
--dry-runpreviews for delegated commands #412/feat(cli): commands with no dry-run preview: read-only ones run, mutators gain one #886) is not this item's work. If that lands first, the CLI criterion applies to the new payload. - The measurement script
/tmp/refine/out/measure_859.pyis not in the repository.
Amended criterion:
- The task file embeds the offline measurement snippet (about 30 lines). It uses
MagicMock(spec=LLMClient), whosechat_messagesrecords the last user message and returns("Finding: " + "x" * 70 + "\n") * (chars // 80), and patchesinvestigate_rag_contexttoNone. It recordscount_tokensand the### Scratchpad Reasoning Contextcount per stage for (5, 1000), (5, 4000), (5, 8000) and (3, 4000). From it, the task file records the before table (base) and the after table (branch), so the numbers can be reproduced without the refinement host's/tmp.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
dan-petty commentedon Oct 1, 2026
Placement (2026-10-01): v0.2.27. Value Medium, Effort High. Not Ready yet. It goes first in v0.2.26 when that starts if it is Ready by then (epic #906); v0.2.27 holds it until then.
Checked against
release/v0.2.24at d38251e. What stops it being Ready:devops ai agentsnever overwrites AGENTS.md #840 (open) and is not yet defined.[-]feat(ai): pipeline stage context budgets and pinned invariants[/-][+]feat(ai): sequential pipeline stages carry a budgeted context, with the scratchpad appended once[/+]feat(ai): sequential pipeline stages carry a budgeted context, with t…
dan-petty-bot commentedon Oct 5, 2026
What changed
#1195, merged into
release/v0.2.27as 195dd90.11 file(s) changed.
How it was verified
Check runs at 39df459:
Acceptance Criteria of
docs/agent/tasks/task-859-pipeline-stage-context-budgets.md:### Scratchpad Reasoning Contextexactly once.stage_context_tokens=0carries every earlier reply verbatim without truncation.DEFAULT_PIPELINE_STAGE_CONTEXT_TOKENS == 4096andMultiAgentPipelinedefaults to it.PipelineStepResult.context_tokensmatches count of carried context sent andcontext_truncatedis recorded accurately.devops ai pipelinesupports--stage-context-tokensand lists it in--dry-runoutput.skip_ragforwarded:agent.run(..., skip_rag=skip_rag)correctly receives argument.changelog.d/859.mdwritten.uv run devops cipass with 100% green status.feat(release): v0.2.27 (#1257)