Skip to content

Fix seeded prompt body + dropped tools so the full agent prompt and toolset reach the model - #1366

Merged
malibio merged 3 commits into
mainfrom
fix/seed-prompt-body-dropped
Jun 6, 2026
Merged

malibio merged 3 commits into
mainfrom
fix/seed-prompt-body-dropped

Conversation

@malibio

@malibio malibio commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator

Overview

Two distinct bugs in the agent seeding/assembly path caused the local agent to receive an incomplete system prompt and a truncated tool list — silently undermining every model. Found via the prompt-dump tool (bun run prompt:dump) during the #1329 12B re-trial: the model was getting an empty TOOL STRATEGY: section, an empty RESPONSE RULES:, the dangling "ENTITY TYPES" reference, and only 5 of 13 tools (no create_schema, no search_skills). The code constants were correct — the content just wasn't reaching the model.

Root cause (two bugs, both in the delivery path — not the markdown parser)

  1. Prompt body dropped — packages/agent/src/prompt_assembler.rs::fetch_prompt_body flattened only the prompt node's direct children via get_children. The TOOL STRATEGY: header line is a direct child, but its bullets (the search_skills mandate, CLARIFICATION CONTRACT, BLAST-RADIUS GATE, etc.) are grandchildren — silently dropped, leaving a bare header.

  2. Tools dropped during seeding — packages/core/src/behaviors/mod.rs::ToolNodeBehavior::validate applied the external-tool depth / additionalProperties trust-boundary guard to all tool nodes. create_schema's valid (depth-5) internal schema was rejected, and seed_nodes_from_templates aborts the whole batch on the first failure — dropping create_schema and every tool seeded after it.

Fix

  • fetch_prompt_body: walk the full descendant subtree via get_subtree_data (depth-first, fractional order) instead of direct children only.
  • ToolNodeBehavior::validate: apply the depth/additionalProperties guard only to source != "internal" tools. Internal tools are compile-time-validated typed definitions; the guard exists to bound untrusted external schemas (per ADR-036's trust boundary), not internal ones.

Verification (proven via the prompt dump on a fresh-seeded DB)

Before: TOOL STRATEGY: header with empty body, no search_skills text; 5-tool subset.
After: system_prompt_len=3645; prompt contains search_skills, CLARIFICATION CONTRACT, BLAST-RADIUS GATE, ALWAYS search first, NEVER use placeholder IDs, and a populated RESPONSE RULES:. 13 tools offered including create_schema AND search_skills.

Smoke test (Ministral 8B), clean end-to-end: search_skills → create_schema (well-formed args) → self-corrected a validation error → succeeded; schema persists.

Tests

  • New regression tests: markdown_test (indented bullets under a HEADER: line survive), prompt_assembler (full-subtree body), skill_pipeline (create_schema/search_skills seed), behaviors (internal tool schema not rejected by the external guard).
  • cargo test -p nodespace-core --lib: 923 passed, 0 failed
  • cargo test -p nodespace-agent --lib: 243 passed, 0 failed
  • Build clean; clippy/fmt/svelte-check pass.

Impact

This was breaking prompt/tool delivery for all local models, not just one. With it fixed, the skill-mediated routing (ADR-036) actually reaches the model. A separate, now-isolated follow-up remains for Gemma 4 specifically (its streaming tool-call parser corrupts arguments — tracked in #1365); that is NOT a model-capability issue and is out of scope here.

Related Issues

🤖 Generated with Claude Code

malibio and others added 2 commits June 6, 2026 22:31
…ach model)

The local agent received an incomplete system prompt and only a 5-tool
subset, so it never learned to call search_skills/create_schema and
behaved badly. Two distinct seeding-path bugs, both fixed here.

1. Prompt body dropped (prompt_assembler.rs)
   `fetch_prompt_body` flattened ONLY the prompt node's direct children
   via get_children. A seeded `HEADER:` line (e.g. `TOOL STRATEGY:`)
   followed by 4-space-indented bullets parses into a NESTED tree: the
   header line is a direct child of the prompt node, and the bullets are
   children of that header line. The direct-children-only flatten kept
   the bare header and silently dropped every bullet — so the assembled
   prompt showed `TOOL STRATEGY:` followed by emptiness, with no
   search_skills mandate, CLARIFICATION CONTRACT, or BLAST-RADIUS GATE.
   The markdown parser was NOT at fault (it preserves the bullets as
   grandchildren). Fix: walk the full descendant subtree via
   get_subtree_data with a depth-first, fractional-order traversal.

2. Tools dropped during seeding (behaviors/mod.rs)
   `seed_nodes_from_templates` inserts the whole batch behind one `?`:
   the first node that fails validation aborts every node after it. The
   `create_schema` tool node was rejected by the external-tool
   parameter_schema depth/additionalProperties guard (its valid internal
   schema reaches depth 5), which dropped create_schema AND every tool
   seeded after it (update_schema, search_skills, delete_node, ...). The
   model was then offered only the first 5 tools. The depth guard is a
   trust-boundary check for UNTRUSTED external schemas; internal tools
   are compile-time-validated typed definitions. Fix: only apply the
   guard to non-internal (external) tool sources.

Verification (fresh-seeded DB, prompt dump):
- system_prompt_len 3645; prompt now contains search_skills mandate,
  CLARIFICATION CONTRACT, BLAST-RADIUS GATE, NODE MODEL, RESPONSE RULES.
- 13 tools offered including create_schema AND search_skills.
- Ministral-8b: search_skills -> create_schema -> self-corrects a
  title_template field error -> schema created; clean confirmation.

Tests: new regression tests added
- markdown_test.rs: bullets-under-header preserved (parser is correct).
- prompt_assembler.rs: assembled prompt contains full TOOL STRATEGY body.
- skill_pipeline.rs: full daemon seed inserts all tool nodes.
- behaviors/mod.rs: internal deep schema accepted; external still rejected.
All nodespace-core (923) and nodespace-agent (243) lib tests pass.

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

Two distinct seeding-path bugs caused the local agent to receive an incomplete
system prompt and a truncated tool list — silently undermining every model:

1. Prompt body dropped (prompt_assembler.rs::fetch_prompt_body): it flattened
   only the prompt node's DIRECT children via get_children. The "TOOL STRATEGY:"
   header is a direct child but its bullets (search_skills mandate, CLARIFICATION
   CONTRACT, BLAST-RADIUS GATE, etc.) are grandchildren — so they were silently
   dropped, leaving a bare header and an empty RESPONSE RULES section. Now walks
   the full descendant subtree via get_subtree_data (depth-first, fractional order).

2. Tools dropped during seeding (behaviors/mod.rs::ToolNodeBehavior::validate):
   the external-tool depth / additionalProperties trust-boundary guard rejected
   create_schema's valid (depth-5) internal schema, and seed_nodes_from_templates
   aborts the whole batch on the first failure — dropping create_schema and every
   tool seeded after it (search_skills, delete_node, …), leaving a 5-tool subset.
   The guard now applies only to source != "internal" tools; internal tools are
   compile-time-validated typed definitions.

Verified via the prompt dump on a fresh-seeded DB: system prompt now contains the
full TOOL_STRATEGY_RULES (search_skills, CLARIFICATION CONTRACT, BLAST-RADIUS GATE)
and a populated RESPONSE RULES; 13 tools offered including create_schema and
search_skills. Ministral-8b now runs the skill-mediated flow cleanly end-to-end.

Regression tests added: markdown_test (indented bullets under a HEADER: line),
prompt_assembler (full subtree body), skill_pipeline (create_schema/search_skills
seed), behaviors (internal tool schema not rejected by the external guard).

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

malibio commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Verdict: Request changes (one Critical, narrowly scoped). Both bugs are real and well-diagnosed, the diagnosis (consumer bug, not parser bug) is correct, and the four regression tests are genuine — they fail without the fix and will catch reintroduction. The fetch_prompt_body subtree fix is correct and safe. The blocking concern is Fix #2: exempting source == "internal" tools from the schema depth / additionalProperties guard directly contradicts ADR-036's explicit "one trust model, both origins ... applies to internal-generated and external-registered tools alike." A simpler, ADR-aligned fix exists (raise MAX_SCHEMA_DEPTH) that fixes the bug without weakening the boundary.

This is otherwise a net-positive, high-value fix to infrastructure that affects every agent turn.

Findings

Critical Issues

[Critical/Blocker] packages/core/src/behaviors/mod.rs:1834 — Gating the trust-boundary guard on source != "internal" contradicts ADR-036 and weakens the boundary ahead of the surface it protects.

ADR-036 ("Trust Boundary (external tools)") is explicit on exactly this code path:

"Generated schemas are validated. Typed tools generated from registry nodes (internal or external) must pass schema validation before reaching inference: bounded nesting depth, no unbounded additionalProperties, size cap."
"One trust model, both origins. The boundary is defined once and applies to internal-generated and external-registered tools alike."

The PR makes internal tools exempt from depth AND additionalProperties entirely. The new test tool_node_accepts_deep_internal_schema codifies this: a 7-level-deep schema with additionalProperties:true now validates as long as source:"internal". That is precisely the unbounded case the ADR calls a "context-flood vector," now permitted for one origin. The principle at stake is keeping a security invariant single-sourced; this fix forks it into two code paths, the riskier of which is the silent one.

Why this matters even though it isn't exploitable today:

  • There is currently no external-tool registration path (it's future work per ADR-035), so an attacker cannot yet set source:"internal" to bypass the guard. The hole is latent, not live.
  • But the guard's entire reason for existing is the external surface ADR-035/036 are opening. Weakening it now, with the rationale "internal tools are compile-time-validated so skip the guard," bakes in a divergence that whoever builds the external path must remember to reason about. The moment a registration API lets a caller influence source (or defaults it), the Some("internal") branch becomes a bypass. Trust decisions that depend on a future contributor remembering an exception are how trust boundaries rot.

Recommended fix (simpler, KISS, ADR-aligned): raise the limit, keep one guard for all origins. The root cause is purely that MAX_SCHEMA_DEPTH = 5 (behaviors/mod.rs:1886) is too low for a legitimate typed schema. Trace of create_schema: object(0) → properties(1) → fields(2) → items(3) → properties(4) → coreValues(5) → rejected at depth >= 5. The recursion increments on every object-valued key (not just structural ones), so the effective budget is small. Bumping MAX_SCHEMA_DEPTH to 6 or 7 (with a comment tying the number to the deepest legitimate internal schema, create_schema) fixes the seed abort while keeping additionalProperties:true rejected for everyone and preserving "one trust model, both origins." This is less code than the diff and doesn't introduce a per-origin branch.

If the team deliberately wants origin-aware validation, that is an ADR-036 amendment, not an inline code exception — it should be decided in the doc, not introduced as a bug-fix side effect. At minimum, internal tools should still be subject to the additionalProperties:true rejection and some (higher) depth bound rather than being fully unbounded.

Suggested Improvements

[Improvement] behaviors/mod.rs:4533,4549 — modified tests now over-specify and mask the source == None default. The pre-existing depth/additionalProperties rejection tests had no source and exercised the None default (which still hits the guard: None != Some("internal") is true — good, that's the safe default). The PR added source:"external" to them. That's fine, but it removes the only coverage proving a tool with no source is still guarded. Add (or keep) one case asserting a source-absent deep schema is rejected, so the safe-default behavior is pinned. This is the one genuinely security-relevant edge of the Option logic and it's currently untested after the change.

[Improvement] prompt_assembler.rs:205-211 — note the silent-skip of orphaned intermediate nodes. The traversal does if let Some(child) = node_map.get(&id) before pushing content but unconditionally pushes that id's grandchildren from adjacency_list. If node_map and adjacency_list ever disagree (an edge whose node wasn't returned), the intermediate content is silently dropped while its descendants are still emitted — re-creating a quieter version of the very class of bug this PR fixes. get_subtree_data builds both from one consolidated query so they should be consistent today; a one-line tracing::warn! in the else would make any future inconsistency visible instead of silent.

Things verified (no action needed)

  • Subtree traversal correctness: Pre-order DFS over adjacency_list (pre-sorted by fractional order in get_subtree_data, mod.rs:1556-1558), pushing children reversed so the first child pops first, yields correct document order — including the "header-with-bullets followed by another top-level paragraph" case (the second top-level node is deeper in the stack and emits after the first subtree drains). Confirmed by assembled_prompt_contains_full_tool_strategy_body.
  • Cycle safety: The structure is parent_id/has_child tree built from a subtree query rooted at the prompt node; no visited-set, so a cycle would infinite-loop. The graph is a tree by construction (single-parent has_child edges), so this is acceptable, consistent with how get_subtree_data is used elsewhere. Worth a one-line comment that acyclicity is assumed.
  • Excluding root content: Correct and matches intent — root content is the prompt label, body lives in descendants. Matches the prior get_children-only behavior's exclusion of the root.
  • Performance on the hot path: Acceptable. assemble runs fetch_prompt_body once per root prompt node per turn; there are a handful of prompt roots (MAX_PROMPT_NODES cap), each subtree is tiny (header + bullets). get_subtree_data is one consolidated query vs get_children's one query — same order of magnitude, negligible. Note fetch_prompt_overrides already does an N+1 get_parent per prompt node; that predates this PR and isn't worsened here.
  • Tests are genuine regressions: full_daemon_seed_inserts_all_tool_nodes asserts names.len() == Tool::ALL.len() (catches the batch-abort drop), assembled_prompt_contains_full_tool_strategy_body asserts nested-bullet needles reach the assembled prompt (catches the flatten bug), and the markdown test correctly documents that the parser nests bullets under the header (parser was not the bug). All four pass on the branch; build/clippy clean.

Nitpicks

  • Nit: prompt_assembler.rs:182 — the doc comment still opens "Fetch the full descendant subtree ... and concatenate every descendant's content." Consider noting the root is excluded right in the first line (it's mentioned later at line 197, but the opening sentence reads as "every descendant" which is accurate, just worth front-loading the root-exclusion).
  • Nit: skill_pipeline.rs test uses limit: Some(256) as a magic number for "all tools"; a brief // > Tool::ALL.len() comment would clarify it's an upper bound, not a meaningful page size.

Bottom line

Approve the fetch_prompt_body fix and the test suite as-is. The blocker is solely Fix #2's origin-based exemption. Preferred resolution: revert the source != Some("internal") gating and instead raise MAX_SCHEMA_DEPTH to accommodate create_schema, keeping one guard for all origins per ADR-036. If origin-aware validation is genuinely wanted, capture it as an ADR-036 amendment first.

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

Review posted as a comment (cannot request-changes on own PR). NET ASSESSMENT: Request changes — one Critical, narrowly scoped item. Fix #2 exempts internal tools from the schema depth / additionalProperties guard, contradicting ADR-036's 'one trust model, both origins.' The prompt-body subtree fix and all four regression tests are correct and net-positive. Preferred resolution: raise MAX_SCHEMA_DEPTH to fit create_schema and keep a single guard for all origins. Full details in the review comment above.

…DR-036)

The prior commit exempted source:"internal" tools from the schema depth /
additionalProperties guard — which contradicts ADR-036's "one trust model, both
origins" and bakes in a latent bypass (a future external-registration path could
set source:"internal" to skip the guard). Per review, revert the origin-based
exemption and instead raise the limit to fit the deepest legitimate tool.

- behaviors/mod.rs: validate_parameter_schema_depth now applies to ALL tool
  nodes regardless of source (single-sourced boundary). MAX_SCHEMA_DEPTH 5 -> 9,
  documented: the recursion counts every object-valued key, and create_schema's
  enum path (properties→fields→items→properties→coreValues→items→properties→
  label) legitimately reaches depth 8.
- Tests: replace tool_node_accepts_deep_internal_schema (which codified the
  exemption) with tool_node_accepts_create_schema_real_depth (real depth-8
  create_schema shape validates under the limit) +
  tool_node_rejects_unbounded_additional_properties_even_when_internal (no
  origin bypass). Restore source:None default coverage on the depth-reject test.
- prompt_assembler.rs: warn on adjacency_list/node_map drift in the subtree walk
  (would otherwise silently drop content); note the acyclic single-parent tree
  assumption.

Addresses the Critical + both Improvements from the PR #1366 review. Skipped the
doc-sentence / test-comment nitpicks (trivial).

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

malibio commented Jun 6, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary

Addressed the Critical + both Improvements from the review. Commit 041e7c83.

✅ Critical — reverted the origin-based exemption; one guard for all origins

Per ADR-036's "one trust model, both origins," the source != "internal" exemption is removed — validate_parameter_schema_depth now applies to ALL tool nodes. Root cause was simply that MAX_SCHEMA_DEPTH = 5 was too low. Verified the real create_schema schema reaches object-nesting depth 8 (properties → fields → items → properties → coreValues → items → properties → label, since the recursion counts every object-valued key). Raised MAX_SCHEMA_DEPTH to 9 with a comment documenting why. Boundary stays single-sourced; no per-origin branch. (You were right the original "depth 5" estimate was low — it's actually 8.)

✅ Improvement — restored source: None coverage + added no-bypass test

  • tool_node_rejects_schema_depth_exceeded now uses no source (exercises the guarded default).
  • Replaced tool_node_accepts_deep_internal_schema (which codified the exemption) with tool_node_accepts_create_schema_real_depth (a real depth-8 create_schema shape validates under the limit — the actual regression).
  • Added tool_node_rejects_unbounded_additional_properties_even_when_internal — additionalProperties:true is rejected even for source:internal (proves no origin bypass).

✅ Improvement — warn on subtree traversal drift

fetch_prompt_body now logs a tracing::warn! if an id in adjacency_list is missing from node_map (would otherwise silently drop content). Added a note that the subtree is an acyclic single-parent tree (no visited-set needed).

⏭️ Skipped (nitpicks)

The doc-sentence ordering and test-comment annotations — trivial, not worth the churn.

Tests

  • cargo test -p nodespace-core --lib: 924 passed, 0 failed
  • cargo test -p nodespace-agent --lib: 243 passed, 0 failed
  • Quality (clippy/fmt/svelte-check): clean.

Re-Review Decision

NO RE-REVIEW NEEDED. The change is a contained simplification (one guard, raised limit) that aligns with the reviewer's explicitly recommended approach, with tests proving both the regression (real create_schema validates) and the security invariant (no origin bypass). Lower risk than the original diff.

Bonus: live validation

With the seed fix in place, a full scenario matrix on Ministral 8B now runs the skill-mediated flow end-to-end: search_skills routing fires, the right tools are reachable, schema creation + instance creation + search-then-update all work. This is the behavior the seed fix was meant to restore.

@malibio
malibio merged commit d47d491 into main Jun 6, 2026
@malibio
malibio deleted the fix/seed-prompt-body-dropped branch June 6, 2026 21:37
malibio added a commit that referenced this pull request Jun 6, 2026
…ror -3 through NodeSpace's inference path, despite clean output via raw llama-server (#1367)

* Fix Gemma 4 12B runaway generation + OAI parser error recovery (closes #1365)

Three root causes, three fixes:

1. EOG token check: replace bare eos_token comparison with model.is_eog_token()
   so all EOG tokens (EOS, <end_of_turn>, <turn|>) stop generation — not just EOS.

2. Gemma 4 stop token augmentation: inject <end_of_turn> and <turn|> into
   additional_stops when chat_format=3 (PEG_GEMMA4), guarding against the ggml-org
   GGUF not marking <turn|> as EOG in its vocabulary metadata.

3. Tool iteration token cap: lower the max_tokens fallback for tool-calling
   iterations from 4096 → 2048, bounding any remaining runaway to seconds instead
   of minutes while still allowing full argument JSON.

4. OAI parser error recovery: count consecutive ffi errors and break after 5,
   rather than continuing to generate garbage up to the token cap.

Tool offering (AC #3) is fixed by #1366 (seed prompt body + full toolset now
reaching the model), merged to main before this branch.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* Address review: CHAT_FORMAT_PEG_GEMMA4 constant, consolidate debug log, finalize comment, test + comment improvements

- Extract magic number 3 into CHAT_FORMAT_PEG_GEMMA4 constant to guard
  against silent drift if llama.cpp renumbers format IDs
- Move Gemma 4 debug log inside augment_gemma4_stops (removes duplicate
  chat_format check at call site)
- Add best-effort finalize comment clarifying warn-and-continue intent
  after the consecutive-error circuit breaker
- Tighten deduplication test: assert pre-existing entry stays at index 0
- Update tests to reference CHAT_FORMAT_PEG_GEMMA4 constant
- Note MAX_RESPONSE_TOKENS symmetry in inference.rs token cap comment

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
malibio added a commit that referenced this pull request Jun 22, 2026
…oolset reach the model (#1366)

* Fix seeded prompt body drop + dropped tools (full prompt/tools now reach model)

The local agent received an incomplete system prompt and only a 5-tool
subset, so it never learned to call search_skills/create_schema and
behaved badly. Two distinct seeding-path bugs, both fixed here.

1. Prompt body dropped (prompt_assembler.rs)
   `fetch_prompt_body` flattened ONLY the prompt node's direct children
   via get_children. A seeded `HEADER:` line (e.g. `TOOL STRATEGY:`)
   followed by 4-space-indented bullets parses into a NESTED tree: the
   header line is a direct child of the prompt node, and the bullets are
   children of that header line. The direct-children-only flatten kept
   the bare header and silently dropped every bullet — so the assembled
   prompt showed `TOOL STRATEGY:` followed by emptiness, with no
   search_skills mandate, CLARIFICATION CONTRACT, or BLAST-RADIUS GATE.
   The markdown parser was NOT at fault (it preserves the bullets as
   grandchildren). Fix: walk the full descendant subtree via
   get_subtree_data with a depth-first, fractional-order traversal.

2. Tools dropped during seeding (behaviors/mod.rs)
   `seed_nodes_from_templates` inserts the whole batch behind one `?`:
   the first node that fails validation aborts every node after it. The
   `create_schema` tool node was rejected by the external-tool
   parameter_schema depth/additionalProperties guard (its valid internal
   schema reaches depth 5), which dropped create_schema AND every tool
   seeded after it (update_schema, search_skills, delete_node, ...). The
   model was then offered only the first 5 tools. The depth guard is a
   trust-boundary check for UNTRUSTED external schemas; internal tools
   are compile-time-validated typed definitions. Fix: only apply the
   guard to non-internal (external) tool sources.

Verification (fresh-seeded DB, prompt dump):
- system_prompt_len 3645; prompt now contains search_skills mandate,
  CLARIFICATION CONTRACT, BLAST-RADIUS GATE, NODE MODEL, RESPONSE RULES.
- 13 tools offered including create_schema AND search_skills.
- Ministral-8b: search_skills -> create_schema -> self-corrects a
  title_template field error -> schema created; clean confirmation.

Tests: new regression tests added
- markdown_test.rs: bullets-under-header preserved (parser is correct).
- prompt_assembler.rs: assembled prompt contains full TOOL STRATEGY body.
- skill_pipeline.rs: full daemon seed inserts all tool nodes.
- behaviors/mod.rs: internal deep schema accepted; external still rejected.
All nodespace-core (923) and nodespace-agent (243) lib tests pass.

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

* Fix seeded prompt body + dropped tools so the full prompt/tools reach the model

Two distinct seeding-path bugs caused the local agent to receive an incomplete
system prompt and a truncated tool list — silently undermining every model:

1. Prompt body dropped (prompt_assembler.rs::fetch_prompt_body): it flattened
   only the prompt node's DIRECT children via get_children. The "TOOL STRATEGY:"
   header is a direct child but its bullets (search_skills mandate, CLARIFICATION
   CONTRACT, BLAST-RADIUS GATE, etc.) are grandchildren — so they were silently
   dropped, leaving a bare header and an empty RESPONSE RULES section. Now walks
   the full descendant subtree via get_subtree_data (depth-first, fractional order).

2. Tools dropped during seeding (behaviors/mod.rs::ToolNodeBehavior::validate):
   the external-tool depth / additionalProperties trust-boundary guard rejected
   create_schema's valid (depth-5) internal schema, and seed_nodes_from_templates
   aborts the whole batch on the first failure — dropping create_schema and every
   tool seeded after it (search_skills, delete_node, …), leaving a 5-tool subset.
   The guard now applies only to source != "internal" tools; internal tools are
   compile-time-validated typed definitions.

Verified via the prompt dump on a fresh-seeded DB: system prompt now contains the
full TOOL_STRATEGY_RULES (search_skills, CLARIFICATION CONTRACT, BLAST-RADIUS GATE)
and a populated RESPONSE RULES; 13 tools offered including create_schema and
search_skills. Ministral-8b now runs the skill-mediated flow cleanly end-to-end.

Regression tests added: markdown_test (indented bullets under a HEADER: line),
prompt_assembler (full subtree body), skill_pipeline (create_schema/search_skills
seed), behaviors (internal tool schema not rejected by the external guard).

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

* Address review: keep one trust-boundary guard for all tool origins (ADR-036)

The prior commit exempted source:"internal" tools from the schema depth /
additionalProperties guard — which contradicts ADR-036's "one trust model, both
origins" and bakes in a latent bypass (a future external-registration path could
set source:"internal" to skip the guard). Per review, revert the origin-based
exemption and instead raise the limit to fit the deepest legitimate tool.

- behaviors/mod.rs: validate_parameter_schema_depth now applies to ALL tool
  nodes regardless of source (single-sourced boundary). MAX_SCHEMA_DEPTH 5 -> 9,
  documented: the recursion counts every object-valued key, and create_schema's
  enum path (properties→fields→items→properties→coreValues→items→properties→
  label) legitimately reaches depth 8.
- Tests: replace tool_node_accepts_deep_internal_schema (which codified the
  exemption) with tool_node_accepts_create_schema_real_depth (real depth-8
  create_schema shape validates under the limit) +
  tool_node_rejects_unbounded_additional_properties_even_when_internal (no
  origin bypass). Restore source:None default coverage on the depth-reject test.
- prompt_assembler.rs: warn on adjacency_list/node_map drift in the subtree walk
  (would otherwise silently drop content); note the acyclic single-parent tree
  assumption.

Addresses the Critical + both Improvements from the PR #1366 review. Skipped the
doc-sentence / test-comment nitpicks (trivial).

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
malibio added a commit that referenced this pull request Jun 22, 2026
…ror -3 through NodeSpace's inference path, despite clean output via raw llama-server (#1367)

* Fix Gemma 4 12B runaway generation + OAI parser error recovery (closes #1365)

Three root causes, three fixes:

1. EOG token check: replace bare eos_token comparison with model.is_eog_token()
   so all EOG tokens (EOS, <end_of_turn>, <turn|>) stop generation — not just EOS.

2. Gemma 4 stop token augmentation: inject <end_of_turn> and <turn|> into
   additional_stops when chat_format=3 (PEG_GEMMA4), guarding against the ggml-org
   GGUF not marking <turn|> as EOG in its vocabulary metadata.

3. Tool iteration token cap: lower the max_tokens fallback for tool-calling
   iterations from 4096 → 2048, bounding any remaining runaway to seconds instead
   of minutes while still allowing full argument JSON.

4. OAI parser error recovery: count consecutive ffi errors and break after 5,
   rather than continuing to generate garbage up to the token cap.

Tool offering (AC #3) is fixed by #1366 (seed prompt body + full toolset now
reaching the model), merged to main before this branch.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* Address review: CHAT_FORMAT_PEG_GEMMA4 constant, consolidate debug log, finalize comment, test + comment improvements

- Extract magic number 3 into CHAT_FORMAT_PEG_GEMMA4 constant to guard
  against silent drift if llama.cpp renumbers format IDs
- Move Gemma 4 debug log inside augment_gemma4_stops (removes duplicate
  chat_format check at call site)
- Add best-effort finalize comment clarifying warn-and-continue intent
  after the consecutive-error circuit breaker
- Tighten deduplication test: assert pre-existing entry stays at index 0
- Update tests to reference CHAT_FORMAT_PEG_GEMMA4 constant
- Note MAX_RESPONSE_TOKENS symmetry in inference.rs token cap comment

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Claude Sonnet 4.6 <[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