Repository navigation
Description
Overview
Tune agent prompts by editing a text file and re-running, with no recompile and no NodeSpace plumbing in the path. The prompt text becomes the artifact under iteration; the NodeSpace assembly line is then engineered to reproduce it (the snapshot gate is a separate issue).
This generalizes a methodology that already worked here. packages/agent/tests/golden_scenario6_handauthored.rs and golden_scenario6_sequence.rs state it in their own headers:
assemble a sequence of literal prompt strings, validate directly against llama.cpp with zero NodeSpace plumbing involved, until a version is found that reliably gets the correct tool call. THAT becomes the target the real assembly pipeline is engineered toward — not the other way around.
Those two files proved the approach but stayed bespoke: one scenario, hand-rolled engine loaders, assertions in Rust, prompts as string literals. Every prompt tweak needs a recompile, which is why it never became the general tuning loop.
Problem Statement
Today, iterating on a prompt hypothesis costs either a full matrix run (daemon rebuild + DB purge + minutes, and it conflates prompt quality with plumbing behavior) or a Rust edit-and-recompile cycle against a bespoke test file.
Neither supports the actual workflow: read the prompt, shorten it, re-run, see if the model still does the right thing.
Separating the two questions is the point:
- "Does this exact prompt text get the right tool call?" — answerable in seconds against llama.cpp directly.
- "Does the real pipeline assemble that exact prompt?" — a deterministic, zero-model-call question (see the snapshot-gate issue).
Conflating them is what made every prior checkpoint expensive.
Fidelity requirement (the load-bearing constraint)
The runner must go through LlamaChatInferenceEngine → nlp-engine::ChatEngine, not a hand-rolled llama.cpp call or llama-server HTTP.
That layer is not neutral. generate_blocking (packages/nlp-engine/src/chat/mod.rs:343) applies the model's chat template and returns chat_format, parse_tool_calls, and additional_stops alongside the prompt — Gemma 4 resolves to PEG_GEMMA4 (format 3), and the code explicitly warns that chat_format=0 silently turns tool calls into unparsed text. Tool-call extraction then runs through NodeSpace's own chat/parser.rs, and argument repairs run through repair_tool_call_arguments.
Tuning against a different template or parser means tuning against a fiction. This project has already been bitten by that class of error: ADR-038's findings were gathered on llama-server build 8660 and ADR-046 later recorded that they did not transfer through NodeSpace's inference path.
So: no NodeSpace plumbing (no daemon, no DB, no gRPC, no agent loop, no PromptAssembler, no routing, no chat-node lifecycle), but the same templating, parsing, and argument repair production uses.
Proposed design
A case file (JSON or TOML) holding everything the model sees, as data:
system— the system prompt, as plain multi-line texttools— tool definitions (name, description, parameters_schema) as literal JSONhistory— prior turns, if the case needs themuser— the user messageexpect— the expected outcomereps— how many times to run it
The tuning surface is deliberately pre-template (messages + tool defs), not the final templated string. That is where all four ADR-064 channels actually live — resident prose (system message), tool schemas and descriptions (tool defs), skill instructions (injected block), and history — and it is what we want to shorten and reword. The template below it is fixed machinery. Post-template fidelity comes free by construction, and NODESPACE_PROMPT_DUMP can dump the final string whenever it needs inspecting.
A bin in packages/agent/src/bin/ (precedent: gen_skill_md.rs) loads a case file, runs it N times through the engine, and reports per-rep outcomes plus an N/N tally.
Expectation kinds
At minimum:
tool— named tool called, optionally with argument assertionssequence— an ordered chain of tool callsclarify— the model calledroute_clarifytext— a text reply with no tool call
clarify is a first-class expected outcome, not a failure mode. route_clarify is already a typed tool (routing.rs:97) and ADR-038's clarification contract is explicit: at most one clarification per intent, and it must surface concrete candidates rather than a bare "what do you mean?". A genuinely ambiguous case whose correct answer is "ask the user" must be assertable as a pass.
Reps are mandatory, not optional
The runner reports N/N, never a single pass/fail. The recorded evidence here is emphatic that single runs are not decision-grade: identical code scored 6/7/7 on the matrix (#1862/#1911), and scenario 6's resolve_query behavior measured 3/3 with no history and 0/8 with history depending on what was carried forward.
Acceptance Criteria
- Case-file format defined and documented, holding system prompt / tools / history / user message / expectation / reps as data
- Runner bin in
packages/agent/src/bin/loads a case file and executes it throughLlamaChatInferenceEngine(same template, same parser, same argument repairs as production) - No daemon, no DB, no gRPC, no agent loop, no
PromptAssembler, no routing in the path - Expectation kinds implemented:
tool(with optional argument assertions),sequence,clarify,text -
repssupported; output reports per-rep outcome and an N/N tally, never a bare pass/fail - Multi-turn cases supported, chaining a real turn's output into the next turn's history (as
golden_scenario6_sequence.rsdoes) rather than a hand-picked stand-in - Editing a prompt and re-running requires no recompile
- The two existing scenario-6 golden tests are expressible as case files, reproducing their current results
- A worked case file is committed alongside the format definition (not only documented), so the schema has a reference instance
- "No tool call parsed" is reported distinctly from "wrong tool called" — the two have opposite fixes
-
expect.kind = "observe"supported: runs reps, prints outcomes, never fails (exploratory probes before a target is known) - Argument assertions are subset matches, not full-blob equality
- A sequence assertion can require the write actually carried properties (see
min_properties_on), not just that the tool name appeared - Both existing scenario-6 goldens ship as case files and reproduce their current results
- Runner is excluded from the default test run (loads a ~5GB GGUF); documented invocation, consistent with the existing
--ignoredgolden tests
Out of scope
- Asserting that production assembly reproduces a golden — that is the snapshot-gate issue
- Authoring the dev-domain golden corpus — separate issue
- Changing any production prompt text
Notes
- Model path convention already used by the golden tests:
$HOME/.nodespace/models/gemma-4-E4B-it-Q4_K_M.gguf(ADR-056 locked native model) NODESPACE_PROMPT_DUMP(packages/nlp-engine/src/chat/prompt_dump.rs) dumps the exact final prompt string at the single native-path chokepoint, covering Stage 1, Stage 2,resolve_query, and the routing probe. Useful for seeding a case file from a real session's assembled prompt.- Eval-contamination guard (Eval-contamination guard does not cover tool descriptions or parameter schemas #1932, landed) now covers tool descriptions and parameter schemas. Golden cases and golden guidance examples must stay lexically distinct, or a case proves only that the model memorized its own answer key.
Activity
malibio commentedon Aug 17, 2026
Paired with #2119 (the snapshot gate). Together they close the loop the scenario-6 golden tests started but never finished:
Neither half is useful alone: without #2119 a tuned prompt is a finding in a test file rather than a target; without #2118 there is nothing to freeze.
Related: #1977 (matrix scenarios → dev-workflow domain) supplies the intents these cases should be written in.
malibio commentedon Aug 17, 2026
Added requirements: model stays resident, and batch/watch over a case directory
Raised while scoping: the model must not be reloaded per tuning iteration.
The locked native model is a 5.0GB GGUF (
gemma-4-E4B-it-Q4_K_M.gguf), andLlamaChatInferenceEngine::load()documents itself as a blocking operation covering model load plus Metal kernel compilation (inference.rs:32,chat/mod.rs:160). Paying that on every prompt edit makes the manual tuning loop unusable — which is a large part of why the existing bespoke golden tests never became the general loop.Three levels, in increasing order of usefulness:
generate_blockingreuses the KV cache across calls via longest-common-token-prefix matching againstcached_prompt(chat/mod.rs:419-456). Cases sharing a system-prompt prefix only decode the delta. Worth not defeating this: run cases sharing a prefix consecutively rather than interleaved.Directory/batch mode also matters for a second reason — once several cases are tuned, a prompt edit needs re-validating against all of them, not just the one being worked on. Shortening resident prose to fix case A while silently breaking case B is exactly the regression this harness exists to catch, and it is only visible if the whole set re-runs cheaply.
Additional acceptance criteria
malibio commentedon Aug 17, 2026
Sequencing: #2118 → #2120 → #2119 → #1977
These four are one line of work. Recording the order and the reasoning so it survives a context reset.
Why the snapshot gate is third, not first
It was initially argued for first, on the grounds that snapshotting today's assembly turns four independently-edited surfaces (
agent_guidance.rs,tools.rs,skill_pipeline.rs,routing.rs) into a reviewable diff — which is real, and would have caught thecoreValues/core_valuescontradiction ADR-064 records as shipped.But the snapshot would capture today's invoice-flavored prompt, and #2120 then rewrites it wholesale. Nearly every diff during that window is intended, so the gate's actual value — catching unintended drift — is thin exactly when it would be running. Capturing the golden once, after the rewrite settles, is cleaner than regenerating it through two rounds of deliberate change.
The risk this ordering carries, and its mitigation
The failure mode is the #1917 pattern repeating: tune by hand, get a good result, close the issue, never build the gate. That is not hypothetical — it is what happened, and
live_stage1_golden_prompts.rsstill carries the header comment saying the snapshot tests are "not yet written."Mitigation is in #2120's acceptance criteria rather than in the ordering: every tuned prompt is checked in as a #2118 case file. The work is durable whether or not #2119 lands promptly, and #2119 becomes the step that converts those case files into a production contract rather than the only thing standing between tuning and lost work.
For reading the current assembled prompt while deciding what to cut,
NODESPACE_PROMPT_DUMPalready dumps it at the native-path chokepoint — the gate is not needed for that.Adjacent, not blocking
friendly_namein schema tools) — independent_seedreconciliation, though evals still need a daemon rebuild since guidance is compiled inmalibio commentedon Aug 17, 2026
What a case file actually looks like, and what "a good response" means
Gap flagged on review: the issue specifies the format but never shows a filled-in case, so an implementer knows the fields exist without knowing what goes in them. Concrete shape below, translated from
golden_scenario6_handauthored.rs::golden_zero_history_control— an already-validated case (resolve_query, 3/3 at zero history, per #1922).Note what the
systemfield is: the whole resident prompt for that case, hand-authored in the file. That is the thing being tuned. Shortening it, rewording it, or deleting a rule is a text edit here, andrepssays whether the change held.The four expectation kinds, concretely
args_containis a subset match rather than equality on purpose — asserting a full argument blob makes every case brittle against harmless phrasing differences in free-text fields.min_properties_onexists because of a measured harness bug worth not repeating: the matrix'stoolSequenceoriginally matched tool names only, soupdate_node({"id": "..."})carrying no properties scored as a pass. Closing it needed three coordinated changes, and the first alone was silently inert (#1917 closing comment). A sequence assertion that cannot see whether the write carried anything is not asserting the thing that matters.What "a good response" means, and the two failure modes to encode
The model's response is judged on the tool call it made, not on its prose.
run_turnin the existing golden test extractsToolCallStart{name}plus concatenatedToolCallArgs{args_json}; everything else is diagnostic.Two failure shapes must be distinguishable in the output, because they have opposite fixes:
agent_loop.rs::looks_like_narrated_tool_callexists because the model does emit well-formed calls as text, and the turn then silently does nothing.)min_properties_oncase above.Report shape
Per-rep line plus a tally, so a flaky case is visibly flaky rather than averaged away:
Cases that are findings rather than assertions
golden_compact_history_variantdeliberately asserts nothing — its comment says "the printed result IS the finding". It is a discriminating experiment (is the defect prompt size/shape, or presence-of-any-history?), and forcing it to declare pass/fail would destroy its purpose.Support
expect.kind = "observe": run the reps, print what happened, never fail. Exploratory probes are how the tuning loop is actually used before a target is known.Seed cases to ship with the runner
To avoid landing a runner with nothing to run — and since the dev-domain corpus is not decided until #2120 — port the two existing scenario-6 goldens as the initial case files. They are already validated, they exercise
tool,sequence, andobserve, and reproducing their known results is the acceptance criterion that proves the runner faithful. #2120 then adds dev-domain cases on top of a harness already known to work.malibio commentedon Aug 17, 2026
Design decisions for implementation (proceeding unless redirected)
Case-file format: TOML. Multi-line prompt text is the primary thing being edited by hand; TOML triple-quoted strings keep system prompts and history readable without JSON escaping. Tool
parameters_schemastays JSON (embedded as a TOML string containing JSON, or an inline TOML table — going with an inline table so it round-trips throughserde_json::Valuecleanly).Parse boundary is production's. The runner accumulates
StreamingChunks and appliesrepair_tool_call_argumentsexactly asagent_loop.rs:1370does — same repairs, same order — so a case measures what a real turn would do.parse_chunksis a private associated fn onLocalAgentLoop; rather than making the whole loop reachable, the runner reimplements the same 20-line accumulation. Flagging that as intentional duplication of a trivially-shaped function, not an oversight.Multi-turn chaining. A case may declare
[[turn]]blocks. Each turn's real output (assistant text + emitted tool calls asToolCallRaw) is appended to the next turn's history viaChatMessage::assistant_with_tool_calls, and a turn may declare a literaltool_resultto feed back — closing the loopgolden_scenario6_sequence.rsleft as a TODO. Reps apply to the whole sequence: N independent runs of the full chain, not N reps of each turn independently.Expectation kinds:
tool,sequence,clarify,text,observe. Argument assertions are recursive subset matches over the parsed JSON.sequencesupportsmin_properties_on = { update_node = 1 }. Outcome reporting distinguishesNoToolCallfromWrongToolas separate variants, so the N/N tally breaks down by failure kind rather than collapsing to a count.Invocation.
cargo run -p nodespace-agent --bin golden_runner -- <case.toml>— a bin, so it is outsidecargo testentirely and cannot be pulled into the default run. Model path defaults to the ADR-056 catalog path, overridable with--model.Committed cases. Both scenario-6 goldens ported:
golden_scenario6_handauthored.rsbecomes a set of single-turn cases (zero-history control, compact-history, medium/terse calibration arms),golden_scenario6_sequence.rsbecomes one 3-turn chained case. Living underpackages/agent/goldens/.Out of scope, confirmed: no change to any production prompt text, no assembly-snapshot gate, no new corpus authoring.
malibio commentedon Aug 17, 2026
Baseline on worktree-issue-2118-golden-prompt-runner — Frontend: 216 test files passed, 4704 tests passed, 0 failed (76.49s).
malibio commentedon Aug 17, 2026
Scope correction: a one-time utility, not a harness
Direction from the user: keep this to a small one-time utility. Drop the harness framing — no watch mode, no directory batch runner, no expectation-kind assertion engine, no pass/fail scoring.
What it is: ~150 lines that read a case file, call the model through NodeSpace's real path, and print what came back. The human reads the output and judges it. That is the loop.
Why the assertion machinery was wrong here: the tuning loop is look at the response and decide, not assert and score. Encoding expectations in the file only matters when something automated consumes them — that is #2119's job (holding production to a frozen golden), and the matrix already covers end-to-end scoring. Building a third scoring system here duplicates both.
Revised scope
ChatMessage[]+ToolDefinition[], callLlamaChatInferenceEngine::generate()--reps N, since single runs are not decision-grade here (identical code scored 6/7/7 on the matrix; scenario 6 measured 3/3 vs 0/8 depending on history)Dropped from the original spec
Watch modeDirectory batch executionExpectation kinds (tool/sequence/clarify/text/observe),args_contain,min_properties_onN/N tallies and pass/fail reportingThe fidelity requirement is unchanged and remains the load-bearing constraint: it must go through
LlamaChatInferenceEngine→ChatEngineso the chat template (PEG_GEMMA4),chat/parser.rs, andrepair_tool_call_argumentsare the real ones. That is the entire reason this is a Rust bin rather than curl againstllama-server.Revised acceptance criteria
packages/agent/src/bin/reads a case file (system prompt, tools, optional history, user message)LlamaChatInferenceEngine— same template, parser, and argument repairs as production--reps Nruns the same case N times with one model loadPromptAssembler, no routingresolve_querygolden, reproducing its known resultSimplify to a one-time utility per rescope (#2118)
malibio commentedon Aug 17, 2026
Revised sequencing: #2118 → #2122 → #2119 → #2120 → #1977
Supersedes the earlier sequencing comment. The chain gained a step and #2120 was rescoped, because the previous plan had no issue that actually produced the golden corpus — #2119 would have asserted against goldens nobody authored.
The split that matters
#2120 previously mixed what should the prompt say with edit the files that emit it. That is the exact conflation this effort exists to remove — a failure could be a bad prompt or bad plumbing, indistinguishable.
Now:
A failure in #2122 is a prompt failure. A failure in #2120 is a plumbing failure. By construction.
Why #2119 moved ahead of #2120
The gate is what defines #2120's done condition. "Make plumbing match" has no test without it.
The governing requirement across all of them
Goldens must be production-shaped: same blocks, same structure, same tool surface as what NodeSpace actually sends — with the content of those blocks being what is tuned. A minimal hand-authored prompt is a useful control but not a target; scenario 6 is the cautionary case, at 3/3 hand-authored vs 0/8 in production for the same task.
malibio commentedon Aug 17, 2026
Closed by PR #2121 (
709e4870)Delivered against the revised acceptance criteria — all 7 met.
What shipped:
packages/agent/src/golden/{case,runner,mod}.rs,src/bin/golden_runner.rs, and two case files inpackages/agent/goldens/. Additive only, +1,523 / −0, entirely withinpackages/agent. 21 unit tests in the default run.Both
golden_scenario6_handauthored.rsandgolden_scenario6_sequence.rsremain intests/as the validated Rust-side reference. An earlier revision deleted them; that was reverted, along with the doc-comment repoints it forced in the daemon.Scope note: this issue delivered the utility. The two committed case files are ports of the existing Rust goldens, run 3/3 to confirm the port is faithful — not tuned prompts. No edit-rerun-compare loop was run here. Authoring and tuning the corpus is #2122, where the measured findings from building this have been posted as a handoff.
Fidelity, verified line-by-line in review:
LlamaChatInferenceEngine→ChatEngine, soapply_chat_template(PEG_GEMMA4),chat/parser.rs, andrepair_tool_call_argumentsare production's own, the last applied at the same parse boundary asagent_loop.rs:1370.parse_outputmirrors the privateLocalAgentLoop::parse_chunks; the one divergence (droppingReasoning) is deliberate and documented.Findings recorded for downstream work — full detail on #2122:
scenario6-full-sequenceturn 3 resolves and then stops, never continuing toupdate_node(0/3). The single-turn-pull boundary, cheaply reproducible.node_typearguments across sessions, each internally 3/3. Tool names were stable; arguments were not.🤖 Generated with Claude Code
Golden prompt corpus: dev-workflow cases + context ablation (closes #…