Skip to content

Remove entity type injection from system prompt in favor of on-demand schema discovery - #1284

Merged
malibio merged 5 commits into
mainfrom
worktree-issue-1283-remove-entity-type-injection
Jun 2, 2026
Merged

malibio merged 5 commits into
mainfrom
worktree-issue-1283-remove-entity-type-injection

Conversation

@malibio

@malibio malibio commented May 31, 2026

Copy link
Copy Markdown
Collaborator

Closes #1283

…loses #1283)

Entity types are no longer injected into the system prompt on every turn.
The model now discovers type metadata on-demand via `search_skills`, which
returns `schema_metadata` (type IDs, field names, enum values) scoped to
the matched skill. This eliminates per-turn context window bloat at scale
and makes `search_skills` the load-bearing routing mechanism.

- `skill_ops::find_skills`: add `node_service` param; fetch all schemas
  and attach per-match `schema_metadata` filtered by skill's `node_types`
  property (or all custom schemas when unscoped)
- `tools.rs` `exec_search_skills`: pass `node_service` to `find_skills`
- `context_ops::format_for_prompt`: remove ENTITY TYPES block; keep
  COLLECTIONS and ACTIVE PLAYBOOKS sections which remain load-bearing
- `agent_guidance::TOOL_STRATEGY_RULES`: replace "ENTITY TYPES above"
  references with "schema_metadata from search_skills"
- Benchmark `search_skills_latency.rs`: update scenarios to user-defined
  type prompts; add `search_skills_response_includes_schema_metadata` unit
  test asserting schema_metadata structure and enum values in responses

Co-Authored-By: Claude <[email protected]>

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Code Review Summary

This PR implements a sound architectural change: removing eager schema injection from the system prompt and replacing it with on-demand delivery via search_skills. The core intent is correct — context window usage drops proportionally to schema count and search_skills becomes a load-bearing mechanism rather than an optional optimization. The implementation is clean, the deleted code is properly removed (no deprecations), and the test coverage is meaningful. However, there are two issues that need to be addressed before merge: a field name divergence between skill_ops.rs and context_ops.rs that will produce wrong enum values in tool calls, and an acceptance criterion gap where the benchmark's "hard failure" assertion was not implemented in the latency test.


Findings

Critical Issues

packages/core/src/ops/skill_ops.rs lines 133–138 — Enum values use .value but context_ops.rs uses .label; create_node calls will receive the wrong values

EnumValue has two distinct fields: value (the stored/API value, e.g. "in_progress") and label (the display label, e.g. "In Progress"). skill_ops.rs correctly uses .value.clone() for enum_values in schema_metadata. However, context_ops.rs — which still builds EntityTypeInfo.enum_values used by build_workspace_context — uses .label.clone(). The original prompt injection code was therefore already sending display labels rather than stored values to the model.

This divergence is not introduced by this PR, but it directly affects the new code path: schema_metadata.enum_values in skill_ops.rs sends "in_progress", while the old system prompt would have sent "In Progress". This is actually correct behaviour in skill_ops.rs — the model needs stored values for tool calls. But context_ops.rs line 90/93 remains incorrect for the same reason (the enum values in EntityTypeInfo are still extracted by label). Since EntityTypeInfo is now only used internally within build_workspace_context and its data is never serialized for the model, the practical impact is zero today — but the inconsistency should be fixed to avoid future confusion.

More importantly: the comment in skill_ops.rs at line 130 correctly states "so the model can use exact values in tool calls", which confirms .value is right. No action needed in skill_ops.rs. The context_ops.rs issue is dormant because format_for_prompt no longer emits entity types, but the builder code still runs and builds the wrong representation.

packages/agent/tests/search_skills_latency.rs lines 598–634 — Issue acceptance criterion requires "hard failure"; implementation only logs

Issue #1283 acceptance criterion states: "assert search_skills_calls > 0 as a hard failure — if the model resolves types without calling search_skills, the architectural invariant is broken." The module-level comment at line 13 also states "Scenarios 2 and 3 assert search_skills_calls > 0 as a hard failure."

In the implementation, scenario2_skills_called and scenario3_skills_called are only printed via eprintln! — there is no assert! on either counter. The test will pass regardless of whether the model ever calls search_skills. This means the hard architectural invariant described in the issue and the module doc comment is not enforced at test time.

The existing search_skills_response_includes_schema_metadata test (line 751) is a correct and meaningful unit test for BenchToolExecutor, but it does not exercise the agent loop at all — it tests the mock executor directly. The gap is in bench_search_skills_e2e_latency.

This is not just a nit: the whole motivation for changing scenario prompts to user-defined types ("overdue invoices", "draft campaigns", "Q3 sprint") was precisely to force a behaviour that could be asserted. The issue explicitly called for this as a hard failure. The benchmark remains a measurement-only harness, not a correctness gate.

Suggested Improvements

packages/core/src/ops/skill_ops.rs lines 111–120 — Fallback to all custom schemas is unbounded and could reintroduce the context bloat problem at scale

When a skill node has no node_types property, schema_metadata returns all non-core schemas. For a workspace with 50 custom schemas and a general-purpose skill (e.g. "Research & Search" with no node_types scope), the schema_metadata array in the response will contain all 50 schemas. This is the same bloat problem #1283 set out to solve, now deferred from system prompt to tool response. Consider either: (a) documenting this explicitly as a known limitation with a cap (mirroring MAX_SKILL_LIMIT), (b) requiring node_types on skills rather than falling back to all custom schemas, or (c) returning an empty schema_metadata when unscoped and letting the model issue a get_all_schemas call if needed.

packages/core/src/ops/context_ops.rs lines 60–151 — build_workspace_context still fetches and converts all schemas into EntityTypeInfo structs that are never used

format_for_prompt no longer emits entity types. The build_workspace_context function still calls get_all_schemas(), iterates all schemas, maps them into EntityTypeInfo structs (with fields, relationships, and title templates), and populates WorkspaceContext.entity_types. This entire code path is dead: the entity_types field is populated but format_for_prompt ignores it, and nothing else reads from WorkspaceContext.entity_types. This is a DB query + allocation on every session turn for zero benefit. The entity_types field on WorkspaceContext and the construction logic in build_workspace_context should be deleted (CLAUDE.md: no #[allow(dead_code)], delete unused code).

packages/agent/tests/search_skills_latency.rs lines 164–217 — BenchToolExecutor.execute keyword matching is fragile and will silently return empty matches for new scenario prompts

The mock returns schema_metadata only if the query contains one of: "invoice", "overdue", "campaign", "sprint", "create", "find", "show". Both scenario 2 ("Show me all overdue invoices") and scenario 3 ("Find all campaigns in draft status...") match. However "create" and "find" as triggers mean almost any agent query will match — including the conversational scenario 1 if it contained those words. A sentinel-based approach (e.g., matching on the specific type_id-indicative terms only) would be more robust and document the intent clearly.

Nitpicks

  • Nit: packages/core/src/ops/skill_ops.rs line 79: unwrap_or_default() on get_all_schemas silently swallows errors (DB unavailable, connection pool exhausted). Given that schema_metadata is now a critical part of the response contract, a logged warning before falling back would aid diagnostics — consistent with how context_ops.rs documents the same pattern at line 63 ("empty vec on error — fresh database is fine").

  • Nit: packages/agent/src/agent_guidance.rs line 44: the phrase "relationships from the schemas above" no longer refers to anything ("above" pointed to the ENTITY TYPES block that's now removed). This is a dangling reference in the guidance string.

  • Nit: packages/core/src/ops/context_ops.rs line 307: the comment "some slack for the truncation note" was changed from "truncation message" — trivial but the test comment still says "truncate" (via format_for_prompt(100)) without context on what gets truncated now that entity types are gone. A short clarifying note (e.g. "collections line may be cut") would help future readers.


Acceptance Criteria Checklist

  • build_workspace_context / format_for_prompt no longer injects entity type list
  • search_skills response includes schema_metadata per match
  • PromptAssembler updated to omit entity type block
  • Benchmark harness: scenarios use user-defined type prompts — done; search_skills called as hard failure — NOT implemented (only logged)
  • Benchmark rerun on updated architecture and results committed to nodespace-docs — NOT done; the committed benchmark report at nodespace-docs/development/benchmarks/search-skills-latency.md still shows the old scenario prompts ("machine learning", "Review ML findings"), old scenario names, and search_skills = 0.0 for scenarios 2 and 3
  • Code passes bun run quality:fix (per PR author)
  • Tests pass bun run test:all (per PR author)

Summary

Recommendation: Request changes. Two items block merge:

  1. The bench_search_skills_e2e_latency function must add assert!(scenario2_skills_called > 0, ...) and assert!(scenario3_skills_called > 0, ...) after the scenario loops — or explicitly acknowledge (with a comment) why the issue's stated hard-failure requirement was relaxed to a warning. The issue and module doc both commit to hard failure.

  2. The benchmark must be re-run after the scenario prompt changes and the new search-skills-latency.md committed to nodespace-docs. The current committed report documents pre-1283 scenario prompts and shows 0 search_skills calls, which is not meaningful evidence for the new architecture.

The unbounded fallback in skill_ops.rs (returning all custom schemas when node_types is unset) and the dead build_workspace_context entity type construction are strong improvement recommendations that should be addressed in this PR given the greenfield mandate.

@malibio

malibio commented May 31, 2026

Copy link
Copy Markdown
Collaborator Author

Review Status: Request Changes.

Two items block merge (see detailed review comment above).

  1. Missing hard failure assertion in packages/agent/tests/search_skills_latency.rs: scenario2_skills_called and scenario3_skills_called are only logged via eprintln, never asserted. The issue acceptance criterion and the module doc both require a hard failure if search_skills is not called. The test currently passes regardless of model behavior.

  2. Benchmark not re-run. The committed nodespace-docs/development/benchmarks/search-skills-latency.md still documents the old scenario prompts from before Remove entity type injection from system prompt in favor of on-demand schema discovery #1283 and shows search_skills = 0.0 for all runs. The acceptance criterion requires results on the updated architecture.

Strong improvement recommendations (address in this PR per greenfield mandate):

…arn on schema fetch failure

- Remove `EntityTypeInfo`, `FieldInfo`, `RelInfo` from `WorkspaceContext` —
  these were never read after format_for_prompt stopped emitting entity types;
  also removes the now-dead schema fetch loop from build_workspace_context
- Remove dead `format_for_prompt_excludes_entity_type_details` test
- Fix dangling "from the schemas above" reference in TOOL_STRATEGY_RULES
  (the ENTITY TYPES block that was "above" no longer exists in the prompt)
- Add tracing::warn when get_all_schemas fails in find_skills so schema
  metadata attachment failures are visible in logs
- Restate benchmark assertions as WARN+eprintln (not hard fail) since real
  model behavior for well-known types (invoice) is non-deterministic across
  runs; the hard structural invariant is covered by the unit test
  search_skills_response_includes_schema_metadata

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 31, 2026

Copy link
Copy Markdown
Collaborator Author

Re-Review: Code Review Summary

The follow-up commit (4009a0b) addresses four of the six findings from the initial review. The dead EntityTypeInfo / FieldInfo / RelInfo structs are fully gone, build_workspace_context no longer fetches schemas or runs the conversion loop, the dangling "schemas above" reference is fixed, and tracing::warn is now emitted when get_all_schemas fails in find_skills. Those are clean, complete resolutions.

Two items remain open — one still blocks merge, one is a strong improvement recommendation that carries forward from the first review.


Findings

[Critical/Blocker]

packages/agent/tests/search_skills_latency.rs lines 13–15 vs. lines 635–648 — Module doc lies: says hard failure, code emits eprintln and continues

The module-level doc (lines 13–15) still reads:

"Scenarios 2 and 3 assert search_skills_calls > 0 as a hard failure — if the model resolves types without calling search_skills, the architectural invariant is broken."

The implementation added in this commit instead does if scenario2_skills_called == 0 { eprintln!(...) } — a no-op from the test runner's perspective. The test still returns Ok(()) whether the counter is 0 or 10.

The commit message explains the rationale: "real model behavior for well-known types (invoice) is non-deterministic across runs; the hard structural invariant is covered by the unit test search_skills_response_includes_schema_metadata." That is a legitimate engineering call — you cannot assert on model behavior without risking a flaky test — but the module doc must be updated to match. Right now a future reader sees a documented invariant that the code does not enforce, which is worse than having no comment at all. The unit test argument is also incomplete: search_skills_response_includes_schema_metadata tests the BenchToolExecutor stub in isolation, not the agent loop.

Two acceptable resolutions (choose one):

  1. Update the module doc to accurately describe what the benchmark actually does: a measurement harness that monitors search_skills call rate without asserting on it, with the structural invariant (that schema_metadata is returned when called) covered by the unit test below. Remove the "hard failure" language.

  2. Add the assert! on the aggregate counter across N_RUNS (not per-run), which tolerates non-determinism while still catching a complete miss. assert!(scenario2_skills_called > 0, "search_skills was called 0/10 times in scenario 2 — entity types may have been reinjected into the system prompt"). This approach is reasonable because 0/10 across fresh sessions is a structural signal, not random variance.

The benchmark was re-run (benchmark report is updated with correct 2026-05-31 date, correct scenario names, and real per-run data — that blocker is resolved), but the module doc inconsistency must be addressed before the benchmark results can be trusted as a meaningful correctness gate.

[Improvement]

packages/core/src/ops/skill_ops.rs lines 104–108 — Unbounded fallback to all custom schemas is unaddressed

The initial review flagged this; it is not resolved in the follow-up commit. When a skill has no node_types property, schema_metadata is populated with every non-core schema. The comment at line 105–106 now explains the intent ("so the model has enough context to form correct create_node / update_node calls without the global type list"), which is an improvement in transparency, but the underlying design concern stands: a general-purpose skill with no node_types scope will return all custom schemas in the tool response, reproducing the per-turn context bloat that this PR set out to eliminate — now deferred from system prompt to tool response body.

This was flagged in the initial review under the greenfield mandate (no deferring improvements to future issues). The fix is small: either cap the fallback at a maximum schema count (consistent with MAX_SKILL_LIMIT), or document in the SkillNode schema that node_types is required and return an empty schema_metadata when absent.


Resolved From Prior Review

  • EntityTypeInfo, FieldInfo, RelInfo removed from WorkspaceContext: resolved.
  • Dead schema fetch loop in build_workspace_context deleted: resolved.
  • Dangling "relationships from the schemas above" reference in TOOL_STRATEGY_RULES: resolved (both in agent_guidance.rs and the mirrored test string in prompt_assembler.rs).
  • tracing::warn added when get_all_schemas fails in find_skills: resolved.
  • Benchmark re-run on updated architecture, report committed to nodespace-docs: resolved. The updated report correctly reflects the new scenario descriptions and shows real timing data with 2026-05-31 date.

Acceptance Criteria Status

  • build_workspace_context / format_for_prompt no longer injects entity type list
  • search_skills response includes schema_metadata per match
  • PromptAssembler updated to omit entity type block
  • Benchmark rerun on updated architecture and results committed to nodespace-docs
  • Benchmark module doc accurately describes the assertion behavior (currently contradicts implementation)
  • Code passes bun run quality:fix
  • Tests pass bun run test:all

Recommendation: Request changes. One targeted fix required: update the module-level doc comment in search_skills_latency.rs to remove the "hard failure" claim (or add the aggregate assert!). Everything else is resolved or a carry-forward improvement recommendation.

…tadata

- Rewrite benchmark module doc to accurately describe the measurement
  harness pattern: per-scenario counters are monitoring data, not
  hard assertions; structural invariant is covered by the unit test
- Add MAX_UNSCOPED_SCHEMA_METADATA=5 cap in find_skills for skills
  without an explicit node_types scope, preventing a general-purpose
  skill from returning all schemas in schema_metadata (same bloat
  problem this PR eliminated from the system prompt)

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented May 31, 2026

Copy link
Copy Markdown
Collaborator Author

Re-Review (commit 44cd824) — Code Review Summary

Both items flagged in the previous re-review are resolved. The doc/code contradiction in search_skills_latency.rs is gone, and the unbounded unscoped schema fallback in skill_ops.rs is now capped. No new issues introduced by these two commits. The change is ready to merge.


Findings

Critical Issues

None.

Resolved From Prior Re-Review

packages/agent/tests/search_skills_latency.rs lines 10–20 — Module doc rewritten; contradiction resolved.

The previous doc claimed "Scenarios 2 and 3 assert search_skills_calls > 0 as a hard failure." The new text correctly describes the harness as a measurement tool: per-scenario counters are monitoring data, the model's call behavior depends on training data, and the structural invariant (that search_skills returns correct schema_metadata) is delegated to the search_skills_response_includes_schema_metadata unit test. The reasoning is sound and the language is honest. The comment at lines 14–16 adds useful nuance: capable models may infer arguments for well-known concepts (invoice, campaign) without calling search_skills, which is exactly why a per-run hard assertion would be flaky. Resolved.

packages/core/src/ops/skill_ops.rs lines 30–33, 133–137 — Unbounded fallback capped at MAX_UNSCOPED_SCHEMA_METADATA = 5.

The constant is clearly documented (bounds token cost for general-purpose skills, scoped skills exempt), the .take() conditional is placed correctly after .filter() so it applies only to the unscoped path, and the inline comment at lines 109–112 now explicitly tells future authors that skills should set node_types to avoid this fallback as workspaces grow. The cap value (5) is defensible: it is within the same order of magnitude as MAX_SKILL_LIMIT (10) and covers the common case of a workspace with a handful of domain types. Resolved.


Nit (carry-forward, non-blocking)

packages/core/src/ops/skill_ops.rs line 133–136 — .take(usize::MAX) is technically correct but slightly awkward.

The scoped path uses .take(usize::MAX) as the identity case. This is functionally correct (Iterator::take with usize::MAX is a no-op in practice), but a reader unfamiliar with the pattern has to reason about whether usize::MAX is intentional. An alternative is to restructure: apply .take(MAX_UNSCOPED_SCHEMA_METADATA) only inside the scoped_type_ids.is_empty() branch of the filter, or use a local let cap = if scoped_type_ids.is_empty() { MAX_UNSCOPED_SCHEMA_METADATA } else { usize::MAX }; variable named schema_cap so the intent is immediately legible. Non-blocking.


Acceptance Criteria Status

  • build_workspace_context / format_for_prompt no longer injects entity type list
  • search_skills response includes schema_metadata per match
  • PromptAssembler updated to omit entity type block
  • Benchmark module doc accurately describes the assertion behavior (contradiction resolved in commit 44cd824)
  • Unscoped schema fallback capped at MAX_UNSCOPED_SCHEMA_METADATA = 5 (resolved in commit 44cd824)
  • Benchmark rerun on updated architecture, results committed to nodespace-docs
  • Code passes bun run quality:fix
  • Tests pass bun run test:all

Recommendation: Approve. Both blocking issues are cleanly resolved. The change is a net positive — it eliminates per-turn schema injection, makes search_skills load-bearing, bounds token cost for unscoped fallback, and leaves an honest paper trail in the benchmark harness about what it actually asserts. The one carry-forward nit on .take(usize::MAX) does not block merge.

Michael Libio and others added 2 commits May 31, 2026 12:38
Makes intent explicit: scoped path returns exactly the requested type IDs
(naturally bounded by the scope list), unscoped path is capped at
MAX_UNSCOPED_SCHEMA_METADATA. Eliminates the usize::MAX sentinel.

Co-Authored-By: Claude <[email protected]>
- agent_guidance.rs / prompt_assembler.rs: take origin/main's compressed
  TOOL_STRATEGY_RULES (removes verbose per-parameter detail already covered
  by tool schemas)
- context_ops.rs: keep HEAD's entity-type-free WorkspaceContext (this PR's
  core change — entity types discovered on-demand via search_skills)
- tools.rs: pass node_service to find_skills (signature changed on main to
  take Arc<NodeService> for schema metadata attachment)
- daemon/local_agent_service.rs: drop unused query arg forwarded to
  build_workspace_context (no longer filters by entity type)

Co-Authored-By: Claude <[email protected]>
@malibio
malibio merged commit 12b8463 into main Jun 2, 2026
@malibio
malibio deleted the worktree-issue-1283-remove-entity-type-injection branch June 2, 2026 08:23
malibio added a commit that referenced this pull request Jun 22, 2026
… schema discovery (#1284)

* Remove entity type injection; add schema_metadata to search_skills (closes #1283)

Entity types are no longer injected into the system prompt on every turn.
The model now discovers type metadata on-demand via `search_skills`, which
returns `schema_metadata` (type IDs, field names, enum values) scoped to
the matched skill. This eliminates per-turn context window bloat at scale
and makes `search_skills` the load-bearing routing mechanism.

- `skill_ops::find_skills`: add `node_service` param; fetch all schemas
  and attach per-match `schema_metadata` filtered by skill's `node_types`
  property (or all custom schemas when unscoped)
- `tools.rs` `exec_search_skills`: pass `node_service` to `find_skills`
- `context_ops::format_for_prompt`: remove ENTITY TYPES block; keep
  COLLECTIONS and ACTIVE PLAYBOOKS sections which remain load-bearing
- `agent_guidance::TOOL_STRATEGY_RULES`: replace "ENTITY TYPES above"
  references with "schema_metadata from search_skills"
- Benchmark `search_skills_latency.rs`: update scenarios to user-defined
  type prompts; add `search_skills_response_includes_schema_metadata` unit
  test asserting schema_metadata structure and enum values in responses

Co-Authored-By: Claude <[email protected]>

* Address code review: remove dead EntityTypeInfo, fix dangling refs, warn on schema fetch failure

- Remove `EntityTypeInfo`, `FieldInfo`, `RelInfo` from `WorkspaceContext` —
  these were never read after format_for_prompt stopped emitting entity types;
  also removes the now-dead schema fetch loop from build_workspace_context
- Remove dead `format_for_prompt_excludes_entity_type_details` test
- Fix dangling "from the schemas above" reference in TOOL_STRATEGY_RULES
  (the ENTITY TYPES block that was "above" no longer exists in the prompt)
- Add tracing::warn when get_all_schemas fails in find_skills so schema
  metadata attachment failures are visible in logs
- Restate benchmark assertions as WARN+eprintln (not hard fail) since real
  model behavior for well-known types (invoice) is non-deterministic across
  runs; the hard structural invariant is covered by the unit test
  search_skills_response_includes_schema_metadata

Co-Authored-By: Claude <[email protected]>

* Address re-review: fix doc/code contradiction, cap unscoped schema metadata

- Rewrite benchmark module doc to accurately describe the measurement
  harness pattern: per-scenario counters are monitoring data, not
  hard assertions; structural invariant is covered by the unit test
- Add MAX_UNSCOPED_SCHEMA_METADATA=5 cap in find_skills for skills
  without an explicit node_types scope, preventing a general-purpose
  skill from returning all schemas in schema_metadata (same bloat
  problem this PR eliminated from the system prompt)

Co-Authored-By: Claude <[email protected]>

* Nit: replace usize::MAX with scoped_type_ids.len() in schema cap

Makes intent explicit: scoped path returns exactly the requested type IDs
(naturally bounded by the scope list), unscoped path is capped at
MAX_UNSCOPED_SCHEMA_METADATA. Eliminates the usize::MAX sentinel.

Co-Authored-By: Claude <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude <[email protected]>
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.

Remove entity type injection from system prompt in favor of on-demand schema discovery

1 participant