Repository navigation
Description
Problem Statement
devops ai chat streams a turn only when streaming is on and tools are off (src/devops_cli/commands/ai.py:1090, if stream and not tools:). Both options default to on (:990-991), so the streamed path runs under --no-tools.
That path, _stream_interactive_chat_turn (commands/ai.py:926-953), builds its request from agent.memory.to_chat_messages() (:940) and never adds the user's prompt to memory: only the reply is added (:953). The other path, agent.run, adds the prompt itself (src/devops_cli/ai/agents/agent.py:821). A probe at ef21785 with a fake client that records what it is sent showed:
- turn 1 sent no messages at all;
- turn 2 sent only turn 1's reply;
- memory then held two assistant entries and no user entry.
When a turn fails, the loop removes the last memory entry (commands/ai.py:1106-1109). In the streamed path that entry is the previous reply, not the failed turn. Since #599 (merged as 8b1e8d4), a stream cut before its final frame raises AIClientError instead of returning partial text, so this handler now runs for every cut stream and silently deletes the previous reply. A Ctrl-C mid-turn is handled separately (except KeyboardInterrupt, :1104-1105): it prints "Interrupted." and pops nothing, so on the tools path a dangling user entry (added at agent.py:821 before the request) stays behind and the next turn sends two consecutive user messages.
The code has been like this since v0.2.0 (491907c); it is not a regression. The only later change to commands/ai.py on this branch (7192da0, #961) touched audit_library_usage_cmd, not the chat loop. The defect affects only the non-default --no-tools mode and has no security impact, so it is not a critical fix.
Proposed Solution
All changes are in src/devops_cli/commands/ai.py and tests/test_ai_cmd.py.
_stream_interactive_chat_turnadds the user's prompt to memory (agent.memory.add_interaction("user", effective_prompt)) before it callsagent.memory.to_chat_messages(), so the model receives it. The stored text iseffective_prompt(the prompt with any RAG snippet prepended,commands/ai.py:1076-1080), the same textagent.runstores on the tools path.- A failed or interrupted turn leaves memory as it was before the turn, on both paths. Both loop handlers (
except KeyboardInterrupt,:1104-1105, andexcept Exception,:1106-1109) remove a trailinguserentry only:if agent.memory.entries and agent.memory.entries[-1].role == "user": agent.memory.entries.pop(). The stream raises or is interrupted, the handler's role-checked pop removes the user entry that was just added, and a pop can never remove a previous reply. The helper does not roll back itself. This also closes the tools path's existing Ctrl-C gap for free, sinceagent.runleaves its user entry behind when it raises or is interrupted afteragent.py:821. - When the model put its whole reply in thinking, the fallback (
:945-951) callsagent.run, which adds the prompt again (agent.py:821) and then the reply (agent.py:1024). The streamed path removes its own user entry first, so the prompt is stored once. - The existing test
test_a_cut_stream_stores_no_reply_in_chat_memory(tests/test_ai_cmd.py:579-598, added by feat(ai): finish reasons and stream completeness for model replies #599) pre-seeds a user entry, calls the helper directly and asserts["user"]afterwards. Under this fix the helper adds the user entry itself, so that test is rewritten to the new contract: no pre-seeded entry, the helper raises, and the loop-level rollback is covered by the CliRunner test below. - A changelog fragment
changelog.d/874.md(under### Fixed) and the task filedocs/agent/tasks/task-874-streamed-chat-turns-send-the-users-message.mdare written in the delivering pull request.CHANGELOG.mdanddocs/ROADMAP.mdare not edited.
Scope
One pull request. Touched files: src/devops_cli/commands/ai.py (the helper at :926-953 and the two except handlers in the chat loop at :1104-1109), tests/test_ai_cmd.py, changelog.d/874.md, the task file. No change to AgentMemory, PydanticAgent or the client.
Key Questions
- Use
agent.run_streaminstead? No. It sends only the current prompt and no history (agent.py:1130,messages = [ChatMessage(role="user", content=user_prompt)]), so a multi-turn chat would lose its context. - Is this a critical fix for the current release? No. It breaks only the non-default
--no-toolsmode and has no security impact. Placed in v0.2.27 by grooming on 2026-10-02 (value High, effort Low). - Who rolls memory back when a streamed turn fails? The loop's handlers (
:1104-1109), not the helper. The helper only adds the user entry and lets the error or interrupt propagate; the handler's pop then removes that entry. This keeps one rollback for both paths (agent.runalso leaves its user entry behind when it raises afteragent.py:821). - Which text is stored as the user entry?
effective_prompt, including the RAG snippet when--ragis on, matching whatagent.runstores on the tools path and matching what is sent to the model. - Does a Ctrl-C mid-stream also roll back, and does the pop check what it removes? Answered (owner decision, 2026-10-02): yes to both. Both handlers (
except KeyboardInterrupt,:1104-1105, andexcept Exception,:1106-1109) remove a trailinguserentry only (if agent.memory.entries and agent.memory.entries[-1].role == "user": agent.memory.entries.pop()), so an interrupt rolls back too and a pop can never remove a previous reply. Before this fix an interrupt on the streamed path was harmless (nothing had been added); after it, without this change, the path would inherit the tools path's gap (agent.runadds the user entry atagent.py:821before the request). It is a two-line change in the same function, it makes the "memory as it was before the turn" promise hold for every way a turn can end, and it closes the tools path's gap for free. The CliRunner test below gains one parametrized case where the fake stream raisesKeyboardInterrupt.
Acceptance Criteria
- The model receives the prompt and the history.
test_a_streamed_turn_sends_the_user_message_and_history(tests/test_ai_cmd.py) runs_stream_interactive_chat_turntwice againstMagicMock(memory=AgentMemory())(the shape oftests/test_ai_cmd.py:589-592) and a fake client whosechat_messages_streamrecords themessagesargument and yields a reply. The structural tuple assertion is[(m.role, m.content) for m in sent] == [("user", "p1")]for turn 1 and[("user", "p1"), ("assistant", "r1"), ("user", "p2")]for turn 2, and memory afterwards reads[("user", "p1"), ("assistant", "r1"), ("user", "p2"), ("assistant", "r2")]. It fails on today's code (turn 1 sends[]). - A failed or interrupted streamed turn leaves memory as it was.
test_a_failed_streamed_turn_leaves_memory_as_it_was, parametrized over two cases, drivesrunner.invoke(ai_app, ["chat", "--no-tools", "--no-rag", "--no-prewarm"])withdevops_cli.commands.ai.get_consolepatched to a console whoseinput.side_effectis["p1", "p2", "exit"](the shape oftests/test_ai_cmd.py:430-443) andLLMClient.chat_messages_streampatched to a fake that records each call'smessages, yields one chunk then raises on the first call, and yields"r2"on the second. Case 1 raisesAIClientError("Provider stream ended before its final frame.")and asserts the output containsError:andbefore its final frame; case 2 raisesKeyboardInterruptand asserts the output containsInterrupted.. In both cases: exit code 0, the second call was sent[("user", "p2")]only, and the agent's memory afterwards reads[("user", "p2"), ("assistant", "r2")](captured by wrappingdevops_cli.ai.agents.PydanticAgentor by patchingAgentMemory). Case 1 fails on today's code (the second call is sent[]); case 2 fails on the helper fix alone without the role-checked pop in the interrupt handler (the second call is sent[("user", "p1"), ("user", "p2")]). - The thinking-only fallback stores the prompt once.
test_a_thinking_only_stream_stores_the_prompt_onceruns_stream_interactive_chat_turnwith a realPydanticAgent(client=fake, system_prompt="...", tools=[])(the shape oftests/test_pydantic_agent.py:77-98) whose fake client'schat_messages_streamrecords itsmessagesand yields only<think>…</think>, and whosechat_messagesreturns"r1"for theagent.runfallback (agent.py:887), withdevops_cli.ai.rag.investigator.investigate_rag_contextpatched to returnNone. The stream call was sent[("user", "p1")](fails today:[]), and memory afterwards reads[("user", "p1"), ("assistant", "r1")]: exactly one user entry (guards the fix against storing it twice). - The feat(ai): finish reasons and stream completeness for model replies #599 test matches the new contract.
test_a_cut_stream_stores_no_reply_in_chat_memory(tests/test_ai_cmd.py:579-598) no longer pre-seeds a user entry; it asserts the error propagates and that, under the helper alone, memory holds the one user entry the helper added and no assistant entry (the loop's rollback is the second criterion's job). - No network. The new tests use fakes for
chat_messages_streamandchat_messagesand patchinvestigate_rag_context; the autouse guardprevent_external_network_calls(tests/conftest.py:98-160) turns any stray connect or external DNS lookup into an error, so a test that reached the network would fail. - Speed.
uv run pytest tests/test_ai_cmd.py -n0 --durations=0 -k "streamed_turn or failed_streamed or thinking_only or cut_stream"shows every new or rewritten test under 0.25 s serially. (The issue's "under 1 s" is kept as intent; feat(ai): finish reasons and stream completeness for model replies #599's task file records why a summed figure under pyproject's-n logicalis not meaningful.) - Gate.
uv run devops cipasses (it runsruff format,ruff check,mypy --strict srcand the test suite). - Fragment and task file.
changelog.d/874.mdexists with a### Fixedentry;docs/agent/tasks/task-874-streamed-chat-turns-send-the-users-message.mdexists with**Status**: Done;tests/test_agent_task_files.pypasses; the pull request does not touchCHANGELOG.mdordocs/ROADMAP.md(devops pr check-readinessblocks either). - Pending a person: in
uv run devops ai chat --no-tools, ask "What is 2+2?". The reply answers that question. Then ask "And times 3?"; the reply uses the first answer, showing the history was sent. Then ask a third question and press Ctrl-C while the reply streams; "Interrupted." prints, and a fourth question gets a reply that still follows the earlier answers.
Out of Scope
agent.run_streamsending history (agent.py:1107-1133): it is not used bydevops ai chat.- The tools path (
agent.run) and its own failure handling beyond the two shared loop handlers atcommands/ai.py:1104-1109. - The fallback's second RAG investigation inside
agent.run(agent.py:830-836) after the loop already prepended a snippet: pre-existing, unchanged. - Pinned invariants, the
AgentMemoryinvariant partition, head re-injection and the cadenced reminder (feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985), and the pipeline stage context budget (feat(ai): sequential pipeline stages carry a budgeted context, with the scratchpad appended once #859). - The streaming client, finish reasons and stream completeness (delivered by feat(ai): finish reasons and stream completeness for model replies #599).
- Acting on cut persona replies (fix(review): a group-analysis reply cut at its token cap is rejected, not shown as a checked explanation #876) and JSON repair (feat(ai): one json repair seam that counts repairs per entry point #875), the other feat(ai): finish reasons and stream completeness for model replies #599 split-offs.
Dependencies
- Depends on: none open. feat(ai): finish reasons and stream completeness for model replies #599 (merged as 8b1e8d4 into release/v0.2.25) is the reason a cut stream now raises
AIClientError; it is delivered. - Lands before docs(agents): instruction surfaces state only what is true, and
devops ai agentsnever overwrites AGENTS.md #840 (v0.2.27): docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840 rewrites theagentscommand (commands/ai.py:849-920) and_pointer_stub(:311) in the same file; its hunk ends six lines above the helper (:926), so docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840 rebases without a conflict in content. Order per the v0.2.27 cross-check: fix(ai): streameddevops ai chatturns send the user's message #874 first (low effort, Ready), docs(agents): instruction surfaces state only what is true, anddevops ai agentsnever overwrites AGENTS.md #840 next. - Lands before feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 (v0.2.27, after docs(agents): instruction surfaces state only what is true, and
devops ai agentsnever overwrites AGENTS.md #840): feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 adds aninvariantsfield toAgentMemorywithout renamingentriesand changes the chat constructor call atcommands/ai.py:1045-1047; this item readsagent.memory.entriesand callsadd_interaction(src/devops_cli/ai/agents/memory.py:63,65) and pops in the handlers at:1104-1109. Landing first means feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985 rebases a three-line constructor change instead of this item rebasing its helper rewrite, and this item's streamed-turn tests then cover the path feat(ai): pinned invariants survive memory summarization, lead every system prompt and recur on a cadence #985's cadence test exercises. - Lands after feat(cli): extend the ruff rule set to the correctness families #420 (v0.2.26): feat(cli): extend the ruff rule set to the correctness families #420 fixes the
B006list default atcommands/ai.py:862(theagentscommand), a different function in the same file; it ships in the earlier release, so this item rebases a no-content-overlap hunk at most. - Same file, different function: feat(ai): sequential pipeline stages carry a budgeted context, with the scratchpad appended once #859 (v0.2.27) edits the
pipelinecommand (commands/ai.py:1146onward); no ordering constraint, whichever lands second rebases without a conflict in content. - Related: fix(ai): streamed
devops ai chatturns send the user's message #874 was split off feat(ai): finish reasons and stream completeness for model replies #599 during the v0.2.25/v0.2.26 readiness review (2026-10-01).
Readiness check (2026-10-04)
Checked against release/v0.2.26 at b61e5a0. The defect is unchanged: the helper still never adds the user entry, and except Exception still pops whatever entry is last.
Line corrections (commands/ai.py moved +9, agent.py +22):
src/devops_cli/commands/ai.py:_stream_interactive_chat_turn:935-962(was:926-953);to_chat_messages():949(was:940); replyadd_interaction:962(was:953); thinking-only fallback:954-960(was:945-951);--stream/--tools:999-1000(was:990-991); RAG prepend:1085-1089(was:1076-1080);if stream and not tools::1099(was:1090);except KeyboardInterrupt:1113-1114andexcept Exception:1115-1118(were:1104-1105,:1106-1109); chat constructor:1054-1056(was:1045-1047);agentscommand:853-929(was:849-920), still ending six lines above the helper; pipeline command:1155onward (was:1146).src/devops_cli/ai/agents/agent.py: user entry:843(was:821); RAG step:849-862, the fallback's second lookup:852-858(was:827-840,:830-836);chat_messagescall:909(was:887); assistant entry:1046(was:1024);run_stream:1129-1155with its single-message list at:1152(was:1107-1133,:1130).tests/conftest.py: the guard fixture starts at:99. Thetests/test_ai_cmd.pyanchors (:430-443,:579-598) andtests/test_pydantic_agent.py:77-98are unchanged.
Dependencies:
- feat(cli): extend the ruff rule set to the correctness families #420 is merged into
release/v0.2.26(be37f46), so "Lands after feat(cli): extend the ruff rule set to the correctness families #420" is satisfied, and feat(ai): finish reasons and stream completeness for model replies #599 was already delivered. - 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), so the order now lives in these Dependencies sections. It is unchanged for
commands/ai.py: this item first, 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.
Rules: the item fits one PR. It uses offline fakes, adds changelog.d/874.md, makes no shared-file edits and has no dry-run surface (interactive chat). No acceptance criterion changes.
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
dan-petty commentedon Oct 2, 2026
Grooming (2026-10-02): Placed in v0.2.27, one of its slots held for P1 work that surfaced after it was planned. Value High, effort Low. Ready.
Checked against the code at the release/v0.2.25 tip.
fix(ai): streamed devops ai chat turns send the user's message, and a…
dan-petty-bot commentedon Oct 5, 2026
What changed
#1196, merged into
release/v0.2.27as 107580e.4 file(s) changed.
How it was verified
Check runs at 8ee2819:
Acceptance Criteria of
docs/agent/tasks/task-874-streamed-chat-turns-send-the-users-message.md:messagescontains[("user", "p1")]. On turn 2,messagescontains[("user", "p1"), ("assistant", "r1"), ("user", "p2")], and memory records both turns.AIClientErroror is aborted withKeyboardInterrupt, memory is rolled back to its pre-turn state and subsequent turns proceed cleanly.agent.runand record exactly one user entry in memory.test_a_cut_stream_stores_no_reply_in_chat_memoryverifies that a cut stream under the helper alone leaves the single user entry and no assistant reply.chat_messages_streamandchat_messages, patchedinvestigate_rag_context, and respectprevent_external_network_calls.pytest.uv run devops cicompletes with 100% passing quality gates.changelog.d/874.mdexists with### Fixed;docs/agent/tasks/task-874-streamed-chat-turns-send-the-users-message.mdexists with**Status**: Done;CHANGELOG.mdanddocs/ROADMAP.mdremain untouched.uv run devops ai chat --no-tools, ask "What is 2+2?". The reply answers that question. Then ask "And times 3?"; the reply uses the first answer, showing the history was sent. Then ask a third question and press Ctrl-C while the reply streams; "Interrupted." prints, and a fourth question gets a reply that still follows the earlier answers.feat(release): v0.2.27 (#1257)