Skip to content

[P2] serialized_budget.enforced is false on 0.27.4 explain packs; packs ship 2× over their declared budget - #402

Merged
mohanagy merged 3 commits into
mainfrom
issue-400-serialized-budget-enforced
May 29, 2026
Merged

mohanagy merged 3 commits into
mainfrom
issue-400-serialized-budget-enforced

Conversation

@mohanagy

@mohanagy mohanagy commented May 29, 2026 •

Copy link
Copy Markdown
Owner

Closes #400

Summary

  • enforce answer-ready explain-pack budgets by trimming and selection-aware matched-node culling
  • honor explicit explain budgets on the stdio/MCP path and keep cached expandable handles working after culling
  • update compare, pack-quality, and stdio regressions around the stricter serialized output surface

Verification

  • npm run typecheck
  • npm run build
  • CI=1 npm run test:run
  • node dist/src/cli/bin.js generate . --no-html
  • node dist/src/cli/bin.js pack "How context-pack budget enforcement works" --task explain --graph out/graph.json --budget 1500 --format json

Summary by CodeRabbit

  • New Features

    • Explanation generation enforces token budgets and records when packs are culled to fit limits; retained content is prioritized.
    • Explain responses now include enforced serialized budget metadata and warnings about culled content.
  • Bug Fixes

    • More robust handling of optional expandable/follow-up fields and cached payloads; malformed stored handles are rejected with clear errors.
  • Tests

    • Added tests covering budget enforcement, culling warnings, confidence changes, and follow-up/handle validation.

Review Change Stack

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: aba21053-10db-4363-b2b9-ad2f9efb569f

📥 Commits

Reviewing files that changed from the base of the PR and between 9379a2c and a9ec500.

📒 Files selected for processing (6)
  • src/infrastructure/context-pack-command.ts
  • src/runtime/stdio/tools.ts
  • tests/unit/context-pack-command.test.ts
  • tests/unit/pack-quality-fixtures.test.ts
  • tests/unit/stdio-server.test.ts
  • tests/unit/stdio-slice-surface.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • tests/unit/pack-quality-fixtures.test.ts
  • tests/unit/context-pack-command.test.ts
  • src/runtime/stdio/tools.ts
  • src/infrastructure/context-pack-command.ts

📝 Walkthrough

Walkthrough

Implements budget enforcement for explain-task context packs by adding a pack_culled_to_budget diagnostic, a diagnostics-aware culling algorithm that preserves workflow anchors while trimming nodes by ranking, flexible handle/storage schemas for optional focus ranges and expandable data, and pipeline wiring to thread selection diagnostics through to budget enforcement with comprehensive test coverage.

Changes

Budget-Enforced Answer-Ready Packs

Layer / File(s) Summary
Diagnostic contract for budget culling
src/contracts/context-pack-diagnostics.ts
ContextPackDiagnosticKind union extends to include 'pack_culled_to_budget'.
Core budget enforcement with node ranking and culling
src/infrastructure/context-pack-command.ts
Adds diagnostics-aware enforcement that ranks matched nodes, preserves workflow anchors, strips expandable focus_ranges, prunes matched_nodes/relationships to meet maxTokens, records dropped node IDs in routing.warnings under pack_culled_to_budget, downgrades workflow-spine confidence/agent directive when spine nodes are dropped, and updates buildAnswerReadyPackSchema to accept selectionDiagnostics.
Storage schema flexibility for optional fields
src/runtime/stdio/tools.ts
Makes follow_up.focus_ranges optional in validators, normalizes stored handles to default follow_up.focus_ranges to [], accepts optional expandable in cached explain payloads and uses cachedPayload.expandable ?? [] when restoring, and uses resolvedBudget for non-diagnostics explain budget calls.
Test fixtures and helpers for culling validation
tests/unit/context-pack-command.test.ts, tests/unit/helpers/pack-quality.ts
Adds ContextPackSelectionDiagnostics import; buildOversizedAnswerReadySchema and buildAnswerReadySelectionDiagnostics helpers; extends PackSchemaPayload to include optional claims and expandable.preview for test payloads.
Unit tests for budget culling and confidence downgrades
tests/unit/context-pack-command.test.ts
Two new tests validate that oversized answer-ready payloads are culled to the budget by ranking, dropped node IDs are reported under pack_culled_to_budget, workflow centers/recommended_first_read align with retained nodes, and confidence/agent directive downgrade when the workflow spine is dropped due to budget.
Integration test updates for budget enforcement
tests/unit/pack-quality-fixtures.test.ts, tests/unit/compare.test.ts, tests/unit/stdio-server.test.ts, tests/unit/stdio-slice-surface.test.ts
Derives surfaced labels from matched_nodes, expandable previews, and claim labels; increases retrieval budgets in compare tests; updates explain response assertions to validate pack shape and serialized_budget.max_tokens; adds tests asserting serialized_budget enforces budgets below 3000 (enforced: true, token_count <= max_tokens) and rejects malformed stored handles with invalid follow_up.focus_ranges.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • mohanagy/madar#380: Overlaps in context-pack-command answer-ready JSON mode and budget/trim behavior; related changes to compact answer-ready generation.
  • mohanagy/madar#394: Modifies answer-ready explain-pack pipeline and fields that interact with the enforcement and guidance shape.
  • mohanagy/madar#302: Related changes to pack schema construction and JSON/text envelope that overlap with the answer-ready rendering paths.

Poem

🐰 I nibbled tokens, two-by-two,

Promised three but packed six—oh boo!
Now ranks and anchors trim the spread,
Warnings show what's left unread.
Happy hopper, budget fed.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main issue: serialized_budget.enforced being false and packs exceeding their declared budget by 2×, which matches the primary objective of enforcing answer-ready explain-pack budgets.
Description check ✅ Passed The PR description includes a summary of changes, verification steps (typecheck, build, test, CLI commands), but lacks explicit checklist items and a dedicated testing section as specified in the template.
Linked Issues check ✅ Passed All major requirements from issue #400 are implemented: serialized_budget.enforced defaults to true, packs are culled when over-budget with matched-node selection-aware ranking, pack_culled_to_budget warnings are emitted, workflow-spine confidence degrades to low when needed, and tests verify budget enforcement.
Out of Scope Changes check ✅ Passed All changes are tightly scoped to budget enforcement and related infrastructure: answer-ready pack culling, selection diagnostics integration, test updates for stricter serialization, and handling of optional follow-up fields. No unrelated changes detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-400-serialized-budget-enforced

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

@mohanagy

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/infrastructure/context-pack-command.ts (1)

561-659: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Run all matched_nodes/relationships trimming through the diagnostics-aware culler.

Lines 590-638 still hard-cap matched_nodes and relationships before Line 658 calls enforceAnswerReadyBudget(). Those removals bypass the workflow-anchor preservation logic and never surface in pack_culled_to_budget, so an anchor can be dropped silently before the ranking-based culler sees it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/infrastructure/context-pack-command.ts` around lines 561 - 659, The code
currently hard-caps pack.matched_nodes, pack.relationships and
pack.community_context via trimArrayField (in buildAnswerReadyPackSchema) which
bypasses the diagnostics-aware culler and can drop workflow anchors silently;
remove those pack-specific trimArrayField calls and instead let the
diagnostics-aware culler run (i.e., ensure these fields are culled by
enforceAnswerReadyBudget with selectionDiagnostics) — either by not trimming
pack.matched_nodes/relationships/community_context here or by invoking the
culler that enforces answer-ready budget (enforceAnswerReadyBudget) on the
payload/pack so that pack_culled_to_budget records these removals in
trimmedFields and preserves anchors per selectionDiagnostics.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/infrastructure/context-pack-command.ts`:
- Around line 425-481: The final path in enforceAnswerReadyBudget can leave
payload over-budget without marking the budget enforced or downgrading when the
remaining surface is the workflow spine; before the final
upsertPackCulledWarning/attachSerializedBudget call, add a detection for the
irreducible workflow-spine case (e.g. if estimatedJsonTokens(payload) >
maxTokens and the remaining pack represents only the workflow spine) and in that
branch call downgradeWorkflowSpineConfidence(payload, trimmedFields) and ensure
the serialized budget is marked enforced (set payload.serialized_budget.enforced
= true or make attachSerializedBudget record enforcement) so the `"budget too
tight for workflow spine"` downgrade and enforced flag are applied.

In `@src/runtime/stdio/tools.ts`:
- Around line 1366-1368: The explain-path currently uses plannerBudget (which is
clamped to >=3) when building the answer pack, violating caller's explicit
budget; change the call that builds the explain payload so it passes
resolvedBudget instead of plannerBudget (i.e., replace plannerBudget with
resolvedBudget in the buildAnswerReadyPackSchema call used to set
responsePayload when task === 'explain' && !includeSelectionDiagnostics) and
ensure any related reporting/logging for the serialized pack also references
resolvedBudget so enforcement and reporting use the caller's budget, not the
planner floor.
- Around line 171-174: The current check lets any array through for
followUp.focus_ranges which allows malformed entries to reach context_expand and
crash when accessing range.source_file; update the condition to not only ensure
followUp.focus_ranges is an array but also that every element matches the same
shape/validation used by isContextPackExpandableFollowUp (i.e. validate each
focus range object has the required properties like source_file and proper
line/offset types). Concretely, change the boolean expression to use
Array.isArray(followUp.focus_ranges) && followUp.focus_ranges.every(/* reuse or
call the element validator from isContextPackExpandableFollowUp or an equivalent
helper predicate */) so only well-formed focus range entries are accepted before
context_expand reads range.source_file.

In `@tests/unit/context-pack-command.test.ts`:
- Around line 826-833: The test currently only asserts that 'helper-low-2' was
dropped, which can pass even if other low-density nodes were also culled;
strengthen it by asserting that 'helper-low-1' is retained: add positive checks
using payload.pack?.matched_nodes (e.g., map to node_id) to include
'helper-low-1' and ensure payload.pack?.relationships (map to to_id/from_id as
appropriate) does not drop relations for 'helper-low-1', and update the
routing.warnings expectation (pack_culled_to_budget.detail.dropped_node_ids) to
specifically contain 'helper-low-2' but not 'helper-low-1' so the test verifies
lowest-density-first behavior while still checking the existing dropped-node
assertion.

---

Outside diff comments:
In `@src/infrastructure/context-pack-command.ts`:
- Around line 561-659: The code currently hard-caps pack.matched_nodes,
pack.relationships and pack.community_context via trimArrayField (in
buildAnswerReadyPackSchema) which bypasses the diagnostics-aware culler and can
drop workflow anchors silently; remove those pack-specific trimArrayField calls
and instead let the diagnostics-aware culler run (i.e., ensure these fields are
culled by enforceAnswerReadyBudget with selectionDiagnostics) — either by not
trimming pack.matched_nodes/relationships/community_context here or by invoking
the culler that enforces answer-ready budget (enforceAnswerReadyBudget) on the
payload/pack so that pack_culled_to_budget records these removals in
trimmedFields and preserves anchors per selectionDiagnostics.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 8654cb47-617b-4260-963f-91533917cff4

📥 Commits

Reviewing files that changed from the base of the PR and between 2851613 and 9379a2c.

📒 Files selected for processing (9)
  • src/contracts/context-pack-diagnostics.ts
  • src/infrastructure/context-pack-command.ts
  • src/runtime/stdio/tools.ts
  • tests/unit/compare.test.ts
  • tests/unit/context-pack-command.test.ts
  • tests/unit/helpers/pack-quality.ts
  • tests/unit/pack-quality-fixtures.test.ts
  • tests/unit/stdio-server.test.ts
  • tests/unit/stdio-slice-surface.test.ts

Comment on lines +425 to +481
function enforceAnswerReadyBudget(
payload: JsonRecord,
maxTokens: number,
trimmedFields: string[],
diagnostics?: ContextPackSelectionDiagnostics,
): void {
const summary: AnswerReadyCullSummary = {
droppedNodeIds: [],
droppedWorkflowSpine: false,
}
const pack = asJsonRecord(payload.pack)

if (stripExpandableFocusRanges(payload, trimmedFields)) {
attachSerializedBudget(payload, maxTokens, trimmedFields)
if (estimatedJsonTokens(payload) <= maxTokens) {
return
}
}

if (!pack) {
attachSerializedBudget(payload, maxTokens, trimmedFields)
return
}

const candidates = buildAnswerReadyCullCandidates(payload, pack, diagnostics)
for (const candidate of candidates) {
upsertPackCulledWarning(payload, summary.droppedNodeIds)
if (summary.droppedWorkflowSpine) {
downgradeWorkflowSpineConfidence(payload, trimmedFields)
}
attachSerializedBudget(payload, maxTokens, trimmedFields)
if (estimatedJsonTokens(payload) <= maxTokens) {
return
}

const removed = removeMatchedNode(pack, candidate.key, trimmedFields)
if (!removed) {
continue
}
filterRelationshipsToRemainingNodes(pack, trimmedFields)
const removedId = typeof removed.node_id === 'string'
? removed.node_id
: candidate.nodeId
if (removedId) {
summary.droppedNodeIds.push(removedId)
}
if (candidate.preserved) {
summary.droppedWorkflowSpine = true
}
}

upsertPackCulledWarning(payload, summary.droppedNodeIds)
if (summary.droppedWorkflowSpine) {
downgradeWorkflowSpineConfidence(payload, trimmedFields)
}
attachSerializedBudget(payload, maxTokens, trimmedFields)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Handle the irreducible workflow-spine case before the final budget report.

On Lines 476-480, if the payload is still over budget after stripping focus ranges and exhausting cull candidates, this path just reattaches serialized_budget. That leaves serialized_budget.enforced false and skips the "budget too tight for workflow spine" downgrade when the remaining surface is the workflow spine itself, which is the explicit fallback contract for this PR.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/infrastructure/context-pack-command.ts` around lines 425 - 481, The final
path in enforceAnswerReadyBudget can leave payload over-budget without marking
the budget enforced or downgrading when the remaining surface is the workflow
spine; before the final upsertPackCulledWarning/attachSerializedBudget call, add
a detection for the irreducible workflow-spine case (e.g. if
estimatedJsonTokens(payload) > maxTokens and the remaining pack represents only
the workflow spine) and in that branch call
downgradeWorkflowSpineConfidence(payload, trimmedFields) and ensure the
serialized budget is marked enforced (set payload.serialized_budget.enforced =
true or make attachSerializedBudget record enforcement) so the `"budget too
tight for workflow spine"` downgrade and enforced flag are applied.

Comment thread src/runtime/stdio/tools.ts Resolved
Comment thread src/runtime/stdio/tools.ts Resolved
Comment thread tests/unit/context-pack-command.test.ts Resolved
mohanagy and others added 2 commits May 29, 2026 05:20
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Resolve the context-pack serializer conflict by keeping main's runtime primary-path preview preservation alongside the issue #400 answer-ready budget enforcement.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@mohanagy
mohanagy merged commit 2466d70 into main May 29, 2026
7 checks passed
This was referenced Jun 1, 2026
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.

[P2] serialized_budget.enforced is false on 0.27.4 explain packs; packs ship 2× over their declared budget

1 participant