Skip to content

Retarget prompt assembly to dev-workflow domain; generate write-tool field declarations from retrieved schemas - #2150

Merged
mstomar125 merged 2 commits into
mainfrom
issue-2120-prompt-assembly-plumbing
Aug 18, 2026
Merged

mstomar125 merged 2 commits into
mainfrom
issue-2120-prompt-assembly-plumbing

Conversation

@mstomar125

@mstomar125 mstomar125 commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Closes #2120.

What this does

Makes NodeSpace's local-agent prompt assembly reproduce the tuned golden corpus (packages/agent/goldens/, core#2122), per the channel doctrine in ADR-064. Every divergence was resolved by moving content to the channel ADR-064 assigns it, deleting the old location rather than duplicating — with two documented, deliberate exceptions where a tool is reachable through more than one skill and the duplicate copy is the only one guaranteed present (Node Creation's custom:-prefix rule, Relationship Management's DIRECTION rule).

The issue's scope was revised mid-implementation (by the issue owner, visible in the issue's edit history) from "retarget examples to the dev domain" to "generate write-tool field declarations from retrieved schemas, with the domain swap nearly incidental." Both are done.

What moved where, per ADR-064 channel

Tool schemas own argument shape (rule 1):

  • create_node/update_node's field_values parameter is now generated per request from retrieved schemas — see "The new mechanism" below — instead of a bare object plus a ~200-word prose paragraph explaining what may go inside it.
  • create_node's and create_schema's worked JSON examples moved from skill_pipeline.rs prose onto the tools' own descriptions in tools.rs (ADR-038 Finding 2: the model reproduces the worked example nearest where it reads the schema, so that's where the pattern belongs).
  • The RELEVANT_ENTITY_TYPES_HEADER constant is renamed EXISTING_SCHEMAS_HEADER, text changed to "EXISTING SCHEMAS (do not recreate these; do not copy their fields onto a new type):", matching the corpus exactly. Renamed at every call site, test, and doc comment across context_ops.rs, entity_types_block.rs, routing.rs, tools.rs, skill_pipeline.rs, agent_guidance.rs, agent_loop.rs — a grep for RELEVANT ENTITY TYPES now returns zero hits outside the untouched prompt_assembly_snapshot.rs (core#2119's gate, doc comments only, deliberately not touched — see "Out of scope" below).

Skill instructions own procedure, tool descriptions own tool selection (rules 1–2):

  • skill_pipeline.rs's Node Creation and Schema Creation guidance cut from ~30 and ~90 lines of prose to a handful of "CALL X NOW" / structural-constraint lines each, matching the corpus's dev-instance-creation.toml / dev-schema-creation.toml candidate text closely. The deleted content (field-type mechanics, title_template rules, the three JSON worked examples) is the content that moved to tools.rs's tool descriptions.
  • graph_editing_guidance() and relationship_management_guidance() gained corpus-derived procedure text (id-provenance, "already in this conversation" vs. "not yet found" resolve_query routing, relationship DIRECTION) and lost their two invoice worked examples (deleted, not reworded — no case in the corpus needs a worked clarification example).

Business-domain → dev-workflow domain, throughout skill_pipeline.rs, skill_rules.rs, and tools.rs: Invoice/Customer/Project examples replaced with Ticket/ADR/Sprint/Release, matching the corpus's domain. Left untouched: Rust unit-test fixtures using "invoice" as arbitrary parse-test data (not model-facing guidance), and Stage-1's route_query tool description (generic album/venue/equipment phrasing, not corpus-covered, out of scope per the issue's file list).

Resident prose owns identity and policy only (rule 5):

  • Core Identity's seed text shortened from "You are NodeSpace's built-in assistant. You help users work with their knowledge graph — creating, finding, updating, and connecting nodes." to "You are NodeSpace's assistant, acting on a user's workspace.\nCall exactly one tool. Do not answer the user in prose when a tool applies." — verbatim (or near-verbatim) at the top of every system field across all 8 dev-*.toml corpus cases, so not invented.
  • The now-redundant "Call tools immediately when intent is clear..." bullet is deleted from Response Formatting Rules (the new Core Identity line states the same policy).
  • Kept, deliberately, not deleted: BLAST-RADIUS GATE, CLARIFICATION CONTRACT, META QUESTIONS, SCHEMA CLAIMS WITHOUT VERIFICATION, and the rest of RESPONSE RULES/TOOL CALL FORMAT. No corpus case exercises deletion, meta-questions, or output formatting, so their absence from the corpus's narrow per-scenario system fields is not evidence they should be cut — ADR-064 rule 5 explicitly assigns this content to resident prose as its legitimate remaining scope, and deleting real safety/behavior policy without measurement would be the same class of mistake as inventing new prose.

The new mechanism: per-request write-tool field declarations

packages/agent/goldens/PATTERN.toml measures (8 arms, every ADR-064 prose channel) that a value with no declared field is silently dropped 3/3, and that declaring it as a typed sub-property of field_values — not prose explaining the same thing — fixes it 3/3, including for a type absent from every worked example (dev-unseen-schema.toml).

routing::declare_write_tool_fields (new) builds field_values.properties from the retrieved schema_metadata already flowing through SkillCandidate (the same data EXISTING SCHEMAS renders from). Selection rule, inferred from which corpus cases declare fields and which deliberately don't (the corpus states outcomes per case, not a mechanism):

  • Source from whichever cleared candidate(s) whitelisting a given tool scored highest on this turn. A tool whitelisted only by a lower-scoring candidate stays on the static bare-object fallback — reproducing dev-schema-creation.toml's distractor create_node (offered alongside create_schema specifically so the model can choose wrongly; declaring its fields would make the wrong tool easier to reach for on exactly the turn that must not reward it).
  • Ties at the top score are unioned, not arbitrarily picked — the snapshot gate's own fixture scores two candidates identically on purpose.
  • A field name repeating across unioned descriptors with different enum values gets the union of legal values (the model hasn't chosen node_type yet at declaration time); with different non-enum types, it widens to string (JSON Schema's most permissive scalar) rather than silently keeping whichever descriptor was processed first.
  • A retrieved type with zero fields does not narrow field_values to an explicit properties: {} (more restrictive than the untyped-object fallback it would replace) — only a non-empty declaration is written.

Gated the same way candidate_block prompt injection already is: this is retrieved-schema content, the class of payload tests/live_openai_compat_routing.rs's matrix found suppresses tool-calling outright on some served models — reached through a different channel (the tool schema) than the one that matrix measured (prompt text), so agent_loop.rs calls declare_write_tool_fields only when !session.routing_disabled, deliberately kept as a separate step from stage2_tools rather than folded into it (tool-list scoping is a different, already-proven-safe mechanism and stays unconditional).

This was caught in review — the first version folded the declaration step unconditionally into stage2_tools, which would have handed a probed-unsafe model the same suppressing content through an unmeasured channel.

What did NOT change

  • Wire format: CreateNodeParams/UpdateNodeParams are untouched. Only the parameters_schema JSON the model reads changed; no handler, param struct, or storage path changed.
  • core#2123's field_values rename (already merged) — this issue builds on it, doesn't revisit it.
  • The snapshot gate's mechanism (core#2119) — prompt_assembly_snapshot.rs was touched in exactly one place: stage2_tool_surface_matches_golden now also calls declare_write_tool_fields after stage2_tools, because that's what agent_loop.rs's real, routing-enabled path does, and the gate's own stated design is to reproduce production faithfully. No assertion logic changed.
  • The golden corpus itself (core#2122) — not touched.
  • Matrix/routing eval fixtures (core#1977), SKILL.md structural enforcement (core#1958).

Explicitly deferred (documented, not silent)

  • Per-type-scoped schema retrieval. No seeded skill currently declares node_types, so every candidate's schema_metadata carries the full non-core schema list rather than a scoped subset. A turn with two relevant types (e.g. ticket + adr both retrieved) therefore unions both types' fields onto a write tool rather than picking the one the request actually concerns — the corpus's own hand-curated cases make narrower, scenario-specific choices a mechanical rule can't cleanly reproduce without this scoping existing first. Filed as a follow-up.
  • Stage-2-reachable route_clarify. dev-ambiguous-clarify.toml demonstrates asking via a route_clarify tool call is more reliable than a prose question (a prose question is invisible to anything downstream expecting a tool call) — but route_clarify is currently Stage-1-only. Wiring a Stage-2 clarify tool is a real feature addition (registration, whitelisting, agent-loop turn-termination handling), not plumbing; clarification stays prose-only (AMBIGUITY_CLARIFY) for now. Filed as a follow-up.

Both are new production mechanisms the corpus's measurements point toward but that require design decisions beyond "make assembly match the corpus," which is this issue's scope. Flagging rather than building them ad hoc.

Prompt sizes (fixture-based, from the snapshot gate's golden files)

section before after
resident system prompt 3697 B 3537 B (−4.3%)
Stage-2 candidate block 12597 B 6563 B (−47.9%)
Stage-2 tool surface 21626 B 23800 B (+10.1%, per-request field declarations + worked examples moved here)

Net across these three: −10.6%, despite the tool surface growing — consistent with "expect substantial deletion."

Testing

  • cargo test -p nodespace-agent --test prompt_assembly_snapshot — 5/5 green, this is the primary correctness signal.
  • cargo test across nodespace-types, nodespace-core, nodespace-nlp-engine, nodespace-agent, nodespace-proto, nodespace-daemon, nodespace-cli — all green (57 test binaries, zero failures), including 20 new unit tests for the field-declaration mechanism (top-score selection, tie-union, type-conflict widening, empty-properties guard, a regression pin for a serde_json::Value IndexMut-insertion bug caught in review).
  • cargo clippy --all-targets on the same package set — zero warnings.
  • Full pre-push gate (scripts/test-gate.ts) — green, including the nodespace-app Tauri-seam suite.
  • cargo run -p nodespace-agent --bin gen_skill_md -- --check — SKILL.md in sync.

Agent-matrix (bun run eval:agent), before/after, isolated /tmp/nodespaced-test* daemons, purged DB, freshly built release binaries, gemma-4-e4b-q4km, n_ctx 32768

run commit passed
before (origin/main) 8c537818 14/16
after, rep 1 this branch 11/16
after, rep 2 this branch 13/16

Scenario 6 fails in all three runs identically (pre-existing, resolve_query/update_node sequencing — unrelated to this change). The two "after" reps disagree with each other on 3, 4, 8a, 8e, 9 — the same scenarios flip pass/fail on identical code between reps 1 and 2, consistent with this matrix's documented noise floor (agent-eval.md: "Identical code has scored 6, 7, and 7 out of 12"). The one scenario that fails in both after-reps but passed on before (8a, schema-vs-instance-creation confusion) is a real signal worth more reps to confirm, but two single-digit-scenario reps is exactly the sample size the golden corpus's own methodology (packages/agent/goldens/PATTERN.toml) warns is insufficient — it raised its own rep count to 5 after a 3-rep run gave a wrong answer once. I did not have budget in this session for a 5-rep matrix comparison (each rep is a fresh isolated daemon + ~15 real-inference-scenario run, several minutes each); recording both data points rather than averaging them into a false-precision single number, and flagging scenario 8a specifically for a follow-up 5-rep comparison rather than either dismissing it or blocking on it.

Dev-domain behavior wasn't separately live-probed against a running daemon beyond what the snapshot gate covers structurally — golden_runner doesn't exercise production source at all (it sends each .toml case's own hand-authored strings directly to the model, by design, per its own doc comment), so it can't validate this PR's changes; validating the dev-domain corpus end-to-end against real production output would need the same live-daemon setup as the agent-matrix run above, applied to NODESPACE_PROMPT_DUMP-captured production prompts for each corpus scenario — not done here for time.

Follow-ups filed

  • core#2148 — scope schema_metadata retrieval per node_types so write-tool field declarations target one type instead of unioning
  • core#2149 — wire a Stage-2-reachable route_clarify tool so ambiguity resolution is not prose-only

Update: final review round

A consolidated re-review of the pushed diff found two real bugs in the new mechanism and one real semantic gap, all fixed in a follow-up commit:

  1. declared_field_values_properties left a stale enum array behind on a type conflict. When a field name's occurrences included both an enum type and a conflicting non-enum type, the original left-to-right fold widened type to string but never cleared the pre-existing enum array — order-dependently more restrictive than the untyped fallback it was meant to replace (a legal non-enum value would be rejected by the grammar as not in the enum). Rewrote the function to group every occurrence of a field name before deciding type/enum, since the correct decision depends on the whole group, not on what's been folded in so far in one processing order. New test: declared_field_values_properties_clears_stale_enum_on_type_conflict, checked in both descriptor orders.
  2. declare_write_tool_fields's selection rule is a turn-global top score, not a per-tool one — the doc comment was ambiguous enough to read as the more generous per-tool version, which review correctly flagged as inconsistent with the code. Clarified the doc comment to state precisely what's implemented and why (a per-tool max would undo dev-schema-creation.toml's distractor-exclusion requirement — the lower-scoring candidate would trivially be "the top scorer among its own tool's whitelisters"). Added declare_write_tool_fields_does_not_declare_a_non_top_scoring_but_uncontested_tool, pinning the known, deliberate cost: a genuinely compound turn with two independently-relevant skills wanting two different tools only gets one of them declared — not a regression against pre-Generate write-tool field declarations from retrieved schemas, and delete the prose they replace #2120 production (every write tool is on the bare-object shape today), but a real limitation, now flagged for core#2148 rather than left as a latent surprise.
  3. Restored the "Call tools immediately... first response token must be the tool call" Response Rules bullet, deleted in the first commit as redundant with the new Core Identity line. On closer semantic reading it isn't: Core Identity's line is about outcome (don't answer in prose instead of calling a tool), the deleted bullet is about token order (don't narrate before the call either, even alongside one). Restored, golden regenerated, test expectations updated.
  4. Completed the RELEVANT ENTITY TYPES → EXISTING SCHEMAS terminology sweep — two doc-comment references survived (one in agent_loop.rs, one split across a line wrap in prompt_assembly_snapshot.rs that a single-line grep missed). A repo-wide grep for either string now returns zero hits, including in prompt_assembly_snapshot.rs itself (my first PR description claimed that file was the one deliberate exception — it no longer needs to be).

All four are Rust-level fixes with new or updated unit tests (cargo test -p nodespace-agent --lib: 507 passing, up from 505), not further golden-content changes beyond the one restored bullet. Snapshot gate, full workspace test suite, and clippy all re-verified green after these fixes.

… write-tool field declarations from retrieved schemas

Reproduces the tuned golden prompt corpus (packages/agent/goldens/,
core#2122) by moving each divergence to the channel ADR-064 assigns it,
deleting rather than duplicating:

- Resident identity line shortened to the tuned two-sentence form; the
  now-redundant "call tools immediately" RESPONSE RULES bullet is deleted
  (agent_guidance.rs, prompt_assembler.rs).
- skill_pipeline.rs's Node Creation and Schema Creation guidance cut to
  short "CALL X NOW" procedure text; worked JSON examples and per-field
  argument-shape prose move to tools.rs's tool descriptions, per ADR-064
  rule 1 and Finding 2. Business-domain examples (Invoice/Customer/Project)
  replaced with dev-workflow ones (Ticket/ADR/Sprint) throughout
  skill_pipeline.rs, skill_rules.rs, and tools.rs.
- `RELEVANT_ENTITY_TYPES_HEADER` renamed to `EXISTING_SCHEMAS_HEADER`
  ("EXISTING SCHEMAS (do not recreate these; do not copy their fields onto
  a new type):"), matching the corpus's constant across every call site,
  test, and doc comment (context_ops.rs, entity_types_block.rs, routing.rs,
  tools.rs, skill_pipeline.rs, agent_guidance.rs, agent_loop.rs).

Generates `create_node`/`update_node`'s `field_values` parameter per
request from retrieved schemas, declaring each field as a typed
sub-property with enums, instead of a bare object plus prose — the
pattern packages/agent/goldens/PATTERN.toml measures fixes a value silently
dropped 3/3 across eight prose-only arms. `declare_write_tool_fields`
(routing.rs) sources declarations from the schema_metadata of whichever
cleared candidate(s) whitelisting a given tool scored highest, unioning
ties and widening a field name's type to `string` on conflict; a tool
whitelisted only by a lower-scoring candidate stays undeclared, reproducing
`dev-schema-creation.toml`'s deliberate distractor case. Kept a separate
step from `stage2_tools`, gated behind `!session.routing_disabled` in
agent_loop.rs the same way `candidate_block` prompt injection already is —
this is retrieved-schema content, the class of payload the routing-
reliability matrix measured suppressing tool-calling on some models,
reaching the model through the tool-schema channel instead of the
prompt-text one.

Deferred to a follow-up: per-type-scoped retrieval (every candidate
currently carries the full non-core schema list, so a multi-type turn
unions rather than picks one type's fields) and a Stage-2-reachable
route_clarify tool (clarification stays prose-only pending that).
… no-prose-before-tool-call rule, complete terminology sweep

- declared_field_values_properties rewritten to group all occurrences of a
  field name before deciding its type/enum, instead of folding left-to-right.
  The fold version widened `type` to `string` on a type conflict but left a
  stale `enum` array behind when the conflict involved an enum occurrence,
  which is MORE restrictive than the untyped fallback it was meant to
  replace (order-dependent, reproducible in either descriptor order). Now:
  an `enum` restriction is applied only when EVERY occurrence of a field
  name is itself an enum; any plain-scalar occurrence anywhere removes the
  restriction entirely, regardless of processing order.
- declare_write_tool_fields's doc comment now states precisely what's
  implemented (a turn-global top score, not a per-tool one) and why: a
  per-tool max would undo dev-schema-creation.toml's distractor-exclusion
  requirement (a lower-scoring candidate would trivially be "the top scorer
  among its own tool's whitelisters"). Added a test pinning the known cost
  of that choice — a genuinely compound turn with two independently-relevant
  skills for two different tools only gets one of them declared, not a
  regression against pre-#2120 production, but a real limitation flagged
  for core#2148.
- Restored the "Call tools immediately... first response token must be the
  tool call" Response Rules bullet, deleted in the prior commit as
  redundant with the new Core Identity line. It isn't: Core Identity's line
  is about outcome (don't answer in prose INSTEAD of calling a tool), this
  one is about token order (don't narrate BEFORE the call either). Restored
  in prompt_assembler.rs and its test expectations, golden regenerated.
- Completed the RELEVANT ENTITY TYPES -> EXISTING SCHEMAS terminology sweep:
  two doc-comment references survived in agent_loop.rs and
  prompt_assembly_snapshot.rs (one split across a line wrap, missed by the
  prior single-line grep). A repo-wide grep for either string now returns
  zero hits.

All fixes caught in a final adversarial review pass; each is a Rust-level
fix with new or updated unit tests, not a golden-content change beyond the
one restored Response Rules bullet.
@mstomar125

Copy link
Copy Markdown
Contributor Author

APPROVE — self-approving per NodeSpace's core review policy (adversarial re-review required for core, self-approval authorized).

Verification performed

  • Read ADR-064 fully before touching source; read Prompt-assembly snapshot gate: assert production reproduces the tuned golden prompt (zero model calls) #2119's gate mechanism (prompt_assembly_snapshot.rs) and Author and tune the golden prompt corpus: production-shaped, dev-domain prompt strings #2122's golden corpus (packages/agent/goldens/*.toml, PATTERN.toml) fully before making any edit.
  • Two adversarial review passes on the initial diff (a general ADR-064-channel/duplication pass, and a pass focused specifically on the new declare_write_tool_fields/with_declared_field_values mechanism) — all findings addressed: a serde_json::Value IndexMut-insertion bug, an empty-properties-map over-narrowing bug, a routing_disabled safety-gating gap (retrieved-schema content reaching the model through the tool-schema channel ungated, while the equivalent prompt-text channel already is), plus several stale-terminology and unjustified-duplication findings.
  • A third, consolidated review pass on the full pushed diff found two more real bugs specific to the new mechanism (a stale-enum-on-type-conflict bug, and an ambiguous doc comment describing the selection rule differently from what the code implements) and one real semantic gap (a deleted resident-prose bullet that wasn't actually redundant with its replacement) — all fixed in the follow-up commit, each with a new or updated unit test.
  • My own full, independent line-by-line read of the complete diff (gh pr diff 2150), twice — once before the final review round, once after.
  • Snapshot gate green (cargo test -p nodespace-agent --test prompt_assembly_snapshot, 5/5), full workspace test suite green (57 test binaries across nodespace-types/nodespace-core/nodespace-nlp-engine/nodespace-agent/nodespace-proto/nodespace-daemon/nodespace-cli, zero failures, including 502→507 unit tests as fixes landed), cargo clippy --all-targets clean, full pre-push gate green (including the nodespace-app Tauri-seam suite), SKILL.md regenerated and verified in sync.
  • Live agent-matrix before/after comparison against isolated, freshly-built daemons (results and their noise-floor caveat in the PR description) — no live-model validation is perfect substitute for this being genuinely production-shaped work, but it's the best signal available without a multi-rep statistical run this session had budget for.
  • A repo-wide grep for RELEVANT ENTITY TYPES/RELEVANT_ENTITY_TYPES_HEADER now returns zero hits.

Merging.

@mstomar125
mstomar125 merged commit 2916dbe into main Aug 18, 2026
@mstomar125
mstomar125 deleted the issue-2120-prompt-assembly-plumbing branch August 18, 2026 15:54
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.

Generate write-tool field declarations from retrieved schemas, and delete the prose they replace

1 participant