Skip to content

ai-chat agent quality: fix runaway/hang + tool-call template leaks, tune prompts - #1331

Merged
malibio merged 5 commits into
mainfrom
worktree-ai-chat-cli-prompting
Jun 5, 2026
Merged

malibio merged 5 commits into
mainfrom
worktree-ai-chat-cli-prompting

Conversation

@malibio

@malibio malibio commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

Summary

Improves local ai-chat agent response quality on Gemma 4 E4B, driven via a headless CLI harness (no UI). Removes the infrastructure-level failure modes that were independent of model size — multi-minute hangs, runaway/repetition loops, and chat-template token leaks — and tunes the seeded prompts/skills.

This builds on the prior WIP commit (dff3b855: embedding-service fix, tool_calls plumbing, model/chat CLI harness).

What changed

Loop & sampling (agent_loop.rs, chat/mod.rs)

  • Cap any single inference round at MAX_RESPONSE_TOKENS=2048 (was 16384) — a runaway is now bounded to seconds, not minutes.
  • Add a repetition penalty to the sampler chain (penalties(256, 1.3, 0, 0) before temp) — kills degenerate loops small models fall into at near-greedy temperature.
  • Persist assistant tool-call turns with empty content (drop chatty prose) so the Gemma template stops collapsing prose+call+result into one malformed turn.

Chat template (chat/mod.rs) — fixes an ffi error -3 turn abort the empty-content change surfaced

  • Emit content: null (not "") for assistant tool-call turns.
  • Normalize non-object tool-call arguments to "{}" so a malformed/empty tool call never feeds invalid JSON into the Jinja template.

Response normalization (response_processing.rs, tested)

  • Strip leaked tool-call/response prose (call:foo{...}response:foo{...}, nested braces handled).
  • Strip Gemma channel/thought reasoning blocks (<|channel>…<channel|> + dangling/stray variants).
  • Add <|channel>/<channel|> to strip_gemma_special_tokens.

Prompt/skill tuning (agent_guidance.rs, prompt_assembler.rs, skill_pipeline.rs)

  • "DATABASE = SCHEMA" routing rule ("create an invoice tracking database" → create_schema).
  • Loud "conversational turns use NO tools" rule.
  • Response rules: 1–2 sentences; empty/error tool result → state and stop, no retry.
  • Schema Creation: "ONE SCHEMA PER REQUEST" — no proactive related-type creation.

Verification

Live matrix on gemma-4-e4b-q4km via the CLI harness: greeting (multi-min hang → ~12s), capability question (no longer loops to the token cap), schema creation (routes to create_schema, recovers cleanly, no leaks), instance creation, listing, and empty-result query all functionally correct and clean.

Tests: agent 232, nlp-engine 61, core 890, frontend 3841, skill 17 — all pass. quality:fix clean.

Follow-ups (filed)

🤖 Generated with Claude Code

Michael Libio and others added 2 commits June 5, 2026 11:37
…ness

## Completed in This Session
- [x] Fix release-build compile error on main: node_to_proto(node.clone(), None, None)
      → 1-arg call in packages/daemon/src/services/node_service.rs (leftover from #1322).
- [x] Fix embedding_service:None production bug: GraphToolExecutor in
      local_agent_service.rs replace_engine was built with embedding_service:None,
      so search_semantic ALWAYS errored and skill-based select_tools routing was
      bypassed (full 13-tool list always sent). Now reads inner.embedding_service.
      Durable fix tracked in #1328.
- [x] Add tool_calls to ChatMessage (agent_types.rs) + ChatMessageInput
      (nlp-engine/chat/types.rs, new ToolCallInput), populate in agent_loop when
      the assistant issues tool calls, plumb into apply_chat_template's messages
      JSON so the assistant turn emits OpenAI-format tool_calls (was dropping them
      → orphan tool result in re-prompt history). Added ChatMessage constructors
      (text / assistant_with_tool_calls / tool_result).
- [x] New CLI subcommand `nodespace model {list|load|recommended}` (cli/commands/model.rs)
      — the CLI had no way to load a model; required for headless prompt testing.
- [x] New bun harness `bun run chat {new|send <id> <msg>|ask <msg>|show <id>}`
      (scripts/aichat.ts) — drives an ai-chat node end-to-end via the CLI, no UI,
      against a throwaway test daemon (/tmp/nodespaced-test).
- [x] Filed 4 parallel tech-debt issues: #1325 (unify ChatMessage/ChatMessageInput),
      #1326 (single tool registry), #1327 (delete duplicated fallback prompt),
      #1328 (embedding service wired by construction).

## Root Cause Found (NOT yet fixed) — the hang/runaway
On a greeting ("Hi there"), Gemma-4-E4B emits chatty prose AND a needless
search_semantic call in the SAME turn. On re-prompt, Gemma's chat template
collapses tool_call + tool_response + the greeting into ONE malformed `model`
turn, then opens a fresh empty `model` turn. With nothing to say and no token
cap, the model runs away to max_tokens=16384 (multi-minute hang → "no reply").
Verified by logging the full templated prompt (temp logging since removed).

## Remaining Work (user wants ALL three)
1. max_tokens safety cap: agent_loop.rs has max_tokens: Some(16384) at two
   InferenceRequest sites — lower to ~2048 so any runaway is bounded to seconds.
2. Prompt/skill tuning (live in DB, then backport to seed_prompt_nodes() in
   prompt_assembler.rs + skill seeds in skill_pipeline.rs): conversational turns
   skip tools; empty tool result → answer directly, never retry; less verbosity;
   "create an invoice tracking database" → create_schema. Build a fuller scenario
   matrix (create several custom node types via NL + CRUD against them).
3. Turn-structure fix: stop sending chatty assistant prose alongside tool calls
   so the template stops collapsing the turn. Deeper agent_loop surgery.

## Current State
- Files modified: agent_types.rs, agent_loop.rs, inference.rs, ollama_integration.rs,
  local_agent_service.rs, node_service.rs, nlp-engine chat/{mod,types}.rs + lib.rs,
  cli lib.rs/commands/{mod,model}.rs, package.json, scripts/aichat.ts.
- Builds: cargo check + release build of daemon/cli pass. NOT yet run: test:all, quality:fix (clippy).
- Tests status: not yet run (WIP checkpoint).
- The embedding + tool_calls fixes are verified working at runtime (search_semantic
  now succeeds, find_skills runs); the runaway is the open problem.

## Context for Next Session
Resume the test loop per memory note project-aichat-prompting-session-handoff (how
to start a fresh test daemon on /tmp/nodespaced-test, load gemma-4-e4b-q4km via the
new `model` CLI command, and drive `bun run chat`). Do the 3 remaining items, then
run test:all + quality:fix, and open the PR. Eval-system + model-capability-guardrails
issues still to be filed (see memory).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Removes the infrastructure-level failure modes in the local ai-chat agent
loop that were independent of model size, and tunes the seeded prompts/skills.

Loop & sampling:
- Cap any single inference round at MAX_RESPONSE_TOKENS=2048 (was 16384), so a
  runaway is bounded to seconds instead of a multi-minute hang.
- Add a repetition penalty to the sampler chain
  (LlamaSampler::penalties(256, 1.3, 0, 0) before temp) — kills the degenerate
  loops small models fall into at near-greedy temperature (e.g. repeating a
  closing phrase until max_tokens).
- Persist assistant tool-call turns with empty content (drop chatty prose) so
  the Gemma chat template stops collapsing prose+call+result into one
  malformed turn.

Chat template (fixes ffi error -3 turn abort introduced by the empty-content
change above):
- Emit content:null (not "") for assistant tool-call turns — the shape the
  OAI-compat path expects.
- Normalize non-object tool-call arguments to "{}" so a malformed/empty tool
  call never feeds invalid JSON into the Jinja template.

Response normalization (all tested):
- Strip leaked Gemma tool-call/response prose (call:foo{...}response:foo{...},
  nested braces handled).
- Strip Gemma channel/thought reasoning blocks (<|channel>...<channel|>, plus
  dangling-opener and stray-marker variants). Reasoning capture/display is
  tracked separately in #1330.
- Add <|channel>/<channel|> to strip_gemma_special_tokens for defense in depth.

Prompt/skill tuning (seeds re-seed a fresh DB, equivalent to live-editing):
- agent_guidance.rs: add "DATABASE = SCHEMA" routing rule (so
  "create an invoice tracking database" → create_schema) and a loud
  "conversational turns use NO tools" rule; byte-lock tests updated.
- prompt_assembler.rs Response Rules: 1-2 sentences; empty/error tool result →
  state and stop, no retry, no compensating tool.
- skill_pipeline.rs Schema Creation: "ONE SCHEMA PER REQUEST" — no proactive
  related-type creation.

Remaining capability-bound behavior (E4B calls tools on conversational turns,
keeps iterating after a complete answer, emits unmarked bare-"thought"
narration) is tracked for the 12B A/B in #1329.

Tests: agent 232, nlp-engine 61, core 890, frontend 3841, skill 17 — all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@malibio

malibio commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1331

Review Type: Initial Review
Scope: Commit 7e9a2321 (the new work), with dff3b855 plumbing as context.
Reviewer: Principal Engineer (Pragmatic Quality framework)

Summary

This is a strong, well-reasoned change that targets the right layer: it removes infrastructure-level failure modes (multi-minute hangs, degenerate repetition loops, chat-template token leaks) rather than papering over a small model's limitations. The commentary is exemplary — nearly every non-obvious decision explains why (the content: null ffi-error rationale, the empty-content turn-structure fix, the repetition-penalty ordering). The ChatMessage::text / assistant_with_tool_calls / tool_result constructors are a real DRY/readability win that also eliminate the repeated tool_call_id: None, name: None boilerplate across the loop.

I verified the two highest-risk claims empirically:

  • Regex ReDoS: No risk. The Rust regex crate is a finite automaton (no backtracking). Pathological inputs (40-deep unbalanced braces, 5000 adjacent {} pairs) all complete in microseconds.
  • Regex correctness: The nested-brace pattern correctly matches the realistic 1–3 level tool-call blobs ({rels:[{target:{type:x}}]} strips cleanly). Truncated/unbalanced blobs are safely left intact.

Net assessment: clear net-positive to code health. Findings below are refinements, none blocking.


Code Review Findings

🟡 Important — Summarization can split an assistant tool-call turn from its tool results (orphan-history regression risk)

📁 packages/agent/src/local_agent/agent_loop.rs:587-591

maybe_summarize_history keeps the last 3 messages via a blind drain(..split_point):

let keep_count = 3.min(session.messages.len());
let split_point = session.messages.len() - keep_count;
let older_messages = session.messages.drain(..split_point).collect();

The whole premise of this PR is that the history must be structurally well-formed: every tool result must be preceded by its assistant tool_calls turn, or Gemma runs away to the token cap. But this boundary cut is structure-blind. A retained 3-message window can begin with an orphan tool result (its assistant tool-call turn was drained), which is exactly the malformed shape 7e9a2321 set out to eliminate. The fix lands the well-formed turn in history, then summarization can re-introduce the orphan on the next over-budget turn.

Recommendation: When choosing split_point, snap it so the cut never lands between an assistant tool_calls turn and its trailing tool results (e.g. advance the split forward past any leading Role::Tool messages in the kept window, or never split mid tool-call group).
Principle: Invariant integrity — an invariant the system now depends on (well-paired tool turns) must be preserved by every code path that mutates the history, not just the happy path.

🟡 Important — Empty-content tool-call turns are summarized losslessly to nothing

📁 packages/agent/src/local_agent/agent_loop.rs:594-603

summary_input is built from msg.content only:

summary_input.push_str(&format!("{}: {}\n", role_str, msg.content));

Now that assistant tool-call turns persist with empty content (the intentional turn-structure fix at line 334-339), any such turn that falls into older_messages summarizes to a bare "Assistant: \n". The summarizer loses all signal that the agent searched/created/connected anything — degrading the recap quality on long sessions.

Recommendation: When msg.content.is_empty() && !msg.tool_calls.is_empty(), render a synthetic line, e.g. Assistant: [called update_schema, create_node].
Principle: Don't let a representational change (content moved from prose into tool_calls) silently break a downstream consumer that only reads the old field.

🟡 Important — MAX_RESPONSE_TOKENS=2048 is a global cap; verify it doesn't truncate large tool-call argument blobs

📁 packages/agent/src/local_agent/agent_loop.rs:38, 235, 432

2048 is a sensible cap for a chat reply, and the comment correctly notes it bounds runaways. Two cases to confirm are not regressed:

  1. Tool-call argument JSON — create_schema with many fields/enums/relationships emits a sizable JSON blob as generated tokens. If that blob exceeds ~2048 tokens it is truncated mid-JSON → the tool call fails to parse. The "ONE SCHEMA PER REQUEST" prompt rule reduces this risk, but the cap is now an enforced ceiling, not a soft target.
  2. Asymmetry with summarization — the summarization path still uses 4096 (line 612). That's defensible (summaries need room), but it means the two caps are now intentionally different; a one-line comment at line 612 noting the deliberate asymmetry would prevent a future "inconsistent magic number" cleanup from wrongly unifying them.

Recommendation: Confirm the largest realistic schema-creation arg blob fits in 2048 tokens (the live matrix exercised schema creation, so likely fine — just call it out). Add the asymmetry comment.
Principle: A newly-introduced hard limit should be validated against the worst-case legitimate payload, not just the runaway it targets.

🟢 Suggestion — Repetition penalty 1.3 over a 256-token window: watch structured/JSON output

📁 packages/nlp-engine/src/chat/mod.rs:393

penalties(256, 1.3, 0.0, 0.0) is reasonable and the rationale (escape degenerate end-phrase loops at temp 0.1) is sound. One caveat worth a note: a 256-token window with repeat-penalty 1.3 penalizes all recently-seen tokens, including the structural tokens that legitimately recur in JSON/Markdown ({, }, ", :, status, repeated enum labels, list markers). At 1.3 this is unlikely to corrupt output, but it can nudge the model away from a correct repeated key. Since frequency/presence are correctly left at 0.0, the risk is low.
Recommendation: No change required, but flag in #1329's A/B matrix whether large structured outputs (multi-field schema JSON, long Markdown lists) degrade under the penalty. If they do, consider scoping the penalty or lowering to ~1.15.
Principle: Sampling constants tuned to fix one regime (conversational loops) should be validated against the other regime they globally affect (structured generation).

🟢 Suggestion — Regex handles ≤3 nesting levels; document the bound and the truncation fallthrough

📁 packages/agent/src/local_agent/response_processing.rs:30-37

Verified empirically: the pattern matches up to 3 brace levels (outer + 2 nested) and safely leaves deeper or truncated blobs intact (no ReDoS, no partial-brace garbage in the common cases). The comment says "covers text plus one nesting level" — it actually covers two nested levels (three total). Minor: the comment understates the real depth. Also worth one line: a token-cap-truncated blob (call:foo{add:[{name:x) is intentionally not stripped and will fall through to the user; in practice strip_channel_blocks / the empty-response synthesis usually mask it, but it's worth noting the limit is "balanced blobs only."
Recommendation: Fix the comment to say "two nested levels (three total)"; note the truncated-blob fallthrough is acceptable because the persisted-side content: null path handles structure separately.
Principle: Comments are a contract — when they understate a regex's actual reach, the next maintainer mis-models the failure surface.

🟢 Suggestion — Confirm no path yields an assistant turn with neither content nor tool_calls

📁 packages/nlp-engine/src/chat/mod.rs:703-718 and agent_loop.rs:261-339

I traced this carefully since it was called out. The template's else if branch only fires when !msg.tool_calls.is_empty(), and emits content: null only inside that branch — so a null-content turn always carries tool_calls. A plain empty-content assistant turn (no tool_calls) falls to the else branch and renders content: "", which is the pre-existing behavior. On the agent side, an assistant turn is only pushed when either (a) normalize_response produced non-empty text / a synthesized confirmation (line 270-309), or (b) it carries real tool_calls (line 334). Conclusion: no path produces an assistant turn that is simultaneously empty-content AND empty-tool_calls via the new code. No action needed — documenting the trace so it's on record.

🟢 Suggestion — content: null normalization lives in the engine; assert it once

📁 packages/nlp-engine/src/chat/mod.rs:683-687

The arguments non-object → "{}" normalization and the content: null shaping are the load-bearing fix for ffi error -3, but they live in apply_chat_template with no direct unit test (the live matrix exercises them end-to-end only). A small table test over apply_chat_template message-shaping (empty args → {}, empty content + tool_calls → null) would lock this behavior against a future refactor of the OAI-compat path.
Principle: Test coverage should track criticality, not just complexity — this is a 3-line block whose regression reintroduces a turn-aborting crash.


Standards & Test Coverage

  • No lint suppression: confirmed — no #[allow] / #[deprecated] introduced. ✅
  • No backward-compat cruft: the old ChatMessage { ... tool_call_id: None, name: None } literals were fully replaced by constructors, not dual-pathed. ✅
  • console.* in scripts/aichat.ts: acceptable — scripts/*.ts are dev tooling (10+ existing scripts use console), exempt from the createLogger rule which targets production app code. ✅
  • .unwrap() on regex Regex::new(...): acceptable — compile-time-constant patterns in OnceLock initializers, consistent with existing backtick_uri_re / md_link_re. ✅
  • tracing::warn!/error! for diagnostics: idiomatic for the Rust agent crate. ✅
  • Test coverage: response_processing.rs has solid new coverage — empty-strip, surrounding-text preservation, the false-positive guard ("Give me a call:" unchanged), channel block, dangling/truncated channel, stray marker. The prompt_assembler.rs byte-lock test was correctly updated to the new prompt text. Gaps: the two 🟡 summarization interactions and the engine-side template shaping (🟢) are untested.

Recommendation: COMMENT (approve-leaning)

No blocking issues. The change is a clear net improvement and the risky parts (regex safety, content/tool_calls invariants) check out under scrutiny. Before merge I'd want the author to at least acknowledge the two 🟡 summarization interactions — the orphan-history split (agent_loop.rs:587-591) is the one most likely to silently re-trigger the very runaway this PR fixes, on long sessions that cross the summarization threshold. It's a pre-existing structural gap that this PR's new invariant makes load-bearing, so it's fair to fix in a fast follow-up rather than block — but it should be a tracked follow-up, not lost.

🤖 Generated with Claude Code

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Initial pragmatic review posted as a PR comment. Recommendation: COMMENT (approve-leaning) — no blocking issues. Please acknowledge/track the two Important findings on the summarization path (agent_loop.rs:587-591 orphan-history split, and 594-603 lossy summary of empty-content tool-call turns) before merge; both are fair as fast follow-ups.

Michael Libio and others added 2 commits June 5, 2026 12:42
…tranded DB prompt edit

Code review (PR #1331) findings:

🟡 maybe_summarize_history could split an assistant tool-call turn from its
   tool results — the naive "keep last 3" drain can leave the kept window
   starting with an orphan Tool message, the exact malformed sequence that
   re-triggers the runaway this PR fixes. Walk the split point back past any
   leading Tool message so every tool result stays paired with its assistant
   turn. New test: summarization_never_orphans_a_tool_result.

🟡 Empty-content tool-call turns summarized to a bare "Assistant:", losing the
   signal of what the agent did. Render a synthetic "called tools: …" line from
   tool_calls when content is empty.

🟡 Documented why the summarization max_tokens (4096) intentionally differs from
   the chat-turn cap (MAX_RESPONSE_TOKENS=2048) so a future cleanup doesn't
   wrongly unify them; noted MAX_RESPONSE_TOKENS also bounds a single tool
   call's generated arguments and is sized for the largest realistic blob.

🟢 Extracted the OAI message-shaping into a pure, model-independent
   chat_message_to_oai_value() and added a direct test block covering
   empty-content→null and non-object-arguments→"{}" (the two shapings whose
   regression reintroduces the turn-aborting ffi error -3).

🟢 Corrected the tool-call-prose regex comment (two nested levels, not one;
   noted the truncated-blob fallthrough and the DFA/no-ReDoS property).

Also backports a prompt edit that was made live in the real DB and never
captured in code: the "Research & Search" skill's SEARCH FIRST guidance now
includes "Skip search for conversational messages or capability questions"
(found by diffing ~/.nodespace prompt/skill node content against the seeds).

Skipped (with reasons): the repetition-penalty A/B note is already tracked in
#1329; the content/tool_calls invariant the reviewer flagged needs no action
(the null-content branch only fires when tool_calls is non-empty).

Tests: agent 233, nlp-engine 66 — all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`cargo fmt --all` (via quality:fix) repeatedly flagged a non-canonical
multi-line struct variant in db/events.rs that predates this branch. Apply the
canonical single-line form so the workspace is rustfmt-clean and a future
`cargo fmt --check` in CI won't fail on it. Formatting-only; no logic change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@malibio

malibio commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed (commits a48dce4f, 13315c6c)

🟡 Important — all addressed

Summarization could orphan a tool-call turn (agent_loop.rs)
maybe_summarize_history now walks the split point back past any leading Tool message, so the kept window never begins with an orphan tool result — the exact malformed sequence that re-triggers the runaway. New test: summarization_never_orphans_a_tool_result.

Empty-content tool-call turns summarized to nothing (agent_loop.rs)
Summarization now renders a synthetic called tools: name(args) line when a turn's content is empty but it has tool_calls, instead of emitting a bare Assistant:.

MAX_RESPONSE_TOKENS asymmetry / sizing (agent_loop.rs)
Documented why the summarization cap (4096) intentionally differs from the chat-turn cap (MAX_RESPONSE_TOKENS=2048) and must not be unified, and noted that 2048 also bounds a single tool call's generated arguments (sized for the largest realistic blob).

🟢 Suggestions — addressed

Engine-side template test (chat/mod.rs)
Extracted the OAI message shaping into a pure, model-independent chat_message_to_oai_value() and added a direct test block: empty content + tool_calls → null, and non-object/empty/malformed arguments → "{}" — the two shapings whose regression reintroduces the turn-aborting ffi error -3.

Regex comment accuracy (response_processing.rs)
Corrected to "two nested levels (three braces deep)", and noted the truncated-blob fallthrough and the DFA/no-ReDoS property.

⏭️ Skipped (with rationale)

  • Repetition-penalty A/B note — already tracked in A/B test Gemma 4 12B (Q4_K_M) vs E4B for the local ai-chat agent #1329, which explicitly evaluates sampler effects on structured output. No code change warranted.
  • content/tool_calls invariant — reviewer confirmed "no action, on record"; the content: null branch only fires when tool_calls is non-empty, so no path yields a turn with neither.

Bonus: captured a stranded live DB edit

Diffing the real ~/.nodespace prompt/skill node content (not the version counter — a direct DB write wouldn't bump it) against the seeds surfaced one un-backported live edit: the "Research & Search" skill's SEARCH FIRST guidance had gained Skip search for conversational messages or capability questions. Now folded into the seed (skill_pipeline.rs). After backport, 0 content deviations remain between DB and seed code.

Plus

chore: rustfmt events.rs — a pre-existing, unrelated rustfmt drift that quality:fix kept flagging; fixed in its own commit so the workspace is fmt-clean.

Tests: agent 233, nlp-engine 66, core 890, frontend 3841, skill 17 — all pass.

@malibio

malibio commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1331 (Re-Review)

Review Type: Re-Review
Scope: Delta only — a48dce4f (address-review) + 13315c6c (rustfmt events.rs), i.e. git diff 7e9a2321..HEAD.
Reviewer: Principal Engineer (Pragmatic Quality framework)

Previous Review Summary

The initial review (COMMENTED, approve-leaning) raised 5 findings: 3 🟡 Important on the summarization path and 2 🟢 minor. This delta addresses all 5. 4 are properly addressed; 1 (the orphan-tool back-off) ships a correct fix but a non-exercising test. No new blocking issues.

Per-Finding Verification

🟡 #1 — Summarization could orphan a tool-call turn → ⚠️ Fix correct, test is a tautology

  • agent_loop.rs:606-608: the back-off loop
    while split_point > 0 && matches!(session.messages[split_point].role, Role::Tool) { split_point -= 1 }
    is logically correct. It checks the right index (messages[split_point] is the first message of the kept window, since drain(..split_point) removes everything before it). It cannot over-drain (only walks back past leading Tool messages), handles multiple consecutive Tool messages, and the prepended System summary at index 0 keeps the final history starting on a non-Tool message. Edge case split_point == 0 (whole history kept, no compaction that pass) is acceptable.
  • However, the new test summarization_never_orphans_a_tool_result (agent_loop.rs:1700-1779) does NOT exercise the back-off. The constructed tail is [assistant-tool-call(18), tool(19), user(20)] with len == 21, so the naive split_point = 21 - 3 = 18 lands on the assistant tool-call turn, not a Tool message. The loop condition matches!(messages[18].role, Role::Tool) is false — the loop body never runs, and the naive window [assistant-tool-call, tool, user] is already well-formed.
  • I verified this empirically: I temporarily disabled the back-off loop and the test still passed. It is a tautology that guards nothing — it would not catch a regression that re-introduced the orphan bug.
  • To actually exercise the fix, the tail must make the naive last-3 window start on a Tool, e.g. tail = [assistant-tool-call, tool, user, user] (keep-last-3 = [tool, user, user], split_point lands on Tool, back-off must fire). Recommend updating the fixture and adding an assertion that split_point was actually walked back (or that the kept-window length grew beyond 3).

🟡 #2 — Empty-content tool-call turns summarized to bare "Assistant:" → ✅ Addressed

  • agent_loop.rs:625-635: renders called tools: name(args), … when content.is_empty() && !tool_calls.is_empty(). Correct and readable. arguments_json is bounded by MAX_RESPONSE_TOKENS (2048) at generation time, so no unbounded-blob risk in summary input. (Nit below.)

🟡 #3 — MAX_RESPONSE_TOKENS asymmetry → ✅ Addressed (docs)

  • agent_loop.rs:40-46 and 641-647: both constants now carry comments explaining why the 2048 chat cap and 4096 summary cap are intentionally separate ("Do NOT unify"). Accurate and grounded.

🟢 #4 — Engine-side template test → ✅ Addressed

  • chat/mod.rs:573-615: chat_message_to_oai_value() extracted. Confirmed behavior-preserving — byte-for-byte identical logic to the previous inline closure (tool/assistant-tool-call/plain branches, content: null shaping, non-object→"{}" normalization). 5 new pure tests at chat/mod.rs:921-1004, all pass. Function is not feature-gated; it follows the exact same pattern as its ungated neighbor strip_gemma_special_tokens. Under --no-default-features both emit a dead_code warning, but chat-service is in the default feature set and this is pre-existing convention, not a regression.

🟢 #5 — Regex comment accuracy → ✅ Addressed

  • response_processing.rs:25-33: comment-only; regex pattern unchanged. New wording accurately describes the two-level hand-unrolled nesting and correctly notes the DFA engine has no ReDoS risk. Truncated/over-deep blobs fail-to-match and are left intact — safe.

Bonus — events.rs (13315c6c) → ✅ Pure formatting

  • events.rs:167: rustfmt struct one-lining only. No logic change.

Bonus — skill_pipeline.rs prompt edit → ✅ Sensible

  • skill_pipeline.rs:43: the "stranded DB prompt edit" — scopes search_semantic to information/action requests and skips conversational/capability messages. Reasonable tuning, no code risk.

New Findings (introduced by the delta)

🟡 [Improvement] — agent_loop.rs:1700 test does not exercise the code it claims to protect.
Principle: tests must fail when the behavior they assert regresses. As shown above, the orphan-prevention test passes with the back-off loop removed. The fix is correct, but it is effectively untested, so a future refactor could silently re-introduce the runaway-prone orphan sequence. Fix the fixture so the naive window starts on a Tool message (see #1).

Nitpicks

  • Nit agent_loop.rs:629: a very large arguments_json (up to the 2048-token cap) is inlined verbatim into the summary input. Bounded, so not a correctness issue, but consider truncating per-call args in the synthetic line to keep summary input lean.
  • Nit agent_loop.rs:606: when split_point walks to 0, the pass keeps the entire history (no compaction) and still spends a summary inference on empty older_messages. Harmless and rare, but a split_point == 0 → return Ok(()) short-circuit would save a wasted inference.

Recommendation

COMMENT (approve-leaning). All five prior findings are resolved in the shipping code; the only material gap is that the headline orphan-prevention test is a tautology. The fix itself is correct and the runaway path is closed — but I recommend strengthening the test fixture before merge so the protection is actually guarded against regression. Not a blocker.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Re-review posted as a PR comment. Recommendation: COMMENT (approve-leaning). All 5 prior findings resolved in shipping code; the back-off fix is correct, but its new test (summarization_never_orphans_a_tool_result) is a tautology — it passes even with the back-off loop removed (verified empirically), because the naive last-3 window lands on the assistant tool-call turn, not a Tool message. Recommend strengthening the fixture before merge. Not a blocker.

…he fix

Re-review (PR #1331) found the new summarization_never_orphans_a_tool_result
test was a tautology — its 3-message tail put the naive split on the assistant
tool-call turn, so the back-off loop never fired and the test passed even with
the fix removed.

- Rework the fixture: tail is now [assistant tool-call, tool, user, user] so the
  "keep last 3" window STARTS on the orphan tool result, forcing the back-off to
  run. Verified the test FAILS when the back-off loop is disabled and passes when
  present — it now genuinely guards the fix.
- Add an explicit assertion that the assistant tool-call turn was RETAINED (not
  drained), proving the back-off pulled it into the kept window.

Also addresses the two re-review nits:
- Short-circuit summarization when the back-off consumes the whole prefix
  (split_point == 0) — no model call on empty input.
- Cap each tool-call argument blob to 120 chars in the summary input (a call can
  emit up to the generation token cap of JSON; the summary only needs the gist).

Tests: agent 233 — all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@malibio

malibio commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review feedback addressed (commit pushed)

🟡 Tautological orphan test → fixed. The fixture now uses a 4-message tail [assistant tool-call, tool, user, user], so the "keep last 3" window starts on the orphan tool result and the back-off loop must fire. Verified the test fails when the back-off is disabled and passes when present — it now genuinely guards the fix. Added an explicit assertion that the assistant tool-call turn is retained (not drained).

Nits, both addressed:

  • Short-circuit summarization when back-off consumes the whole prefix (split_point == 0) — no model call on empty input.
  • Cap each tool-call argument blob to 120 chars in the summary input.

Tests: agent 233 — all pass. The summarization back-off (the runaway-prevention path) is now regression-guarded.

@malibio
malibio merged commit 3c3f778 into main Jun 5, 2026
@malibio
malibio deleted the worktree-ai-chat-cli-prompting branch June 5, 2026 11:04
malibio added a commit that referenced this pull request Jun 22, 2026
…une prompts (#1331)

* WIP: ai-chat agent quality — embedding/tool-call fixes + CLI test harness

## Completed in This Session
- [x] Fix release-build compile error on main: node_to_proto(node.clone(), None, None)
      → 1-arg call in packages/daemon/src/services/node_service.rs (leftover from #1322).
- [x] Fix embedding_service:None production bug: GraphToolExecutor in
      local_agent_service.rs replace_engine was built with embedding_service:None,
      so search_semantic ALWAYS errored and skill-based select_tools routing was
      bypassed (full 13-tool list always sent). Now reads inner.embedding_service.
      Durable fix tracked in #1328.
- [x] Add tool_calls to ChatMessage (agent_types.rs) + ChatMessageInput
      (nlp-engine/chat/types.rs, new ToolCallInput), populate in agent_loop when
      the assistant issues tool calls, plumb into apply_chat_template's messages
      JSON so the assistant turn emits OpenAI-format tool_calls (was dropping them
      → orphan tool result in re-prompt history). Added ChatMessage constructors
      (text / assistant_with_tool_calls / tool_result).
- [x] New CLI subcommand `nodespace model {list|load|recommended}` (cli/commands/model.rs)
      — the CLI had no way to load a model; required for headless prompt testing.
- [x] New bun harness `bun run chat {new|send <id> <msg>|ask <msg>|show <id>}`
      (scripts/aichat.ts) — drives an ai-chat node end-to-end via the CLI, no UI,
      against a throwaway test daemon (/tmp/nodespaced-test).
- [x] Filed 4 parallel tech-debt issues: #1325 (unify ChatMessage/ChatMessageInput),
      #1326 (single tool registry), #1327 (delete duplicated fallback prompt),
      #1328 (embedding service wired by construction).

## Root Cause Found (NOT yet fixed) — the hang/runaway
On a greeting ("Hi there"), Gemma-4-E4B emits chatty prose AND a needless
search_semantic call in the SAME turn. On re-prompt, Gemma's chat template
collapses tool_call + tool_response + the greeting into ONE malformed `model`
turn, then opens a fresh empty `model` turn. With nothing to say and no token
cap, the model runs away to max_tokens=16384 (multi-minute hang → "no reply").
Verified by logging the full templated prompt (temp logging since removed).

## Remaining Work (user wants ALL three)
1. max_tokens safety cap: agent_loop.rs has max_tokens: Some(16384) at two
   InferenceRequest sites — lower to ~2048 so any runaway is bounded to seconds.
2. Prompt/skill tuning (live in DB, then backport to seed_prompt_nodes() in
   prompt_assembler.rs + skill seeds in skill_pipeline.rs): conversational turns
   skip tools; empty tool result → answer directly, never retry; less verbosity;
   "create an invoice tracking database" → create_schema. Build a fuller scenario
   matrix (create several custom node types via NL + CRUD against them).
3. Turn-structure fix: stop sending chatty assistant prose alongside tool calls
   so the template stops collapsing the turn. Deeper agent_loop surgery.

## Current State
- Files modified: agent_types.rs, agent_loop.rs, inference.rs, ollama_integration.rs,
  local_agent_service.rs, node_service.rs, nlp-engine chat/{mod,types}.rs + lib.rs,
  cli lib.rs/commands/{mod,model}.rs, package.json, scripts/aichat.ts.
- Builds: cargo check + release build of daemon/cli pass. NOT yet run: test:all, quality:fix (clippy).
- Tests status: not yet run (WIP checkpoint).
- The embedding + tool_calls fixes are verified working at runtime (search_semantic
  now succeeds, find_skills runs); the runaway is the open problem.

## Context for Next Session
Resume the test loop per memory note project-aichat-prompting-session-handoff (how
to start a fresh test daemon on /tmp/nodespaced-test, load gemma-4-e4b-q4km via the
new `model` CLI command, and drive `bun run chat`). Do the 3 remaining items, then
run test:all + quality:fix, and open the PR. Eval-system + model-capability-guardrails
issues still to be filed (see memory).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Fix ai-chat runaway/hang + tool-call template leaks; tune agent prompts

Removes the infrastructure-level failure modes in the local ai-chat agent
loop that were independent of model size, and tunes the seeded prompts/skills.

Loop & sampling:
- Cap any single inference round at MAX_RESPONSE_TOKENS=2048 (was 16384), so a
  runaway is bounded to seconds instead of a multi-minute hang.
- Add a repetition penalty to the sampler chain
  (LlamaSampler::penalties(256, 1.3, 0, 0) before temp) — kills the degenerate
  loops small models fall into at near-greedy temperature (e.g. repeating a
  closing phrase until max_tokens).
- Persist assistant tool-call turns with empty content (drop chatty prose) so
  the Gemma chat template stops collapsing prose+call+result into one
  malformed turn.

Chat template (fixes ffi error -3 turn abort introduced by the empty-content
change above):
- Emit content:null (not "") for assistant tool-call turns — the shape the
  OAI-compat path expects.
- Normalize non-object tool-call arguments to "{}" so a malformed/empty tool
  call never feeds invalid JSON into the Jinja template.

Response normalization (all tested):
- Strip leaked Gemma tool-call/response prose (call:foo{...}response:foo{...},
  nested braces handled).
- Strip Gemma channel/thought reasoning blocks (<|channel>...<channel|>, plus
  dangling-opener and stray-marker variants). Reasoning capture/display is
  tracked separately in #1330.
- Add <|channel>/<channel|> to strip_gemma_special_tokens for defense in depth.

Prompt/skill tuning (seeds re-seed a fresh DB, equivalent to live-editing):
- agent_guidance.rs: add "DATABASE = SCHEMA" routing rule (so
  "create an invoice tracking database" → create_schema) and a loud
  "conversational turns use NO tools" rule; byte-lock tests updated.
- prompt_assembler.rs Response Rules: 1-2 sentences; empty/error tool result →
  state and stop, no retry, no compensating tool.
- skill_pipeline.rs Schema Creation: "ONE SCHEMA PER REQUEST" — no proactive
  related-type creation.

Remaining capability-bound behavior (E4B calls tools on conversational turns,
keeps iterating after a complete answer, emits unmarked bare-"thought"
narration) is tracked for the 12B A/B in #1329.

Tests: agent 232, nlp-engine 61, core 890, frontend 3841, skill 17 — all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Address review: protect tool-turn pairing in summarization; capture stranded DB prompt edit

Code review (PR #1331) findings:

🟡 maybe_summarize_history could split an assistant tool-call turn from its
   tool results — the naive "keep last 3" drain can leave the kept window
   starting with an orphan Tool message, the exact malformed sequence that
   re-triggers the runaway this PR fixes. Walk the split point back past any
   leading Tool message so every tool result stays paired with its assistant
   turn. New test: summarization_never_orphans_a_tool_result.

🟡 Empty-content tool-call turns summarized to a bare "Assistant:", losing the
   signal of what the agent did. Render a synthetic "called tools: …" line from
   tool_calls when content is empty.

🟡 Documented why the summarization max_tokens (4096) intentionally differs from
   the chat-turn cap (MAX_RESPONSE_TOKENS=2048) so a future cleanup doesn't
   wrongly unify them; noted MAX_RESPONSE_TOKENS also bounds a single tool
   call's generated arguments and is sized for the largest realistic blob.

🟢 Extracted the OAI message-shaping into a pure, model-independent
   chat_message_to_oai_value() and added a direct test block covering
   empty-content→null and non-object-arguments→"{}" (the two shapings whose
   regression reintroduces the turn-aborting ffi error -3).

🟢 Corrected the tool-call-prose regex comment (two nested levels, not one;
   noted the truncated-blob fallthrough and the DFA/no-ReDoS property).

Also backports a prompt edit that was made live in the real DB and never
captured in code: the "Research & Search" skill's SEARCH FIRST guidance now
includes "Skip search for conversational messages or capability questions"
(found by diffing ~/.nodespace prompt/skill node content against the seeds).

Skipped (with reasons): the repetition-penalty A/B note is already tracked in
#1329; the content/tool_calls invariant the reviewer flagged needs no action
(the null-content branch only fires when tool_calls is non-empty).

Tests: agent 233, nlp-engine 66 — all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* chore: rustfmt events.rs (pre-existing drift)

`cargo fmt --all` (via quality:fix) repeatedly flagged a non-canonical
multi-line struct variant in db/events.rs that predates this branch. Apply the
canonical single-line form so the workspace is rustfmt-clean and a future
`cargo fmt --check` in CI won't fail on it. Formatting-only; no logic change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* Address re-review: make orphan-summarization test actually exercise the fix

Re-review (PR #1331) found the new summarization_never_orphans_a_tool_result
test was a tautology — its 3-message tail put the naive split on the assistant
tool-call turn, so the back-off loop never fired and the test passed even with
the fix removed.

- Rework the fixture: tail is now [assistant tool-call, tool, user, user] so the
  "keep last 3" window STARTS on the orphan tool result, forcing the back-off to
  run. Verified the test FAILS when the back-off loop is disabled and passes when
  present — it now genuinely guards the fix.
- Add an explicit assertion that the assistant tool-call turn was RETAINED (not
  drained), proving the back-off pulled it into the kept window.

Also addresses the two re-review nits:
- Short-circuit summarization when the back-off consumes the whole prefix
  (split_point == 0) — no model call on empty input.
- Cap each tool-call argument blob to 120 chars in the summary input (a call can
  emit up to the generation token cap of JSON; the summary only needs the gist).

Tests: agent 233 — all pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant