Skip to content

Deterministic cross-turn duplicate-write guard: make the persisted completed_writes enforceable, not advisory - #1790

Merged
malibio merged 6 commits into
mainfrom
issue-1787-deterministic-write-guard
Jul 29, 2026
Merged

malibio merged 6 commits into
mainfrom
issue-1787-deterministic-write-guard

Conversation

@malibio

@malibio malibio commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Closes #1787

malibio and others added 2 commits July 28, 2026 23:19
The persisted completed_writes record from #1780 made the model aware a
write had already happened, but the step from evidence to not-repeating
ran entirely through the model choosing to honour a prompt note. Not
writing the user's data twice should not rest on a probabilistic
component.

Enforce it at the tool-execution path instead. AiChatCompletedWrite now
carries the call's canonical args, which together with the tool name is
the write's identity. run_ai_chat_turn replays those into the rebuilt
session as prior_writes, and the executor refuses a guarded call that
matches one.

Canonicalisation is the same function the per-turn seen_calls detector
uses, promoted from a local closure, so the two cannot drift into
disagreeing about what the same call means.

Scope. Only the creates plus delete_node are guarded: re-setting a node
to the same content, or a task to the same status, is idempotent, and
blocking that would break a user legitimately re-asserting a value.

The refusal returns an informative tool result naming the existing node,
not a silent block — a user genuinely re-asking for the same node is rare
but real, so the model must be able to say it already exists.

Oversized args drop the identity rather than truncating it: a truncated
string could compare equal to a different call sharing a long prefix,
turning a size limit into a wrongly-blocked write. The guard fails open.

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

Pragmatic Code Review — PR #1790

Review Type: Initial Review

Summary

This is a well-executed change that does what #1787 asked: it converts an advisory prompt note into an enforced check at the tool-execution path. The core design decision — reusing the same canonical_args function for both the per-turn seen_calls detector and the cross-turn guard, by promoting the closure to a shared pub fn — is exactly right, and the doc comment explaining why (so the two "cannot drift into disagreeing about what the same call means") is the kind of intent-capturing comment this codebase asks for. The RecordingToolExecutor deserves specific praise: asserting on ground truth (did the call reach the executor?) rather than on the returned result closes the "guard executed the write and relabelled the result" hole that a weaker test would have left open.

I independently verified the load-bearing claims rather than taking them at face value:

  • Key-order canonicalisation holds. preserve_order is not enabled anywhere — no preserve_order in any Cargo.toml or Cargo.lock entry for serde_json 1.0.149, and indexmap is present only via unrelated transitive dependents. I compiled a probe against this workspace's actual libserde_json rlib: {"z":1,"a":2,"m":3} → {"a":2,"m":3,"z":1}. The sorted-key assumption is real, and the doc comment's phrasing ("Round-tripping through serde sorts nothing by itself, but ... BTreeMap-backed objects") is accurate and honest about the mechanism.
  • All 12 new tests pass, and I ran them directly: 6 in nodespace-agent (cross_turn_duplicate_write_is_not_executed, refused_duplicate_names_the_existing_node, guard_matches_regardless_of_argument_key_order, a_different_write_still_executes, idempotent_update_repeat_is_not_blocked, no_prior_writes_leaves_execution_untouched) and 6 in nodespace-daemon.
  • delete_node guarding is safe in the create/delete/recreate scenario. DeleteNodeParams.id is the node id, and a recreated node gets a new id, so the second delete carries different args and does not match. The concern raised in the brief does not materialise.
  • CLAUDE.md compliance is clean: no lint suppression, no #[allow(dead_code)], no backward-compat shims, no issue numbers in code or doc comments.

Two findings below are worth addressing. The first is a concrete correctness gap I reproduced; the second is an architectural one where the codebase already contains the mechanism that solves it. Neither is large, and neither undermines the design.


Requirements Check

  • ✅ A repeated write with identical canonical args in a later turn does not execute a second time — enforced at agent_loop.rs:871-878 and verified by cross_turn_duplicate_write_is_not_executed, which asserts against the executor's call log, not the result.
  • ✅ The model receives an informative tool result naming the already-written node, not a silent failure — duplicate_write_result emits skipped/id/message; refused_duplicate_names_the_existing_node asserts both the node id and the summary appear.
  • ✅ Legitimately idempotent repeats are not broken by the guard — enforced in two independent places (is_cross_turn_guarded_tool excludes all updates; prior_writes_from_history filters again on load), covered by idempotent_update_repeat_is_not_blocked and idempotent_updates_are_not_carried_into_the_guard. Defence in depth here is appropriate, not redundant.
  • ✅ A regression test covers the cross-turn duplicate at the execution layer — six execution-layer tests, complementing the history-level test from Persist completed graph writes so the next turn can see them (closes #1780) #1786.
  • 📝 The acceptance criteria are met. The findings below concern robustness of the identity, not the criteria themselves.

Code Review Findings

🟡 Important: The recorded identity and the compared identity are produced by two different paths, and they diverge on the empty-args case

📁 packages/agent/src/local_agent/agent_loop.rs:853-859 (record) and :872 (compare)
📁 packages/daemon/src/services/local_agent_service.rs:1457-1459 (persist)

The guard compares canonical_args(&tc.arguments_json) — the raw model-emitted string — against a stored value derived from ToolExecutionRecord.args, which is the parsed Value, re-stringified. For the ordinary path these agree, because args is exactly serde_json::from_str(&tc.arguments_json) and canonical_args is that same round-trip. But parsed_args has a special case:

let parsed_args = if tc.arguments_json.trim().is_empty() {
    Ok(serde_json::json!({}))   // <- substituted, not parsed
} else {
    serde_json::from_str::<serde_json::Value>(&tc.arguments_json)
};

When the model emits a call with empty arguments, the record stores {} but the comparison canonicalises the empty string. I verified this against the compiled serde_json:

raw=""     recorded="{}"  compared=""      MATCH=false
raw="   "  recorded="{}"  compared="   "   MATCH=false
raw="\n"   recorded="{}"  compared="\n"    MATCH=false

So a guarded write emitted with empty args records an identity that can never match itself. This is not hypothetical: empty-argument tool calls are a known failure mode for the local models this targets — the predecessor work (#1781) exists specifically because "the agent emits malformed tool calls ... and calls with empty arguments."

Practically the blast radius is small, because a create with no arguments fails its required-field check and !r.is_error keeps it out of the record. But the guard is a correctness mechanism, and this is a silent, permanent mismatch rather than a loud one. The fix is one line — canonicalise from the same value the record will store:

let incoming = canonical_args(&args.to_string());

This makes the recorded and compared identity provably the same expression applied to the same value, rather than two expressions that happen to agree on most inputs. It also removes the unparseable-args asymmetry for free (that arm is unreachable here, since the guard sits inside Ok(args), but deriving from args makes the invariant structural instead of incidental).

Engineering principle: an equality check is only sound if both sides are produced by the same function applied to the same representation. Deriving the two sides from different upstream values makes agreement a coincidence that must be re-verified whenever either path changes — precisely the drift this PR set out to eliminate by sharing canonical_args in the first place.


🟡 Important: A Tool enum registry already exists to prevent exactly this list drift, and the three hand-maintained lists bypass it

📁 packages/agent/src/local_agent/agent_loop.rs:115-124 (is_cross_turn_guarded_tool)
📁 packages/daemon/src/services/local_agent_service.rs:1380-1392 (is_write_tool), :1359-1374 (write_summary_arg)
📁 packages/agent/src/local_agent/tools.rs:819-845 (the existing registry)

The brief asks whether every_guarded_tool_is_also_recorded_as_a_write is adequate. It is not, and the reason is stronger than "it iterates a hardcoded list." The test's loop body is:

if is_cross_turn_guarded_tool(tool) {
    assert!(is_write_tool(tool), ...);
}

A tool added to is_cross_turn_guarded_tool but not to the test's hardcoded array is never passed to the loop, so the assertion never runs — the test passes vacuously on exactly the change it is meant to catch. I verified the lists are consistent today (all 5 guarded tools are in is_write_tool; the test array covers all 8 write tools), so this is a latent gap, not a live bug.

What makes this worth raising rather than accepting: tools.rs already has the mechanism, and its doc comment states the intent explicitly:

"This enum is the single source of truth for the tool surface. Everything that used to be a separate hand-maintained list is derived from it ... Adding a tool means adding one variant and filling in its arms; the compiler then forces every derivation to account for it. There are no drift-detector tests because the lists can no longer drift — they are computed from here."

So the codebase has already litigated this question and chosen compiler enforcement over drift-detector tests. This PR adds a third hand-maintained list plus a drift-detector test — the pattern that registry was built to retire. The predecessor PR's review flagged the hand-synced-list failure mode and deferred it here, so this is the natural place to close it.

The pragmatic fix is small: add a Tool::is_write(self) -> bool and Tool::is_cross_turn_guarded(self) -> bool as match self arms on the enum. A match without a wildcard makes the compiler reject any new variant until both are answered, which is a stronger guarantee than any test and removes the need for the drift test entirely. Note Tool::name() is currently pub(crate), so exposing a name→Tool lookup across the crate boundary is part of the work.

I would accept a follow-up issue here rather than blocking the merge — the lists are correct today and the guard works. But please don't let it sit: the value of the registry is that it stays the only place tools are enumerated, and each bypass erodes that.

Engineering principle: prefer making invalid states unrepresentable (exhaustive match) over detecting them after the fact (a test). A test that enumerates its own inputs can only catch drift its author remembered to enumerate; the compiler cannot forget.


🟢 Suggestion: The refusal message is well-judged; one phrase could be firmer

📁 packages/agent/src/local_agent/agent_loop.rs:87-101

The brief asks whether is_error: false risks the model reading a refusal as a successful write and telling the user it created something it didn't. I think the wording largely handles this — it opens with "Not executed:" and instructs "Tell the user it already exists rather than repeating the write," and the structured "skipped": "duplicate_write" field gives a non-prose signal. The reasoning for is_error: false in the inline comment (flagging it as a failure "would invite a repair retry — the exact loop this guard exists to stop") is correct and worth keeping.

One softening: "The result of that write still stands (id)" is slightly ambiguous about when it happened. Small local models are the target here, and they are the ones most likely to compress that into "created." Consider "was created earlier in this conversation and still exists (id)" — anchoring it in past tense makes the temporal claim explicit. Minor, and only worth doing if you are touching this function anyway.


🟢 Suggestion: delete_node's node_id alias creates two identities for one logical call

📁 packages/agent/src/local_agent/tools.rs:138-143

DeleteNodeParams accepts node_id as a serde alias for id. Because canonicalisation is textual, the two spellings produce different identities — I verified:

{"id":"nodespace://n1"}       vs  {"node_id":"nodespace://n1"}   -> same call? false

A model that emits id on turn N and node_id on turn N+1 slips past the guard. This is a fail-open miss, not a wrong block, so it is a gap in coverage rather than a defect. write_summary_arg already looks under both id and node_id for the same reason, so the aliasing is a known model behaviour. Not worth solving generally in this PR (that would mean schema-aware normalisation); noting it so the guard's actual coverage is understood rather than assumed to be total.


🟢 Suggestion: Node-size growth is bounded in practice, but the cap interacts oddly with the tool it was written for

📁 packages/agent/src/local_agent/agent_loop.rs:50-58

The brief asks whether the 4096 cap plus unbounded per-conversation accumulation is a real problem. My read: not currently. Only 5 tools are guarded, only successful writes are recorded, and each entry is capped, so growth is bounded by (writes per conversation × 4KB) — a chat with 50 creates adds ~200KB worst case, and realistic create_node args are far below the cap. There is no message-history cap in load_node_history, so this scales with conversation length, but the messages themselves dominate long before the args do.

Worth noting the interaction, though: the constant's doc comment justifies the cap by citing create_nodes_from_markdown ("carries an entire import in its arguments"), which is exactly the tool whose args will nearly always exceed 4096 and therefore nearly always have the identity dropped. So the guard is effectively inactive for the single tool where a duplicate is most expensive — a duplicated subtree import. The fail-open direction is the right call and the reasoning against truncation is sound (a truncated string could compare equal to a different call sharing a long prefix). But if duplicate markdown imports show up in practice, hashing that tool's args would give a fixed-size identity without the prefix-collision hazard. The user chose full args over hashing for the general case, which I am not re-litigating — this is narrowly about the one tool the cap structurally excludes.


🟢 Nit: load_prior_writes and load_node_history each fetch and parse the same node

📁 packages/daemon/src/services/local_agent_service.rs:1533-1546

Both call get_node(node_id) and AiChatNode::from_node on the same node in the same request path — two DB round-trips and two parses where one would do. The doc comment explains the split honestly (ChatMessage has no room for the write record — "the very erasure that let the original duplicate through"), and the silent-error handling correctly avoids a duplicate log line for one underlying failure. Both are good calls.

Still, the cleaner shape is to load the AiChatNode once and derive both. Fine to leave as-is for now given it is one extra read per turn against a local SQLite store and clarity is arguably better with the split — flagging only because it is the sort of thing that gets copied.


Recommendation

COMMENT — approve-with-follow-ups in spirit. The change is a clear net improvement to code health and meets all four acceptance criteria, with genuinely good tests and doc comments that explain why. Nothing here is a security issue or an architectural regression, and I would not block the merge.

Before merging, I would like to see the empty-args identity mismatch fixed, since it is a one-line change (canonical_args(&args.to_string())) that makes the guard's central equality structurally sound rather than incidentally correct.

The Tool registry consolidation is the more valuable long-term fix and the one the predecessor review deferred here, but it is reasonable as a follow-up issue given the lists are verified correct today — provided it actually gets filed. Everything else is optional polish.

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

Initial review posted above: COMMENT. All four acceptance criteria met; 12 new tests verified passing locally. One 🟡 worth fixing before merge (empty-args identity mismatch, one line) and one 🟡 worth a follow-up issue (Tool registry consolidation). No blockers.

…ix empty-args identity

Two findings from the review of #1790.

Registry consolidation. The guard's tool set was a hand-maintained string
list, and the drift test guarding it iterated a hardcoded array — so it
passed vacuously on exactly the change it existed to catch, a tool added
to neither list. tools.rs already carries a Tool enum built to retire
this pattern. Classification now lives there as write_semantics(), an
exhaustive match: adding a variant fails to compile until its duplicate
semantics are declared. is_write_tool and is_cross_turn_guarded_tool are
computed from it, deleting the parallel list in the daemon. Verified by
adding a probe variant — five non-exhaustive-match errors.

Empty-args identity. The guard compared the raw argument text while the
record side stored the parsed form. These agree everywhere except the
empty-args path, where arguments are read as {} before execution: the
stored identity was {} and the compared one , so such a write could
never match itself and the guard was silently disarmed for it. Both
sides now derive from the parsed value.

The drift test now iterates Tool::ALL, and a companion test pins that
every guarded tool can describe what it wrote — a refusal that cannot
name the existing node is not the informative result #1787 asks for.

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

Pragmatic Code Review — PR #1790

Review Type: Re-Review (delta 6c83d3ed..22ee27fc)

Previous Review Summary

The initial review posted COMMENT with 6 findings: 2 🟡 Important, 4 🟢 Suggestion.

# Finding Severity Status
1 Empty-args identity mismatch (record stored parsed {}, compare used raw "") 🟡 ✅ Addressed
2 Third hand-maintained tool list bypassing the Tool registry; drift test passes vacuously 🟡 ✅ Addressed
3 Refusal message temporal ambiguity ("still stands") 🟢 ⬜ Not addressed (deferred)
4 delete_node's node_id serde alias yields two identities 🟢 ⬜ Not addressed (deferred)
5 4096-char cap structurally excludes create_nodes_from_markdown 🟢 ⬜ Not addressed (deferred)
6 load_prior_writes / load_node_history double-fetch 🟢 ⬜ Not addressed (deferred)

New issues found in this delta: 1 🟡, 3 🟢.

On the deferral of 3–6: defensible. Each is a bounded fail-open gap or a cosmetic nit — none can cause a wrong block, and all four remain exactly as true and as cheap to fix later as they were. Crucially, none became more urgent because of this delta: finding 4 (delete_node alias) and finding 5 (markdown cap) both live below the classification layer this commit rewrote, so consolidating the registry neither widened nor narrowed them. Prioritising the two 🟡s was the right call.


Verification I performed independently

I re-verified every load-bearing claim rather than accepting it:

  • Empty-args fix, mutation-tested. Reverting line 859 to canonical_args(&tc.arguments_json) fails exactly one test — empty_arguments_compare_against_their_parsed_form — with 315 others passing. The claim holds precisely.
  • Behaviour-neutral on the ordinary path. Compiled a probe against this workspace's actual libserde_json rlib: for every parseable input, canonical_args(raw) and canonical_args(&parsed.to_string()) produce byte-identical output ({"b":1,"a":2} → {"a":2,"b":1} both ways). The fix changes behaviour only on the empty/whitespace-args path, which is the intent.
  • Registry teeth are real. Adding a probe Tool variant produced 5 E0004 non-exhaustive-match errors, including write_semantics at tools.rs:946. Confirmed.
  • args borrow is sound. args is owned by the Ok(args) arm; args.to_string() takes an immutable borrow that ends before args is moved into the result tuple. No move-before-use, no lifetime issue. Clippy -D warnings clean on both crates.
  • Read-classification audit. I audited all six WriteSemantics::Read executor bodies end to end. No user-visible mutation in any of them (see 🟢 finding below for the one nuance worth recording).
  • from_name fail-open is unreachable in practice. GraphToolExecutor::execute resolves through the same Tool::from_name (tools.rs:2033) and returns ToolError::UnknownTool on None. So a name the guard fails open on is a name that cannot execute at all — the fail-open window is empty, not merely safe. Good property, arrived at structurally.

Requirements Check (issue #1787)

  • ✅ A repeated write with identical canonical args in a later turn does not execute a second time — still enforced at agent_loop.rs:850-864; the identity is now more faithful than at initial review, since the empty-args class is no longer permanently unmatchable.
  • ✅ Informative tool result naming the already-written node — unchanged, and the delta adds every_guarded_tool_can_describe_what_it_wrote to pin it as a registry-wide invariant rather than a per-tool accident.
  • ⚠️ Legitimately idempotent repeats are not broken — met for update_node and update_task_status, which the issue names explicitly. But update_schema, which the issue does not name, is classified IdempotentWrite and is not idempotent (see 🟡 below). The guard still does not block it, so the criterion is not violated — but the new enum now asserts a property that does not hold.
  • ✅ Regression test at the execution layer — 13 tests now (12 + empty_arguments_compare_against_their_parsed_form), plus the two registry-derived invariant tests.

All four criteria remain met.


Findings

🟡 Important: Tool::UpdateSchema is classified IdempotentWrite, but repeating it is a hard error — the enum now asserts a property that is false

📁 packages/agent/src/local_agent/tools.rs:955-960

The new arm groups UpdateSchema with UpdateNode and UpdateTaskStatus under this comment:

"Idempotent writes. Setting a node to the same content, or a task to the same status, twice is a no-op — the second call is not a duplicate…"

For the two update tools that is accurate; I verified it. exec_update_node hardcodes add_to_collection: None / remove_from_collection: None (tools.rs:1541-1542), so the collection-append path in node_ops::update_node is unreachable from the tool, and property merging is insert/replace per key — arrays are replaced wholesale, never extended. exec_update_task_status writes a single scalar. Both genuinely converge.

update_schema does not. handle_update_schema rejects a repeat outright:

// packages/core/src/schema/mod.rs:689-701
if let Some(ref add_fields) = params.add_fields {
    for field in add_fields {
        if fields.iter().any(|f| f.name == field.name) {
            return Err(MarkdownError::invalid_params(format!(
                "Field '{}' already exists in schema '{}'", field.name, params.schema_id
            )));
        }
    }
    fields.extend(add_fields.clone());
}

The identical pattern exists for add_relationships (mod.rs:714-726). rename_fields (mod.rs:652-664) is worse: a repeat of {from: "a", to: "b"} fails on the second call because a no longer exists, and renames run in Phase 1 before the add/remove phases, so a partially-applied multi-rename batch is reachable. All three of these parameters are exposed to the model in the tool schema (tools.rs:689, :712, :725) — this is not a theoretical arm.

So update_schema is a third thing the enum has no name for: a write whose repeat fails. Not IdempotentWrite (the repeat is not a no-op) and not DuplicableWrite (it does not duplicate — the handler catches it). Because exec_update_schema surfaces handler errors as error_result rather than ToolError (tools.rs:1738-1741), the model sees "Field 'x' already exists in schema 'y'" as a tool failure, which is precisely the shape that invites the repair-retry loop the inline comment at agent_loop.rs:886-888 says this guard exists to stop.

Why this is worth raising now rather than deferring like the 🟢s. At initial review, update_schema's exclusion from the guarded set was an unremarkable line in a matches! list. This commit promotes that exclusion into a named semantic category with a doc comment that makes a positive claim about behaviour. The behaviour did not change — is_cross_turn_guarded_tool("update_schema") is false before and after — but the documented rationale is now wrong, and it is wrong in the one place the codebase has designated as the single source of truth for this question. A future author reading WriteSemantics::IdempotentWrite's doc ("a repeat with identical arguments converges on the same result") has been told something they can safely rely on, and cannot.

Two ways out, both small:

  1. Reclassify to DuplicableWrite. Behaviourally the closer fit: the guard would refuse the repeat and return the informative "already done" result instead of letting the handler emit a confusing "already exists" error. This changes guarded behaviour, so it is a scope decision, not a mechanical fix.
  2. Keep it unguarded but stop asserting idempotency. Either add a fourth variant (RepeatFails, still !is_write() == false, still not guarded) or narrow the comment to state that update_schema is excluded because its repeat failure is self-limiting rather than duplicating.

I would take (2) unless the user wants to widen the guard's scope, since (1) touches the explicit scope decision the issue made and this PR honours.

Engineering principle: a type that names a semantic category is a contract, and a doc comment on it is part of that contract. Grouping a member that violates the stated invariant is worse than the untyped list it replaced — the list made no promise, so nobody could rely on one.


🟢 Suggestion: the registry consolidation is correct and the blast-radius concern is answered, but the drift tests are still vacuous one level up

📁 packages/daemon/src/services/local_agent_service.rs:2386-2402, :2405-2418
📁 packages/agent/src/local_agent/tools.rs:850-865

The consolidation itself is right, and I want to be specific about why the shared-classifier concern raised in the brief does not materialise. Concentrating the guard and the evidence-recording path behind one function increases the consequence of a misclassification but decreases its probability, and the tests now pin the one interaction that matters: every_guarded_tool_is_also_recorded_as_a_write enforces DuplicableWrite ⊆ !Read, which is the exact coupling that made two independent lists dangerous. A tool cannot now be guarded-but-unrecorded, which was the silent-guard-never-fires failure. Net reduction in risk, clearly.

One residual, and it is inherited rather than introduced: both tests iterate Tool::ALL, which is itself a hand-maintained const array, not derived from the variant set. I probed this — added a ProbeVariant with DuplicableWrite semantics, filled every match arm, but omitted it from Tool::ALL. It compiles, and both drift tests pass. That is the same vacuity class the initial review flagged in the old hardcoded array, relocated one level up rather than eliminated.

The mitigating facts are strong: Tool::from_name also iterates Tool::ALL, so a variant missing from it is unreachable from the wire entirely — it cannot be called, cannot be guarded, cannot be recorded. It is inert, not dangerous. And all_tool_definitions(), seed_tool_nodes(), and the skill pipeline all derive from ALL too, so an omission is uniformly invisible rather than inconsistently visible. This is a pre-existing property of the registry, not something this PR made worse.

Not worth fixing here. Recording it because the commit message says the registry means lists "can no longer drift," and the accurate statement is narrower: the derivations cannot drift from ALL; ALL itself is still authored by hand. If you want to close it, a strum-style derive or a const assertion that ALL.len() matches the variant count would do it — but a variant outside ALL is dead code, which CLAUDE.md would have you delete anyway.

Engineering principle: enumerating a set exhaustively is only as strong as the enumeration's own source. Compiler-enforced exhaustiveness over match is real; exhaustiveness over a hand-written const array is a convention.


🟢 Suggestion: canonical_args's doc comment now overstates the sharing it guarantees

📁 packages/agent/src/local_agent/agent_loop.rs:59-61, and the two consumers at :791, :807, :859

The doc comment still reads:

"Shared by the per-turn duplicate detector and the cross-turn write guard so the two cannot drift into disagreeing about what 'the same call' means."

That was accurate before this commit, when both consumers passed tc.arguments_json. It is no longer. The cross-turn guard now passes &args.to_string() (parsed), while seen_calls at lines 791 and 807 still passes &tc.arguments_json (raw). I confirmed against the compiled serde_json that these diverge on exactly the empty-args class the fix was written for:

raw=""     seen_calls=""     guard="{}"   agree=false
raw="   "  seen_calls="   "  guard="{}"   agree=false

So the two detectors do now disagree about what "the same call" means — just in the opposite direction from before, and harmlessly. The per-turn detector is a loop-breaker, not a correctness mechanism; treating "" and "" as equal within a turn is still correct behaviour for it, and the divergence only means an empty-args call is grouped slightly differently between the two. No behavioural defect here — I checked. But the comment now claims a property the code stopped providing, in a file where the sharing of this function is the stated design rationale.

Cheapest honest fix is to have seen_calls derive from the parsed args too, which would restore the claim literally and cost nothing (the loop-breaker is indifferent). Failing that, narrow the comment to say the two share the normalisation, not the input.

Engineering principle: when a comment states an invariant as the justification for a design, changing the code without changing the comment converts documentation into a false claim — more harmful than no comment, because it is load-bearing for the next reader's reasoning.


🟢 Suggestion: WriteSemantics::Read's doc says "does not change state"; on first read of a stale node, that is literally false

📁 packages/agent/src/local_agent/tools.rs:987-988

Auditing the six Read classifications, I found none of them mutates user-visible graph content — the classification is correct for every purpose this enum serves, and I am not asking for it to change. Worth recording one nuance, though: NodeService::get_node (packages/core/src/services/node_service/crud.rs:529-564) and query_nodes (query.rs:90, :317) both call apply_lazy_migration, which does persist:

// packages/core/src/services/node_service/crud.rs:1829-1839
let update = NodeUpdate { properties: Some(migrated_node.properties.clone()), ..Default::default() };
self.store.update_node(&node.id, update, self.client_id.clone()).await

So get_node, search_nodes, search_semantic, get_related_nodes and search_skills can all write on first read of a node whose _schema_version lags its schema. It is convergent and self-extinguishing (fires only while current_version < target_version, crud.rs:1820; the write makes them equal), so a second read is a genuine no-op — which is why Read remains the right classification and the guard should not care.

I also chased the embed-and-persist concern specifically, since a lazily-generated-and-stored embedding would be a state change: it is clean. EmbeddingService::semantic_search (embedding_service.rs:660) generates the query vector into a local, passes it to store.search_embeddings, and drops it. Nodes without embeddings fall back to BM25-only rather than being embedded on the read path.

Suggest the doc line read "does not change user-visible graph state" rather than "does not change state" — one word, and it keeps the next person from having to redo this audit to convince themselves.


🟢 Nit: the || name == "create_relationship" escape hatch is legitimate, but names the exception where it could test it

📁 packages/daemon/src/services/local_agent_service.rs:2411-2416

The brief asks whether this weakens the test into something that would not catch a real regression. It does not: create_relationship genuinely has no single describing argument, and completed_writes_from renders it from its own fields instead (local_agent_service.rs, the None if r.name == "create_relationship" arm producing "{from} -[{type}]-> {to}"). The escape hatch mirrors a real second code path rather than papering over a gap, and the test still has teeth for every other guarded tool: adding a DuplicableWrite variant without a write_summary_arg entry fails it.

The residual weakness is narrow. If someone deleted the create_relationship rendering arm in completed_writes_from, the test would still pass — it asserts the exception by name rather than asserting that the exception's alternative path exists. Tightening it would mean asserting against completed_writes_from output for a synthetic relationship record instead of against write_summary_arg alone, which is a bigger test than this invariant warrants. Fine as-is; flagging so the boundary of what it pins is understood.

Nit: the string literal "create_relationship" here duplicates knowledge that Tool::CreateRelationship.name() already owns — in a test whose whole point is that names come from the registry. name == Tool::CreateRelationship.name() reads consistently with the loop above it.


CLAUDE.md Compliance

Clean. I scanned the delta specifically: no lint suppression, no #[allow(dead_code)], no #[deprecated], no backward-compat shims or transition language, no docs/ additions. No issue or PR numbers appear in code or doc comments — the references live in the commit message, which is where the standard permits them. cargo clippy -p nodespace-agent -p nodespace-daemon --all-targets is warning-free. The deleted is_write_tool in the daemon and the deleted is_cross_turn_guarded_tool in agent_loop.rs were removed outright rather than deprecated, as the standard requires.

Visibility widening (Tool::name / Tool::from_name, pub(crate) → pub): justified and coherent. Tool and Tool::ALL were already pub, so the type and its enumeration were public while the only two operations that make them useful were not — the widening removes an inconsistency rather than creating exposure. The daemon test consumes both. definition() and humanized() correctly stay pub(crate), so the widening is minimal rather than blanket. is_write_tool / is_cross_turn_guarded_tool as pub free functions alongside the pub methods is a reasonable shape: the methods are the typed API, the free functions are the wire-name adapter for callers holding a String from the model. I would not ask for a change.


Recommendation

COMMENT — the delta is a clear net improvement and I would not block on it.

Both 🟡s from the initial review are properly resolved, and resolved in the stronger of the available ways: the empty-args fix makes the guard's central equality structurally sound (both sides are now literally canonical_args(&value.to_string()) applied to the same Value), and the registry consolidation replaces three hand-maintained lists with one compiler-enforced classifier, which I verified has real teeth. The deletion of the daemon's parallel is_write_tool is the part I like most — that list existing at all was the original sin.

The one thing I would like addressed before merge is the update_schema misclassification, and specifically the doc comment, not necessarily the behaviour. The guard's actual behaviour toward update_schema is unchanged and defensible; what is new is a source-of-truth type asserting an idempotency property that handle_update_schema demonstrably does not have for add_fields, add_relationships, or rename_fields. Either narrowing that comment or adding a fourth variant is a few minutes' work, and leaving it means the registry — whose entire value proposition is being the one place this question is answered — answers it wrongly.

Everything else here is optional. The four deferred 🟢s from the initial review remain correctly deferred; none was made more urgent by this delta.

🤖 Generated with Claude Code

@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 above: COMMENT. Both 🟡 findings from the initial review are properly resolved — I mutation-tested the empty-args fix (reverting it fails exactly one test, 315 pass) and verified the registry has real compile-time teeth (probe variant → 5 E0004 errors). One new 🟡 worth addressing before merge: Tool::UpdateSchema is classified IdempotentWrite, but handle_update_schema hard-errors on a repeat of add_fields/add_relationships/rename_fields — the guarded behaviour is unchanged and fine, but the new source-of-truth enum now documents an idempotency property that does not hold. No blockers.

…mpleteness compiler-enforced

update_schema was classified IdempotentWrite with a comment claiming a
repeat is a no-op. It is not: a repeated add_fields rejects the field as
already present, add_relationships likewise, and rename_fields fails
because the source name is gone. The registry exists to answer exactly
this question, so documenting a false property there is worse than not
documenting it.

Adds a SelfLimitingWrite variant for it. Deliberately not guarded: the
guard keys on whole-call arguments, and update_schema batches
independent edits, so a call repeating one applied rename alongside a
new field is not the same write yet would be refused wholesale. Refusing
a legitimate schema edit is worse than the error the schema layer
already returns for the redundant part.

Tool::ALL was itself hand-maintained, so a variant omitted from it was
invisible to everything derived from it — the previous commit's claim
that the lists can no longer drift was narrower than stated. ALL_IS_COMPLETE
now proves completeness at compile time: an exhaustive match pins each
variant to its index, and a count assertion catches a trailing omission
the index check cannot see. Verified both failure modes produce E0080.

Also corrects two doc comments the re-review found overstated: canonical_args
is shared for its normalisation rules but its two callers deliberately
pass different inputs, and WriteSemantics::Read means no user-visible
state change (reads may still persist convergent lazy migration).

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

malibio commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1790

Review Type: Re-Review (third round, delta 22ee27fc..1a59c11f)

Previous Review Summary

Round 2 posted COMMENT with 1 🟡 Important and 3 🟢 Suggestions (carrying 4 deferred 🟢s from round 1).

# Finding Severity Status
R2-1 UpdateSchema classified IdempotentWrite, but a repeat is a hard error 🟡 ✅ Addressed
R2-2 Tool::ALL is itself hand-maintained; drift tests vacuous one level up 🟢 ⚠️ Partially addressed — see 🟡 below
R2-3 canonical_args doc overstates the sharing it guarantees 🟢 ✅ Addressed
R2-4 WriteSemantics::Read doc says "does not change state" 🟢 ✅ Addressed
R2-5 create_relationship string literal duplicates Tool::…name() (Nit) 🟢 ⬜ Not addressed (deferred)
R1-3/4/5/6 Refusal wording, delete_node alias, 4096 cap, double-fetch 🟢 ×4 ⬜ Still correctly deferred

New issues found in this delta: 1 🟡, 1 🟢.


Verification I performed independently

The brief flagged that the first attempt at the ALL_IS_COMPLETE construct compiled clean while Tool::ALL was genuinely missing DeleteNode, and asked me not to take the corrected version at face value. I mutation-tested all six cases against a real compile rather than reasoning about them. Results:

Mutation Expected Actual
(a) Remove middle variant (UpdateTaskStatus) from ALL fail ✅ E0080: Tool::ALL lists a variant out of order
(b) Remove last variant (CreateNodesFromMarkdown) from ALL fail ✅ E0080: Tool::ALL is missing a variant
(c) Add new enum variant absent from ALL fail ❌ COMPILES CLEAN
(d) Reorder two ALL entries (CreateSchema/UpdateSchema) fail ✅ E0080: … out of order
(e) Release/optimized profile fires ✅ cargo check --release fails identically — const eval is profile-independent, assert! is not a debug artifact
(f) all_tool_definitions() always compiled yes ✅ No cfg/feature gating; called from 5 production sites in tools.rs (:1981, :2003, :2007, :2066) plus an integration test. Anchor is sound.

Case (c) is the one that matters, and it fails. Detail below in the 🟡 finding.

Other claims verified:

  • Behaviour diff across the delta, all 14 tools. I injected a matrix-dump test at both 22ee27fc and 1a59c11f and compared write_semantics / is_write / duplicate_is_destructive / is_write_tool / is_cross_turn_guarded_tool. Output is byte-identical across both commits for all 14 tools except the sem= label on update_schema (IdempotentWrite → SelfLimitingWrite). is_write=true, guarded=false, is_write_tool=true, is_cross_turn=false — all unchanged. Adding the variant changed classification vocabulary and nothing else. Confirmed as intended.
  • SelfLimitingWrite's doc claims are true. Read handle_update_schema end to end. add_fields (schema/mod.rs:689-701) and add_relationships (:714-726) both return Err(… "already exists" …) on a repeat; rename_fields runs in Phase 1 (:652-664) and fails on repeat because the source name is gone. The doc comment matches the handler.
  • canonical_args doc correction is accurate at HEAD. The two callers genuinely do pass different inputs: seen_calls passes raw &tc.arguments_json (agent_loop.rs:795, :811), the guard passes parsed &args.to_string() (:863). The corrected comment now describes this rather than claiming identical inputs. Claim holds.
  • No consumer breaks on the new variant. grep for WriteSemantics across all of packages/ returns hits only inside tools.rs. The two consumers are is_write() (!matches!(…, Read)) and duplicate_is_destructive() (matches!(…, DuplicableWrite)) — both matches!-based, so neither is an exhaustive match that a fourth variant could break. No external exhaustive match exists. Zero blast radius, confirmed rather than assumed.
  • Test/lint state. cargo test -p nodespace-agent: 316 passed, 0 failed. cargo test -p nodespace-daemon --lib local_agent_service: 22 passed, 0 failed. cargo clippy -p nodespace-agent -p nodespace-daemon --all-targets -- -D warnings: clean. The five acceptance-criteria tests (cross_turn_duplicate_write_is_not_executed, refused_duplicate_names_the_existing_node, idempotent_update_repeat_is_not_blocked, empty_arguments_compare_against_their_parsed_form, duplicate_tool_call_breaks_loop) all pass.
  • All mutations reverted. git status --porcelain is empty in both the worktree and the primary checkout; HEAD recompiles clean.

Requirements Check (issue #1787)

  • ✅ A repeated write with identical canonical args in a later turn does not execute a second time — unchanged by this delta; guard logic at agent_loop.rs:854-866 untouched. Verified by cross_turn_duplicate_write_is_not_executed.
  • ✅ The model receives an informative tool result naming the already-written node — unchanged; refused_duplicate_names_the_existing_node passes.
  • ✅ Legitimately idempotent repeats are not broken by the guard — this criterion is now better documented than at round 2. The round-2 ⚠️ was that WriteSemantics asserted an idempotency property update_schema does not have; that false assertion is now gone. update_node and update_task_status remain the only IdempotentWrite members and both genuinely converge.
  • ✅ A regression test covers the cross-turn duplicate at the execution layer — unchanged, still 13 guard tests plus the two registry-derived invariant tests.

All four criteria met.


Findings

🟡 Important: ALL_IS_COMPLETE does not catch the failure mode it was written to catch — a new variant omitted from Tool::ALL still compiles

📁 packages/agent/src/local_agent/tools.rs:872-911

This construct exists to answer round 2's 🟢: Tool::ALL is hand-maintained, so a DuplicableWrite variant left out of it would be silently unguarded and both drift tests would pass vacuously. The doc comment states the goal precisely:

"Completeness is compiler-enforced via Tool::ALL_IS_COMPLETE: a variant added to the enum but omitted here fails to build."

That statement is false. I added a 15th variant ProbeVariant with DuplicableWrite semantics, filled every exhaustive match it forced (name, definition, humanized, write_semantics, the executor dispatch, and the index match in ALL_IS_COMPLETE itself — giving it index 14), and deliberately left it out of Tool::ALL. Result:

$ cargo check -p nodespace-agent
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.35s
$ cargo test -p nodespace-agent --lib
test result: ok. 316 passed; 0 failed

Clean compile, and all 316 tests pass — including every_guarded_tool_is_also_recorded_as_a_write and every_guarded_tool_can_describe_what_it_wrote, both of which iterate Tool::ALL and therefore never see the missing tool. This is precisely the round-2 vacuity, unchanged.

Root cause: the 14 is a literal, and nothing forces it to move. The two mechanisms cover different things:

  • The index match is exhaustive, so a new variant forces an edit — but the edit it forces is adding Tool::ProbeVariant => 14, which is satisfied without touching ALL. The comment says the match "forces this number to be revisited"; it forces the match to be revisited, not the number.
  • The length assertion compares against a hardcoded 14. It catches a trailing deletion from ALL (case b, verified) because that shortens the list below a fixed target. It cannot catch an addition to the enum, because nothing on the right-hand side grew.

So the construct is genuinely load-bearing for reordering and for removal from ALL — cases (a), (b), (d) all fail to compile, and I confirmed each. What it does not cover is the direction that actually happens in practice: someone adds a tool. Adding a tool is the entire reason the check was requested.

There is a real fix, and it is local. Derive the count from the same exhaustive-match trick rather than a literal, via a successor chain:

const COUNT: usize = {
    let mut n = 0;
    let mut v = Tool::SearchNodes;
    loop {
        n += 1;
        v = match v {
            Tool::SearchNodes => Tool::ResolveQuery,
            // … one arm per variant, in order …
            Tool::DeleteNode => Tool::CreateNodesFromMarkdown,
            Tool::CreateNodesFromMarkdown => break,
        };
    }
    n
};
assert!(Self::ALL.len() == COUNT, "Tool::ALL is missing a variant …");

I implemented this against the branch and re-ran the probe. It compiles clean on unmodified HEAD, and with ProbeVariant added-but-omitted it fails:

error[E0080]: evaluation panicked: Tool::ALL is missing a variant — every variant must be listed
   --> packages/agent/src/local_agent/tools.rs:937:9
    |
938 |             Self::ALL.len() == COUNT,

Because the successor chain is exhaustive, a new variant must be threaded into it, and threading it in increments COUNT — the count can no longer be satisfied by an edit that ignores ALL. Cases (a), (b), (d) continue to fail as before. (std::mem::variant_count would be cleaner but is still nightly-only on the 1.94.1 toolchain this repo pins, and strum would be a new dependency — CLAUDE.md asks that new third-party deps be justified, and this does not warrant one.)

Alternative, if this feels like too much machinery for the payoff: delete ALL_IS_COMPLETE and narrow the doc comment on ALL to state the honest, still-valuable property — that a variant missing from ALL is unreachable from the wire (from_name iterates ALL), hence inert rather than dangerous, which is what round 2 concluded and explicitly said was not worth fixing here. What I would not merge is the current middle ground: a construct whose doc comment promises the one guarantee it does not deliver. The guard's correctness does not depend on this either way — is_cross_turn_guarded_tool resolves through from_name, so an unlisted tool cannot execute at all — so this is a documentation-integrity issue, not a live defect.

Engineering principle: a compile-time assertion is only as strong as the weakest link in what forces it to be re-evaluated. Pinning a derived fact to a literal makes the check self-satisfying under exactly the edit it was meant to police — and an assertion that carries a stronger claim than it enforces is worse than none, because it retires the reader's suspicion. This is the same class of error as the let () = … version the brief describes: both compiled clean while ALL was incomplete, and both would have been caught by the mutation test rather than by inspection.


🟢 Suggestion: SelfLimitingWrite is the right call, but "rejected by the tool's own validation" is broader than the handler guarantees

📁 packages/agent/src/local_agent/tools.rs:1006-1017, :1050-1053

The reclassification is correct and I would keep it. The reasoning in the arm comment is sound and I want to be explicit about why, since the brief asks:

The stated rationale — the guard keys on whole-call arguments while update_schema batches independent edits, so a call repeating one applied rename alongside a new field is not the same write yet would be refused wholesale — is exactly right, and it is not hypothetical. rename_fields, add_fields, add_relationships, remove_fields, and remove_relationships are all independently optional parameters on the same call, and renames execute in Phase 1 before the add/remove phases (schema/mod.rs:652-664), so a partially-applied batch is reachable. Guarding on the whole argument blob would be the wrong granularity for a batch operation. Leaving it unguarded and letting the schema layer reject the redundant part is the correct trade: the failure mode of guarding is refusing legitimate work, the failure mode of not guarding is a clear error message on the redundant part only. Fail-open is right here.

Keeping is_write() == true is also correct and I verified the consequence: update_schema remains recorded as evidence (is_write_tool("update_schema") == true, unchanged across the delta), so the conversation record still shows the schema edit happened. That matters — evidence-recording and guarding are separate concerns, and only the latter should be narrow.

The one thing I would tighten is the variant doc, which generalises further than the audit supports:

"Changes state, and a repeat is rejected by the tool's own validation rather than converging or duplicating."

remove_fields and remove_relationships are fields.retain(…) (schema/mod.rs:681-685, :708-712) — a repeat removes nothing and succeeds. So a repeat of a remove-only update_schema call converges; it is not rejected. The arm comment above is careful and accurate (it names add_fields/add_relationships/rename_fields specifically), but the variant doc drops that qualification and states rejection as the defining property of the category. Since the whole point of the round-2 finding was that a variant's doc comment is a contract a future reader relies on, the same standard applies to the new one.

Suggest something like: "Changes state, and a repeat is either rejected by the tool's own validation or is a no-op — never a second copy. Not guarded: the tool handles the redundant work itself, and the call may batch independent edits that should not be refused wholesale." That covers both the reject path and the retain path, and folds in the batching rationale that is the actual reason for not guarding.

Engineering principle: a category's doc should describe the boundary of the category, not just its most salient member. Where the arm comment and the variant comment disagree in scope, the reader trusts the one attached to the type.


CLAUDE.md Compliance

Clean. Scanned the delta specifically: no lint suppression, no #[allow(dead_code)], no #[deprecated], no backward-compat or transition language, no docs/ additions, no .md files added. No issue or PR numbers in code or doc comments — the references live in the commit message, which the standard permits. cargo clippy … -D warnings is clean on both crates. The const _: () = … form is the correct idiom for forcing const evaluation (the brief's let () = … predecessor genuinely does not force it — I confirmed the corrected form fires in cases a/b/d/e).


Recommendation

COMMENT — net positive, and I would not block merge on it.

Three of the four round-2 items are cleanly resolved, and two of them (canonical_args, WriteSemantics::Read) I verified are now literally true rather than approximately true. The update_schema reclassification is the substantive win: the registry no longer asserts an idempotency property that handle_update_schema demonstrably lacks, the behaviour matrix confirms zero behavioural change across all 14 tools, and the decision to leave it unguarded is well-reasoned and correctly fail-open for a batch operation.

The ALL_IS_COMPLETE construct is where I would ask for one more pass. It is not broken — it has real teeth against reordering and against removal from ALL, which I verified — but it does not catch a variant added to the enum and omitted from ALL, which is both the failure mode it was written for and the one that occurs in practice. The hardcoded 14 is satisfied by the very edit it is supposed to police. Either derive the count from the successor chain (verified working, ~15 lines, no new dependency) or delete the construct and keep the honest narrower claim round 2 landed on. Shipping it as-is means the codebase carries a comment asserting compiler-enforced completeness that a future author will reasonably trust and that will not hold.

Worth saying plainly: this is the second time this construct has passed self-verification while being wrong in the same direction. That is not a criticism of the fix — it is an argument that this specific check should not be trusted without a mutation test, and that the mutation test (add a variant, omit it from ALL, compile) is cheap enough to be the standing acceptance criterion for it.

Everything else — the deferred 🟢s from rounds 1 and 2 — remains correctly deferred; none was made more urgent by this delta.

🤖 Generated with Claude Code

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

Third-round re-review posted above: COMMENT. The update_schema reclassification is correct and I verified it is behaviourally inert (matrix diff across all 14 tools: only the sem= label changed). Both doc corrections are now literally true. One 🟡: ALL_IS_COMPLETE does not catch the case it was written for — I added a 15th variant with DuplicableWrite semantics, filled every exhaustive match, omitted it from Tool::ALL, and it compiles clean with all 316 tests passing. The hardcoded 14 is satisfied by the same edit it is meant to police. Cases (a) middle-removal, (b) trailing-removal, (d) reorder, (e) release profile all correctly fail — so the construct has real teeth, just not against additions. A successor-chain-derived COUNT fixes it (verified working, no new dependency); deleting the construct and narrowing the comment is an equally acceptable resolution. Not a live defect — an unlisted tool is unreachable via from_name — so this is documentation integrity, not correctness. All four acceptance criteria met. All mutations reverted; tree clean.

malibio and others added 2 commits July 29, 2026 02:16
…ten for

The check compared Tool::ALL.len() against the literal 14, which is
satisfied by exactly the edit it was meant to police. Adding a variant
forces an edit to the exhaustive index match — Tool::NewThing => 14 —
and nothing about that edit touches ALL or moves the literal. Verified:
a 15th variant with DuplicableWrite semantics, absent from ALL, compiled
clean and passed all 316 tests including both registry drift tests.

The count is now derived from Tool::COUNT, itself an exhaustive successor
chain, so a new variant must be threaded through it and threading it in
increments the count. mem::variant_count would say this directly but is
nightly-only, and strum does not earn a dependency for one assertion.

Verified by mutation, not inspection: a new variant omitted from ALL now
fails with E0080, and removal of a middle entry, removal of the last
entry, and reordering two entries all still fail. Clean on unmodified
HEAD in both dev and release profiles.

This construct has now been wrong twice in the same direction while
passing inspection, so the doc comment states the mutation test as its
standing acceptance criterion rather than describing the mechanism alone.

Also narrows the SelfLimitingWrite doc, which defined the category as
'rejected by the tool's own validation'. remove_fields and
remove_relationships are retain() calls, so a repeated remove converges
instead of being rejected — both paths now stated, along with the
batching rationale for leaving the category unguarded.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HkymyKtLHm5NcNbf2CjrT9
Resolves an import-block conflict in local_agent_service.rs: main added
ChatModelSpec (#1791) while this branch added PriorWrite and the
agent_loop imports for the duplicate-write guard. Both are needed, so
the resolution is the union of the two import lists.

No logic conflict. The SelfLimitingWrite doc's claims about
handle_update_schema were re-verified against the merged schema/mod.rs
(#1788 touched that file): adds still error on an existing name, removes
are still retain() calls that converge.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HkymyKtLHm5NcNbf2CjrT9
@malibio
malibio merged commit b17c931 into main Jul 29, 2026
2 checks passed
@malibio
malibio deleted the issue-1787-deterministic-write-guard branch July 29, 2026 01:09
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.

Deterministic cross-turn duplicate-write guard: make the persisted completed_writes enforceable, not advisory

1 participant