Skip to content

Add the entity-resolution tier, and the measurement that shows it works - #2856

Merged
malibio merged 7 commits into
mainfrom
issue-2841-entity-tier
Sep 22, 2026
Merged

malibio merged 7 commits into
mainfrom
issue-2841-entity-tier

Conversation

@malibio

@malibio malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator

Completes the entity tier for #2841. The FTS5 index landed separately in #2845; this is the resolution step that uses it, plus the measurement apparatus needed to tell whether it works.

The three-tier context is now complete

A turn's prompt carries three tiers. Two already shipped — schemas+relationships and skills/tools, both bounded deterministic retrieval rendered as fact. Entities were the missing top tier, and this adds it following the same shape rather than inventing a parallel mechanism.

The failure it removes: a turn naming a node the graph contains stalled asking the user for an id.

"I need a Node ID to update the capacity for Northwind Trading."

Retrieval matched the message against type-level text only, so an instance name was just tokens.

Measured results

3 reps, gemma-4-e4b-q4km, purged database between reps. Zero variance — every scenario passed 3/3 or failed 0/3.

Category Result
pass^3 7/9
Skill routing 3/3
Operation selection 21/22
Instance-vs-type boundary 3/3
Entity resolution 2/4
ADR-056 known failures 2/2
Flipped (unstable) 0/9

Four scenarios went from failing every rep to passing every rep, including op-read-then-write (an ADR-056 recorded failure) and schema-shared-name-signed — "When did we sign Northwind?", one of the three prompts this issue was filed on.

These numbers are a new baseline, not a delta against the recorded 5/8. The workspace, chat structure and scoring categories all differ. Three variables also moved together — the tier, the tool-schema wording, and group isolation — so the aggregate is attributable but the individual contributions are not.

What made the measurement possible

The decision fixture could not measure this at all, for two structural reasons. Three full 3-rep runs were spent discovering them, each looking like a model result rather than a harness one.

Scenarios shared one chat. All of them sat in a single group, and a group is one conversation. A measured run recorded toolsCalled: [] for every scenario after the fourth — including ones unrelated to this work that pass in isolation. That is conversation length being scored as decision quality. Each scenario now gets its own group.

Instances could not be seeded. The fixture's setup turns create TYPES; entity resolution needs a named NODE. Seeding was not expressible: seedGroup fires inside the group loop, and --between-runs wipes the database between reps, so the first group of every rep saw a workspace whose types its own setup turns had not created yet. A seed hung there silently no-ops.

So this adds EvalFixture.seedRun — once per rep, after the wipe and the gate, before any group. That is the only point where "every scenario in this rep has the instance" is expressible. The hook is general; any fixture acting on named instances needs it.

Verified against a genuinely cold database, not the warm one an earlier attempt checked against — which is why that attempt passed its checks and still measured nothing.

Precision calibration

The cutoff was calibrated against a probe of the landed index (8 entities plus 5 decoys carrying a real message's noise words):

-6.53  Northwind Trading                the intended entity
-3.27  Northwind Logistics              a real sibling entity
-2.13  Trading terms for new customers  a noise-word decoy

The factor was 0.55, putting the bar at -3.59 — which dropped the sibling, collapsing exactly the ambiguity "render all candidates" exists to preserve. Now 0.45 (bar -2.94): sibling survives, decoy excluded. Pinned by a test verified to fail at the old value.

Relative rather than absolute despite the probe suggesting a band near -2.5 to -3.0: bm25 is corpus-dependent, so a raw threshold calibrated on 51 rows would drift as the workspace grows.

Design decisions

  • Cap + relative cutoff, not unique-match. Unique-match goes silent exactly when the tier is most needed: a name resolving to two nodes of different types is the case the turn most needs to see.
  • Runs in build_workspace_context, which the daemon already calls before the session reaches Stage 1 — so no relocation of context assembly was needed.
  • Three-state output. "Resolved to nothing" means CREATE and renders explicitly; "did not run" renders nothing. Collapsing those reintroduces the ambiguity the tier removes.
  • Name + type + id. Withholding the id would preserve the exact failure being fixed.

A tool bug found while verifying

Asked "when did we sign Northwind?", the model resolved the entity correctly — it produced node_type and the full stored title from the tier — then failed on the filter it attached:

{"operator": "equals", "property": "signed_date", "value": null}

That is projection expressed as a filter. The schema now states that filters never select fields, and QueryService no longer rejects with a bare "Missing value". Also deletes an unreachable Some(Value::Null) arm — value is Option<Value>, so serde folds JSON null into None.

Measured effect: the model now omits value rather than sending null. It still does not retry, so this narrows the failure rather than removing it.

Two known gaps, both deliberate

schema-on-menu-company fails, and is left asserting the wanted behaviour rather than blessing the observed one. "Add X" when X exists produces a silent duplicate. This is NOT missing instruction: guidance prose, the create_node tool description, and both together all produced the duplicate with the entity rendered and route_clarify on the menu. ADR-064 measured the tool-schema channel at 100% where prose reached 87.5%, and it moved this not at all — "do not take the obvious action when a condition holds" appears harder than the output-shape constraints that measurement covered. Closing it needs a deterministic guard on the write path, filed separately.

Child nodes carry their own body text as a title and so enter the entity index. The cause is in the create path, not here — create_node_in_tx recomputes a title with rootness unknown, before the parent edge exists. Filed separately; pinned by a test that documents current behaviour and says to invert it when fixed.

Not in scope

Prevalence ("what fraction of real messages name a resolvable entity") stays deferred per the decision recorded on #2841: no legitimate corpus exists, and fixture prompts would invert the signal. The general-vs-special-case gate depends on it and stays open with it.

Verification

  • Full test:all via the pre-push gate: frontend 262 files, skill 95, scripts 565, full Rust suite
  • bun run quality:fix clean
  • Goldens regenerated and diffed by hand — only the intended lines moved
  • Every new test verified to fail without the code it pins

Part of #2841 — does not close it; the routing tiers and prevalence remain open.

🤖 Generated with Claude Code

malibio and others added 4 commits September 22, 2026 17:53
…#2841)

Completes the three-tier context the prompt carries. Two tiers already
shipped — schemas+relationships and skills/tools, both bounded
deterministic retrieval rendered as fact — and entities were the missing
top tier. This adds it following the same shape rather than inventing a
parallel mechanism.

The failure it removes: a turn naming a node the graph contains stalled
asking the user for an id ("I need a Node ID to update the capacity for
Northwind Trading"). Retrieval matched the message against type-level
text only, so an instance name was just tokens.

Resolution is a deterministic index lookup over the `node_title_fts`
index added earlier, with no model call and no generative pass — which is
what lets it run as a system step ahead of routing without spending a
turn, consistent with ADR-038 keeping retrieval out of the model's hands.

Runs inside `build_workspace_context`, which the daemon already calls
before the session reaches Stage 1, so a resolved entity is available to
constrain the decisions downstream. No relocation of context assembly was
needed.

Precision policy is cap + relative bm25 cutoff, not unique-match.
Unique-match goes silent exactly when the tier is most needed: a name
resolving to two nodes of different types is the case the turn most needs
to see. The cutoff is relative to the best score rather than absolute
because bm25 is corpus-dependent, so a fixed threshold that works on a
small workspace excludes everything on a large one.

The tier's output is three-state. "Resolved to nothing" means CREATE and
renders explicitly; "did not run" renders nothing at all. Collapsing
those would reintroduce the ambiguity the tier exists to remove.

Fixture: the three scenarios previously scored as schema-selection
failures are re-scored as entity-resolution cases, and a Northwind
INSTANCE is now seeded. Both setup turns created types only, so those
scenarios asked the agent to update and read a company that had never
existed — they could not have been resolution successes. A no-match
scenario is added so seeding does not lose that signal. Numbers from this
fixture are a NEW baseline, not a delta against the recorded 5/8: the
workspace differs, so the two are different experiments.

Known limitation, pinned rather than asserted away: child nodes currently
carry their own body text as a title and so enter the entity index. The
cause is in the create path, not here (#2849) — `create_node_in_tx`
recomputes a title with rootness unknown, before the parent edge exists.
They rank poorly and the cutoff drops them when a real entity is present,
so the tier degrades rather than breaks.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018ePBsnfpieijs3XGXWDBfo
Found while verifying the entity tier end to end. Asked "when did we sign
Northwind?", the model resolved the entity correctly — it produced
`node_type` and the full stored title from the tier — and then failed on
the filter it attached:

    {"operator": "equals", "property": "signed_date", "value": null}

That is projection expressed as a filter. Filters only narrow WHICH
nodes match; every matching node already comes back with all of its
properties, so the right call carried no filter at all.

Two changes, because the model's mistake was made easy and then punished
opaquely.

The tool schema now says what a filter is for. `value`'s description
states that it never selects fields, that matching nodes already include
every property, and that `exists` is the operator for "is this set at
all" — which the schema already offered but described only as
"Comparison operator". Measured effect: the model now omits `value`
entirely rather than sending null. It still does not retry after the
error, so this narrows the failure rather than removing it.

`QueryService` no longer rejects with a bare "Missing value". The
message names both real intents: drop the filter to read a property, or
use `exists` to test for one. The model demonstrably reads it — it
paraphrased the text back accurately in a manual turn.

Also deletes the `Some(Value::Null)` arm in `bind_json_value`. It was
unreachable from the wire: `QueryFilter::value` is `Option<Value>`, so
serde folds an explicit JSON null and an absent key into the same `None`.
Binding SQL NULL would have been wrong even if reached, since
`json_extract(...) = NULL` is never true and would match nothing rather
than finding unset fields. The clean build with no unreachable-pattern
warning confirms it was dead.

Test verified to fail against the old message. The `exists` half is
already covered by `test_property_filter_exists_status`.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_018ePBsnfpieijs3XGXWDBfo
The decision fixture could not measure the entity tier, for two reasons
that were both structural rather than incidental. Three full 3-rep runs
were spent discovering them, and each looked like a model result rather
than a harness one.

**Scenarios shared one chat.** `groups: [[...SETUP, ...FIXTURES]]` put
every scenario in a single group, and a group is one conversation. A
measured run recorded `toolsCalled: []` for every scenario after the
fourth — including `skill-instance-request`, which is unrelated to this
work and passes in isolation. That is conversation length being scored
as decision quality. Each scenario now gets its own group, so it starts
from a short conversation; the setup turns are cheap to repeat and
idempotent in effect.

**Instances could not be seeded.** The fixture's setup turns create
TYPES. Entity resolution needs a named NODE to resolve to, so the
scenarios were asking the agent to update and read a company that had
never existed — "When did we sign Northwind?" is only a sensible
question if Northwind exists.

Seeding it was not expressible with the hooks available. `seedGroup`
fires inside the group loop, and `--between-runs` wipes the database
between reps, so the first group of every rep sees a workspace whose
types its own setup turns have not created yet. A seed hung there finds
nothing and silently no-ops — every scenario then scores against a
workspace with no instance in it, invisibly.

So this adds `EvalFixture.seedRun`: once per rep, after the between-runs
wipe and after the preflight gate, before any group. That is the only
point at which "every scenario in this rep has the instance" can be
stated. The hook is general; any fixture whose scenarios act on named
instances needs it rather than `seedGroup`.

Verified against a genuinely COLD database — zero non-core schemas, the
state a rep actually starts from — rather than the warm one an earlier
attempt was checked against, which is why that attempt passed its checks
and still measured nothing. Confirmed through the runner: the instance
was present with zero turns run, and again after the rep-2 wipe.

Also re-scores the three scenarios that were filed as schema-selection
failures. They are entity-resolution cases: the model never reached a
choice among the candidates on offer, it could not get from "Northwind"
to a node id and deferred. Scoring that as a bad schema pick attributes a
lookup failure to a judgment the model never made. A no-match scenario is
added so seeding does not lose the "resolved to nothing means create"
signal, and the summary gains an `Entity resolution` line.

Five fixture-assembly invariants are pinned in decisions.test.ts,
including that seeding stays run-scoped — moving it back to `seedGroup`
now fails the build rather than silently measuring an empty workspace.

Numbers from this fixture are a NEW baseline, not a delta against the
recorded 5/8: the workspace, the chat structure and the scoring
categories all differ.

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

Three things, all from measuring the tier rather than reasoning about it.

**Cutoff calibrated against a probe of the landed index.** A seeded
workspace of 8 entities plus 5 decoys carrying a real message's noise
words scored "Northwind Trading" as:

    -6.53  Northwind Trading               the intended entity
    -3.27  Northwind Logistics             a real sibling entity
    -2.13  Trading terms for new customers a noise-word decoy

The factor was 0.55, putting the bar at -3.59 — which dropped the
sibling. That collapses exactly the ambiguity "render all candidates"
was chosen to preserve: a partial name legitimately matching two
entities is the case the tier exists to surface, not one to resolve
silently. 0.45 puts the bar at -2.94, keeping the sibling and excluding
the decoy. Pinned by a test that fails at the old factor.

Relative rather than absolute despite the probe suggesting an absolute
band near -2.5 to -3.0: bm25 is corpus-dependent, so a raw threshold
calibrated on 51 indexed rows would drift as the workspace grows. The
probe calibrates the factor, not the score.

**`route_clarify` added to Node Creation's whitelist**, with guidance for
the already-exists case. "Add X" when X is already in the graph is
ambiguous — a second distinct record is a real thing to want — so the
turn should hand the choice back rather than guess. The tool was
previously unreachable from this skill, so the model had no way to ask
even if it wanted to.

This does NOT fix the behaviour, and the commit does not claim it does.
Measured on the locked model with the entity rendered and the tool on
the menu: guidance prose, the `create_node` tool description, and both
together all still produced `create_node` and a silent duplicate. The
middle result is worth recording — ADR-064 measured the tool-schema
channel at 100% compliance where prose reached 87.5%, and it moved this
not at all. "Do not take the obvious action when a condition holds"
appears to be a harder ask than the output-shape constraints that
measurement covered. Closing it needs a deterministic guard on the write
path, tracked separately. The guidance and whitelist are kept because
they are correct regardless: the tool should be reachable.

**Fixture fix, not a weakening.** `schema-field-disambiguates` asserted a
schema decision on a turn that correctly calls `update_node` — which
takes a node id and records no schema decision, so the assertion could
not pass however well the model reasoned. It now scores the operation,
which is what the scenario can actually observe.

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

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review Type: Initial Review (no prior reviews on this PR)

This is strong, well-argued work. The three-tier framing is right, the mechanism follows the two shipped tiers rather than inventing a parallel one, the three-state output is a genuinely good design call, and the commit messages are unusually honest about what was measured versus what was reasoned. Test quality is high: I reverted ENTITY_SCORE_CUTOFF_FACTOR to 0.55 and the cutoff test failed with exactly the message it promises; I reverted groups/seedRun in decisions.ts and both corresponding invariants in decisions.test.ts failed. The claims hold.

However, I found one blocking defect that I believe invalidates the PR's headline measurement.

resolve_entities is fed the blended retrieval query (up to 2 prior conversational turns, prepended before the current message), while resolve_entities_by_title keeps only the first 6 non-stop-word tokens. On any turn that is not the first in a conversation, the prior turns consume the token budget and the entity named in the current message is truncated away entirely. The tier then reports NoMatch, which renders a positive assertion that the named thing does not exist.

I verified this against a real database using the exact prior turns the eval's own per-scenario groups produce. All three entity scenarios resolve to nothing.


Requirements Check (against the AMENDED criteria)

Reviewed against the criteria as amended by the issue comments, not the issue body.

Criterion Status
FTS5 title index, separate table, null-skipping triggers ✅ Landed in #2845, not in scope here
Offline sizing measurement — struck, replaced by a precision check ✅ Correctly treated as struck. The precision check was run and recorded on the issue (2026-09-22T15:50:40Z), and the numbers it produced are what calibrate ENTITY_SCORE_CUTOFF_FACTOR. The PR does not pretend the sizing was done.
General-vs-special-case decision — deferred pending real traffic ✅ Correctly left open and said so under "Not in scope"
Entity resolution runs as a deterministic system step before Stage-1 routing, consistent with ADR-038 ⚠️ Structurally yes — it runs in build_workspace_context, upstream of routing, with no model call. Functionally compromised by 🔴-1: on a multi-turn conversation it resolves nothing.
The three failing scenarios re-scored as entity-resolution cases ✅ Done, plus a fourth no-match scenario. The re-scoring rationale (scoring a lookup failure as a schema judgment the model never made) is correct.
test:all passes, quality:fix clean ✅ Verified independently: 1636 core lib tests, 9 entity_resolution_test tests, 565 scripts tests all pass; no lint suppression, no #[allow(dead_code)], no #[deprecated], no migration code, no raw console.* in production TS, Bun-only.

Code Review Findings

🔴 Critical

📁 packages/core/src/ops/context_ops.rs:452-465 (and packages/core/src/db/sqlite_store/nodes.rs:3705-3712) — the blended retrieval query starves the entity out of its own token budget, and the tier then asserts the entity does not exist.

build_workspace_context's query is not the user's message. The daemon passes schema_retrieval_query(&prior_history, &user_message) (local_agent_service.rs:775), which is build_retrieval_query — and that function prepends the last 2 conversational turns before the current message, each capped at 400 chars:

let mut parts: Vec<&str> = recent.into_iter().rev().collect();
if !current.is_empty() { parts.push(current); }   // current message goes LAST
parts.join("\n")

resolve_entities_by_title then applies .take(ENTITY_RESOLUTION_MAX_TOKENS) — 6 tokens, taken from the front. Two prior turns of ordinary prose supply well over 6 non-stop-word tokens, so the current message contributes nothing to the FTS query.

Verified empirically against a real DB, seeding Northwind Trading through NodeService and calling build_retrieval_query with the two turns the eval's own groups produce (setup-venue's prompt and a plausible assistant reply):

msg="Add Northwind Trading to the companies we sell to."   resolved=false  titles=[]
msg="When did we sign Northwind?"                          resolved=false  titles=[]
msg="Northwind can seat 200 people now."                   resolved=false  titles=[]

A minimal case with a single prior turn is enough to break it:

blended = "Show me every invoice Contoso sent last quarter please\nAdd Northwind Trading"
  -> []
bare    = "Add Northwind Trading"
  -> ["Northwind Trading"]

Two consequences, and the second is worse than the first:

  1. The tier is inert on every turn but the first. The motivating failure ("I need a Node ID to update the capacity for Northwind Trading") arises in conversation, which is exactly where this does not fire.

  2. It does not fail silent — it asserts the opposite fact. Empty candidates take the NoMatch branch, which renders:

    MENTIONED ENTITIES: none found — anything named in this message does not exist yet.

    The design correctly identifies that conflating no-match with not-run is dangerous. This is that danger realised from the other side: a lookup that could not see the name is reported as a confirmed absence, and the prompt instructs the model to treat that as CREATE. create_node's new description reinforces it: "Only 'MENTIONED ENTITIES: none found' … means this tool is right." So a truncation bug is laundered into a positive instruction to duplicate the user's data.

This changes how the PR's own results should be read. schema-on-menu-company producing create_node and a silent duplicate on 3/3 reps is attributed in the commit message and the PR body to channel authority — "ADR-064 measured the tool-schema channel at 100% … and it moved this not at all. 'Do not take the obvious action when a condition holds' appears to be a harder ask." That inference requires the entity to have been rendered. Under the blend above it was not; the model was told none found and did precisely what every channel instructed. The measured 2/4 on Entity resolution, and the conclusion that closing the gap "needs a deterministic guard on the write path", both rest on that premise.

To be fair to the PR: I cannot rerun the eval to prove the counterfactual, and the commit does say the entity was "rendered" during manual verification — a single-turn manual probe would indeed have rendered it, which is consistent with both the manual observation and the eval result. That is the shape of the confound, not a contradiction.

Suggested direction (for the author to weigh — I am not prescribing the shape):

  • Pass the current message to resolve_entities, separately from the blended embedding query. The blend exists because embedding recall needs pronoun antecedents; a lexical name lookup does not have that problem, and the current message is where the entity is named. This looks like the smallest correct change and build_workspace_context already has both strings available at the call site.
  • If blending is genuinely wanted, take tokens from the end (or raise/remove the cap for this path) so the current message is never the part dropped.
  • Whichever route: add a regression test with a non-empty prior turn. Every existing test calls resolve_entities_by_title with a bare message, which is why none of them caught this. That gap is the generalisable lesson — the unit under test was exercised with an input shape its only production caller never produces.

🟡 Improvements

📁 packages/core/tests/entity_resolution_test.rs:200 — the pinned-bug test's name asserts the opposite of its assertion.

a_body_node_mentioning_the_name_is_not_an_entity asserts hits.len() == 1 — that the body node is resolved. Pinning the bug is the right call here (I agree with it: the fix lives in the create path with a real blast radius, the tier degrades rather than breaks, and an inverted test is the cleanest tripwire for the fix landing). The doc comment is excellent and genuinely prevents a future reader from "fixing" it by weakening the assertion.

But the name is the one thing a reader sees in test output, and it states the wanted behaviour while the body pins the unwanted one. A cargo test line reading a_body_node_mentioning_the_name_is_not_an_entity ... ok communicates the exact opposite of what is true. Suggest a_body_node_is_currently_resolved_as_an_entity_bug or similar — something whose passing reads as "the bug is still here." The doc comment can keep the full story.

Also: the comment references #2849 for the create-path cause, but CLAUDE.md's documentation standard is "Do not embed GitHub issue numbers in documentation content or code comments — describe the behavior/constraint directly." The commit message (process) is fine; the code comment should describe the constraint without the number. The same comment already describes the mechanism precisely enough (create_node_in_tx recomputing title with rootness unknown) that the number adds nothing a reader needs.

📁 scripts/eval/fixtures/decisions.ts:150-160, 178-196 — doc comments reference seedGroup for a mechanism that is now seedRun.

SEEDED_COMPANY_TITLE's comment says "Seeded through seedGroup rather than as a scored setup TURN", and seedNorthwind's says "--runs shares one database across reps and calls seedGroup on every rep." Both are stale — the seed is seedRun, and the second claim is now wrong in a load-bearing way (--between-runs wipes the database between reps; that is the entire premise of the seedRun hook this PR adds). The idempotency rationale stated there is still correct, just for a different reason (a warm rep without --between-runs). Worth fixing because this is precisely the kind of comment drift that cost three measured runs the first time.

Minor along the same lines: those blocks use /// rather than /** */. In TypeScript /// is a plain comment, so the prose does not reach editor hovers. Cosmetic, but these comments are clearly written to be read.

📁 packages/core/src/ops/context_ops.rs:707-718 — the header can be emitted with zero entity lines.

If out.len() + header.len() <= max_chars passes but the first entity line does not fit, the block renders MENTIONED ENTITIES (already resolved — use these ids directly, do not ask for one): followed by nothing. An empty list under a header that promises resolved ids is a third rendering the three-state design does not account for, and it is closer in meaning to NoMatch than to Resolved.

This mirrors the pre-existing EXISTING_SCHEMAS_HEADER pattern, so it is not a regression — but this tier's semantics are what make it matter. Buffering the lines and emitting the header only if at least one fits would close it. Low likelihood at max_chars: 4000; noting it because the tier is unbounded and the PR's own reasoning says this is the one tier that can flood.

📁 packages/core/src/db/sqlite_store/nodes.rs:3706 — ENTITY_RESOLUTION_MAX_TOKENS = 6 is asserted, not derived.

Given how central this constant turns out to be (🔴-1), its doc comment is thinner than the neighbouring ENTITY_SCORE_CUTOFF_FACTOR, which is calibrated against a measured probe and pinned by a test. 6 is stated as "bound a long message to a fixed query cost" with no measurement behind the specific number and no test pinning it. Worth either a probe (does 6 vs 10 change precision on the seeded workspace?) or an explicit note that it was chosen conservatively. Related: the constant's own comment says it "may want to diverge" from BM25_MAX_TOKENS — it already differs (6 vs 4), so a word on why 6 rather than 4 would help.


🟢 Nitpicks

Nit: 📁 packages/core/src/ops/context_ops.rs:475 — the debug log fires only on the Resolved path. NoMatch logs nothing, so a turn where resolution ran and found nothing is indistinguishable in the logs from one where it never ran — the exact collapse the type system is carefully designed to prevent. Given 🔴-1, a tracing::debug! on NoMatch carrying the query would likely have surfaced the truncation much earlier.

Nit: 📁 packages/core/src/ops/context_ops.rs:468 — bar assumes best < 0. FTS5's bm25() is negative in practice, so this holds today, and the tests pin the arithmetic. But if best were ever 0.0, bar would be 0.0 and the filter score <= 0.0 would admit every candidate rather than none. A debug_assert!(best < 0.0) would make the invariant the whole comparison rests on explicit rather than documentary. Genuinely defensive — flagging it only because the sign convention is the single most easily-inverted thing in this file.

Nit: 📁 packages/agent/src/local_agent/tools.rs:901-905 — create_node's description now carries a ~60-word conditional prologue ahead of its actual contract, and it is on every Stage-2 prompt for this skill regardless of whether any entity resolved. The PR's own measurement says this channel moved the behaviour "not at all" for this case. Keeping it is defensible (it is correct guidance, and the whitelist change is right independent of it), but it is worth noting the cost — prompt real estate spent on a rule that was measured not to work, which the model reads on every create. I would not block on this; re-evaluating it after 🔴-1 is fixed seems more informative than either keeping or cutting it now, since the measurement it was judged against is confounded.

Nit: 📁 packages/core/src/ops/context_ops.rs:1770 — entity_tier_respects_the_char_budget passes trivially. With max_chars = RESOLVED_ENTITIES_HEADER.len() + 40, the header (+2 newlines) fits and the first entity line does not, so the assertion out.len() <= max_chars is satisfied by the break. It never exercises the case it is named for: several entities where some fit and the rest are truncated. A budget sized to admit exactly one of the two would test the boundary and, incidentally, would have surfaced the empty-header case above.


Commit Separation

Coherent and well-separated. Each of the four is independently revertible and independently reviewable, and the mechanical/behavioural split is respected:

  • 7e1bc858 — the tier (store + ops + tests + goldens). Atomic.
  • 792335e9 — the search_nodes filter/projection fix. Genuinely independent of the tier; it happens to have been found while verifying the tier, which the commit message says plainly. Correct to split rather than fold in.
  • 10bb9201 — the harness. Correctly separated from the fixture semantics it enables.
  • f79f8db9 — calibration + whitelist + fixture fix. Three things, but all "from measuring the tier rather than reasoning about it", and the message says so. Acceptable.

Two small notes on 792335e9: deleting the Some(Value::Null) arm is correct — QueryFilter::value is Option<Value> and serde folds explicit null into None, so the arm was unreachable from the wire, and the commit's reasoning about json_extract(...) = NULL never being true is right. And route_clarify is not in removes_user_data_tool, so stage2_permitted_names is unaffected by the whitelist addition — the commit's safety claim about the destructive rung checks out.

Doc-Comment Accuracy

I checked the specific empirical claims rather than trusting them:

  • ADR-064's gradient — accurate. ADR-064 line 64: tool schema 100%, absent 62.5%, resident prose 87.5%. The doc comment's caveat that this was measured on output-shape constraints rather than conditional suppression is a fair and self-aware qualification.
  • ADR-064 rule 4 / the 100%-vs-0% resolution measurement — accurate (ADR-064 line 68).
  • The bm25 probe scores (-6.53 / -3.27 / -2.13) — consistent with the precision check recorded on the issue, and the arithmetic is right: 0.45 × -6.53 = -2.94, admitting -3.27 and excluding -2.13; 0.55 gives -3.59, which drops the sibling. Verified by reverting the constant and watching the test fail with that exact bar.
  • lifecycle_status != 'archived' — safe: the column is NOT NULL DEFAULT 'active' (schema.rs:31) and indexed (idx_node_lifecycle), so no three-valued-logic trap.
  • "Same tokenization and stop-word list as bm25_search_roots" — accurate, verbatim apart from the token cap.
  • SQL injection via the format!'d LIMIT — not exploitable. The only production caller passes ENTITY_CANDIDATE_LIMIT, a const i64; tests pass literals. It mirrors bm25_search_roots exactly, so it is consistent with the established pattern rather than a new risk. FTS MATCH is correctly bound as ?1, and the tokenizer strips " before quoting, so the MATCH expression cannot be escaped either.
  • Resolved(vec![]) unreachable — confirmed. resolve_entities is the only constructor and its kept.is_empty() branch returns NoMatch. The invariant is stated in the doc comment; it is not type-enforced (a NonEmpty wrapper would be), but the single construction site makes that proportionate.
  • seedRun placement — correct. It runs after runBetween and after gate() on rep > 1, and after the rep-1 gate that produced firstProvenance. A throwing seed calls abortOnEnvironment, which is the right failure mode: scoring scenarios against an unseeded workspace is exactly the invisible failure the hook exists to prevent, so failing loudly is correct. A fixture without seedRun is entirely unaffected (if (fixture.seedRun)).

Known-Gap Handling

schema-on-menu-company asserting the wanted behaviour rather than the observed one is the right call, and the in-fixture comment documents it thoroughly enough that a future reader will not weaken it. Blessing the observed duplicate would turn a known defect into a pinned requirement. Given 🔴-1, though, the stated cause of the gap needs revisiting — the comment's conclusion ("the cause is NOT missing instruction … tracked as a write-path guard") may be right, but the evidence offered for it is confounded.


Recommendation

REQUEST CHANGES

The design is sound and I would happily approve the shape of this. One blocking item:

  • 🔴-1 — the blended retrieval query starves the entity out of the 6-token budget, making the tier inert on every non-first turn and, worse, causing it to assert none found for entities that exist. Needs a fix and a regression test with a non-empty prior turn. Once fixed, the eval's Entity-resolution numbers and the "channel authority cannot move this" conclusion should be re-measured before being relied on — they may well hold, but they were measured under a confound.

The 🟡 items are worth addressing in the same pass (the stale seedGroup comments and the pinned-bug test's name are both cheap), and the 🟢 items are optional.

Everything else here is net-positive by a wide margin: the tier is the right mechanism in the right place, the three-state output is a genuinely good decision, the cutoff is calibrated against measurement rather than intuition and pinned by a test that I confirmed fails without it, and the seedRun hook fixes a real class of invisible harness failure. The honesty of the commit messages — particularly recording that the tool-schema channel did not work here, against ADR-064's expectation — is exactly the right instinct, and it is what made 🔴-1 findable.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

malibio and others added 2 commits September 22, 2026 21:08
…ookup (#2841)

Review found a blocking defect, and it invalidates part of this PR's own
headline measurement. Confirmed independently before fixing.

`build_workspace_context` received the BLENDED retrieval query — up to two
prior conversational turns prepended before the current message — and
`resolve_entities_by_title` kept only the first 6 non-stop-word tokens.
On any turn but the first, the prior turns consumed the whole budget:

    "Add Northwind Trading to the companies we sell to"
      bare  -> add northwind trading companies sell
      blend -> set up new type places hold        (the prior turn's opening)

The entity never reached the index. Worse than failing silent: empty
candidates take `NoMatch`, which renders "anything named in this message
does not exist yet" — a lookup that could not SEE the name reported as a
confirmed absence, and `create_node`'s description then cites exactly
that string as licence to create. A truncation laundered into an
instruction to duplicate user data.

Two fixes, because the blend was only half of it.

`build_workspace_context` now takes `entity_query` separately from
`query`. The blend exists for EMBEDDING recall of pronoun antecedents,
which a lexical name lookup does not need; the daemon has both strings at
the call site and passes the current message.

The resolver's token cap now keeps CAPITALISED tokens in preference
rather than the first N. Taking the first N was arbitrary — the budget
went to whatever the sentence opened with — and the regression test
proves the daemon fix alone was insufficient: a single long message
still truncated. This is the proper-noun bias as a SELECTION input, not
a pre-filter: a lowercase name is deprioritised, never dropped, and a
message with no capitalised tokens falls back to the plain order.
`a_partial_name_still_resolves` and `stop_words_alone_do_not_resolve`
both still pass, which is what distinguishes a bias from a filter.

`a_name_late_in_a_long_message_still_resolves` pins it. It failed against
the daemon fix alone, which is why the resolver changed too. Every
pre-existing test passed a bare message, which is why none caught this.

What this means for the measurement, stated plainly: the 2/4
Entity-resolution score and the conclusion that ADR-064 channel authority
could not move `schema-on-menu-company` both assumed the entity was
rendered. Under the blend it was not, on any scenario with a prior turn.
Those numbers need re-measuring before they are relied on; the single-turn
manual probes remain valid, since a bare message never hit the truncation.

Also from review: renamed the known-limitation test to say it pins a bug
rather than the wanted behaviour, and corrected two fixture comments that
still described `seedGroup` and claimed `--runs` shares one database
across reps — the exact comment drift that cost three measured runs.

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

The remaining review items, after the truncation blocker.

**A header with no entities under it.** `format_for_prompt` wrote the
header, then checked each line against the budget — so a budget that fit
the header but not the first line left a heading promising resolved ids
above nothing. That reads as a fourth state `EntityResolution` does not
have, and it is worse than rendering nothing: the model is told entities
were resolved and then shown none. Lines are now built before the header
is committed. Pinned by a test verified to fail against the old ordering.

**The budget test was passing trivially.** It exercised only the case
where the header fits and no line does, so the `break` satisfied it
without ever testing partial truncation. It now asserts that a budget one
line short renders the first entity and drops the second.

**`NoMatch` logged nothing.** The type distinguishes "ran and found
nothing" from "never ran"; the logs did not, so a resolver failing to see
the entity looked exactly like one correctly reporting absence. That is
how the truncation went unnoticed through three measured runs. Both
NoMatch paths now log, the cutoff one with the candidate count.

**`ENTITY_RESOLUTION_MAX_TOKENS` was asserted, not justified.** Its
comment said it "may want to diverge" from `BM25_MAX_TOKENS` while
already diverging, unexplained. Now states why 6: entity names run to two
or three tokens, so a message naming two entities needs room for both.
Pinned by a test that fails at a cap of 2, where only the first name
resolves.

Skipped, with reasons:

- `debug_assert!(best < 0.0)` on the cutoff. `best` comes from FTS5
  `bm25()`, which is negative by construction; the assert would guard a
  state the source cannot produce.
- Trimming `create_node`'s already-exists prologue. The review suggests
  re-evaluating it once the truncation is fixed — which is now true but
  unmeasured, since the eval that produced "channel authority cannot move
  this" ran under the truncation. Removing it on a hunch is worse than
  leaving it pending a real measurement.

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

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Review Type: Re-Review (scope: f79f8db9..HEAD — 24cb1ff2, 8932e269)

The 🔴 blocker is fixed, and fixed more thoroughly than I asked for. I pushed on every claim the commit messages make and they hold under independent verification. The author did not stop at the daemon-side separation I suggested — they discovered it was insufficient on its own and fixed the resolver too, which is the correct depth. Every 🟡 and 🟢 from the prior review is either addressed or skipped with a reason I accept.

Two things I want to single out as unusually good practice:

  • The commit message states plainly that the PR's own headline measurement is confounded by the bug it fixes, and which conclusions now need re-measuring. Invalidating your own results in the commit that fixes the cause is the right instinct and rare.
  • ENTITY_RESOLUTION_MAX_TOKENS' new comment explicitly says "Raising this alone would not have fixed it" — it records the near-miss fix that would have moved the cliff rather than removing it. That is the kind of note that stops a future reader "simplifying" the selection logic away.

I found one new 🟡 (a genuine residual starvation case that survives the fix) and two 🟢. None block.


Previous Review Summary

Prior finding Status
🔴 Blended query starves the entity out of its token budget ✅ Fixed, at both layers. Verified below.
🟡 Pinned-bug test name asserts the opposite of its assertion ✅ Renamed a_body_node_is_currently_resolved_as_an_entity_which_is_a_bug. Passing now reads as "the bug is still here."
🟡 Same comment embeds an issue number against CLAUDE.md's doc standard ✅ Removed. The comment still describes the create_node_in_tx mechanism and the blast radius precisely; nothing was lost.
🟡 Stale seedGroup comments in decisions.ts ✅ Both corrected, including the load-bearing --runs-shares-one-database claim, now restated accurately (the hook must not depend on --between-runs having wiped).
🟡 Header can be emitted with zero entity lines ✅ Fixed and pinned. Verified below.
🟡 ENTITY_RESOLUTION_MAX_TOKENS = 6 asserted, not derived ✅ Justified and pinned by a test. Verified below.
🟢 NoMatch logs nothing ✅ Both NoMatch paths now log; the cutoff path carries the candidate count.
🟢 entity_tier_respects_the_char_budget passes trivially ✅ Strengthened to exercise partial truncation.
🟢 debug_assert!(best < 0.0) ⏭️ Skipped — I accept this. See below.
🟢 create_node prologue re-evaluation ⏭️ Deferred pending re-measurement — I accept this. See below.
🟢 /// vs /** */ in decisions.ts ⏭️ Not addressed. Cosmetic, was already marked optional, not restating.

Verification of the blocker fix

1. Is the separation complete? — Yes

I traced every call site of context_ops::build_workspace_context. There are exactly three, and no path remains where the blended query reaches resolve_entities:

Call site query entity_query Correct?
📁 packages/daemon/src/services/local_agent_service.rs:778 (the only production path) retrieval_query (blend) user_message ✅
📁 packages/daemon/src/services/local_agent_service.rs:2777 (thin daemon wrapper) forwards forwards ✅ pass-through
📁 packages/daemon/src/services/local_agent_service.rs:3026 (test) query query ✅ bare message, no blend exists

resolve_entities is private to context_ops and has exactly one caller (:570), now reading entity_query. resolve_entities_by_title has one production caller (context_ops.rs:461); everything else is tests. There is no second ingress.

The doc comment on build_workspace_context is the right mitigation for the remaining hazard — two Option<&str> params of the same type next to each other are transposable, and the comment states which is which and why the separation is load-bearing, not merely that it exists. A newtype would be stronger, but with one production caller and a comment this explicit, that is disproportionate.

2. Is the token-selection fix sound? — Yes, with one caveat (🟡-1 below)

I extracted the exact selection logic and ran it against adversarial inputs:

"set up new type places hold events booking capacity roster venue schedule
 then add Northwind Trading"
  -> ["northwind", "trading", "set", "type", "places", "hold"]      ✅ the motivating case

"please can you update the capacity for northwind trading today thanks"   (all-lowercase)
  -> ["update", "capacity", "northwind", "trading", "today", "thanks"]    ✅ bias, not filter

"ADD NORTHWIND TRADING TO THE COMPANIES WE SELL TO IMMEDIATELY PLEASE OK"
  -> ["northwind", "trading", "companies", "sell", "immediately", "ok"]   ✅ degrades to plain order

"北風貿易 の 情報 を 更新 して ください 資料 データ 会社 名前 追加"     (CJK, no case)
  -> ["北風貿易", "の", "情報", "を", "更新", "して"]                      ✅ graceful — plain order

Answering each sub-question directly:

  • All-lowercase message: works. partition puts everything in rest, and chain yields the original order — byte-for-byte the old behaviour. The "bias, not filter" claim is accurate, and a_partial_name_still_resolves / stop_words_alone_do_not_resolve continuing to pass is the right evidence for it.
  • Does partition preserve relative order? Yes, and I confirmed it rather than trusting it — ["A","b","C","d","E"] partitions to (["A","C","E"], ["b","d"]). Iterator::partition extends both collections in iteration order. The comment's claim is correct.
  • Is to_lowercase() at the right point? Yes. It is applied after take, so the partition sees original case, which is what is_uppercase requires. The stop-word filter separately does t.to_lowercase().as_str() at filter time, so stop-words are still stripped case-insensitively. This is actually a latent improvement: previously a sentence-initial "The" was lowercased before the filter and stripped; the refactor preserves that. I checked — it does not regress. (Note 🟢-2 on a small allocation cost.)
  • Unicode hazard (CJK): degrades gracefully. char::is_uppercase is false for caseless scripts, so every token lands in rest and the plain order applies. Nothing is dropped. Παρακαλώ Northwind correctly treats the Greek capital as capitalised. No panic risk: chars().next() on a non-empty token always yields, and is_some_and handles the empty case that filter(|t| !t.is_empty()) already excludes anyway.

3. Does the regression test actually pin it? — Yes, verified

I reverted the selection to front-first .take(N) and re-ran:

test a_name_late_in_a_long_message_still_resolves ... FAILED
  assertion `left == right` failed: a name after many leading words must still
  resolve — if this fails, the token budget is being consumed before the entity: []
  left: None   right: Some("07a6b157-...")

It fails with exactly the message it promises, and the other 10 pass — so it isolates the selection change specifically. Restored immediately; git status --porcelain empty.

Worth recording: two_multi_token_names_in_one_message_both_resolve still passes under that revert. That is correct and not a defect — it pins the cap, not the selection, and I verified it does pin the cap: setting ENTITY_RESOLUTION_MAX_TOKENS = 2 fails it with the promised message. The two tests pin two different constants, which is the right factoring.

4. Was anything missed? — One residual case (🟡-1)

See below. MAX_TOKENS = 6 is now adequate for the cases the tests cover, but the selection change moves the starvation risk rather than eliminating it entirely.


Code Review Findings

🟡 Improvements

📁 packages/core/src/db/sqlite_store/nodes.rs:3737-3747 — a Title Case sentence can still starve the entity, and the new comment does not mention the residual.

The capitalised-first bias fixes the case where filler is lowercase. It does not help when the competing tokens are also capitalised — and Title Case is common in exactly the register where users name entities. Measured against the real logic:

"Could You Kindly Update The Customer Record And Billing Address For Northwind Trading"
  -> ["update", "customer", "record", "billing", "address", "northwind"]
                                                              ^^^^^^^^^ "trading" dropped

Northwind survives, so the entity is not lost outright — bm25 OR on the one token still ranks the node. But this is now a one-token match competing with the an_exact_title_outranks_a_longer_one_containing_it ranking logic, and the relative cutoff may or may not keep it depending on what else is in the index. Push a couple more capitalised words in front and northwind goes too.

This is materially less severe than the blocker — it needs an unusual message register rather than merely a second conversational turn — so I am not blocking on it. Two things I would want, in decreasing order of value:

  1. Say it in the comment. The comment currently reads as though capitalised-first solves the problem class. It solves the common instance. The same argument the comment makes for why front-first was wrong ("the budget goes to whatever the sentence opens with") applies verbatim within the capitalised class — the budget goes to whatever capitalises first. One sentence acknowledging the residual would stop a reader concluding the class is closed.
  2. Consider whether 6 should be larger now. The prior review asked for 6 to be justified and it now is, well — but the justification ("two entity names of 2-3 tokens each") is reasoning about the ideal token set, whereas the cap operates on the selected set, which under Title Case contains filler. That is not an argument for a specific number without a probe; it is an argument that the stated derivation is slightly narrower than the constant's actual job.

A stronger long-term shape, if this ever needs revisiting: prefer runs of adjacent capitalised tokens over isolated ones, since a multi-token entity name is contiguous and Title Case filler is not clustered around the name specifically. Not worth doing speculatively — noting it so the option is on record.

🟢 Nitpicks

Nit: 📁 packages/core/src/ops/context_ops.rs:1819 — entity_tier_respects_the_char_budget's full.len() - 20 is a magic offset the test does not explain.

The strengthening is real and I verified the intent: the test now asserts abc123 present and def456 absent, which the prior version did not. But - 20 is derived from the second line's length (- "Contoso Ltd" (customer) id=def456\n is 37 chars) by an argument the test does not state, and it is only coincidentally in the window that drops exactly one line. If someone lengthens RESOLVED_ENTITIES_HEADER or renames the fixture entities, the test either still passes for the wrong reason or fails confusingly.

full.len() - 5 would be more obviously "just barely short", or better, compute it: full.len() - second_line.len() + 1. Cheap, and it makes the boundary self-documenting. The assertions themselves are right — this is about why the number is that number.

Nit: 📁 packages/core/src/db/sqlite_store/nodes.rs:3730-3735 — the stop-word filter now allocates a String per token to test membership.

!BM25_STOP_WORDS.contains(&t.to_lowercase().as_str()) allocates for every token, where the old code lowercased once and reused it. Bounded by message length and this runs once per turn against an FTS query, so the cost is irrelevant in absolute terms — flagging only because it is the kind of thing that reads as accidental. t.chars().next().is_some_and(char::is_uppercase) could be captured alongside a single lowercased copy if anyone ever cares. Genuinely optional.


The header fix (item 5)

Budget arithmetic is correct. The predicate is:

if out.len() + header.len() + lines.len() + line.len() > max_chars { break; }

All four components are accounted for: what is already emitted, the header not yet committed, the lines accumulated so far, and the candidate. The prior version's inner check was out.len() + line.len() with the header already pushed into out — correct by accident of ordering, but it could not express "the header is conditional." The new form can, and if !lines.is_empty() is the right commit point. There is no off-by-one: > with <= semantics elsewhere in the function is consistent (out.len() + section.len() <= max_chars is the same boundary inverted).

a_budget_too_small_for_any_entity_renders_no_header pins it — verified. I reverted format_for_prompt to header-first and it failed with exactly its promised message, printing the orphaned header above nothing. Restored immediately.

Is the strengthened budget test non-trivial now? — Yes, but see 🟢-1. It genuinely exercises partial truncation (first entity present, second absent), which the prior version did not. It does not fail against the old ordering — correctly, since partial truncation worked before; the header-empty case is what the old ordering broke, and that is the new test's job. Two tests, two properties, cleanly separated.

One observation on scope: EXISTING_SCHEMAS_HEADER immediately below still has the original header-first shape and can still render an empty header. I flagged this as pre-existing in the prior review and I am not asking for it here — this tier's semantics (a header promising resolved ids) are what made it matter, and widening the commit would break its atomicity. Reasonable follow-up if anyone touches that block.

NoMatch logging (item 6)

Both paths log, and the cutoff path carrying candidates = candidates_len is a good call — it distinguishes "FTS returned nothing" from "FTS returned 12 and the bar rejected all of them," which are different bugs with different fixes. Exactly the discrimination whose absence hid the truncation.

On logging the user message at debug level: acceptable, and consistent rather than novel. query = q already appears on three pre-existing paths in this same function (:497, :505, :589) and in skill_ops.rs:619; the NoMatch paths were the anomaly in not logging it. These are tracing::debug!, off by default in production, in a local-first desktop app where the graph contains the user's data anyway and the logs are on their own machine. No new exposure surface — this closes an inconsistency rather than opening one. If message-content logging is ever revisited, it should be revisited across all five sites as one decision, not here.

The two skips (item 7)

debug_assert!(best < 0.0) — I accept the skip, and the reasoning is better than my original suggestion. best comes from FTS5 bm25(), which is negative by construction for any row that matched. A debug_assert guarding a state the source cannot produce is noise that reads as though the state is reachable, which is worse than absent. My original nit said "genuinely defensive" and flagged it only because sign conventions invert easily — the author's counter is that documenting the invariant (which the comment at :483-485 already does, clearly) is the proportionate response, and I agree. Not pushing back.

create_node prologue trimming — I accept the deferral, and it is the strictly correct call. My own nit said re-evaluating after the blocker is fixed is more informative than keeping or cutting now. The blocker is fixed but the eval has not re-run, so the measurement the trim would be judged against still does not exist. Cutting it now on the reasoning "the entity renders now, so the prologue may be redundant" would be exactly the unmeasured hunch this PR has been careful to avoid everywhere else. Leaving it pending is consistent with that discipline. The prologue is correct guidance regardless; the only cost is prompt real estate.

Both skips are argued from the mechanism rather than from effort, which is the standard I would want.

New issues introduced (item 8)

Nothing beyond 🟡-1 and the two 🟢s. Specifically checked and clear:

  • No panic paths in the new token logic (chars().next() on non-empty, is_some_and on the Option).
  • No behavioural change for single-class messages — verified the all-lowercase and all-caps paths reproduce the prior ordering exactly.
  • String allocation change is a refactor of map(|t| t.trim(...).to_lowercase()) into map(trim) … map(to_string); the .trim_matches semantics are unchanged.
  • candidates_len is captured before into_iter() consumes the vector — correct, and it has to be there.
  • No lint suppression, no #[allow], no #[deprecated], no migration code, no raw console.* introduced.
  • The entity_query parameter is threaded through the daemon wrapper without a default, so a future call site cannot silently omit it.

Test suites

Run independently, all green on HEAD:

  • cargo test -p nodespace-core --lib — 1637 passed (was 1636; +1 for the new header test)
  • cargo test -p nodespace-core --test entity_resolution_test — 11 passed (was 9; +2)
  • cargo test -p nodespace-daemon --lib — 238 passed
  • bun run test:scripts — 565 passed, 1401 assertions

Three revert experiments run and restored; git status --porcelain confirmed empty after each and at the end.


Recommendation

APPROVE

The blocker is genuinely fixed, at both layers, and the fix is pinned by a test I confirmed fails without it. The author went past the fix I suggested to find that the daemon-side separation alone was insufficient — which is the difference between addressing a review and addressing the defect. Every 🟡 is closed; both skips are argued from the mechanism and I accept them.

🟡-1 (Title Case residual) is worth a comment amendment and does not block: it requires an unusual message register rather than merely a second turn, and degrades to a one-token match rather than to NoMatch. The 🟢s are optional.

One non-blocking carry-forward, already acknowledged in the commit message and the PR body: the Entity-resolution 2/4 and the "channel authority cannot move this" conclusion were measured under the truncation and need re-measuring before they are cited. The commit says so plainly, which is why this is a note rather than a finding — but it should land in the PR body's results table too, so a reader of the merged history does not take those numbers at face value.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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

Re-review approved the blocker fix and found one genuine residual the
fix does not cover. Reproduced before acting on it.

The capitalised-first selection helps when the filler competing for the
token budget is lowercase. It does nothing when the competing tokens are
capitalised too — front-first truncation then applies WITHIN the
capitalised class, which is the same defect one level down:

    "Could You Kindly Update The Customer Record And Billing Address
     For Northwind Trading"
      -> kindly update customer record and billing   (entity dropped)

Left unfixed, deliberately. "Prefer the longest run of adjacent
capitalised tokens" was the obvious next heuristic and was tried: it
gives no discrimination here, because a Title Case sentence is one long
run. Inventing a fourth variant to chase an unusual register is worse
than recording the limit accurately.

It is also materially less severe than the bug it replaced, in the way
that decides whether it can mislead: it degrades to a weak one-token
match rather than to `NoMatch`, so it cannot produce the false "does not
exist" claim that licenses creating a duplicate. A test pins that
distinction — asserting the entity is still FOUND, with a note to invert
the assertion if a future change makes it rank first, since that would be
an improvement rather than a regression.

The comment now also records that the cap's justification reasons about
the IDEAL token set (a name is two or three tokens) while the cap applies
to the SELECTED set — those coincide only when selection puts the name
first, which is exactly what the residual breaks.

Also from re-review: the budget test's `full.len() - 20` magic offset now
derives from the dropped line's own length, so the boundary stays correct
if the rendered line format changes.

Not addressed: `///` vs `/** */` in decisions.ts. Cosmetic, and the
reviewer marked it optional.

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

malibio commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Corrected results — the earlier numbers were measured under a bug this PR fixes

The results table originally posted here reported 7/9 pass^3, Entity resolution 2/4. Those numbers are withdrawn. They were measured while the entity was being truncated out of its own lookup — review found that build_workspace_context received the blended retrieval query (prior turns prepended before the current message) while the resolver kept only the first 6 tokens, so on any turn with a prior turn the name never reached the index and the tier reported NoMatch.

Re-measured on 8932e269, after the fix. 3 reps, gemma-4-e4b-q4km, database purged between reps, seeded via seedRun.

Category Under truncation Fixed
pass^3 7/9 8/9
Entity resolution 2/4 3/4
Skill routing 3/3 3/3
Operation selection 21/22 22/23
Schema selection 1/2 1/1
Instance-vs-type boundary 3/3 3/3
Ambiguous (several types plausible) 1/2 2/2
ADR-056 known failures 2/2 2/2
Off-menu type named 0 0
Flipped (unstable) 0/9 0/9

Per rep: 8/9, 8/9, 8/9. Stage-1 decision cost 2424 / 2037 / 1896 ms mean.

✓ op-list-by-type                3/3 reps
✓ op-read-then-write             3/3 reps
✓ skill-type-request-direct      3/3 reps
✓ skill-type-request-indirect    3/3 reps
✓ skill-instance-request         3/3 reps
✗ schema-on-menu-company         0/3 reps
✓ schema-field-disambiguates     3/3 reps
✓ schema-shared-name-signed      3/3 reps
✓ entity-no-match-is-a-create    3/3 reps

What moved, and what actually caused it

Three things differ between the two runs, so the aggregate improvement should not be attributed to one of them:

  • schema-field-disambiguates 0/3 → 3/3 is the assertion fix, not the truncation fix. It was asserting a schema decision on a turn that correctly calls update_node — which takes a node id and records no schema decision — so it could not pass however well the model reasoned.
  • Entity resolution 2/4 → 3/4 tracks the truncation fix: the name now reaches the index on turns that have a prior turn.
  • Ambiguous 1/2 → 2/2 follows from the same two.

What is clean about both runs: zero variance across three reps, so neither set of numbers is noise, and the v4 run's provenance is 8932e269 — the fixed code.

The one remaining failure is the documented gap, and it is now better evidenced

schema-on-menu-company fails 0/3: "Add Northwind Trading to the companies we sell to", with Northwind already in the graph, produces create_node and a silent duplicate. Confirmed live during this run — a second Northwind row appeared mid-eval, carrying no signed_date, alongside the seeded one that has 2025-03-14.

This was previously reported with a caveat that it might be confounded: if the entity had been truncated away, the model never saw it, and concluding "instruction channels cannot move this" would have been unfounded.

That caveat is now resolved, and the conclusion holds. With the entity correctly rendered in MENTIONED ENTITIES and route_clarify on the offered tool surface, the model still creates the duplicate — and called route_clarify zero times across the entire run. Guidance prose, the create_node tool description, and both together were each measured and each failed. ADR-064 measured the tool-schema channel at 100% compliance for output-shape constraints; a conditional suppression ("do not take the obvious action when a condition holds") appears to be a materially harder ask.

Closing it needs a deterministic guard on the write path — the system already holds the resolved entity, so the collision is detectable before the write with no model judgment — which is tracked separately.

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.

1 participant