Skip to content

feat(ai): sequential pipeline stages carry a budgeted context, with the scratchpad appended once #859

Closed

Description

@dan-petty

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:

Proposed Solution

In MultiAgentPipeline.run (sequential only):

  1. Add stage_context_tokens: int to MultiAgentPipeline.__init__ (pipeline.py:79-88), default DEFAULT_PIPELINE_STAGE_CONTEXT_TOKENS = 4096 in src/devops_cli/config/defaults.py. 0 disables the cut (the once-appended scratchpad in step 3 applies regardless).
  2. Replace the growing accumulated_context string 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 with truncate_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 Stages header. Counting uses count_tokens, the same function the budget test uses, so the heuristic fallback and tiktoken both satisfy the assertions.
  3. 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 by ScratchpadBuffer.max_chars=4000, models/ai.py:104).
  4. Record on PipelineStepResult (pipeline.py:39-48): context_tokens: int (tokens of carried context the stage received) and context_truncated: bool.
  5. devops ai pipeline gains --stage-context-tokens (help text as a new AICommandHelp field in src/devops_cli/lang/en/help.py:79-226, covered by tests/test_language_catalogs.py:63), passed to the constructor; the dry-run details dict (commands/ai.py:1193-1203) lists it.
  6. Forward skip_rag from run to agent.run (pipeline.py:170-175), and pass skip_rag=not rag from 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, PipelineStepResult fields, constructor option, skip_rag forwarding.
  • 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 new tests/test_pipeline_context_budget.py), tests/test_ai_cmd.py.
  • changelog.d/859.md, docs/agent/tasks/task-859-pipeline-stage-context-budgets.md with 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_tokens and truncate_to_token_limit from context_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 per MultiAgentPipeline and via devops ai pipeline --stage-context-tokens; 0 disables 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 of LLMClient.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_rag fix; feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 holds the AgentMemory invariant partition, head re-injection and SystemReminders cadence, depends on docs(agents): instruction surfaces state only what is true, and devops ai agents never overwrites AGENTS.md #840 and lands after fix(ai): streamed devops ai chat turns send the user's message #874. The budget is pipeline-only, measured and dependency-free; the invariant store changes agent.py and memory.py and 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 fake LLMClient whose chat_messages records 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 the omitted, over budget line 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 Context exactly once. Fails today: stage 5 contains it four times. Same test module.
  • Budget off: stage_context_tokens=0 carries every earlier reply verbatim in stage order (a 5-stage run with 4,000-char replies sends all four replies to stage 5), and test_multi_agent_pipeline (tests/test_agent.py:99) and test_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 == 4096 and that MultiAgentPipeline() without the argument sets stage_context_tokens to it; a 5-stage run with 1,000-char replies under the default cuts nothing (context_truncated is False for every step, matching the measurement's 1,210-token stage-5 prompt).
  • Recorded: PipelineStepResult.context_tokens equals count_tokens of the carried block the stage was sent, and context_truncated is True only for stages whose block was cut; asserted as a tuple over the five steps. Stages 1-3 are False and stage 5 is True under 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 from count_tokens of 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-rag with MultiAgentPipeline.run patched (pattern tests/test_ai_cmd.py:121-143) exits 0, constructs the pipeline with stage_context_tokens=512 and calls run with skip_rag=True; --dry-run (pattern tests/test_ai_cmd.py:538-543) output lists stage_context_tokens.
  • skip_rag forwarded: a test with devops_cli.ai.rag.investigator.investigate_rag_context patched asserts it is not called when run(..., skip_rag=True) and is called once per stage when skip_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) and test_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:99 guard stays silent), and each new test runs in under 1 s; uv run devops ci passes.
  • changelog.d/859.md written; docs/agent/tasks/task-859-pipeline-stage-context-budgets.md records the before and after measurement table from /tmp/refine/out/measure_859.py re-run against the branch. CHANGELOG.md and docs/ROADMAP.md are not edited.

Out of Scope

Dependencies

Readiness check (2026-10-04)

Checked against release/v0.2.26 at b61e5a0. The pipeline.py anchors hold:

  • run is at :123, and skip_rag is still dropped at :170-175.
  • The scratchpad is still re-appended at :203-206.
  • PipelineStepResult is at :39-48 and the constructor at :79-93.
  • run_async still forwards skip_rag at :307,318.

Corrections:

Rule alignment:

Amended criterion:

  • The task file embeds the offline measurement snippet (about 30 lines). It uses MagicMock(spec=LLMClient), whose chat_messages records the last user message and returns ("Finding: " + "x" * 70 + "\n") * (chars // 80), and patches investigate_rag_context to None. It records count_tokens and the ### Scratchpad Reasoning Context count 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.

Activity

  1. added
    type/feature
    scope/ai
    priority/p0-critical
    on Oct 1, 2026
  2. added this to the v0.2.27 milestone on Oct 1, 2026
  3. dan-petty commented on Oct 1, 2026

    @dan-petty
    OwnerAuthor

    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.24 at d38251e. What stops it being Ready:

    • The ~20K-token bloat and the ~4K per-stage budget are unmeasured. The issue's own key question asks to measure first, so that answer is open.
    • The invariant set depends on docs(agents): instruction surfaces state only what is true, and devops ai agents never overwrites AGENTS.md #840 (open) and is not yet defined.
    • 'Every N turns' for the reminder block is unspecified.
    • The acceptance criteria are generic ('each deliverable lands with a test'). There are no concrete pass conditions such as stage budget adherence or verbatim invariant re-injection.
    • Three deliverables (pipeline packing, memory partition, reminder cadence) likely exceed one PR. Split them, or land the measurement first.
    • The stale pipeline.py:196-199 ref is now :203-206. It also does not mention the existing compaction pin()/reinject_pinned to reuse.
  4. changed the title [-]feat(ai): pipeline stage context budgets and pinned invariants[/-] [+]feat(ai): sequential pipeline stages carry a budgeted context, with the scratchpad appended once[/+] on Oct 2, 2026
  5. dan-petty-bot commented on Oct 5, 2026

    @dan-petty-bot
    Collaborator

    What changed

    #1195, merged into release/v0.2.27 as 195dd90.

    Resolves #859.

    11 file(s) changed.

    How it was verified

    Check runs at 39df459:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • Static Analysis: pass
    • Analyze (python): pass
    • Tests & Coverage: pass
    • Analyze (actions): pass
    • DevContainer Image: skipping
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-859-pipeline-stage-context-budgets.md:

    • Budget holds: 5-stage pipeline under 2048 budget keeps prompt context <= 2048, keeps stage 4 verbatim in stage 5, and cuts stage 1.
    • Scratchpad once: every stage prompt from stage 2 onward contains ### Scratchpad Reasoning Context exactly once.
    • Budget off: stage_context_tokens=0 carries every earlier reply verbatim without truncation.
    • Default is 4096: DEFAULT_PIPELINE_STAGE_CONTEXT_TOKENS == 4096 and MultiAgentPipeline defaults to it.
    • Recorded metrics: PipelineStepResult.context_tokens matches count of carried context sent and context_truncated is recorded accurately.
    • CLI support: devops ai pipeline supports --stage-context-tokens and lists it in --dry-run output.
    • skip_rag forwarded: agent.run(..., skip_rag=skip_rag) correctly receives argument.
    • Parallel execution untouched: parallel pipeline tests continue to pass without regression.
    • Changelog fragment changelog.d/859.md written.
    • All 10 gates in uv run devops ci pass with 100% green status.
  6. added a commit that references this issue on Oct 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p0-criticalscope/aitype/feature

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions