Skip to content

Golden-prompt runner: iterate on agent prompts as data against llama.cpp, no recompile, no plumbing #2118

Closed

Description

@malibio

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 text
  • tools — tool definitions (name, description, parameters_schema) as literal JSON
  • history — prior turns, if the case needs them
  • user — the user message
  • expect — the expected outcome
  • reps — 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 assertions
  • sequence — an ordered chain of tool calls
  • clarify — the model called route_clarify
  • text — 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 through LlamaChatInferenceEngine (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
  • reps supported; 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.rs does) 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 --ignored golden 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

  1. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    Paired with #2119 (the snapshot gate). Together they close the loop the scenario-6 golden tests started but never finished:

    1. Golden-prompt runner: iterate on agent prompts as data against llama.cpp, no recompile, no plumbing #2118 — tune the prompt as data against llama.cpp until it reliably does the right thing
    2. Freeze the passing prompt as a golden
    3. Prompt-assembly snapshot gate: assert production reproduces the tuned golden prompt (zero model calls) #2119 — fails until production assembly reproduces it
    4. Fix the assembly line (delete prose the tuned version proved unnecessary; move content to the channel ADR-064 says owns it)

    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.

  2. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    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), and LlamaChatInferenceEngine::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:

    1. Load once per invocation, run all reps and all cases — the floor. A directory of 10 cases × 3 reps pays one model load, not 30.
    2. Watch mode — process stays alive with the model resident, re-runs when a case file changes on disk. This is the actual tuning loop: edit prompt, save, watch the result, adjust. Model load is paid once per session.
    3. Free win already in place — generate_blocking reuses the KV cache across calls via longest-common-token-prefix matching against cached_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

    • Model is loaded once per invocation, not once per case or per rep
    • Runner accepts a directory of case files and executes all of them in one process
    • Watch mode: process stays alive with the model resident and re-runs on case-file change
    • Summary output reports per-case N/N across the whole set, so a prompt edit's effect on every tuned case is visible in one run
    • Case execution order does not gratuitously defeat the existing KV-cache prefix reuse
  3. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    Sequencing: #2118 → #2120 → #2119 → #1977

    These four are one line of work. Recording the order and the reasoning so it survives a context reset.

    # issue why here
    1 #2118 — golden-prompt runner Nothing else can proceed without a fast tuning loop. No domain decisions, no live-measurement dependency.
    2 #2120 — retarget guidance + trim The substantive manual work. Needs #2118 to be iterable; must precede the eval retarget.
    3 #2119 — assembly snapshot gate Freezes the tuned prompt as production's target. Placed after #2120 so the golden is captured once, not churned through a wholesale rewrite.
    4 #1977 — matrix + routing fixtures Retargeting the eval before the guidance would tune the two in opposite directions — scores would likely drop with nothing actually wrong.

    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 the coreValues/core_values contradiction 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.rs still 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_DUMP already dumps it at the native-path chokepoint — the gate is not needed for that.

    Adjacent, not blocking

  4. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    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).

    name = "indirect-reference-resolves-without-asking-for-an-id"
    reps = 3
    
    system = """
    You are a graph-editing assistant. When a request refers to something \
    indirectly (a bare value, a description) rather than by name, call \
    resolve_query to find it. Never ask the user to supply a node id yourself.
    """
    
    user = "The 2400 one came back — set it to returned"
    
    [[tools]]
    name = "resolve_query"
    description = """
    Resolve an indirect reference (a bare value, a relative date, a description) \
    to the single node it refers to. Returns the node directly -- do not call \
    search_nodes afterward.
    """
    parameters_schema = '''
    {
      "type": "object",
      "properties": {
        "request":   {"type": "string", "description": "The user's request, verbatim."},
        "node_type": {"type": "string", "description": "The target node type id."}
      },
      "required": ["request", "node_type"]
    }
    '''
    
    [[tools]]
    name = "update_node"
    description = "Update an existing node's properties, given its id."
    parameters_schema = '''
    {
      "type": "object",
      "properties": {
        "id":         {"type": "string"},
        "properties": {"type": "object"}
      },
      "required": ["id"]
    }
    '''
    
    [expect]
    kind = "tool"
    tool = "resolve_query"

    Note what the system field 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, and reps says whether the change held.

    The four expectation kinds, concretely

    # 1. A specific tool, optionally with argument assertions
    [expect]
    kind = "tool"
    tool = "create_schema"
    args_contain = { name = "Spec" }        # optional; subset match, not equality
    
    # 2. An ordered chain
    [expect]
    kind = "sequence"
    tools = ["resolve_query", "update_node"]
    min_properties_on = "update_node"        # guards the id-only-call failure below
    
    # 3. Asking the user is the correct answer
    [expect]
    kind = "clarify"
    
    # 4. A text reply with no tool call
    [expect]
    kind = "text"

    args_contain is 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_on exists because of a measured harness bug worth not repeating: the matrix's toolSequence originally matched tool names only, so update_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_turn in the existing golden test extracts ToolCallStart{name} plus concatenated ToolCallArgs{args_json}; everything else is diagnostic.

    Two failure shapes must be distinguishable in the output, because they have opposite fixes:

    • No tool call parsed at all — the model replied in prose, or narrated a tool call as text. Distinct from calling the wrong tool. The runner must print "no tool call parsed" rather than collapsing it into a generic failure. (agent_loop.rs::looks_like_narrated_tool_call exists because the model does emit well-formed calls as text, and the turn then silently does nothing.)
    • Right tool, empty or wrong arguments — the min_properties_on case above.

    Report shape

    Per-rep line plus a tally, so a flaky case is visibly flaky rather than averaged away:

    indirect-reference-resolves-without-asking-for-an-id   3/3  ✓
      rep 1  resolve_query({"request":"The 2400 one came back...","node_type":"equipment"})
      rep 2  resolve_query({"request":"The 2400 one came back...","node_type":"equipment"})
      rep 3  resolve_query({"request":"The 2400 one came back...","node_type":"equipment"})
    
    compact-history-variant                                1/3  ✗
      rep 1  resolve_query({...})
      rep 2  no tool call parsed
      rep 3  update_node({"id":"<unknown>"})
    

    Cases that are findings rather than assertions

    golden_compact_history_variant deliberately 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, and observe, 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.

  5. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    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_schema stays JSON (embedded as a TOML string containing JSON, or an inline TOML table — going with an inline table so it round-trips through serde_json::Value cleanly).

    Parse boundary is production's. The runner accumulates StreamingChunks and applies repair_tool_call_arguments exactly as agent_loop.rs:1370 does — same repairs, same order — so a case measures what a real turn would do. parse_chunks is a private associated fn on LocalAgentLoop; 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 as ToolCallRaw) is appended to the next turn's history via ChatMessage::assistant_with_tool_calls, and a turn may declare a literal tool_result to feed back — closing the loop golden_scenario6_sequence.rs left 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. sequence supports min_properties_on = { update_node = 1 }. Outcome reporting distinguishes NoToolCall from WrongTool as 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 outside cargo test entirely 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.rs becomes a set of single-turn cases (zero-history control, compact-history, medium/terse calibration arms), golden_scenario6_sequence.rs becomes one 3-turn chained case. Living under packages/agent/goldens/.

    Out of scope, confirmed: no change to any production prompt text, no assembly-snapshot gate, no new corpus authoring.

  6. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    Baseline on worktree-issue-2118-golden-prompt-runner — Frontend: 216 test files passed, 4704 tests passed, 0 failed (76.49s).

  7. self-assigned this
    on Aug 17, 2026
  8. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    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

    • Read a case file: system prompt, tools (name/description/parameters_schema), optional history, user message
    • Build ChatMessage[] + ToolDefinition[], call LlamaChatInferenceEngine::generate()
    • Print the tool call (name + arguments) or the text reply, or "no tool call parsed"
    • Optional --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)
    • Model loaded once per invocation

    Dropped from the original spec

    • Watch mode
    • Directory batch execution
    • Expectation kinds (tool/sequence/clarify/text/observe), args_contain, min_properties_on
    • N/N tallies and pass/fail reporting

    The fidelity requirement is unchanged and remains the load-bearing constraint: it must go through LlamaChatInferenceEngine → ChatEngine so the chat template (PEG_GEMMA4), chat/parser.rs, and repair_tool_call_arguments are the real ones. That is the entire reason this is a Rust bin rather than curl against llama-server.

    Revised acceptance criteria

    • Bin in packages/agent/src/bin/ reads a case file (system prompt, tools, optional history, user message)
    • Calls the model through LlamaChatInferenceEngine — same template, parser, and argument repairs as production
    • Prints the tool call name and arguments, distinguishing "no tool call parsed" from a wrong call
    • --reps N runs the same case N times with one model load
    • No daemon, no DB, no gRPC, no agent loop, no PromptAssembler, no routing
    • Editing the prompt and re-running requires no recompile
    • One committed example case file, ported from the validated zero-history resolve_query golden, reproducing its known result
  9. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    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.

    # issue deliverable touches production source?
    1 #2118 the utility (PR #2121) new bin only
    2 #2122 tuned golden prompt strings no
    3 #2119 snapshot gate test only
    4 #2120 assembly emits the goldens yes
    5 #1977 eval retargeted to match fixtures only

    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.

  10. malibio commented on Aug 17, 2026

    @malibio
    CollaboratorAuthor

    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 in packages/agent/goldens/. Additive only, +1,523 / −0, entirely within packages/agent. 21 unit tests in the default run.

    Both golden_scenario6_handauthored.rs and golden_scenario6_sequence.rs remain in tests/ 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, so apply_chat_template (PEG_GEMMA4), chat/parser.rs, and repair_tool_call_arguments are production's own, the last applied at the same parse boundary as agent_loop.rs:1370. parse_output mirrors the private LocalAgentLoop::parse_chunks; the one divergence (dropping Reasoning) is deliberate and documented.

    Findings recorded for downstream work — full detail on #2122:

    • History compaction should produce terse facts, not shorter narrative summaries. Style beat size in a controlled comparison: a narrative arm failed at a token count a terse arm passed.
    • scenario6-full-sequence turn 3 resolves and then stops, never continuing to update_node (0/3). The single-turn-pull boundary, cheaply reproducible.
    • Within-session 3/3 overstates stability: the same case gave different node_type arguments across sessions, each internally 3/3. Tool names were stable; arguments were not.

    🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions