Repository navigation
Retarget prompt assembly to dev-workflow domain; generate write-tool field declarations from retrieved schemas - #2150
Merged
Conversation
… 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).
9 tasks
… 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.
Contributor
Author
|
APPROVE — self-approving per NodeSpace's core review policy (adversarial re-review required for core, self-approval authorized). Verification performed
Merging. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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'scustom:-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'sfield_valuesparameter 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 andcreate_schema's worked JSON examples moved fromskill_pipeline.rsprose onto the tools' own descriptions intools.rs(ADR-038 Finding 2: the model reproduces the worked example nearest where it reads the schema, so that's where the pattern belongs).RELEVANT_ENTITY_TYPES_HEADERconstant is renamedEXISTING_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 acrosscontext_ops.rs,entity_types_block.rs,routing.rs,tools.rs,skill_pipeline.rs,agent_guidance.rs,agent_loop.rs— a grep forRELEVANT ENTITY TYPESnow returns zero hits outside the untouchedprompt_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'sdev-instance-creation.toml/dev-schema-creation.tomlcandidate text closely. The deleted content (field-type mechanics,title_templaterules, the three JSON worked examples) is the content that moved totools.rs's tool descriptions.graph_editing_guidance()andrelationship_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, andtools.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'sroute_querytool 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 everysystemfield across all 8dev-*.tomlcorpus cases, so not invented.systemfields 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.tomlmeasures (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 offield_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) buildsfield_values.propertiesfrom the retrievedschema_metadataalready flowing throughSkillCandidate(the same dataEXISTING SCHEMASrenders from). Selection rule, inferred from which corpus cases declare fields and which deliberately don't (the corpus states outcomes per case, not a mechanism):dev-schema-creation.toml's distractorcreate_node(offered alongsidecreate_schemaspecifically 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).node_typeyet at declaration time); with different non-enum types, it widens tostring(JSON Schema's most permissive scalar) rather than silently keeping whichever descriptor was processed first.field_valuesto an explicitproperties: {}(more restrictive than the untyped-object fallback it would replace) — only a non-empty declaration is written.Gated the same way
candidate_blockprompt injection already is: this is retrieved-schema content, the class of payloadtests/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), soagent_loop.rscallsdeclare_write_tool_fieldsonly when!session.routing_disabled, deliberately kept as a separate step fromstage2_toolsrather 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
CreateNodeParams/UpdateNodeParamsare untouched. Only theparameters_schemaJSON the model reads changed; no handler, param struct, or storage path changed.field_valuesrename (already merged) — this issue builds on it, doesn't revisit it.prompt_assembly_snapshot.rswas touched in exactly one place:stage2_tool_surface_matches_goldennow also callsdeclare_write_tool_fieldsafterstage2_tools, because that's whatagent_loop.rs's real, routing-enabled path does, and the gate's own stated design is to reproduce production faithfully. No assertion logic changed.SKILL.mdstructural enforcement (core#1958).Explicitly deferred (documented, not silent)
node_types, so every candidate'sschema_metadatacarries the full non-core schema list rather than a scoped subset. A turn with two relevant types (e.g.ticket+adrboth 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.route_clarify.dev-ambiguous-clarify.tomldemonstrates asking via aroute_clarifytool call is more reliable than a prose question (a prose question is invisible to anything downstream expecting a tool call) — butroute_clarifyis 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)
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 testacrossnodespace-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 aserde_json::ValueIndexMut-insertion bug caught in review).cargo clippy --all-targetson the same package set — zero warnings.scripts/test-gate.ts) — green, including thenodespace-appTauri-seam suite.cargo run -p nodespace-agent --bin gen_skill_md -- --check—SKILL.mdin 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 32768origin/main)8c537818Scenario 6 fails in all three runs identically (pre-existing,
resolve_query/update_nodesequencing — 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_runnerdoesn't exercise production source at all (it sends each.tomlcase'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 toNODESPACE_PROMPT_DUMP-captured production prompts for each corpus scenario — not done here for time.Follow-ups filed
route_clarifytool so ambiguity resolution is not prose-onlyUpdate: 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:
declared_field_values_propertiesleft a staleenumarray 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 widenedtypetostringbut never cleared the pre-existingenumarray — 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.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 undodev-schema-creation.toml's distractor-exclusion requirement — the lower-scoring candidate would trivially be "the top scorer among its own tool's whitelisters"). Addeddeclare_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.RELEVANT ENTITY TYPES→EXISTING SCHEMASterminology sweep — two doc-comment references survived (one inagent_loop.rs, one split across a line wrap inprompt_assembly_snapshot.rsthat a single-line grep missed). A repo-wide grep for either string now returns zero hits, including inprompt_assembly_snapshot.rsitself (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.