feat(agent): strip raw tool-scaffolding from streamed answers — deterministic filter with one bounded recovery
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
# Phase 70 — Harness-Aligned Agent Tools: `ls` / `read(path)` / `grep(pattern, path?)`
|
||||
|
||||
**Source:** owner request (chat, 2026-09-03) — live incident: the question "What are the
|
||||
correct llama.cpp arguments for Qwen 3.8?" was answered with the raw model text
|
||||
`<|tool_call_start|>[read(path='/homelab/backup-notes.md')]<|tool_call_end|>`
|
||||
(`query_log`: top_score=0.040, fts_hits=0, deflected=true — the turn was DEFLECTED, so
|
||||
no tools were even offered). Diagnosis: the chat model (`lite` per `.env`; owner keeps
|
||||
`lite` for everything — it's faster, owner decision 2026-09-03) reaches for the tool
|
||||
shapes it was trained on — a `read` tool taking a **single** `path` argument — and our
|
||||
`read_document(source, path)` fights that prior (the `_resolve_document` combined-form
|
||||
self-correction and "teach the split" refusals are the scar tissue). Owner direction:
|
||||
"match existing harnesses as much as possible" — the mapping below mirrors the
|
||||
**pi.dev** tool surface (`dist/core/tools/`: `read{path}`, `ls{path?}`,
|
||||
`grep{pattern, path?}`).
|
||||
**Story:** `.agent/user_stories/agent-document-tools.md` (this phase reshapes the tools
|
||||
that story delivered; phase 68's search contract rides along renamed)
|
||||
**Context:**
|
||||
- `app/rag/agent.py` — `AGENT_TOOLS` (OpenAI function definitions:
|
||||
`list_documents` / `read_document(source, path)` / `search_documents(pattern,
|
||||
source?, path?)`), `_execute_tool` (execution + refusals: `ALREADY_IN_CONTEXT`,
|
||||
`UNKNOWN_TOOL`, `MISSING_READ_ARGS`, `MISSING_SEARCH_ARGS`; combined-form
|
||||
self-correction in `_resolve_document`), `AgentHolder`, `run_agent` (round cap
|
||||
`BOR_AGENT_MAX_ROUNDS`, default 10; `0` = no-tools kill switch).
|
||||
- `app/rag/prompts.py` — `TOOLS_SECTION` (HIGH prompt only, ends the prompt; the E2E
|
||||
mock keys off the `<tools>` marker's *presence*, not the wording).
|
||||
- `app/api/chat.py` — the `ToolCallPiece` → SSE `{"type":"tool","name":…,"argument":…}`
|
||||
derivation (read → `source/path`, search → pattern, list → null), `done.sources`,
|
||||
per-turn log line (`tool_calls=N`).
|
||||
- `tests/e2e/mock_llm.py` — the deterministic mock flows keyed on `TOOLS_TRIGGER`
|
||||
("use your tools"), `MULTI_READ_TRIGGER`, `SEARCH_TRIGGER` + the `<tools>` marker;
|
||||
the flows emit `tool_calls` deltas with the current names/args and parse the
|
||||
`source: X | path: Y | title: Z` catalog lines.
|
||||
- `frontend/assets/app.js` — `.tool-call` lines (one row per `tool` frame, generic
|
||||
render of `name` + `argument`), docstring name references; `frontend/assets/shared.js`
|
||||
L159 special-cases `t.name === "read_document"` (shared-chat view).
|
||||
- `tests/` — unit: `test_agent.py`, `test_prompts.py`, `test_chat_gate.py`,
|
||||
`test_mock_tool_flow.py`, `test_sse_events.py`; integration: `test_agent_tools.py`,
|
||||
`test_chat_api.py`, `test_api.py`, `test_chats_api.py`; E2E:
|
||||
`test_agent_document_tools.py`, `test_agent_unlimited_tools.py`,
|
||||
`test_search_tool.py`. `README.md` L173–176 documents the current tool names/args.
|
||||
|
||||
## Objective
|
||||
Rename and reshape the three server-side agent tools to the harness-trained surface —
|
||||
**`ls`**, **`read(path)`** (single combined `source/path` argument), **`grep(pattern,
|
||||
path?)`** — so the model's trained priors emit valid calls instead of fighting the
|
||||
schema. Capabilities and all owner-locked semantics (full-document reads, fixed-
|
||||
substring locator searches, round cap, kill switch, SSE contract shape) are unchanged;
|
||||
only the tool surface, its descriptions, and the ripples (prompt copy, SSE names,
|
||||
mock, tests, docs) change.
|
||||
|
||||
## Dependencies
|
||||
- `68_search_tool` (complete) — the search semantics this phase renames (A5 locked
|
||||
match/output contract preserved).
|
||||
- `45_agent_unlimited_tools` (complete) — the round-cap design the loop keeps.
|
||||
- No todo dependencies; runs on the current head. Phase `71_scaffolding_guardrails`
|
||||
(todo) follows this one (its mock changes build on the new tool names).
|
||||
|
||||
## Tasks
|
||||
1. `01_tool_schemas.md` — `app/rag/agent.py`: `AGENT_TOOLS` → `ls` / `read` / `grep`
|
||||
schemas + descriptions; `_execute_tool` argument handling (single combined `path`),
|
||||
updated refusals; unit tests.
|
||||
2. `02_prompt_section.md` — `app/rag/prompts.py`: `TOOLS_SECTION` rewritten for
|
||||
`ls`/`read`/`grep`; prompt unit pins.
|
||||
3. `03_api_sse.md` — `app/api/chat.py`: SSE `tool`-frame `argument` derivation for the
|
||||
new shapes + module/docstring contract copy; integration tests.
|
||||
4. `04_frontend.md` — `app.js` + `shared.js` name references and the
|
||||
`read_document` special case; frontend unit pins; persisted-chat note.
|
||||
5. `05_mock_e2e_commit.md` — `mock_llm.py` flows on the new names/args, the three
|
||||
existing E2E suites updated, the new dedicated E2E suite, README, full gates,
|
||||
commit.
|
||||
|
||||
## Testing & Quality
|
||||
- Unit: `tests/unit/test_agent.py` — the new schemas (names, required/optional args,
|
||||
descriptions), `read` path resolution (combined form split at the FIRST slash, bare
|
||||
source name refusal, already-in-context, full content), `ls` scoping (no-arg full
|
||||
catalog, `path`=source scope, unknown-source refusal, empty-source "0 documents"),
|
||||
`grep` (required `pattern`, optional `path` single-doc scope, the locked A5 output
|
||||
contract: fixed substring, case-insensitive, 20 matches, 200-char lines, locator
|
||||
only), the round cap + kill switch (`agent_max_rounds=0` → `tools=None`,
|
||||
byte-identical request) unchanged.
|
||||
- Unit: `tests/unit/test_prompts.py` / `test_chat_gate.py` — `TOOLS_SECTION` copy
|
||||
(marker present, HIGH-only), byte-identical LOW prompt (this phase does not touch
|
||||
the deflection path).
|
||||
- Integration: `tests/integration/test_agent_tools.py`, `test_chat_api.py` — SSE
|
||||
`tool` frames with the new `name`/`argument` values end-to-end (mock LLM),
|
||||
`done.sources` / `query_log.sources` / `tool_calls=N` log line unchanged in meaning.
|
||||
- E2E (mandatory, house rule): NEW dedicated suite
|
||||
`tests/e2e/test_harness_aligned_tools.py`, run in isolation — the `ls` → `read`
|
||||
(combined path) → answer flow and the `grep` → `read` flow over the real UI; plus
|
||||
the three existing suites (`test_agent_document_tools.py`,
|
||||
`test_agent_unlimited_tools.py`, `test_search_tool.py`) updated to the new names and
|
||||
green in isolation.
|
||||
- Coverage: **>90%** on `app/` (validate.sh gate).
|
||||
|
||||
## Completion Criteria
|
||||
- [ ] `AGENT_TOOLS` defines exactly `ls` (optional `path`), `read` (required `path`),
|
||||
`grep` (required `pattern`, optional `path`); the old names exist nowhere in
|
||||
`app/` (`rg "list_documents|read_document|search_documents" app/` → no matches).
|
||||
- [ ] `read` accepts the combined `source/path` form (the model's natural shape),
|
||||
splits at the first slash, appends the **full** document (A7-revised: never
|
||||
truncated); `grep` keeps the locked A5 match/output contract and is a locator
|
||||
only; `ls` prints the phase-63 `source: X | path: Y | title: Z` lines.
|
||||
- [ ] SSE `tool` frames carry the new `name` values; `argument` is the single string
|
||||
the model passed (`read`'s `path`, `grep`'s `pattern`, `ls`'s `path`) or null.
|
||||
- [ ] `BOR_AGENT_MAX_ROUNDS=0` still disables the tools entirely (request
|
||||
byte-identical to the no-tools path); the deflected path is byte-identical
|
||||
(LOW prompt and `tools=None` untouched by this phase).
|
||||
- [ ] `uv run pytest` green; `uv run pytest --cov=app` TOTAL **>90%**;
|
||||
`uv run ruff check . && uv run pyright` clean.
|
||||
- [ ] `uv run pytest tests/e2e/test_harness_aligned_tools.py -v --no-cov` green in
|
||||
isolation; regression suites green in isolation: `test_agent_document_tools.py`,
|
||||
`test_agent_unlimited_tools.py`, `test_search_tool.py`, `test_chat_rag.py`.
|
||||
- [ ] README tool documentation updated to the new surface.
|
||||
- [ ] One `--no-gpg-sign` commit (message in the Commit block); phase dir moved to
|
||||
`.agent/phases/complete/`.
|
||||
|
||||
## Locked decisions
|
||||
- **Owner (chat, 2026-09-03):** the tool surface is remapped to the pi.dev harness
|
||||
shape — `ls` / `read(path)` / `grep(pattern, path?)` — "to match existing harnesses
|
||||
as much as possible"; `lite` stays the chat model for everything (no model swap);
|
||||
the chat model is NOT flipped to `turbo`. This supersedes the phase-37 tool
|
||||
names/args and the phase-68 tool *name* (`search_documents` → `grep`); the phase-68
|
||||
match/output contract (fixed substring, case-insensitive, 20×200, locator-only) is
|
||||
preserved verbatim.
|
||||
- **`read` is `path`-only.** No `offset`/`limit` (pi has them, but the A7-revised
|
||||
contract is "never truncated" — implementing paging would violate it; `path`-only
|
||||
still carries the trained shape, which is the point).
|
||||
- **The combined `source/path` string is the canonical document identity** in every
|
||||
tool argument, refusal, and result header (it already is in search result lines and
|
||||
`done.sources`). The old two-argument split and its self-correction/teaching
|
||||
refusals are deleted — the model's combined form is now *correct*, not a mistake to
|
||||
fix.
|
||||
- **SSE contract shape unchanged** (A15 extension honoured): `{"type":"tool",
|
||||
"name":…,"argument":…}` — only the `name` values and the `argument` derivation
|
||||
change. `delta`/`thinking`/`retry`/`done`/`error` frames are untouched.
|
||||
- **No env changes, no schema change.** `BOR_AGENT_MAX_ROUNDS` keeps its meaning
|
||||
(round cap; `0` = no-tools kill switch). Saved chats persisting old tool names
|
||||
render fine (the UI renders whatever `name`/`argument` arrive — no migration).
|
||||
|
||||
## Commit
|
||||
```bash
|
||||
git add -A .agent/ app/ tests/ frontend/ README.md && git commit --no-gpg-sign -m "feat(agent): align the document tools with the harness-trained shape — ls, read(path), grep(pattern, path?)"
|
||||
```
|
||||
@@ -0,0 +1,78 @@
|
||||
# Task 05 — Mock LLM, E2E Suites, README, Gates, Commit
|
||||
|
||||
**Phase:** `70_harness_aligned_tools` · **Story:** `.agent/user_stories/agent-document-tools.md`
|
||||
|
||||
## Objective
|
||||
Bring the E2E world onto the new surface: the mock LLM's deterministic tool flows
|
||||
emit `ls`/`read`/`grep` calls with the new argument shapes, the three existing tool
|
||||
E2E suites assert the new names/frames, and a NEW dedicated suite pins the remap
|
||||
end-to-end. Then the full quality gates and the phase commit.
|
||||
|
||||
## Work
|
||||
1. `tests/e2e/mock_llm.py` — update the deterministic flows (trigger strings
|
||||
`TOOLS_TRIGGER` / `MULTI_READ_TRIGGER` / `SEARCH_TRIGGER` and the `<tools>`
|
||||
marker keying stay unchanged):
|
||||
- READ flow: request 1 streams `ls` (no arguments, synthetic id `call_0`,
|
||||
`finish_reason: "tool_calls"`); request 2 (a `tool`-role catalog result in the
|
||||
messages) streams `read` with the **combined** `source/path` parsed from the
|
||||
first `source: X | path: Y` catalog line (the mock joins them — the catalog
|
||||
format is unchanged, so this is the only parse change); request 3 (a
|
||||
`tool`-role read result — content starting with the `Document source/path:`
|
||||
header) streams the plain answer.
|
||||
- MULTI-READ flow: same, `read` on the first then second combined path.
|
||||
- SEARCH flow: request 1 streams `grep` with the pattern argument (the existing
|
||||
SEARCH_TRIGGER pattern value); request 2 (a `tool`-role search result —
|
||||
`source/path:line: text` lines) streams the plain answer. Update the
|
||||
`tool`-role result detection strings where they key on the old headers.
|
||||
- Update the module docstring's flow descriptions (names/args) + the phase-70
|
||||
note.
|
||||
2. Existing E2E suites — update assertions to the new names/frames (behavior
|
||||
otherwise unchanged): `tests/e2e/test_agent_document_tools.py` (tool frame
|
||||
`name` values: `ls` then `read`; the `.tool-call` line copy "📄 Reading …"),
|
||||
`tests/e2e/test_agent_unlimited_tools.py` (multi-read frames),
|
||||
`tests/e2e/test_search_tool.py` (the `grep` frame + pattern argument).
|
||||
3. NEW `tests/e2e/test_harness_aligned_tools.py` (the phase's dedicated suite,
|
||||
house pattern, run in isolation):
|
||||
- Grounded turn with the READ trigger: the UI shows the `ls` line then the
|
||||
`📄 Reading <source/path>` line, the answer streams, and the done-state
|
||||
sources include the read document; no raw tool markup anywhere in the DOM.
|
||||
- Grounded turn with the SEARCH trigger: the `🔎 Searching for <pattern>` line
|
||||
then the answer.
|
||||
- The SSE wire itself (in-browser `fetch` capture or the existing SSE-capture
|
||||
house pattern): `tool` frames carry `name` ∈ {`ls`, `read`, `grep`} and the
|
||||
`argument` rule (read → combined path as passed; grep → pattern; ls → null
|
||||
unscoped).
|
||||
4. `README.md` — the agent-tools section (L173–176): document `ls` / `read(path)` /
|
||||
`grep(pattern, path?)` with the combined-path identity and the A5 locator
|
||||
semantics; the `.env.example` comment near `BOR_AGENT_MAX_ROUNDS` stays accurate
|
||||
(no env changes this phase).
|
||||
5. Gates + commit:
|
||||
- `uv run pytest` green; `uv run pytest --cov=app --cov-report=term-missing`
|
||||
TOTAL **>90%**; `uv run ruff check . && uv run pyright` clean.
|
||||
- E2E in isolation (DB up): `test_harness_aligned_tools.py`, then the regression
|
||||
suites `test_agent_document_tools.py`, `test_agent_unlimited_tools.py`,
|
||||
`test_search_tool.py`, `test_chat_rag.py`.
|
||||
- One atomic commit (message below); move
|
||||
`.agent/phases/todo/70_harness_aligned_tools/` →
|
||||
`.agent/phases/complete/70_harness_aligned_tools/`.
|
||||
|
||||
## Testing & Quality
|
||||
- E2E: the new dedicated suite + the four regression suites (isolation runs).
|
||||
- Coverage: **>90%** on `app/` (phase-level gate).
|
||||
|
||||
## Completion Criteria
|
||||
- [ ] `rg "list_documents|read_document|search_documents" app/ frontend/ tests/
|
||||
README.md` → matches only in legacy-render pins/comments explicitly marked
|
||||
legacy (the frontend legacy branches and their unit pins).
|
||||
- [ ] `uv run pytest` green; `uv run pytest --cov=app` TOTAL **>90%**;
|
||||
`uv run ruff check . && uv run pyright` clean.
|
||||
- [ ] `uv run pytest tests/e2e/test_harness_aligned_tools.py -v --no-cov` green in
|
||||
isolation; regression suites green in isolation.
|
||||
- [ ] README documents the new surface; no stale tool-name copy in `README.md` /
|
||||
`.env.example` / `frontend/`.
|
||||
- [ ] One `--no-gpg-sign` commit; phase dir moved to `.agent/phases/complete/`.
|
||||
|
||||
## Commit
|
||||
```bash
|
||||
git add -A .agent/ app/ tests/ frontend/ README.md && git commit --no-gpg-sign -m "feat(agent): align the document tools with the harness-trained shape — ls, read(path), grep(pattern, path?)"
|
||||
```
|
||||
@@ -0,0 +1,77 @@
|
||||
# Task 01 — `app/rag/scaffolding.py`: Pattern Registry + Streaming Filter
|
||||
|
||||
**Phase:** `71_scaffolding_guardrails` · **Story:** n/a (owner request from chat, 2026-09-03)
|
||||
|
||||
## Objective
|
||||
A pure-Python streaming filter that removes known tool-scaffolding from answer text
|
||||
as it flows — no I/O, no model, fully unit-testable — plus the pattern registry that
|
||||
defines "known" (every entry traces to an observed capture).
|
||||
|
||||
## Work
|
||||
1. `app/rag/scaffolding.py` (new module):
|
||||
- `SCAFFOLD_PATTERNS: tuple[re.Pattern, ...]` — module-level, compiled:
|
||||
1. `re.compile(r"<\|tool_call_start\|>[\s\S]*?<\|tool_call_end\|>")` — the
|
||||
observed span (incident 2026-09-03), non-greedy so multiple spans each
|
||||
strip to their own end token.
|
||||
2. `re.compile(r"<\|tool_calls\|>")` — standalone sibling token (same
|
||||
tokenizer family).
|
||||
3. `re.compile(r"<\|tool_call\|>")` — standalone sibling token.
|
||||
Module docstring: the registry is the extension point — a new entry needs an
|
||||
observed capture (the strip warning log, task 03) + a unit fixture here; no
|
||||
speculative entries.
|
||||
- `class ScaffoldingFilter` — streaming state machine over a **content** stream:
|
||||
- `feed(chunk: str) -> str` — appends to an internal pending buffer and
|
||||
returns the clean text safe to emit now. Algorithm: repeatedly (a) take the
|
||||
leftmost complete match among `SCAFFOLD_PATTERNS` in the pending buffer —
|
||||
drop it (count into `stripped_chars`) and continue; then (b) check the
|
||||
buffer tail for a **live prefix**: the longest suffix that is either a
|
||||
proper prefix of any pattern's literal opening (`<|tool_call_start|>`,
|
||||
`<|tool_calls|>`, `<|tool_call|>`) or an **open span** (a start token with
|
||||
no end token yet in the buffer — everything from that start token onward is
|
||||
held, since the span may continue in future chunks). Emit everything before
|
||||
the held tail; keep the held tail as the new pending state. (Bounded: the
|
||||
held tail in NORMAL state is ≤ the longest opening token minus one char;
|
||||
in an open span it is unbounded but is being *stripped*, never emitted.)
|
||||
- `flush() -> str` — end of stream: the pending tail is emitted **as-is**
|
||||
(a partial marker at EOF is content, not scaffolding — a documented
|
||||
choice, pinned).
|
||||
- `stripped_chars: int` — total characters removed (property or attribute;
|
||||
read by the caller after the round/turn, task 03).
|
||||
- One filter instance per model request (callers create fresh instances —
|
||||
the phase-67 retry-after-dead-attempt case is safe: a dead attempt never
|
||||
fed the filter).
|
||||
- No logging, no settings, no imports beyond `re` (pure module; the strip
|
||||
*warning* log is emitted by the integration layer, task 03, so the module
|
||||
stays I/O-free).
|
||||
2. `tests/unit/test_scaffolding_filter.py` (new) — the matrix from the phase
|
||||
overview:
|
||||
- span in one chunk → stripped, `stripped_chars` exact.
|
||||
- span split across chunks: feed the incident text
|
||||
`<|tool_call_start|>[read(path='/homelab/backup-notes.md')]<|tool_call_end|>`
|
||||
at **every** split offset of the start token (0..len) plus a mid-span split
|
||||
and an end-token split → nothing ever emits until the span completes; total
|
||||
output empty; `stripped_chars` = full span length.
|
||||
- two spans in one chunk (with text between) → between-text emitted, spans
|
||||
stripped.
|
||||
- standalone `<|tool_calls|>` / `<|tool_call|>` stripped (alone and embedded in
|
||||
a line).
|
||||
- look-alikes **not** stripped, emitted verbatim: `tool_call_start` as prose;
|
||||
`<|tool_call_start|` (missing delimiter close) as prose; an unknown
|
||||
`<|some_other_token|>`; a lone `<|tool_call_end|>` without a start.
|
||||
- partial start token at EOF (`feed("<|tool_call_st")` then `flush()`) →
|
||||
flush emits it as-is, `stripped_chars == 0`.
|
||||
- surrounding text preserved exactly: `hello <|…span…> world` → `hello world`
|
||||
(no reflow beyond the removal); empty chunk no-op; `flush()` on a clean
|
||||
stream emits nothing new.
|
||||
|
||||
## Testing & Quality
|
||||
- Unit: `tests/unit/test_scaffolding_filter.py` (above) — exhaustive boundary
|
||||
offsets, parametrized.
|
||||
- Coverage: **>90%** on `app/rag/scaffolding.py` (every branch: match, open-span
|
||||
hold, live-prefix hold, flush-emits-as-is).
|
||||
|
||||
## Completion Criteria
|
||||
- [ ] `uv run pytest tests/unit/test_scaffolding_filter.py -v --no-cov` green.
|
||||
- [ ] `rg "import (os|sys|logging|app)" app/rag/scaffolding.py` → no matches (pure
|
||||
module).
|
||||
- [ ] `uv run ruff check . && uv run pyright` clean.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Task 02 — Filter Integration in `chat_stream` / `chat_stream_retried`
|
||||
|
||||
**Phase:** `71_scaffolding_guardrails` · **Story:** n/a (owner request from chat, 2026-09-03)
|
||||
|
||||
## Objective
|
||||
Route `delta.content` through the caller-supplied `ScaffoldingFilter` in
|
||||
`app/rag/llm.py` — content filtered, thinking raw, tail flushed before tool-call
|
||||
materialization — with `None` keeping today's byte-identical raw path.
|
||||
|
||||
## Work
|
||||
1. `app/rag/llm.py` — `chat_stream(..., scaffolding: "ScaffoldingFilter | None =
|
||||
None)"` (type imported under `TYPE_CHECKING` or as a string annotation to keep
|
||||
the module's import graph clean — the filter type is only needed for typing):
|
||||
- Content path: `content = delta.content` → when a filter is present,
|
||||
`cleaned = scaffolding.feed(content)`; yield `StreamPiece("content",
|
||||
cleaned)` only when `cleaned` is non-empty (an empty clean result yields
|
||||
**nothing** — no empty `delta` frames). Without a filter the existing
|
||||
`if content: yield` stands untouched (byte-identical).
|
||||
- Thinking path: unchanged — `reasoning_content` pieces are never filtered
|
||||
(locked: the scratchpad stays raw).
|
||||
- End of stream: after the `async for` exhausts and **before** the tool-call
|
||||
materialization block (`if calls and not emitted: …` and the
|
||||
finish-reason emission), `tail = scaffolding.flush()` when a filter is
|
||||
present; yield a content piece for the tail when non-empty. Order pinned:
|
||||
flushed-tail content precedes `ToolCallPiece`s (content-before-tools wire
|
||||
convention).
|
||||
- Teardown (phase 48) untouched: the `finally: await stream.close()` behavior is
|
||||
independent of the filter.
|
||||
- Docstring: a short "Scaffolding guardrail (phase 71)" paragraph — the filter
|
||||
is caller-owned (one per request), content-only, `None` = raw path.
|
||||
2. `app/rag/llm.py` — `chat_stream_retried(..., scaffolding=None)` — pass-through
|
||||
to `llm.chat_stream`. The same filter object is used across retry attempts of
|
||||
one logical request: safe by construction (a restarted attempt only happens
|
||||
when no piece was emitted, i.e. the filter was never fed — note this in the
|
||||
docstring).
|
||||
3. `tests/unit/test_llm_client.py` — scripted-chunk tests (the existing
|
||||
fake-client pattern):
|
||||
- with a filter: a chunk carrying a span mid-stream → the `delta` pieces carry
|
||||
only the clean text; a span split across two chunks → no partial emit;
|
||||
`filter.stripped_chars` correct after consumption.
|
||||
- thinking pieces pass through raw even when they contain a span (pinned).
|
||||
- `scaffolding=None` → the yielded pieces are byte-identical to the pre-phase
|
||||
raw path (a span in content is yielded verbatim — the raw contract for
|
||||
callers that opt out).
|
||||
- flush ordering: a trailing partial-then-complete tail yields its content
|
||||
piece **before** the materialized `ToolCallPiece` (a chunk stream that ends
|
||||
with `…clean tail` + tool_calls deltas).
|
||||
- teardown interaction: the phase-48 `aclose()`/abandon tests
|
||||
(`tests/unit/test_llm_stream_teardown.py`) stay green with and without a
|
||||
filter (run, don't rewrite).
|
||||
|
||||
## Testing & Quality
|
||||
- Unit: `tests/unit/test_llm_client.py` (+ the untouched teardown suite green).
|
||||
- Coverage: **>90%** on this task's modified code (`app/rag/llm.py`).
|
||||
|
||||
## Completion Criteria
|
||||
- [ ] `uv run pytest tests/unit/test_llm_client.py tests/unit/test_llm_stream_teardown.py
|
||||
-v --no-cov` green.
|
||||
- [ ] `scaffolding=None` callers (including the kill-switch no-tools requests) are
|
||||
byte-identical (pinned).
|
||||
- [ ] `uv run ruff check . && uv run pyright` clean.
|
||||
@@ -0,0 +1,104 @@
|
||||
# Task 03 — Recovery Policy: One Bounded `tools=None` Retry + Terminal Error
|
||||
|
||||
**Phase:** `71_scaffolding_guardrails` · **Story:** n/a (owner request from chat, 2026-09-03)
|
||||
|
||||
## Objective
|
||||
When a round/turn's visible content ends up empty **because scaffolding was the
|
||||
whole answer**, run exactly one deterministic recovery (same turn, `tools=None`,
|
||||
fixed correction line in the system prompt, fresh filter); a second empty reply
|
||||
settles with a dedicated error frame. Both the grounded agent loop and the
|
||||
deflected path get the policy; the per-turn log line gains `scaffold_stripped=N`.
|
||||
|
||||
## Work
|
||||
1. `app/rag/agent.py`:
|
||||
- `CORRECTION_INSTRUCTION: str` — the harness-owned constant (verbatim, single
|
||||
line): "Your previous reply contained raw tool-call markup, which is not
|
||||
interpreted here. Answer the user's question directly in plain text — no
|
||||
tool syntax." (The E2E mock in task 05 keys on a stable substring of it —
|
||||
pick the exact constant now; the mock copies it.)
|
||||
- `class MalformedReplyError(LLMError)` — raised only by the recovery policy
|
||||
(never from inside a stream, so `chat_stream_retried`'s retry rule never
|
||||
sees it). Module docstring: the phase-71 note (deterministic-only, owner
|
||||
permission 2026-09-03).
|
||||
- `run_agent` — per round: create a fresh `ScaffoldingFilter`, pass it to
|
||||
`chat_stream_retried(..., scaffolding=round_filter)`, and count the
|
||||
round's visible content (sum of the lengths of the yielded
|
||||
`StreamPiece("content", …)` texts — the filtered ones). After the round,
|
||||
when `not calls` (today's "the answer was streamed" exit):
|
||||
- if round content > 0 → return (as today).
|
||||
- if round content == 0 and `round_filter.stripped_chars > 0` → **one
|
||||
recovery**: `messages_recovered = [*messages[:-1], {"role": "system",
|
||||
"content": system_prompt + "\n" + CORRECTION_INSTRUCTION}, messages[-1]]`
|
||||
(the correction folds into the ORIGINAL single system message —
|
||||
provider-safe; the user message stays last) — one
|
||||
`chat_stream_retried` request with `tools=None`, a fresh filter, the same
|
||||
`retries`/`delay` budget; yield its pieces through the normal piece flow.
|
||||
If the recovery's visible content > 0 → return. Otherwise →
|
||||
`logger.warning` + `raise MalformedReplyError(…)`.
|
||||
- if round content == 0 and nothing was stripped → return (today's
|
||||
empty/thinking-only answer behavior — the UI handles it; unchanged).
|
||||
- Log one warning per strip event here: `logger.warning("agent: stripped
|
||||
N chars of tool-scaffolding in round %d: %r", …)` with the stripped span
|
||||
truncated to 200 chars (the capture mechanism for new registry entries —
|
||||
the filter exposes the stripped spans for this; add a
|
||||
`stripped_spans: list[str]` to the filter if needed).
|
||||
- A scaffolding-only round that also **carried tool calls** needs no
|
||||
recovery (the clean content stands / the tool ran) — the policy keys on
|
||||
the `not calls` exit only (pinned).
|
||||
2. `app/api/chat.py` — the **deflected** path (the grounded path is covered by
|
||||
`run_agent`):
|
||||
- Create one `ScaffoldingFilter` for the turn's request, pass it to
|
||||
`chat_stream_retried(..., scaffolding=filter)`; count visible content across
|
||||
the piece loop (a `content_chars` counter next to `thinking_chars`).
|
||||
- After the piece loop (deflected branch only): content == 0 and
|
||||
`filter.stripped_chars > 0` → one recovery request: the same
|
||||
`messages` with the system prompt extended by
|
||||
`CORRECTION_INSTRUCTION` (import from `app.rag.agent`), `tools=None`, a
|
||||
**fresh** filter, the same retry budget; stream its pieces through the
|
||||
SAME piece-handling code (extract the piece loop into a small inner
|
||||
helper/coroutine to avoid duplicating the thinking/tool/retry/delta
|
||||
handling — the extraction must be behavior-preserving for the first pass,
|
||||
pinned by the existing integration suite). If the recovery content > 0 →
|
||||
continue to the normal `done` flow; else → the terminal path below.
|
||||
- Catch `MalformedReplyError` **before** the generic `LLMError` handler:
|
||||
`settled = True`, yield `ChatErrorEvent(detail="The model returned a
|
||||
malformed reply — please try again.")`, return (no `query_log` row, no
|
||||
`done` — the existing terminal-error semantics; the generic
|
||||
"dropped the connection" copy stays for transport failures).
|
||||
- Per-turn log line: append `scaffold_stripped=N` after `retries=N` — the sum
|
||||
across the turn's requests (rounds + any recovery; 0 on clean turns —
|
||||
uniform field, the phase-67 `retries=N` pattern). The recovery does not
|
||||
bump `retries=N` (it is not a phase-67 endpoint-retry).
|
||||
- Module docstring: the phase-71 paragraph (deterministic guardrail +
|
||||
recovery + log field).
|
||||
3. `tests/unit/test_agent.py` — the grounded matrix (scripted fake LLM,
|
||||
monkeypatched DB): scaffolding-only round → exactly **two** model requests,
|
||||
the second `tools=None` with `CORRECTION_INSTRUCTION` in its system prompt →
|
||||
clean answer ends the turn, `done`-side state normal (holder untouched by the
|
||||
recovery); scaffolding twice → `MalformedReplyError` (assert it subclasses
|
||||
`LLMError`); scaffolding + real content → one request only, clean content
|
||||
yielded, no recovery; clean turn → one request, no correction in any system
|
||||
prompt; the round cap + kill-switch tests stay green.
|
||||
4. `tests/integration/test_chat_api.py` — the deflected matrix over
|
||||
`POST /api/chat` (mock LLM): scaffolding-only deflected turn → clean recovery
|
||||
answer + `done` frame; scaffolding twice → the error frame with the dedicated
|
||||
copy, no `done`, no `query_log` row (assert against the table); mixed
|
||||
scaffolding+content → clean answer, `scaffold_stripped>0` in the log line;
|
||||
the log-line pin gains `scaffold_stripped=0` on clean turns and the summed
|
||||
value on stripped turns.
|
||||
|
||||
## Testing & Quality
|
||||
- Unit: `tests/unit/test_agent.py` (grounded matrix).
|
||||
- Integration: `tests/integration/test_chat_api.py` (deflected matrix + log line).
|
||||
- Coverage: **>90%** on this task's modified code (`app/rag/agent.py`,
|
||||
`app/api/chat.py`).
|
||||
|
||||
## Completion Criteria
|
||||
- [ ] `uv run pytest tests/unit/test_agent.py tests/integration/test_chat_api.py -v
|
||||
--no-cov` green.
|
||||
- [ ] Exactly one recovery per turn, on both paths; the recovery request is
|
||||
`tools=None` + correction line; a second empty reply → the dedicated error
|
||||
frame, no `query_log` row.
|
||||
- [ ] Clean turns: no correction in any system prompt, `scaffold_stripped=0`,
|
||||
request counts unchanged (kill-switch/deflection byte-identical pins green).
|
||||
- [ ] `uv run ruff check . && uv run pyright` clean.
|
||||
@@ -0,0 +1,35 @@
|
||||
# Task 04 — Deflect Prompt: Plain-Text-Only Line (Prevention)
|
||||
|
||||
**Phase:** `71_scaffolding_guardrails` · **Story:** n/a (owner request from chat, 2026-09-03)
|
||||
|
||||
## Objective
|
||||
Close the door at the prompt: the deflected (LOW) turn offers no tools, so any tool
|
||||
markup there is always wrong — add one plain-text-only instruction line to the
|
||||
`DEFLECT_MODE` body. This is the owner-permitted change to the otherwise-locked LOW
|
||||
prompt; the `DEFLECT_MODE` marker and everything else in the prompt stay put (the
|
||||
E2E mock keys on the marker's presence, not the wording).
|
||||
|
||||
## Work
|
||||
1. `app/rag/prompts.py` — `build_deflect_prompt`: append one line to the
|
||||
`DEFLECT_MODE` body (after "…propose 2-3 alternative questions."):
|
||||
"Reply in plain text only — you have no tools in this mode." The weak-hit
|
||||
title list follows exactly as today; `build_high_prompt`, `PERSONA`,
|
||||
`TOOLS_SECTION`, and the section order are untouched. Update the module
|
||||
docstring: the phase-71 note (owner-permitted 2026-09-03 LOW-prompt line;
|
||||
the marker-keying contract unchanged).
|
||||
2. `tests/unit/test_prompts.py` (and `test_chat_gate.py` where the deflection body
|
||||
is pinned) — pins: the new line present in the LOW prompt; the `DEFLECT_MODE`
|
||||
marker still present (mock keying); the HIGH prompt unchanged (byte-identical
|
||||
pins stay green — the line must not leak into HIGH); the byte-identical-when-
|
||||
empty steering/overview behavior unchanged.
|
||||
|
||||
## Testing & Quality
|
||||
- Unit: the prompt pins above.
|
||||
- Coverage: **>90%** on this task's modified code (`app/rag/prompts.py`).
|
||||
|
||||
## Completion Criteria
|
||||
- [ ] `uv run pytest tests/unit/test_prompts.py tests/unit/test_chat_gate.py -v
|
||||
--no-cov` green.
|
||||
- [ ] LOW prompt = pre-phase text + exactly the one new line (a diff pin, or a
|
||||
reconstruction pin in the test).
|
||||
- [ ] `uv run ruff check . && uv run pyright` clean.
|
||||
Reference in New Issue
Block a user