Skip to content

Persist completed graph writes so the next turn can see them (closes #1780) - #1786

Merged
malibio merged 3 commits into
mainfrom
issue-1780-cross-turn-duplicate
Jul 28, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-1780-cross-turn-duplicate

Conversation

@malibio

@malibio malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Closes #1780

closes #1780)

The agent re-executed the previous turn's create instruction, writing a
second identical node. The per-turn `seen_calls` guard cannot cover this,
and neither can a wider-scoped version of it: the session is destroyed at
the end of every turn.

Root cause. `run_ai_chat_turn` builds a brand-new ephemeral session per
turn (local_agent_service.rs:341-435), seeded from the ai-chat node's
persisted messages. `AiChatMessage` had only role/content/timestamp/
reasoning, so the assistant tool-call message and every tool result were
never persisted; `load_node_history` additionally dropped any non
user/assistant role and rebuilt messages via `ChatMessage::text`, which
hard-codes `tool_calls: vec![]`.

Turn N+1 therefore saw the user's original instruction alongside an
unverifiable prose claim ("I have added X") and no proof the write ever
happened. Weighing its own narration against an explicit instruction still
in view, the model could satisfy that instruction twice. Being a soft cue
rather than a hard error, it reproduced in only 1 of 3 matrix runs.

Fix. Record successful, state-changing tool calls on the assistant message
(`completed_writes`: tool, node id, short label) and replay them into the
rebuilt history as a system-role note. Failed calls are excluded — a write
that errored did not happen, and suppressing the retry would lose the work.
Reads are excluded: repeating a search is wasteful, not a duplicate.

The evidence is deliberately system-role, not tool-role. A tool-role
message is rendered with a `tool_call_id` and must be preceded by the
assistant tool-call turn it answers; those calls are not persisted, so a
tool-role note here would be an orphan tool result — the shape the
summarization back-off in agent_loop.rs exists to avoid, and which can
abort a turn with llama.cpp `ffi error -3`.

Regression tests cover the cross-turn case specifically, which the existing
per-turn guard tests do not. The primary test was verified to fail on the
defect: with the replay removed it fails on the missing evidence.

Eval attribution (acceptance criterion 4): no change needed. Attribution is
already per-turn at every layer — aichat.ts slices the daemon log from a
byte offset captured before the send, and runner.ts:337 scores with the
scenario's own turn only, prior context turns excluded. The issue's premise
that one stray call was attributed to two scenarios does not hold; 8d
genuinely made two create_node calls in its own turn.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HkymyKtLHm5NcNbf2CjrT9
@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review Type: Initial Review

PR #1786 — issue-1780-cross-turn-duplicate — persist completed graph writes so the next turn cannot re-execute them.

Overall: this is a net-positive change with a correctly diagnosed root cause and a well-argued design. The root-cause analysis on #1780 is genuinely good work — it is code-verified rather than inferred, and it correctly kills the issue's own proposed fix (a session-scoped seen_calls) by showing there is no cross-turn session to hold it. The persistence-shaped fix is the right layer to attack.

My reservations are about sufficiency and completeness, not about direction. Two substantive defects: the WRITE_TOOLS list silently mis-handles the two write tools that don't return an id, and the summary extraction reads argument keys that half the write tools do not have. Neither is fatal; both mean the evidence note degrades to a bare tool name for a meaningful fraction of writes, which is precisely the case where the note is weakest.


Requirements Check

Against the four acceptance criteria on #1780:

# Criterion Verdict
1 Root-cause why the next turn re-executes the previous turn's create instruction (with a captured prompt dump, not inference) Met, with a caveat. The mechanism is established from code with exact line references (run_ai_chat_turn rebuilding the session per turn; AiChatMessage having no tool-call field; load_node_history returning None for non-user/assistant; ChatMessage::text hard-coding tool_calls: vec![]). I independently verified each of these. Caveat: the criterion explicitly asked for a captured NODESPACE_PROMPT_DUMP, and the issue is emphatic about why ("inferring from behavior alone produced a wrong diagnosis twice on #1775/#1760"). No dump is presented. The code-path evidence is strong enough that I don't think the diagnosis is wrong — the data-flow is deterministic and I traced it myself — but the final step (model re-executes because evidence is missing) remains a behavioral inference, and that is the step the dump was meant to nail down.
2 A completed create instruction is not re-executed on a subsequent turn Partially met. The evidence is now durably persisted and replayed, which removes the cause (a history that provably lacked proof of the write). But the mechanism converting that evidence into non-repetition is the model choosing to obey a prompt note. See finding 🟡-1 — this is a strong mitigation, not a guarantee, and the PR description ("cannot re-execute them") overstates it.
3 A regression test covers the cross-turn case specifically Met. completed_write_is_visible_in_the_next_turns_history exercises the real round-trip (persist → reload via load_node_history) rather than a unit-level stub, asserts ordering, and asserts the negative (no Role::Tool). The author verified it fails with the replay removed. Good test. Gaps noted in 🟡-4.
4 State whether the eval should attribute tool calls per turn Met. Answered "no change needed", with a self-correction posted when the first answer was wrong. I verified runner.ts:337 scores [scored] only. Correcting your own prior analysis in-thread rather than quietly is the right call.

Code Review Findings

🔴 Critical

None. No security exposure, no data-loss path, no architectural regression.


🟡 Improvements

🟡-1 — 📁 packages/daemon/src/services/local_agent_service.rs:1385-1416 — prompt-based guidance is a mitigation, not a guard; the commit message frames it as a guarantee.

You asked me to be direct here, so: the fix is correct and it addresses the actual root cause, but it is not sufficient on its own, and the commit subject line — "so the next turn cannot re-execute them" — is not true. What the change does is restore evidence that was structurally absent. That is a real and necessary repair: previously the model was being asked to make a correct decision from a history that genuinely did not contain the information needed to make it. Now it can. But the conversion from "evidence present" to "not repeated" runs entirely through the model's compliance with do not repeat them, and the same reasoning the analysis applies to the assistant's prose ("a model weighing its own narration against an explicit instruction still in view may re-execute") applies with reduced but nonzero force to a system note — it is stronger evidence, not binding evidence. The original failure reproduced 1-in-3; this change plausibly moves that to something much lower, but nothing here makes it zero.

The principle is defence in depth: a correctness property that matters (not writing the user's data twice) should not rest solely on a probabilistic component. There is a stronger complementary guard available now, and the PR is one small step from it — the persisted completed_writes is exactly the cross-turn state the issue said didn't exist. A programmatic check in the tool-execution path that compares an incoming write against the persisted (tool, canonical_args) set from prior turns and, on a hit, returns a tool result saying "this exact write was already completed as <node_id>" would make the duplicate a hard, deterministic no-op. Note the issue's own caution — a user genuinely re-asking for the same node is rare but real — which argues for returning an informative result the model can reason about rather than a silent block. That is more work than belongs in this PR, and I would not block on it. But it should be a follow-up issue, and the commit message should not claim the property it doesn't yet have. Recommend: soften the claim to what the change actually establishes, and file the programmatic-dedup follow-up.

🟡-2 — 📁 packages/daemon/src/services/local_agent_service.rs:1333-1342 — WRITE_TOOLS is complete, but two entries can never produce a node_id and one can never produce a summary.

I cross-checked every one of the 14 registered tools in Tool::ALL (packages/agent/src/local_agent/tools.rs:830-845). The classification is correct: the 8 listed are exactly the state-changing tools, and the 6 omitted (search_nodes, resolve_query, search_semantic, get_node, get_related_nodes, search_skills) are all reads. No write is missing and no read is wrongly included. Good.

The problem is what the listed tools actually return:

  • create_relationship (tools.rs:1509-1513) returns {"from_id", "to_id", "type", "created"} — no id, no node_id. Its args are from_id/to_id/relationship_type — no content/title/name. So a completed relationship write records as the bare line - create_relationship, with no indication of which relationship. That is close to useless as evidence: the model cannot match it to the instruction, which is the stated purpose ("so the model can match it against the instruction still in history").
  • create_nodes_from_markdown (tools.rs:1792-1796) passes the MCP handler result straight through; it is a multi-node import and there is no single id. Its arg key is markdown, not content — so again, bare tool name only. This is the highest-stakes duplicate in the set (re-running it duplicates an entire subtree) and it gets the weakest evidence line.
  • create_schema / update_schema (tools.rs:1642, :1665) return the handler's value, which is not a node id. Their arg key is name, so the summary works — the node_id is simply absent, which is fine and correct.

So the extraction "accept either id or node_id" (finding 🟡-3) is fine as far as it goes, but the design assumed a uniform {id, content} shape that only create_node/update_node/update_task_status/delete_node actually have. The fix is small: add markdown to the summary key fallback chain, and give create_relationship a rendering that uses its own fields. Or — cleaner, and I'd prefer it — make the tool-name → evidence-fields mapping explicit rather than a guessed key-probe, so adding a tool forces you to say what its evidence looks like. That mirrors the pattern Tool already establishes in tools.rs, where the doc comment says outright: "the lists can no longer drift — they are computed from here." This new list sits in a different crate and can drift from it. Consider deriving WRITE_TOOLS from a method on Tool (e.g. Tool::is_write()) so the exhaustive match forces every future tool to declare its side-effect class.

🟡-3 — 📁 packages/daemon/src/services/local_agent_service.rs:1359-1364 — the recorded node_id is a nodespace:// URI, not a bare id, and the test asserts otherwise.

create_node returns json!({ "id": node_uri(&output.node_id) }) (tools.rs:1414), and node_uri prefixes nodespace://. Same for update_node (:1481), update_task_status (:1718), delete_node (:1747). So in production the evidence line reads -> nodespace://f1f25564, not -> f1f25564.

This is the right value to store — the system prompt instructs the model to use nodespace://uuid URIs when referencing nodes, so a URI is exactly what matches what the model sees elsewhere, and it round-trips through strip_node_uri if the model ever feeds it back as an argument. No change needed to the behavior.

But completed_write_is_visible_in_the_next_turns_history builds its fixture as json!({"id": "f1f25564"}) — a bare id that the real create_node never returns. The assertion evidence.content.contains("f1f25564") passes either way (substring), so the test doesn't catch the discrepancy, but it does mean the test's fixture is not the shape the code under test receives in production. Principle: a test whose fixture diverges from the real contract can pass while the integration is broken. Use "nodespace://f1f25564" in the fixture and assert on the full URI — it costs nothing and pins the contract. (update_task_status's real result key is id, not node_id, so the node_id_is_extracted_from_either_result_shape fixture is also synthetic — the node_id branch is currently reachable only via get_node-shaped results, i.e. no registered write tool actually exercises it. Worth either finding the real producer or dropping the branch. Dead defensive branches are a maintenance cost with no payer — and note CLAUDE.md's stance on speculative code.)

🟡-4 — 📁 packages/daemon/src/services/local_agent_service.rs:1418-1455 — unbounded growth is real but modest; the interaction with maybe_summarize_history is the part that needs a look.

Each write-performing turn adds one system message of roughly tool + 120-char summary + URI ≈ 40-60 tokens, replayed into every subsequent prompt. Direct budget impact is small — 20 write turns is on the order of 1K tokens against a 32K window. I would not call this a blocker.

The subtler issue is summarization. maybe_summarize_history estimates the budget by concatenating msg.content across session.messages (agent_loop.rs:1155-1159), so these notes are counted — good. But when it fires, it drains everything before split_point into a single summary message, and the evidence notes go in with it. The summarization prompt is generic; there is no guarantee the LLM-generated summary preserves "node X was already created" with the fidelity that made the note work. So in a long conversation — exactly the case where a cross-turn duplicate is most likely — the fix can silently degrade. The tool-role back-off at :1200 protects tool pairing specifically; nothing protects write evidence.

I checked the safety question you raised and it's fine: run_turn prepends a system message at agent_loop.rs:382 and extends with session.messages, so a second Role::System mid-history is a pre-existing, already-shipped pattern — maybe_summarize_history inserts its summary at session.messages[0] as Role::System (:1290), landing in exactly the same position. chat_message_to_oai_value (nlp-engine/src/chat/mod.rs:915-920) renders any non-tool, non-tool-call message as plain {role, content}, so nothing special happens at that layer. The orphan-tool-result reasoning also checks out precisely: the Role::Tool branch (:876-887) emits tool_call_id, and the :1200 back-off exists for exactly the failure the comment cites. The Role::System choice is correct and well-justified — this is the strongest reasoning in the PR. If the Gemma template did merge-or-reject non-leading system messages, the existing summarization path would already be broken, so this PR isn't introducing that risk. Worth a follow-up to make evidence notes summarization-resilient (e.g. carry them forward verbatim rather than letting them be drained), but not a blocker here.

🟡-5 — 📁 packages/nodespace-types/src/ai_chat.rs:6-18 — a hand-mirrored type with a comment admitting it's a mirror.

AiChatCompletedWrite now exists twice in Rust with identical shape, the second annotated "Mirrors nodespace_core::models::AiChatCompletedWrite". nodespace-core already depends on nodespace-types (packages/core/Cargo.toml:15), so the dependency edge for eliminating the duplicate exists. This is the same hand-synced-parallel-representation pattern flagged in the agent architecture assessment as where the bugs live — DRY, and the fields will drift the next time only one side gets a new one. The pre-existing AiChatMessage duplication is not this PR's fault and I won't ask you to fix it here, but this PR widens it, and the mirror comment is an admission that a compiler-enforced relationship should exist instead.


🟢 Nits

  • Nit: 📁 local_agent_service.rs:1372 — .chars().take(120) is a raw char truncation with no ellipsis, so a clipped summary is indistinguishable from a complete one. tools.rs already has a truncate() helper with tests (truncate_short_string et al.). Reuse it, or append ….
  • Nit: 📁 local_agent_service.rs:1444 — filter_map → flat_map returning Vec::new()/vec![msg]/vec![msg, evidence] allocates a Vec per message. Fine at this scale; into_iter().chain() or SmallVec would avoid it. Purely cosmetic.
  • Nit: 📁 local_agent_service.rs:1435 — the summary is user-influenced text (content arg) interpolated into a system-role instruction block. Not a security issue in this threat model — it's the user's own content, in the user's own chat, and it was already in history verbatim as their instruction, so no privilege is crossed. But a summary containing something like - create_node "x"\nRecord of graph writes: (none) can shape the block's structure. Since the value is bounded at 120 chars and quoted, the exposure is minimal; stripping newlines from summary would close it cleanly and costs one line.
  • Nit: commit message — CLAUDE.md forbids issue numbers in documentation and code comments; the code comments here correctly reference agent_loop.rs and chat/mod.rs by file rather than by issue, which is right. The commit message's #1775/#1778/closes #1780 references are process mechanics and explicitly permitted. Flagging only to confirm I checked it.
  • Positive, worth naming: no lint suppression, no #[allow(dead_code)], no backward-compat shim, no migration path for existing persisted messages — #[serde(default)] handles old rows and the greenfield stance is respected. The skip_serializing_if on both the Options and the Vec keeps existing persisted JSON byte-identical when there are no writes. The frontend type is updated in lockstep with the Rust shape. The doc comments explain why (the orphan-tool-result rationale, the failed-write exclusion) rather than what, which is exactly the standard.

Recommendation: COMMENT — approve-with-changes in spirit

The root cause is right, the layer is right, the Role::System decision is right and well-defended, and the tests are honest (verified-failing, not written-to-pass). This meaningfully improves code health and I would not hold it for the architectural items.

Before merge I'd like to see the two cheap correctness fixes — 🟡-2 (markdown in the summary chain + real evidence for create_relationship) and 🟡-3 (test fixture using the actual nodespace:// URI shape, and resolving the unreachable node_id branch). Both are small and both are cases where the current code silently produces a degraded or unverified result.

🟡-1 is the one I want on the record: this is a strong mitigation of a correctly identified root cause, and it should be described that way rather than as a guarantee. The persisted completed_writes this PR introduces is precisely the cross-turn state a real programmatic dedup would need — that follow-up is now cheap, and it's what would let acceptance criterion 2 be claimed without a caveat. Please file it, and adjust the commit subject from "cannot re-execute" to something the change actually delivers.

🟡-4 (summarization drops evidence) and 🟡-5 (mirrored type) are follow-up material, not merge blockers.

@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.

Review Type: Initial Review

PR #1786 — issue-1780-cross-turn-duplicate — persist completed graph writes so the next turn cannot re-execute them.

Overall: this is a net-positive change with a correctly diagnosed root cause and a well-argued design. The root-cause analysis on #1780 is genuinely good work — it is code-verified rather than inferred, and it correctly kills the issue's own proposed fix (a session-scoped seen_calls) by showing there is no cross-turn session to hold it. The persistence-shaped fix is the right layer to attack.

My reservations are about sufficiency and completeness, not about direction. Two substantive defects: the WRITE_TOOLS list silently mis-handles the two write tools that don't return an id, and the summary extraction reads argument keys that half the write tools do not have. Neither is fatal; both mean the evidence note degrades to a bare tool name for a meaningful fraction of writes, which is precisely the case where the note is weakest.


Requirements Check

Against the four acceptance criteria on #1780:

# Criterion Verdict
1 Root-cause why the next turn re-executes the previous turn's create instruction (with a captured prompt dump, not inference) Met, with a caveat. The mechanism is established from code with exact line references (run_ai_chat_turn rebuilding the session per turn; AiChatMessage having no tool-call field; load_node_history returning None for non-user/assistant; ChatMessage::text hard-coding tool_calls: vec![]). I independently verified each of these. Caveat: the criterion explicitly asked for a captured NODESPACE_PROMPT_DUMP, and the issue is emphatic about why ("inferring from behavior alone produced a wrong diagnosis twice on #1775/#1760"). No dump is presented. The code-path evidence is strong enough that I don't think the diagnosis is wrong — the data-flow is deterministic and I traced it myself — but the final step (model re-executes because evidence is missing) remains a behavioral inference, and that is the step the dump was meant to nail down.
2 A completed create instruction is not re-executed on a subsequent turn Partially met. The evidence is now durably persisted and replayed, which removes the cause (a history that provably lacked proof of the write). But the mechanism converting that evidence into non-repetition is the model choosing to obey a prompt note. See finding 🟡-1 — this is a strong mitigation, not a guarantee, and the PR description ("cannot re-execute them") overstates it.
3 A regression test covers the cross-turn case specifically Met. completed_write_is_visible_in_the_next_turns_history exercises the real round-trip (persist → reload via load_node_history) rather than a unit-level stub, asserts ordering, and asserts the negative (no Role::Tool). The author verified it fails with the replay removed. Good test. Gaps noted in 🟡-4.
4 State whether the eval should attribute tool calls per turn Met. Answered "no change needed", with a self-correction posted when the first answer was wrong. I verified runner.ts:337 scores [scored] only. Correcting your own prior analysis in-thread rather than quietly is the right call.

Code Review Findings

🔴 Critical

None. No security exposure, no data-loss path, no architectural regression.


🟡 Improvements

🟡-1 — 📁 packages/daemon/src/services/local_agent_service.rs:1385-1416 — prompt-based guidance is a mitigation, not a guard; the commit message frames it as a guarantee.

You asked me to be direct here, so: the fix is correct and it addresses the actual root cause, but it is not sufficient on its own, and the commit subject line — "so the next turn cannot re-execute them" — is not true. What the change does is restore evidence that was structurally absent. That is a real and necessary repair: previously the model was being asked to make a correct decision from a history that genuinely did not contain the information needed to make it. Now it can. But the conversion from "evidence present" to "not repeated" runs entirely through the model's compliance with do not repeat them, and the same reasoning the analysis applies to the assistant's prose ("a model weighing its own narration against an explicit instruction still in view may re-execute") applies with reduced but nonzero force to a system note — it is stronger evidence, not binding evidence. The original failure reproduced 1-in-3; this change plausibly moves that to something much lower, but nothing here makes it zero.

The principle is defence in depth: a correctness property that matters (not writing the user's data twice) should not rest solely on a probabilistic component. There is a stronger complementary guard available now, and the PR is one small step from it — the persisted completed_writes is exactly the cross-turn state the issue said didn't exist. A programmatic check in the tool-execution path that compares an incoming write against the persisted (tool, canonical_args) set from prior turns and, on a hit, returns a tool result saying "this exact write was already completed as <node_id>" would make the duplicate a hard, deterministic no-op. Note the issue's own caution — a user genuinely re-asking for the same node is rare but real — which argues for returning an informative result the model can reason about rather than a silent block. That is more work than belongs in this PR, and I would not block on it. But it should be a follow-up issue, and the commit message should not claim the property it doesn't yet have. Recommend: soften the claim to what the change actually establishes, and file the programmatic-dedup follow-up.

🟡-2 — 📁 packages/daemon/src/services/local_agent_service.rs:1333-1342 — WRITE_TOOLS is complete, but two entries can never produce a node_id and one can never produce a summary.

I cross-checked every one of the 14 registered tools in Tool::ALL (packages/agent/src/local_agent/tools.rs:830-845). The classification is correct: the 8 listed are exactly the state-changing tools, and the 6 omitted (search_nodes, resolve_query, search_semantic, get_node, get_related_nodes, search_skills) are all reads. No write is missing and no read is wrongly included. Good.

The problem is what the listed tools actually return:

  • create_relationship (tools.rs:1509-1513) returns {"from_id", "to_id", "type", "created"} — no id, no node_id. Its args are from_id/to_id/relationship_type — no content/title/name. So a completed relationship write records as the bare line - create_relationship, with no indication of which relationship. That is close to useless as evidence: the model cannot match it to the instruction, which is the stated purpose ("so the model can match it against the instruction still in history").
  • create_nodes_from_markdown (tools.rs:1792-1796) passes the MCP handler result straight through; it is a multi-node import and there is no single id. Its arg key is markdown, not content — so again, bare tool name only. This is the highest-stakes duplicate in the set (re-running it duplicates an entire subtree) and it gets the weakest evidence line.
  • create_schema / update_schema (tools.rs:1642, :1665) return the handler's value, which is not a node id. Their arg key is name, so the summary works — the node_id is simply absent, which is fine and correct.

So the extraction "accept either id or node_id" (finding 🟡-3) is fine as far as it goes, but the design assumed a uniform {id, content} shape that only create_node/update_node/update_task_status/delete_node actually have. The fix is small: add markdown to the summary key fallback chain, and give create_relationship a rendering that uses its own fields. Or — cleaner, and I'd prefer it — make the tool-name → evidence-fields mapping explicit rather than a guessed key-probe, so adding a tool forces you to say what its evidence looks like. That mirrors the pattern Tool already establishes in tools.rs, where the doc comment says outright: "the lists can no longer drift — they are computed from here." This new list sits in a different crate and can drift from it. Consider deriving WRITE_TOOLS from a method on Tool (e.g. Tool::is_write()) so the exhaustive match forces every future tool to declare its side-effect class.

🟡-3 — 📁 packages/daemon/src/services/local_agent_service.rs:1359-1364 — the recorded node_id is a nodespace:// URI, not a bare id, and the test asserts otherwise.

create_node returns json!({ "id": node_uri(&output.node_id) }) (tools.rs:1414), and node_uri prefixes nodespace://. Same for update_node (:1481), update_task_status (:1718), delete_node (:1747). So in production the evidence line reads -> nodespace://f1f25564, not -> f1f25564.

This is the right value to store — the system prompt instructs the model to use nodespace://uuid URIs when referencing nodes, so a URI is exactly what matches what the model sees elsewhere, and it round-trips through strip_node_uri if the model ever feeds it back as an argument. No change needed to the behavior.

But completed_write_is_visible_in_the_next_turns_history builds its fixture as json!({"id": "f1f25564"}) — a bare id that the real create_node never returns. The assertion evidence.content.contains("f1f25564") passes either way (substring), so the test doesn't catch the discrepancy, but it does mean the test's fixture is not the shape the code under test receives in production. Principle: a test whose fixture diverges from the real contract can pass while the integration is broken. Use "nodespace://f1f25564" in the fixture and assert on the full URI — it costs nothing and pins the contract. (update_task_status's real result key is id, not node_id, so the node_id_is_extracted_from_either_result_shape fixture is also synthetic — the node_id branch is currently reachable only via get_node-shaped results, i.e. no registered write tool actually exercises it. Worth either finding the real producer or dropping the branch. Dead defensive branches are a maintenance cost with no payer — and note CLAUDE.md's stance on speculative code.)

🟡-4 — 📁 packages/daemon/src/services/local_agent_service.rs:1418-1455 — unbounded growth is real but modest; the interaction with maybe_summarize_history is the part that needs a look.

Each write-performing turn adds one system message of roughly tool + 120-char summary + URI ≈ 40-60 tokens, replayed into every subsequent prompt. Direct budget impact is small — 20 write turns is on the order of 1K tokens against a 32K window. I would not call this a blocker.

The subtler issue is summarization. maybe_summarize_history estimates the budget by concatenating msg.content across session.messages (agent_loop.rs:1155-1159), so these notes are counted — good. But when it fires, it drains everything before split_point into a single summary message, and the evidence notes go in with it. The summarization prompt is generic; there is no guarantee the LLM-generated summary preserves "node X was already created" with the fidelity that made the note work. So in a long conversation — exactly the case where a cross-turn duplicate is most likely — the fix can silently degrade. The tool-role back-off at :1200 protects tool pairing specifically; nothing protects write evidence.

I checked the safety question you raised and it's fine: run_turn prepends a system message at agent_loop.rs:382 and extends with session.messages, so a second Role::System mid-history is a pre-existing, already-shipped pattern — maybe_summarize_history inserts its summary at session.messages[0] as Role::System (:1290), landing in exactly the same position. chat_message_to_oai_value (nlp-engine/src/chat/mod.rs:915-920) renders any non-tool, non-tool-call message as plain {role, content}, so nothing special happens at that layer. The orphan-tool-result reasoning also checks out precisely: the Role::Tool branch (:876-887) emits tool_call_id, and the :1200 back-off exists for exactly the failure the comment cites. The Role::System choice is correct and well-justified — this is the strongest reasoning in the PR. If the Gemma template did merge-or-reject non-leading system messages, the existing summarization path would already be broken, so this PR isn't introducing that risk. Worth a follow-up to make evidence notes summarization-resilient (e.g. carry them forward verbatim rather than letting them be drained), but not a blocker here.

🟡-5 — 📁 packages/nodespace-types/src/ai_chat.rs:6-18 — a hand-mirrored type with a comment admitting it's a mirror.

AiChatCompletedWrite now exists twice in Rust with identical shape, the second annotated "Mirrors nodespace_core::models::AiChatCompletedWrite". nodespace-core already depends on nodespace-types (packages/core/Cargo.toml:15), so the dependency edge for eliminating the duplicate exists. This is the same hand-synced-parallel-representation pattern flagged in the agent architecture assessment as where the bugs live — DRY, and the fields will drift the next time only one side gets a new one. The pre-existing AiChatMessage duplication is not this PR's fault and I won't ask you to fix it here, but this PR widens it, and the mirror comment is an admission that a compiler-enforced relationship should exist instead.


🟢 Nits

  • Nit: 📁 local_agent_service.rs:1372 — .chars().take(120) is a raw char truncation with no ellipsis, so a clipped summary is indistinguishable from a complete one. tools.rs already has a truncate() helper with tests (truncate_short_string et al.). Reuse it, or append ….
  • Nit: 📁 local_agent_service.rs:1444 — filter_map → flat_map returning Vec::new()/vec![msg]/vec![msg, evidence] allocates a Vec per message. Fine at this scale; into_iter().chain() or SmallVec would avoid it. Purely cosmetic.
  • Nit: 📁 local_agent_service.rs:1435 — the summary is user-influenced text (content arg) interpolated into a system-role instruction block. Not a security issue in this threat model — it's the user's own content, in the user's own chat, and it was already in history verbatim as their instruction, so no privilege is crossed. But a summary containing something like - create_node "x"\nRecord of graph writes: (none) can shape the block's structure. Since the value is bounded at 120 chars and quoted, the exposure is minimal; stripping newlines from summary would close it cleanly and costs one line.
  • Nit: commit message — CLAUDE.md forbids issue numbers in documentation and code comments; the code comments here correctly reference agent_loop.rs and chat/mod.rs by file rather than by issue, which is right. The commit message's #1775/#1778/closes #1780 references are process mechanics and explicitly permitted. Flagging only to confirm I checked it.
  • Positive, worth naming: no lint suppression, no #[allow(dead_code)], no backward-compat shim, no migration path for existing persisted messages — #[serde(default)] handles old rows and the greenfield stance is respected. The skip_serializing_if on both the Options and the Vec keeps existing persisted JSON byte-identical when there are no writes. The frontend type is updated in lockstep with the Rust shape. The doc comments explain why (the orphan-tool-result rationale, the failed-write exclusion) rather than what, which is exactly the standard.

Recommendation: COMMENT — approve-with-changes in spirit

The root cause is right, the layer is right, the Role::System decision is right and well-defended, and the tests are honest (verified-failing, not written-to-pass). This meaningfully improves code health and I would not hold it for the architectural items.

Before merge I'd like to see the two cheap correctness fixes — 🟡-2 (markdown in the summary chain + real evidence for create_relationship) and 🟡-3 (test fixture using the actual nodespace:// URI shape, and resolving the unreachable node_id branch). Both are small and both are cases where the current code silently produces a degraded or unverified result.

🟡-1 is the one I want on the record: this is a strong mitigation of a correctly identified root cause, and it should be described that way rather than as a guarantee. The persisted completed_writes this PR introduces is precisely the cross-turn state a real programmatic dedup would need — that follow-up is now cheap, and it's what would let acceptance criterion 2 be claimed without a caveat. Please file it, and adjust the commit subject from "cannot re-execute" to something the change actually delivers.

🟡-4 (summarization drops evidence) and 🟡-5 (mirrored type) are follow-up material, not merge blockers.

…pped labels

Three findings from the review of #1786, all verified against the actual
tool implementations before changing anything.

Per-tool evidence mapping instead of a key probe. The extractor probed
`content`/`title`/`name` across every write tool, but the write tools do
not share one argument shape, so two of them silently degraded to a bare
tool name — no way for the model to match the evidence against the
instruction it satisfied, which is the entire purpose. `create_relationship`
takes none of those keys and returns no node id; it now renders the edge
itself (`from -[type]-> to`). `create_nodes_from_markdown` keys on
`markdown`, and is the highest-stakes duplicate in the set: a repeat
re-imports a whole subtree. Schema writes key on `name`. The mapping is
explicit so a new write tool has to state what its evidence looks like
rather than falling through to nothing.

Match the real result shape. Every write tool that reports an affected
node returns it under `id`, as a `nodespace://` URI — never `node_id`.
The `node_id` fallback was unreachable, so it is gone rather than left as
speculative defensive code. Storing the URI is correct and stays: it is
the same form the model uses to refer to nodes elsewhere. The test fixture
used a bare id no tool actually returns; it now pins the production shape,
and the assertion checks the full URI.

Clipped labels are marked and flattened. A silently truncated summary was
indistinguishable from a complete one; it now ends in an ellipsis. Newlines
are flattened so user-supplied content cannot reshape the evidence block's
line structure.

Tests cover each write tool's label, the URI shape, and clipping.

On the review's main point, which is fair: this change removes the cause of
the duplicate (a history that structurally could not show the write had
happened), but the step from "evidence present" to "not repeated" still runs
through the model honouring the note. That is a strong mitigation, not a
guarantee, and the previous subject line claimed more than it delivers. The
persisted `completed_writes` is precisely the cross-turn state a deterministic
guard would need, so that follow-up is now cheap — filed separately.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HkymyKtLHm5NcNbf2CjrT9
@malibio malibio changed the title Agent re-executes the previous turn's instruction, creating a duplicate node (cross-turn; the per-turn duplicate guard cannot catch it) Persist completed graph writes so the next turn can see them (closes #1780) Jul 28, 2026
@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks — the two correctness findings were real and are fixed in 40436b9. I verified each against the tool implementations before changing anything.

🟡-2 — fixed. Confirmed both cases: create_relationship returns {"from_id","to_id","type","created"} and takes none of the probed arg keys; create_nodes_from_markdown keys on markdown. Both were degrading to a bare tool name.

Replaced the key probe with an explicit per-tool mapping (write_summary_arg), so a new write tool has to declare what its evidence looks like rather than silently falling through to nothing. create_relationship now renders the edge itself (from -[type]-> to); markdown imports key on markdown; schema writes on name.

I did not derive the list from Tool::is_write(). It is the better design and you are right about the drift risk, but Tool lives in nodespace-agent and the daemon would need that enum exported and matched exhaustively — a wider change than this fix warrants. The matches! form at least makes the classification a single readable block. Worth doing when someone next touches the tool registry.

🟡-3 — fixed, and the dead branch is gone. Confirmed create_node/update_node/update_task_status/delete_node all return id as a nodespace:// URI, and none return node_id — so that fallback was unreachable. Removed rather than left as speculative defensive code (CLAUDE.md). Fixtures now use the production URI shape and assert on the full URI.

Also took the nits: clipped summaries end in an ellipsis so a truncation is distinguishable from a complete label, and newlines are flattened so user content cannot reshape the evidence block.

🟡-1 — agreed, and this is the right call-out. The change removes the cause (a history that structurally could not show the write happened), but the step from "evidence present" to "not repeated" still runs through the model honouring the note. Mitigation, not guarantee. I have corrected the PR title and stated the limitation explicitly in the follow-up commit message.

Filed #1787 for the deterministic guard. As you note, it is now cheap: the persisted completed_writes is exactly the cross-turn state it needs. I included your point about returning an informative tool result rather than a silent block, plus a caveat that update_node/update_task_status are legitimately idempotent and must not be caught by it.

🟡-4 (summarization can drain evidence) and 🟡-5 (mirrored type) — agreed as follow-up material, not addressed here. Worth noting on 🟡-4 that summarization_prompt does instruct "Preserve node IDs, tool results", so there is partial protection, but you are right that nothing guarantees it and the degradation would hit exactly the long conversations where duplicates are likeliest.

On acceptance criterion 1 (the prompt dump): fair caveat, and I should be straight about it — I did not capture one. The data flow from persisted message to assembled prompt is deterministic and I traced it end-to-end in code, so I am confident the evidence was absent from turn 8d's prompt. But you have correctly identified that the final step — the model re-executing because of that absence — remains an inference, and that is precisely the step the issue wanted nailed down given the two wrong diagnoses on #1775/#1760. The real end-to-end Tauri seam test passing against a live model exercises the new path but does not reproduce the original duplicate, so it is not a substitute.

test:all green after the fixes (4104 frontend, all Rust suites), full pre-push gate passed.

@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Review Type: Re-Review

Re-review of PR #1786 covering only 40436b98 ("Address review: per-tool evidence extraction, real result shapes, clipped labels") against the previously-reviewed bab52887. Diff is 163/-45 in a single file, packages/daemon/src/services/local_agent_service.rs. I verified every claim in the commit message against the actual tool definitions, param structs, and executor return values in packages/agent/src/local_agent/tools.rs rather than accepting the message at its word. Daemon tests: 15 passed, 0 failed.


Previous Review Summary

Count
Recommendations in prior review 5 (🟡-1 … 🟡-5) + nits
Addressed 3 (🟡-1 via title/commit/#1787, 🟡-2 partially, 🟡-3 fully) + both nits
Explicitly deferred 2 (🟡-4, 🟡-5)
New issues found in this commit 2 (1 Improvement, 1 Nit)

🟡-2 (write tools degrade to a bare tool name) — substantially addressed. create_relationship now renders from -[type]-> to from its real arg names, and create_nodes_from_markdown keys on markdown. I confirmed both against CreateRelationshipParams (from_id/to_id/relationship_type, tools.rs:96-100) and def_create_nodes_from_markdown (required: ["markdown"]). The claim is accurate. But the mapping is not correct for every tool — see New Issue 1.

🟡-3 (unreachable node_id branch) — fully and correctly addressed. I traced all eight write executors: create_node returns {"id": node_uri(...)}, update_node returns {"id": node_uri(...), "updated": true}, update_task_status returns {"id": node_uri(...), "status", "updated"}, delete_node returns {"id": node_uri(...), "deleted"}. create_relationship returns {from_id, to_id, type, created} — no id. Schema and markdown handlers return no id either. No registered write tool returns node_id. Removing the fallback is genuinely safe, and deleting it rather than leaving speculative defensive code is the right call under the repo's no-dead-code rule. The fixture change to nodespace://f1f25564 correctly pins the production shape, since node_uri() (tools.rs:240) always prefixes.

Nits — both addressed correctly. Clipping is marked with …; newlines flattened.


Requirements Check

Item Status
write_summary_arg covers every write tool ⚠️ One tool mismapped (update_schema)
node_id fallback removal safe ✅ Verified against all 8 executors
create_relationship rendering matches real arg names ✅ from_id/relationship_type/to_id exact
clip_summary ellipsis + newline flattening ✅ Correct; assertion is right
New tests pin the production contract ✅ Real shapes, not synthetic
CLAUDE.md compliance ✅ No suppressions, no deprecation, no docs added
Tests pass ✅ 15/15 daemon lib tests

Findings

New Issues

🟡 [Improvement] update_schema keys on name, but the tool has no name argument — it takes schema_id
📁 packages/daemon/src/services/local_agent_service.rs:1350

"create_schema" | "update_schema" => Some(&["name"]),

This is correct for create_schema — def_create_schema declares "required": ["name"] and name is the display name. It is wrong for update_schema. Its schema (tools.rs, def_update_schema) declares "required": ["schema_id"] and there is no top-level name property at all; UpdateSchemaParams (packages/core/src/schema/mod.rs:359-361) confirms pub schema_id: String. The only name keys in an update_schema payload are nested inside add_fields[]/add_relationships[] items, which r.args.get("name") will never reach.

Net effect: update_schema falls straight through to summary: None and renders as a bare - update_schema line — precisely the degradation this commit was written to eliminate, and the commit message's claim that "Schema writes key on name" is accurate for only one of the two. The fix is one token: "update_schema" => Some(&["schema_id"]), split out from the create_schema arm.

This matters because a schema update is a genuinely destructive repeat: rename_fields rekeys property data on all existing nodes of that type, so re-executing a rename that already landed silently corrupts data with no matching source field to rename back. It is second only to the markdown import in blast radius, and it is the one arm the new mapping gets wrong.

🔵 [Nit] write_summary_arg has a redundant create_relationship => None arm shadowed by the catch-all
📁 packages/daemon/src/services/local_agent_service.rs:1352

"create_relationship" => None is behaviourally identical to _ => None on the next line. It is deliberate self-documentation (the doc comment explains the None contract), and I would normally leave it — but it also means the None if r.name == "create_relationship" branch at the call site is reached via the same path as a genuinely unregistered tool. A future write tool added to is_write_tool but forgotten in write_summary_arg silently yields a bare name with no compile-time signal. Consider modelling this as an enum (Args(&[&str]) / Relationship / NoLabel) so the intent is in the type, or at minimum drop the shadowed arm since the doc comment already carries the explanation.

Verified Correct (no action)

  • clip_summary ellipsis logic — chars().count() and chars().take() are both char-based, so no UTF-8 boundary panic and no byte/char mismatch. The > SUMMARY_MAX_CHARS guard means a summary of exactly 120 chars is not clipped, which is right. Newline flattening uses replace(['\n','\r'], " ") — covers LF, CR, and CRLF (as two spaces, cosmetically imperfect but harmless). Unicode line separators (U+2028/U+2029) are not covered, but they do not break the evidence block's line structure in this rendering, so this is complete for its stated purpose.
  • The SUMMARY_MAX_CHARS + 1 assertion (:2107) — correct, not off-by-one. 120 head chars plus the single-char … (U+2026, one char) is exactly 121. This assertion would catch a regression to byte-slicing or to a three-dot ..., so it is doing real work.
  • create_relationship args are read pre-normalization and that is fine here. I checked agent_loop.rs:790-834: ToolExecutionRecord.args stores the raw model-emitted JSON, not the deserialized params. So serde aliases are not applied. For create_relationship this is safe — CreateRelationshipParams declares no aliases, so from_id/to_id/relationship_type are the only accepted spellings and the extractor's keys match exactly. The "?" placeholder is therefore unreachable on a successful call (deserialization would have failed first), which makes it correct defensive rendering rather than dead code.
  • The ["content","title","id"] list is right, including the tools that only take an id. delete_node takes only id (DeleteNodeParams) and update_task_status takes id + status — neither has content or title. Listing all three keys in one arm is not sloppiness: the ordered find_map degrades gracefully, so create_node/update_node prefer content while delete_node/update_task_status fall through to id. Because raw args are stored unnormalized, a model emitting the node_id alias (accepted by AgentUpdateNodeParams, UpdateTaskStatusParams, and DeleteNodeParams) would miss — but the id spelling is what all four tool schemas advertise, so this is a rare tail case, and create_node/update_node still recover via content. Not worth blocking on; adding "node_id" to that arm would close it for one word if the author is touching the line anyway.
  • title in the key list is vestigial — no write tool declares a title argument, and create_node's doc comment explicitly states "The agent never sets or manipulates the title field." It is harmless (models do occasionally emit it, and exec_create_node promotes unknown flat keys into properties), so it is defensible as tolerance for model drift rather than dead code.
  • Error filtering is sound for schema tools. exec_create_schema/exec_update_schema return validation failures through error_result(...) with is_error: true (tools.rs:214-221), so the !r.is_error filter correctly excludes them. A failed schema write is not recorded as completed. Confirmed by the still-passing failed_writes_are_not_recorded_as_completed test.

On declining Tool::is_write()

The author's justification holds and should not block. is_write_tool lives in the daemon while Tool lives in packages/agent; threading a method across the crate boundary means either exporting Tool into the daemon's dependency surface or reshaping ToolExecutionRecord to carry a typed tool rather than a String name. That is a real refactor with blast radius well beyond this PR's stated purpose — bundling it here would violate the atomic-change principle the review framework asks for, and this is a bug fix on a live duplicate-write defect.

The trade-off being accepted is that is_write_tool and write_summary_arg are two hand-maintained lists that must stay in sync with a third list in another crate, with no compile-time enforcement. New Issue 1 is exactly that failure mode occurring within the very commit that introduced the second list — which strengthens, rather than undermines, the case for doing the typed refactor when someone next touches the tool registry. Worth capturing that observation on #1787 or a sibling issue so the rationale is not lost. But deferring it is the right call for this PR.


Assessment

This is a solid response to the previous review. The author verified claims against real code rather than pattern-matching, correctly identified that create_relationship needed different treatment rather than forcing it into the key-probe, deleted the unreachable branch instead of leaving speculative defensive code, and the three new tests pin production shapes (nodespace:// URIs, real result payloads, real arg keys) rather than convenient synthetic ones. The commit message is unusually honest about the residual limitation — the model-honouring gap between "evidence present" and "not repeated" — and #1787 captures the deterministic guard. That candour is the right instinct.

The one substantive miss is that the mechanism introduced to eliminate bare-tool-name degradation still degrades on update_schema, the second-most-destructive tool in the set. It is a one-line fix, fully within the scope this commit already claims, and the existing every_write_tool_produces_a_usable_label test is the natural home for a case pinning it.

Recommendation: REQUEST CHANGES

Blocking on one line only:

  1. Split the schema arm: "create_schema" => Some(&["name"]), "update_schema" => Some(&["schema_id"]), and add an update_schema case to every_write_tool_produces_a_usable_label so the test name becomes true of every write tool.

Optional, non-blocking: add "node_id" to the ["content","title","id"] arm to cover the serde alias in raw args; consider the enum shape from the Nit; note the sync-hazard rationale on #1787.

Everything else in 40436b98 is correct as written.

@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.

Re-review posted as a PR comment above.

@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.

Re-review posted as a PR comment above.

Caught in re-review. `create_schema` and `update_schema` were sharing a
mapping arm keyed on `name`, but `update_schema` has no top-level `name`
argument — it identifies its target by `schema_id`, and the only `name`
keys sit nested inside `add_fields[]`, out of reach of a top-level lookup.

So `update_schema` fell through to no summary and rendered as a bare tool
name: the exact degradation the previous commit set out to remove, on one
of the most destructive tools in the set. A repeated schema update is not
benign — `rename_fields` rekeys property data on every existing node of
that type, so re-running a rename that already landed corrupts data with no
matching source field left to rename back.

Also taken from the re-review, both non-blocking:

- Added `node_id` to the node-tool key chain. `ToolExecutionRecord.args`
  stores the raw model-emitted JSON rather than the deserialized params, so
  serde aliases are not applied; a model emitting the `node_id` spelling
  (which the params structs do accept) would otherwise miss.
- Dropped the `create_relationship` arm that was shadowed by the catch-all.
  The doc comment already carries the contract, and the duplicate arm gave
  the false impression of a compile-time signal that is not there.

The test now pins `update_schema` too, so `every_write_tool_produces_a_usable_label`
is true of its full name.

The re-review also observed that this mismap is itself the hand-synced-list
failure mode — two lists here plus a third in another crate, none enforced
by the compiler. That is a fair reading and is noted on #1787 rather than
refactored here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HkymyKtLHm5NcNbf2CjrT9
@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Good catch — the blocking issue was real. Fixed in e9052a3.

update_schema → schema_id. Verified before changing: def_update_schema declares schema_id at top level, and the only name keys are nested inside add_fields[], unreachable from args.get("name"). Split into separate arms with a comment explaining why they differ, and added an update_schema case to every_write_tool_produces_a_usable_label so the test name is true of its full name.

Your point about blast radius is what made this worth blocking on rather than a nit: rename_fields rekeys property data across every existing node of the type, so a repeat corrupts data with no matching source field left to rename back. Bare-name evidence on that tool was the worst place for the mapping to have a hole.

Also took both non-blocking suggestions:

  • node_id added to the node-tool key chain. You're right that ToolExecutionRecord.args stores raw model JSON rather than deserialized params, so serde aliases never apply — a model emitting node_id would have missed. One word, closes the tail case.
  • Dropped the shadowed create_relationship => None arm. Your framing convinced me: it read as a compile-time signal that isn't actually there, which is worse than the catch-all plus the doc comment. I left the enum reshape alone — it's the same cross-crate change as Tool::is_write() and belongs with it.

On the sync hazard: your observation that this mismap is itself the hand-synced-list failure mode, occurring inside the commit that added the second list, is the most useful thing in this review. I've noted it on #1787 so the rationale survives — two lists in the daemon plus a third in packages/agent, none compiler-enforced, and the empirical evidence that it drifts within a single commit.

test:all green, full gate passed.

One note on the push: the gate initially failed on architecture-benchmarks.test.ts (bulk indent/outdent, 37ms against a 25ms threshold). That's the known machine-load-flaky benchmark, not a regression — it passes in 43ms total on a quiet machine, and this PR touches no frontend code. Re-ran and it passed. Flagging rather than silently retrying, since "retried until green" is exactly how a real intermittent failure gets buried.

@malibio

malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review — PR #1786 (Re-Review, cycle 3)

Review Type: Re-Review (second re-review) — scoped to e9052a32 against 40436b98
Recommendation: ✅ APPROVE


Previous Review Summary

Recommendations made 1 blocking (update_schema mismapped to name), 1 non-blocking (node_id in key chain), 1 Nit (shadowed create_relationship arm)
Addressed All 3
Not addressed None outstanding; the enum reshape was explicitly declined with a rationale I accept (see below)
New issues introduced None

Requirements Check — the blocking item

Verified fixed, and I checked it against real code rather than the commit message.

📁 packages/daemon/src/services/local_agent_service.rs:1351-1355 — the arm is split as required, with a comment stating why the two schema tools differ rather than restating the mechanics.

I confirmed schema_id is genuinely the right key, from two independent sources:

  • 📁 packages/agent/src/local_agent/tools.rs:677 — def_update_schema declares schema_id and no top-level name; the only name keys are nested in add_fields[].items.properties, exactly as claimed.
  • 📁 packages/core/src/schema/mod.rs:359-361 — UpdateSchemaParams.schema_id is a bare String, not Option<String> and with no #[serde(default)]. It is structurally required, so it is present in every payload that deserializes at all. That is the strongest form of this guarantee: the label cannot be absent on a call that succeeded.

The new test is meaningful — I verified it empirically rather than by reading it. I reverted the arm to the buggy shared "create_schema" | "update_schema" => Some(&["name"]) form and re-ran:

assertion `left == right` failed
  left: None
 right: Some("album_to_listen")

It fails with left: None — precisely the bare-tool-name degradation the fix targets, not an incidental assertion failure. The fixture is realistic in the way that matters: top-level schema_id plus a nested add_fields[].name, so a regression to ["name"] cannot accidentally pass by finding the nested key. Restored to e9052a32; working tree clean. Full module suite: 15/15 pass.


Findings

Critical Issues

None.

Verification of the other three changes

node_id added to the node-tool key chain — correct, and the ordering is safe.
📁 local_agent_service.rs:1347-1349 — chain is ["content","title","id","node_id"]. I checked the ordering concern directly: node_id is a #[serde(alias = "node_id")] for id on AgentUpdateNodeParams, UpdateTaskStatusParams, and DeleteNodeParams (📁 tools.rs:77,88,105,133,141). Because it is an alias for the same field, a payload carries id or node_id, never both — so node_id sitting last can never shadow a better label. It is reached only when the preceding three miss, which is exactly the gap it was added to close. The premise is real: ToolExecutionRecord.args stores raw model-emitted JSON, so serde aliases are not applied at this layer.

Dropping the create_relationship => None arm — no behavior change.
📁 local_agent_service.rs:1358-1360 — the catch-all _ => None returns the identical value the deleted arm did, and the call site's None if r.name == "create_relationship" guard (📁 :1414) still matches on the tool name, independent of which arm produced the None. The create_relationship branch of every_write_tool_produces_a_usable_label still asserts the a -[mentions]-> b rendering and passes. Removing an arm that the compiler could never distinguish from the catch-all is a genuine readability win — it had implied a compile-time signal that does not exist.

Declining the enum reshape — right call. Modelling the evidence shape as Args(&[&str]) / Relationship / NoLabel is the correct end state, but it is the same cross-crate change as Tool::is_write(): Tool lives in packages/agent, the classification in the daemon, and ToolExecutionRecord carries a String name. That is a refactor, not a bug fix, and it does not belong in a live-defect PR. Recording it on #1787 — where the deterministic guard must reason about tool identity and side-effect class anyway — puts it in front of the right person at the right time. I'd note the sync hazard is now documented with the strongest possible evidence: it drifted within the commit that introduced it.

Deferred items — still correctly scoped

  • 🟡-4 (summarization drains evidence) and 🟡-5 (mirrored type) — nothing in e9052a32 touches either surface. This commit is 22 added lines confined to one function and one test. Neither became more urgent.

Nitpicks

None. The previous Nit was taken.


New Issues in e9052a32

None. I scanned the added lines for lint suppression, #[allow(dead_code)], #[deprecated], backward-compat scaffolding, and issue numbers in code comments — all clean. The comments explain intent (why the two schema tools key differently, why a repeat is destructive) rather than mechanics, which is the standard this codebase asks for. Issue references appear only in the commit message and on #1787, never in code — correct per CLAUDE.md.

Flaky-test disclosure — sanity-checked and unrelated. src/tests/performance/architecture-benchmarks.test.ts (bulk indent/outdent, 37ms vs a 25ms threshold) does not appear anywhere in this PR's diff. The full PR touches six files — Rust in packages/core, packages/daemon, packages/nodespace-types, plus one TS type file — and nothing in the indent/outdent path. This is the known machine-load-flaky benchmark. Flagging it rather than silently retrying is the right instinct and I'd rather see it disclosed than buried.


Merge Readiness

Ready to merge. Being explicit, as asked:

The single blocking item is genuinely resolved — verified against the tool definition, the params struct, and by deliberately reintroducing the bug to confirm the test catches it. The two non-blocking items were taken and neither introduces a regression. No new issues. The deferred work is filed on #1787 with the architectural rationale preserved, which is the correct home for it.

Weighing this as a net-positive change: this is a bug fix on a live duplicate-write defect where the current behavior can write a user's data twice. It is strictly better than main in that respect, and the remaining work is a structural improvement to a hand-synced list — real, but not a reason to keep a data-corruption fix out of the tree. Holding it for a cross-crate refactor would be perfection blocking net-positive.

One thing worth saying plainly about the process: the defect this cycle caught was introduced by the previous review's own remediation. That is a good argument for the empirical verification standard applied here — reverting the fix to confirm the test actually fails — rather than trusting a test name or a commit message. That standard is now encoded in the test itself, so the next person to touch write_summary_arg gets a compile-time-adjacent signal for update_schema specifically, even though the broader list remains unenforced.

Nothing remains that should block merge.

@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.

Code Review — PR #1786 (Re-Review, cycle 3)

Review Type: Re-Review (second re-review) — scoped to e9052a32 against 40436b98
Recommendation: ✅ APPROVE


Previous Review Summary

Recommendations made 1 blocking (update_schema mismapped to name), 1 non-blocking (node_id in key chain), 1 Nit (shadowed create_relationship arm)
Addressed All 3
Not addressed None outstanding; the enum reshape was explicitly declined with a rationale I accept (see below)
New issues introduced None

Requirements Check — the blocking item

Verified fixed, and I checked it against real code rather than the commit message.

📁 packages/daemon/src/services/local_agent_service.rs:1351-1355 — the arm is split as required, with a comment stating why the two schema tools differ rather than restating the mechanics.

I confirmed schema_id is genuinely the right key, from two independent sources:

  • 📁 packages/agent/src/local_agent/tools.rs:677 — def_update_schema declares schema_id and no top-level name; the only name keys are nested in add_fields[].items.properties, exactly as claimed.
  • 📁 packages/core/src/schema/mod.rs:359-361 — UpdateSchemaParams.schema_id is a bare String, not Option<String> and with no #[serde(default)]. It is structurally required, so it is present in every payload that deserializes at all. That is the strongest form of this guarantee: the label cannot be absent on a call that succeeded.

The new test is meaningful — I verified it empirically rather than by reading it. I reverted the arm to the buggy shared "create_schema" | "update_schema" => Some(&["name"]) form and re-ran:

assertion `left == right` failed
  left: None
 right: Some("album_to_listen")

It fails with left: None — precisely the bare-tool-name degradation the fix targets, not an incidental assertion failure. The fixture is realistic in the way that matters: top-level schema_id plus a nested add_fields[].name, so a regression to ["name"] cannot accidentally pass by finding the nested key. Restored to e9052a32; working tree clean. Full module suite: 15/15 pass.


Findings

Critical Issues

None.

Verification of the other three changes

node_id added to the node-tool key chain — correct, and the ordering is safe.
📁 local_agent_service.rs:1347-1349 — chain is ["content","title","id","node_id"]. I checked the ordering concern directly: node_id is a #[serde(alias = "node_id")] for id on AgentUpdateNodeParams, UpdateTaskStatusParams, and DeleteNodeParams (📁 tools.rs:77,88,105,133,141). Because it is an alias for the same field, a payload carries id or node_id, never both — so node_id sitting last can never shadow a better label. It is reached only when the preceding three miss, which is exactly the gap it was added to close. The premise is real: ToolExecutionRecord.args stores raw model-emitted JSON, so serde aliases are not applied at this layer.

Dropping the create_relationship => None arm — no behavior change.
📁 local_agent_service.rs:1358-1360 — the catch-all _ => None returns the identical value the deleted arm did, and the call site's None if r.name == "create_relationship" guard (📁 :1414) still matches on the tool name, independent of which arm produced the None. The create_relationship branch of every_write_tool_produces_a_usable_label still asserts the a -[mentions]-> b rendering and passes. Removing an arm that the compiler could never distinguish from the catch-all is a genuine readability win — it had implied a compile-time signal that does not exist.

Declining the enum reshape — right call. Modelling the evidence shape as Args(&[&str]) / Relationship / NoLabel is the correct end state, but it is the same cross-crate change as Tool::is_write(): Tool lives in packages/agent, the classification in the daemon, and ToolExecutionRecord carries a String name. That is a refactor, not a bug fix, and it does not belong in a live-defect PR. Recording it on #1787 — where the deterministic guard must reason about tool identity and side-effect class anyway — puts it in front of the right person at the right time. I'd note the sync hazard is now documented with the strongest possible evidence: it drifted within the commit that introduced it.

Deferred items — still correctly scoped

  • 🟡-4 (summarization drains evidence) and 🟡-5 (mirrored type) — nothing in e9052a32 touches either surface. This commit is 22 added lines confined to one function and one test. Neither became more urgent.

Nitpicks

None. The previous Nit was taken.


New Issues in e9052a32

None. I scanned the added lines for lint suppression, #[allow(dead_code)], #[deprecated], backward-compat scaffolding, and issue numbers in code comments — all clean. The comments explain intent (why the two schema tools key differently, why a repeat is destructive) rather than mechanics, which is the standard this codebase asks for. Issue references appear only in the commit message and on #1787, never in code — correct per CLAUDE.md.

Flaky-test disclosure — sanity-checked and unrelated. src/tests/performance/architecture-benchmarks.test.ts (bulk indent/outdent, 37ms vs a 25ms threshold) does not appear anywhere in this PR's diff. The full PR touches six files — Rust in packages/core, packages/daemon, packages/nodespace-types, plus one TS type file — and nothing in the indent/outdent path. This is the known machine-load-flaky benchmark. Flagging it rather than silently retrying is the right instinct and I'd rather see it disclosed than buried.


Merge Readiness

Ready to merge. Being explicit, as asked:

The single blocking item is genuinely resolved — verified against the tool definition, the params struct, and by deliberately reintroducing the bug to confirm the test catches it. The two non-blocking items were taken and neither introduces a regression. No new issues. The deferred work is filed on #1787 with the architectural rationale preserved, which is the correct home for it.

Weighing this as a net-positive change: this is a bug fix on a live duplicate-write defect where the current behavior can write a user's data twice. It is strictly better than main in that respect, and the remaining work is a structural improvement to a hand-synced list — real, but not a reason to keep a data-corruption fix out of the tree. Holding it for a cross-crate refactor would be perfection blocking net-positive.

One thing worth saying plainly about the process: the defect this cycle caught was introduced by the previous review's own remediation. That is a good argument for the empirical verification standard applied here — reverting the fix to confirm the test actually fails — rather than trusting a test name or a commit message. That standard is now encoded in the test itself, so the next person to touch write_summary_arg gets a compile-time-adjacent signal for update_schema specifically, even though the broader list remains unenforced.

Nothing remains that should block merge.

@malibio
malibio merged commit 461bab1 into main Jul 28, 2026
2 checks passed
@malibio
malibio deleted the issue-1780-cross-turn-duplicate branch July 28, 2026 20:52
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.

Agent re-executes the previous turn's instruction, creating a duplicate node (cross-turn; the per-turn duplicate guard cannot catch it)

1 participant