Skip to content

Count Stage-2 prose clarifications against the one-per-intent contract (closes #2905) - #3196

Merged
malibio merged 8 commits into
mainfrom
issue-2905-prose-clarification-guard
Sep 28, 2026
Merged

malibio merged 8 commits into
mainfrom
issue-2905-prose-clarification-guard

Conversation

@malibio

@malibio malibio commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #2905.

What was wrong

ADR-038's contract allows at most one clarification per intent. The guard found the current intent by scanning back for the last assistant message that did not start with the composed-clarification opener. A clarification Stage 2 asked in its own prose carried no opener, so:

  1. it was not counted, and
  2. it was read as the intent resolving, which dropped any earlier route_clarify from the window. Clarifications could alternate forever.

What this does

Each assistant turn records how it ended, structurally, and the guard reads that record instead of reply text.

  • AiChatTurnOutcome (Acted / Clarified / Replied) is persisted on each assistant AiChatMessage and seeded back into AgentSession::prior_turns from history.
  • AgentTurnResult::outcome() derives it from what the turn did: a composed clarification is Clarified; a successful write is Acted; anything else, including a turn that only read, is Replied.
  • The intent boundary is the last Acted turn. A Replied turn stays inside the intent, so a prose question can no longer erase an earlier clarification.
  • The intent is already clarified when it holds a composed clarification, or at least two turns that did not write. One such turn is as likely an answer ("hi" → "Hello!") as a question; counting it alone suppressed the first genuine clarification of any chat that opened with conversation or a lookup. Two in one intent is the loop the contract stops. The cost: an intent clarified only in prose can ask twice.
  • The duplicate-entity guard disarms only for records a composed clarification asked about. A read-only answer that linked the record stays in the intent but asked nothing.
  • When the intent is already clarified and Stage 2 replies in prose with no tool call at all, it is put back once with the contract stated (ALREADY_CLARIFIED_NUDGE). The prose is dropped from history so the model does not re-read its own question. The nudge never fires after a tool call, so a turn whose search answered the user is not pushed to call another tool.
  • route_clarify's Stage-2 description now says to clarify through it, never in a plain reply (tool-selection guidance, per ADR-064). The detection does not depend on it being followed.

Why only a write closes an intent

The first version counted any tool call as acting. The routing eval showed why that fails: Stage 2 searched and then asked in prose, twice, so each search closed the intent and nothing was on record by the scored turn. Structurally, "searched, then showed results" and "searched, then asked about them" are identical, so reads cannot close an intent.

The cost is on the other side: a conversation that has only read keeps its intent open. With the two-turn rule above, that costs a clarification or a re-prompt only from its third non-writing turn, which errs toward acting over asking again — the direction ADR-038's contract prefers over looping.

A deleted test

an_unanswered_clarification_is_not_treated_as_already_clarified was removed. It pinned two things:

  • A clarification still awaiting its answer is not a prior one. That state cannot occur any more: run_turn writes the PriorTurn record only after a turn ends, and the guard reads it only inside the next turn, whose user message is the answer.
  • One clarification must not disable the guard for the rest of the chat. Still pinned, by the_clarification_contract_re_arms_on_a_new_intent (clarified → armed → acted → re-armed).

Verification

  • Unit tests: the erasure case, prose counting (one non-writing turn does not count, two do — threshold pinned both ways), outcome derivation (read-only → Replied, failed write → Replied), the re-prompt fires / does not fire after a tool call / does not fire after a single earlier reply / fires once, two search-then-prose turns count, a linked read-only answer does not disarm the duplicate guard, and the daemon round-trip. Each new test was checked to fail with its fix reverted.

  • bun run test:changed passes.

  • Routing eval, targeted to the two scenarios this rule can reach (the only ones with prior turns in their chat), 5 reps, E4B, isolated daemon, no other model loaded:

    Scenario main this branch
    clarification-then-fallthrough 0/3 5/5
    instance-not-schema-invoice (control) — 5/5

    Re-run on the final two-turn rule: again 5/5 and 5/5. The re-prompt fired on all 5 scored turns in both runs: each pass came through the new path, not a lucky first reply. The run reused a database where the model's search finds two plausible trackers, which is what produced the search-then-ask turns that failed before the write-only rule.

The full routing suite was not re-run. Its other scenarios start in a fresh chat, where no prior turn exists for the guard or re-prompt to read; the only change they see is the route_clarify description. Rewording that fixture's scenarios into the developer-workflow domain is #3189, which is sequenced after this merges.

After merge

Update ADR-038's "What the agent loop does today" clarification-contract bullet: the contract is enforced from the persisted turn outcome; only a successful write closes an intent; the intent is clarified by a composed clarification or two non-writing turns.

🤖 Generated with Claude Code

@malibio

malibio commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #3196

Review Type: Initial Review

Requirements Check (#2905)

  • ✅ A Stage-2 prose clarification is counted. Any turn without a successful write is recorded as Replied, and answered_clarifications counts it. Pinned by a_prose_reply_counts_as_the_intents_clarification.
  • ✅ A prose clarification no longer erases an earlier route_clarify. The intent boundary is now the last Acted turn, not a text match. Pinned by a_prose_reply_does_not_erase_a_composed_clarification.
  • ✅ Detection is structural. CLARIFICATION_OPENER is now used only to format the question text. The outcome is derived from clarify, pending_deletions and whether a write succeeded.
  • ✅ Tool-selection guidance, plus detection that holds without it. The route_clarify description is updated. The count and the re-prompt do not depend on the model following that description.
  • ✅ / ⚠️ Eval and erasure test. The erasure test exists. The eval result (clarification-then-fallthrough 5/5, targeted run) comes from the PR body and was not re-run by the reviewer.
  • ⚠️ test:all. test:changed passes. The full suite runs in the merge gate, so this item stays open until merge.

Code Review Findings

🔴 Critical: an ordinary read-only answer can switch off the duplicate-entity guard

📁 packages/agent/src/local_agent/agent_loop.rs:747-768 (mentioned_entity_duplicated_by), fed from :2070

  • What changed. The guard is switched off for an entity when any text in answered_clarifications contains that entity's id. On main that list held only composed clarifications. It now also holds the response of every Replied turn in the intent, including read-only answers, and those routinely contain grounded nodespace://<id> links.
  • Failure scenario:
    1. User: "Do I have Northwind Trading?"
    2. Stage 2 searches and replies with nodespace://nw-1. The turn is Replied and stays in the intent.
    3. User: "Add Northwind Trading to customers." The model calls create_node.
    4. The id is found in the earlier answer, so the guard is off and a duplicate is created with no question asked.
  • Recommendation: feed the guard only turns that are actually Clarified. Add a test: a Replied turn whose text contains nw-1, then create_node for Northwind, must still be refused.
  • Principle: the one-clarification rule and the duplicate guard now share one input but need different things from it. Widening it for one silently widened the other.

🟡 Important: in read-only chats the re-prompt fires with a false statement

📁 packages/agent/src/local_agent/agent_loop.rs:132-134, :2615-2640

  • What triggers it. "hi" → "Hello!" (Replied), then "what can you do?" The correct answer is prose, but the re-prompt fires first. It claims "the user has already answered a clarifying question" and pushes the model toward a tool call.
  • Costs:
    • A wasted generation.
    • A risk of a spurious tool call. When Stage 1 fails open, the full surface includes writes.
    • The discarded prose may already have streamed to the client.
  • Recommendation: fire the re-prompt only when the intent window contains a Clarified turn, or reword it so it states only what is known.
  • Principle: a guard should fire on the condition it is meant to detect.

🟡 Important: any earlier read-only turn turns off Stage-1 clarification (design trade-off)

📁 packages/agent/src/local_agent/agent_loop.rs:1405-1413, :2131, :3817

  • Scenario: "hi" → "Hello!", then an ambiguous request. Its clarification is suppressed until the chat writes something.
  • Recommendation: decide this together with the re-prompt finding, for example count Replied turns only when the window already holds a Clarified or Replied turn. At minimum, record the trade-off in the planned ADR-038 update.

🟡 Important: the persisted enum's doc comments describe the replaced rule

📁 packages/core/src/models/ai_chat_node.rs:229-250, packages/desktop-app/src/lib/types/ai-chat-node.ts:121-124

  • Problem. They still describe Acted as "at least one tool call" and Replied as "without calling a tool", which is the rule this PR replaced.
  • Recommendation: align them with AgentTurnResult::outcome():
    • Acted: a write succeeded, or a delete confirmation was issued.
    • Replied: anything else.

🟢 Suggestion: nothing pins "no re-prompt after a tool call"

📁 packages/agent/src/local_agent/agent_loop.rs:2624

  • The gap. Deleting the !any_real_tool_calls condition would not fail any test.
  • Add a test: a clarification on record, then Stage 2 runs search_nodes followed by prose. Assert there is no re-prompt message and exactly two Stage-2 generations.

🟢 Verified correct

  • Deleted test. Its justification holds: PriorTurn is recorded only after a turn ends, the daemon rebuilds the session each turn, and history must end in a user message. The re-arm property is still pinned by the_clarification_contract_re_arms_on_a_new_intent.
  • Guard order. The outcome is computed after confirm_held_deletions and duplicate_entity_backstop.
  • Failed turns persist outcome: None and are skipped when history is seeded.
  • Wire names match across core, nodespace-types and the TypeScript types.
  • The re-prompt is one-shot and bounded by the iteration cap.
  • Project rules. No new #NNNN references, no lint suppression, no #[allow(dead_code)], no backward-compat code.

🟢 Nits

  • agent_loop.rs:1284-1287: the Stage1Outcome::clarification doc still mentions "session_already_clarified's scan", which no longer exists.
  • agent_types.rs:599-613: outcome() calls into local_agent::tools::is_write_tool from the plain-types module. Optional.

Recommendation: REQUEST CHANGES

  • The core design is sound: structural outcomes, a write-only intent boundary, and a one-shot re-prompt.
  • The blocker is the duplicate-guard regression.
  • The re-prompt's trigger should be narrowed, or its wording made accurate.
  • The stale doc comments are a quick fix.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-review verdicts). Full findings in the review comment above.

@malibio

malibio commented Sep 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed

Commits bd9dd387 and d163948b.

✅ Addressed

  • 🔴 A read-only answer disarmed the duplicate-entity guard. Confirmed and fixed. The guard now reads only Clarified turns in the intent (composed_clarifications). New test a_read_only_answer_linking_the_entity_does_not_disarm covers the reviewer's Northwind scenario, and fails when the old list is passed.
  • 🟡 The re-prompt fired in read-only chats with a false statement, and 🟡 Stage-1 clarification was lost after any read-only turn. Both are fixed with one rule, decided with the author: the intent is already clarified when it holds a composed clarification or at least two turns that did not write.
    • "hi → Hello!" no longer counts, so the first genuine clarification survives and a plain reply isn't re-prompted.
    • The eval's shape, two search-then-ask turns, still counts.
    • The reviewer's alternative (composed clarifications only) was not taken. The failing eval chat had no composed clarification (both earlier questions were search-then-prose), so it would have undone the fix.
    • answered_clarifications had no remaining non-test caller and was removed.
    • Tests pin the threshold both ways (≥1 and ≥3 each fail a test). one_earlier_reply_does_not_put_a_plain_reply_back is new.
  • 🟡 Stale doc comments on the persisted enum (core and TS) and on Stage1Outcome::clarification now match the write-only rule.
  • 🟢 No test pinned "no re-prompt after a tool call". a_reply_after_a_tool_call_is_not_put_back was added and fails without the condition.

⏭️ Skipped

  • 🟢 Moving outcome() out of agent_types. It's optional, and the dependency is a single registry lookup (is_write_tool). I'd revisit it if agent_types gains more reach into local_agent.

Verification

  • nodespace-agent: 729 passed.
  • Targeted routing eval on the final rule, 5 reps, E4B, isolated daemon, no other model loaded:
    • clarification-then-fallthrough: 5/5
    • instance-not-schema-invoice: 5/5
    • The re-prompt fired on all 5 scored turns.

Re-Review Decision

RE-REVIEW NEEDED. This round fixed a 🔴 finding and changed the counting rule the contract uses.

@malibio

malibio commented Sep 28, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — Re-Review (bd9dd38, d163948)

Previous review: 7 recommendations.

  • Addressed: 6.
  • Skipped with a reason: 1 (moving outcome() out of agent_types, which was optional).
  • New: 1 🟡, 1 🟢.

Rejecting the composed-only alternative is sound. The eval's failing chat had two search-then-prose turns and nothing recorded Clarified. Under composed-only, the scored turn would not be counted as already clarified. That brings back the #2905 failure. Counting turns that did not write is the only structural signal that covers this shape, and a threshold of 2 is a defensible middle ground.

Requirements (#2905):

  • ✅ A prose clarification is counted: as the second non-writing turn, or straight after a composed clarification.
  • ✅ A prose reply does not erase an earlier composed clarification.
  • ✅ Detection is structural.
  • ✅ Guidance, plus detection that holds without it.
  • ⚠️ Eval: 5/5 is the author's result; not re-run by the reviewer.
  • ✅ cargo test -p nodespace-agent --lib: 729 passed.

🟡 A chat that only reads keeps one intent open indefinitely

📁 packages/agent/src/local_agent/agent_loop.rs:1402-1411, :2645-2665, :129-133

  • Failure scenario: "Do I have Northwind?" (search) → "What about Contoso?" (search) → "thanks". The third turn's tool-free reply is re-prompted with "The user has already answered a clarifying question…".
  • Same chat, Stage-1 side: from its third turn, an ambiguous request loses its clarification until the chat writes something.
  • Status: the previous 🟡 has moved from turn 2 to turn 3, not gone.
  • Recommendation:
    • (a) Reword the nudge so it asserts only what is known.
    • (b) Document this cost in the session_already_clarified doc and the ADR-038 update.
    • (c) Optionally bound the window.
  • Not a blocker: the eval depends on the nudge firing on this shape.

🟢 Leftovers from deleting answered_clarifications

  • agent_loop.rs:139: an intra-doc link still points at the deleted function.
  • agent_loop.rs:750, 766: the parameter of mentioned_entity_duplicated_by is still named answered_clarifications, while its callers pass composed_clarifications.
  • agent_loop.rs:2643-2644: the nudge comment doesn't mention the two-non-writing-turns branch.

🟢 Verified correct

  • All three callers (Stage-1 suppression, Stage-2 route_clarify withholding, the nudge) use the same rule.
  • The duplicate guard's confirmation path still disarms correctly.
  • The threshold is pinned both ways.
  • The two retained re-prompt tests still mean what they say.
  • The doc comments on the enum and the TS mirror are accurate.
  • Project rules hold.

Recommendation: APPROVE (with comments)

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review (re-review): APPROVE with comments (posted as a comment — GitHub blocks self-approval). Findings in the comment above.

@malibio

malibio commented Sep 28, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review addressed (8be973b)

  • ✅ 🟡 Read-only-chat cost is now documented in session_already_clarified. It will also go in the ADR-038 update after merge. A chat that only reads never closes its intent, so from its third non-writing turn a tool-free reply is re-prompted once, and an ambiguous request falls through to retrieval.
  • ⏭️ Rewording ALREADY_CLARIFIED_NUDGE: skipped. The 5/5 eval was measured on this wording, and changing it needs another eval run. Worth revisiting alongside Re-theme the routing eval's scenarios into NodeSpace's developer-workflow domain #3189's eval work.
  • ✅ 🟢 Stale names. Fixed the dangling doc link to the deleted answered_clarifications, renamed the guard parameter to composed_clarifications, and made the nudge comment name both halves of the rule.

nodespace-agent: 729 passed.

Re-Review Decision

NO RE-REVIEW NEEDED. Doc comments and a parameter rename only; no logic changed.

malibio and others added 8 commits September 28, 2026 10:16
…t contract

## Completed in This Session
- [x] Design chosen with user: persisted turn outcome (acted/clarified/replied) + one-shot nudge + route_clarify guidance
- [x] AiChatTurnOutcome on core + wire AiChatMessage (and TS mirror); AgentSession.prior_turns / PriorTurn
- [x] AgentTurnResult::outcome() derives the outcome structurally; run_turn records it after the guards
- [x] answered_clarifications reads prior_turns (intent boundary = last Acted turn); opener string-match removed
- [x] Stage-2 nudge: zero-tool-call prose after an answered clarification is put back once (ALREADY_CLARIFIED_NUDGE)
- [x] Daemon persists outcome (AssistantRecord struct replaces append_assistant_message positional args) and seeds prior_turns_from_history
- [x] route_clarify Stage-2 description: "never ask one in a plain reply"; prompt golden regenerated
- [x] Tests: erasure case, prose counting, outcome derivation, nudge fires/doesn't/once, daemon round-trip; mutation-checked
- [x] bun run test:changed passes (rebased onto origin/main)

## Remaining Work
- [ ] Routing eval: clarification-then-fallthrough must pass (was 0/3). Run was stopped mid rep 1 before reaching it.
      Setup: cargo build --release -p nodespace-daemon -p nodespace-cli; start isolated daemon per
      nodespace-docs/development/agent-eval.md (/tmp/nodespaced-test, RUST_LOG=debug); model load gemma-4-e4b-q4km;
      NS_BIN=target/release/nodespace ... bun run eval:routing issue2905 <out.json> --runs 3
- [ ] Partial rep 1 showed indirect-schema-{money-owed,freelance,expenses} and instance-not-schema-invoice failing —
      single-turn, untouched by the guard/nudge; compare against a baseline (main) run before attributing
- [ ] bun run quality:fix + commit, push, gh pr create --head issue-2905-prose-clarification-guard
- [ ] /pragmatic-code-review then /address-review
- [ ] After merge: update ADR-038 "What the agent loop does today" clarification-contract bullet (enforced from
      persisted turn outcome; a prose reply counts and does not close the intent) — commit straight to nodespace-docs main

## Current State
- Files modified: core ai_chat_node.rs/mod.rs, nodespace-types ai_chat.rs, desktop-app ai-chat-node.ts,
  agent agent_types.rs/agent_loop.rs/tools.rs + stage2 golden, daemon local_agent_service.rs, AiChatMessage test literals
- Tests status: Passing (test:changed)
- Known issues: none known; eval result pending
- Dependencies: none

## Context for Next Session
The guard no longer reads reply text: each assistant turn persists how it ended, and a turn that did not call a
tool keeps the intent open and counts as its clarification. Counting alone cannot fix the eval's scored turn, so
Stage 2 is re-prompted once when it replies in prose after an answered clarification. Next: finish the eval run.

## Acceptance Criteria Status
From issue #2905:
- [x] A clarification asked in Stage-2 prose is counted against the at-most-one-per-intent contract
- [x] A Stage-2 prose clarification does not erase a prior route_clarify from the current intent window
- [x] Detection relies only on module-written text or structural turn properties
- [x] Guidance directs Stage 2 to clarify via route_clarify; detection holds when it is ignored
- [ ] clarification-then-fallthrough passes in the routing eval (erasure test is pinned: done)
- [ ] Tests pass / quality:fix (test:changed passes; quality:fix not yet run)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…ct (refs #2905)

A turn that searched and then asked in prose was recorded as Acted, so each
search closed the intent and no clarification was ever on record. The routing
eval hit exactly this: two search-then-ask turns, then a third prose question
the guard could not see. Reading and then replying looks the same whether the
reply showed results or asked about them, so only a successful write counts
as acting; a read-only turn is Replied and stays on record.

The re-prompt stays keyed on a turn with no tool call at all, so a search that
answered the user is never pushed to call another tool.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… (refs #2905)

- The duplicate-entity guard disarms for a record a clarification asked
  about. It read answered_clarifications, which now holds every turn that did
  not act, so a read-only answer linking the record disarmed it. It now reads
  only Clarified turns in the intent. Test: a linked Replied answer followed
  by create_node is still refused (fails when the old list is passed).
- Pin that a reply after a tool call is never re-prompted (fails without the
  no-tool-call condition).
- Align the persisted outcome's doc comments (core enum, TS mirror) and the
  Stage1Outcome clarification doc with the write-only rule.

Skipped: moving outcome() out of agent_types — optional; the dependency is a
single registry lookup.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…g turns (refs #2905)

Counting one turn that did not write as the intent's clarification made any
chat that opened with conversation or a lookup lose its first genuine
clarification, and re-prompted its next plain reply with a false 'the user
already answered' statement. One such turn is as likely an answer as a
question; two in one intent is the loop the contract stops.

session_already_clarified: a composed clarification in the intent, or at
least two turns that did not write. The re-prompt uses the same rule. The
eval's shape (two search-then-ask turns, then a prose reply) still triggers it.
answered_clarifications had no remaining non-test caller and is removed.

Tests: threshold pinned both ways (>=1 and >=3 each fail a test); 'hi ->
Hello!' then a plain reply is not re-prompted.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…es (refs #2905)

- Document in session_already_clarified that a chat which only reads never
  closes its intent: from its third non-writing turn a tool-free reply is
  re-prompted once and an ambiguous request falls through to retrieval.
- Point the CLARIFICATION_OPENER and nudge docs at session_already_clarified
  (the deleted answered_clarifications was still linked), rename the duplicate
  guard's parameter to composed_clarifications, and name both halves of the
  rule in the nudge comment.

Skipped: rewording ALREADY_CLARIFIED_NUDGE. The 5/5 eval was measured on this
wording; changing it needs another eval run.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@malibio
malibio force-pushed the issue-2905-prose-clarification-guard branch from 8be973b to 1c76ddb Compare September 28, 2026 08:26
@malibio
malibio merged commit 5ee57a0 into main Sep 28, 2026
@malibio
malibio deleted the issue-2905-prose-clarification-guard branch September 28, 2026 08:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A Stage-2 prose clarification escapes the at-most-one contract, and erases the prior clarification from the intent window

1 participant