Repository navigation
SDK context budgets, cursor-chain efficiency, and MCP mutation parity - #849
Conversation
Expose token-budget controls across list, get, search, SDK contracts, and MCP schemas. Add truthful feasibility receipts, deterministic row compaction, budget-derived paging, and cursor-chain metadata references. Align raw SDK/MCP mutation defaults with the CLI lean envelope while retaining explicit full results. Refresh generated contracts, token baselines, changelog, docs, tests, and PM evidence.
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
📝 WalkthroughSummary by CodeRabbit
WalkthroughThe change adds token-budget controls across CLI and SDK surfaces, derives bounded intent projections, compacts continuation metadata, strengthens release-gate validation, and aligns default CLI and MCP mutation envelopes. ChangesBounded output and contract updates
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant CLI
participant SDK
participant MCP
participant ReleaseGate
CLI->>SDK: Submit intent and token budget
SDK->>SDK: Derive limits and compact output
SDK-->>CLI: Return bounded result or omission receipt
SDK->>MCP: Project mutation result
MCP-->>SDK: Return compact default or full opt-in result
ReleaseGate->>CLI: Measure intent-aware commands
CLI-->>ReleaseGate: Return context_intent receipt
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
Reviewer's GuideEnforces token-budget-aware context intents across CLI, SDK, and MCP, adds truthful feasibility/omission receipts and deterministic row compaction, collapses continuation metadata via fingerprints, tightens token-budget gates, and aligns MCP mutation envelopes with the CLI’s lean defaults while preserving explicit full-delta options. Sequence diagram for token-budget-aware context intents and continuation pagingsequenceDiagram
actor User
participant Cli as pm_cli
participant Runtime as attachReadOutputContracts
participant Intent as attachContextIntentReceipt
participant Rows as compactContextIntentRows
participant Cursor as collapseContinuationMetadata
User->>Cli: list --for triage --token-budget 3200 --json
Cli->>Runtime: attachReadOutputContracts(command, options, result)
Runtime->>Intent: attachContextIntentReceipt(builtInCommand, options, result)
Intent->>Intent: updateContextIntentEstimate(projected, receipt)
alt estimated_tokens > token_budget
Intent->>Rows: compactContextIntentRows(command, projected, receipt)
alt rows compacted
Rows-->>Intent: true
Intent->>Intent: set degradation = budget_row_compaction
Intent->>Intent: updateContextIntentEstimate(projected, receipt)
else no compaction or still too large
Rows-->>Intent: false
Intent->>Intent: set degradation = budget_receipt_only
Intent->>Intent: set declaration_feasible = false
Intent->>Intent: set result_omitted = true
Intent->>Intent: updateContextIntentEstimate(projected, receipt)
end
end
Intent-->>Runtime: projectedWithIntent
alt options.after is set
Runtime->>Cursor: collapseContinuationMetadata(options, projectedWithIntent)
Cursor-->>Cli: continuation page with continuation_contract
else first page
Runtime-->>Cli: full page with context_intent and metadata
end
Cli-->>User: JSON result
Sequence diagram for token-budget gate and intent negative controlssequenceDiagram
participant Main as main
participant Measure as measureCorpus
participant Budgets as compareBudgets
participant NegCtrl as compareNegativeControls
participant Fail as fail
Main->>Measure: measureCorpus(cliPath)
Measure->>Measure: runCliJson(..., args, options)
Measure-->>Main: {measurements, negativeControl, intentNegativeControl}
alt update manifest
Main->>Budgets: buildManifest(measurements, multiplier)
Budgets-->>Main: nextManifest
else verify budgets
Main->>Budgets: compareBudgets(measurements, manifest)
Budgets-->>Main: budgetViolations
Main->>NegCtrl: compareNegativeControls(negativeControl, intentNegativeControl)
NegCtrl-->>Main: controlViolations
Main->>Main: collect violations
alt violations.length > 0
Main->>Fail: fail("Token budget gate failed", violations)
else
Main->>Main: log "Token budget gate passed (...) infeasible intent receipt verified"
end
end
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Update the Claude plugin acceptance workflow and unit coverage to consume and validate the default id/status/changed_field_count response. Record the exact-head CI correction and verification on pm-awe3t6.
|
New exact head @greptileai please review this exact head. |
|
✅ Action performedFull review finished. Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 50 minutes. |
|
Bot feedback acknowledgement for the first review head:
The only runner failure was the stale Claude smoke consumer; exact head |
There was a problem hiding this comment.
Actionable comments posted: 5
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/sdk/runtime.ts (1)
3497-3510: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winHonor
idOnlyforrunMcpAppendAction.
withMutationCompactioncan produceidOnly, but this action discards it. Therefore,pm_runappend withidOnly: truestill returnschanged_field_countinstead of the id/status-only result documented for single-item mutations.Pass
idOnlytoprojectMutationResultand disablecompactEnvelopewhen it is set. Add a regression test for the append action.Proposed fix
- const { changedFields, runnerOptions } = withMutationCompaction( + const { changedFields, idOnly, runnerOptions } = withMutationCompaction( ctx.args, ctx.options, ); @@ - compactEnvelope: changedFields === "compact", + compactEnvelope: changedFields === "compact" && !idOnly, + idOnly,🤖 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/sdk/runtime.ts` around lines 3497 - 3510, Update the runMcpAppendAction result flow around withMutationCompaction and projectMutationResult to propagate the returned idOnly option, and ensure compactEnvelope is disabled whenever idOnly is true. Add a regression test covering an append with idOnly: true and verify it returns the documented id/status-only result rather than changed_field_count.
🤖 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 @.agents/pm/issues/pm-sf31yl.toon:
- Around line 21-22: Update the pm-sf31yl issue record to link the remaining
acceptance artifacts before closure: a full-walk cost gate using a current-scale
corpus, a repeated-metadata negative control, and a before/after whole-chain
evidence table. Add PM-linked artifact paths or references to their canonical PM
owner, and retain the existing delivery evidence.
In `@src/cli/register-list-query.ts`:
- Around line 348-351: Update the option handling around
applyContextIntentProjection so --token-budget is rejected when options.for is
absent, while preserving its existing mapping when --for is provided.
Alternatively, revise the option description and contract only if token-budget
is intentionally supported without a selected intent; ensure the CLI behavior
matches the documented contract.
In `@src/sdk/context-intent-contracts.ts`:
- Around line 490-544: Optimize compactContextIntentRows by avoiding one full
updateContextIntentEstimate serialization per removed row: measure the current
payload once, estimate rows to remove using the excess token count and
representative bytes-per-row, then remove that batch while retaining at least
one row. Re-estimate after the batch and use one-at-a-time candidate.rows.pop()
removals only for the final boundary adjustment until the token budget is
satisfied.
- Around line 609-616: Remove the final duplicate receipt.within_budget
assignment and updateContextIntentEstimate(projected, receipt) call after the
compaction/fallback pipeline in the context-intent processing flow. Preserve the
earlier updateContextIntentEstimate call and all branch-specific within_budget
assignments, including budget_receipt_only behavior, then return projected
unchanged.
In `@tests/fixtures/contracts/full.json`:
- Around line 14257-14272: The shared tokenBudget description is incorrectly
deps-specific in non-deps schemas. Update the CLI contract definition that
generates tokenBudget descriptions for pm_get, pm_list, pm_search, and
list-family action branches to use generic command-output wording, while
retaining the deps-specific description exclusively for deps tool/action
schemas; regenerate the affected contract fixture ranges.
---
Outside diff comments:
In `@src/sdk/runtime.ts`:
- Around line 3497-3510: Update the runMcpAppendAction result flow around
withMutationCompaction and projectMutationResult to propagate the returned
idOnly option, and ensure compactEnvelope is disabled whenever idOnly is true.
Add a regression test covering an append with idOnly: true and verify it returns
the documented id/status-only result rather than changed_field_count.
🪄 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: Repository UI (base), Organization UI (inherited)
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 3bac55bf-6310-4825-967c-bc6c642bffe8
📒 Files selected for processing (34)
.agents/pm/features/pm-nilh.toon.agents/pm/history/pm-7hbfch.jsonl.agents/pm/history/pm-awe3t6.jsonl.agents/pm/history/pm-nilh.jsonl.agents/pm/history/pm-sf31yl.jsonl.agents/pm/history/pm-wv47pf.jsonl.agents/pm/history/pm-yekkvt.jsonl.agents/pm/issues/pm-7hbfch.toon.agents/pm/issues/pm-awe3t6.toon.agents/pm/issues/pm-sf31yl.toon.agents/pm/issues/pm-wv47pf.toon.agents/pm/issues/pm-yekkvt.toonCHANGELOG.mddocs/COMMANDS.mddocs/OUTPUT_PROJECTION_CONTRACTS.mdscripts/agent-token-surface-baseline.jsonscripts/release/token-budget-gate.mjsscripts/release/token-budgets.jsonsdk/public-surface.jsonsrc/cli/register-list-query.tssrc/sdk/cli-contracts/flag-contracts.tssrc/sdk/cli-contracts/tool-option-contracts.tssrc/sdk/cli-contracts/tool-schema.tssrc/sdk/context-intent-contracts.tssrc/sdk/runtime.tstests/fixtures/contracts/full.jsontests/integration/mcp-dynamic-package-actions.spec.tstests/integration/sdk-cli-contract-integrity.integration.spec.tstests/unit/cli/context-intent-registration.spec.tstests/unit/commands/query-pagination.spec.tstests/unit/mcp/mutation-envelope-parity.spec.tstests/unit/scripts/release/token-budget-gate.spec.tstests/unit/sdk/context-intent-contracts.spec.tstests/unit/sdk/sdk-index.spec.ts
There was a problem hiding this comment.
1 issue found and verified against the latest diff
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="src/cli/register-list-query.ts">
<violation number="1" location="src/cli/register-list-query.ts:483">
P2: `--token_budget` does not override the budget for list, search, or get: projection sets the declared default because it only reads `tokenBudget`, and the receipt also reports that default. Canonicalize this alias before applying/rendering the intent, or have the intent helpers accept `token_budget`.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Validate measured output independently from receipt claims, normalize token-budget aliases, preserve recoverable read rows, and batch row compaction. Propagate idOnly through aggregated MCP append, scope parameter descriptions correctly, and add high-scale regressions. Record exact release-gate evidence while returning incomplete acceptance work to open.
|
Exact review-fix head: @greptileai please review this exact head. The local adapter currently reports @coderabbitai full review |
|
✅ Action performedFull review finished. Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 4 minutes. |
|
Review reconciliation for exact head
|
Include the SDK token-budget usage error in the generated error-code source inventory and regenerated full contract fixture. Record CI evidence and return the remaining calibration acceptance to open.
|
New exact head @greptileai please review this exact head if review capacity is available. @coderabbitai full review |
|
Your plan includes PR reviews subject to rate limits. More reviews will be available in 59 minutes. |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
scripts/release/token-budget-gate.mjs (1)
511-518: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a comment distinguishing the two token-budget comparisons.
Line 514 (
measurement.estimated_tokens > receipt.token_budget) and Line 515 (receipt.estimated_tokens > receipt.token_budget) look like a duplicated condition, but they check different things: Line 514 independently validates the actually measured output against the declared budget, Line 515 validates the receipt's internal self-consistency. Both are exercised by distinct tests intests/unit/scripts/release/token-budget-gate.spec.ts(lines 495-546 and 548-573).A short inline comment would prevent a future refactor from treating one of these as a redundant duplicate and removing it.
📝 Suggested clarifying comment
if ( !receipt || receipt.declaration_feasible !== true || receipt.result_omitted !== false || receipt.within_budget !== true || !Number.isFinite(receipt.estimated_tokens) || !Number.isFinite(receipt.token_budget) || + // Independently verify the actual measured output against the declared budget... measurement.estimated_tokens > receipt.token_budget || + // ...and separately verify the receipt's own estimate is internally consistent. receipt.estimated_tokens > receipt.token_budget ) {🤖 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 `@scripts/release/token-budget-gate.mjs` around lines 511 - 518, Add a concise inline comment in the validation condition distinguishing measurement.estimated_tokens > receipt.token_budget as validation of the actual measured output against the declared budget from receipt.estimated_tokens > receipt.token_budget as validation of the receipt’s internal consistency; leave both comparisons and their behavior unchanged.
🤖 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 @.agents/pm/history/pm-awe3t6.jsonl:
- Line 23: Update the PM record through the pm CLI, not by editing .agents/pm
files directly: append a PM update correcting the src/mcp/server.ts note to
state that the default MCP mutation envelope is lean and contains no item, then
regenerate the derived projection in .agents/pm/issues/pm-awe3t6.toon. Apply the
update at .agents/pm/history/pm-awe3t6.jsonl lines 23-23 and regenerate
.agents/pm/issues/pm-awe3t6.toon lines 34-42; do not edit the history entry
manually.
In `@tests/unit/sdk/context-intent-contracts.spec.ts`:
- Around line 395-397: Make the assertions in the test around
attachContextIntentReceipt meaningful: either include a truncated field in the
input fixture so the test verifies compaction removes stale truncation state, or
remove the ineffective truncated and next_cursor absence assertions. Do not
retain assertions that are guaranteed by the fixture or compactContextIntentRows
precondition.
---
Outside diff comments:
In `@scripts/release/token-budget-gate.mjs`:
- Around line 511-518: Add a concise inline comment in the validation condition
distinguishing measurement.estimated_tokens > receipt.token_budget as validation
of the actual measured output against the declared budget from
receipt.estimated_tokens > receipt.token_budget as validation of the receipt’s
internal consistency; leave both comparisons and their behavior unchanged.
🪄 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: Repository UI (base), Organization UI (inherited)
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: befb1ec6-38d2-46ee-820a-8940aa99810a
📒 Files selected for processing (17)
.agents/pm/history/pm-awe3t6.jsonl.agents/pm/history/pm-sf31yl.jsonl.agents/pm/history/pm-yekkvt.jsonl.agents/pm/issues/pm-awe3t6.toon.agents/pm/issues/pm-sf31yl.toon.agents/pm/issues/pm-yekkvt.toonscripts/release/token-budget-gate.mjsscripts/smoke-claude-plugin.mjssrc/sdk/cli-contracts/tool-parameter-tables.tssrc/sdk/context-intent-contracts.tssrc/sdk/generated-error-code-catalog.tssrc/sdk/runtime.tstests/fixtures/contracts/full.jsontests/unit/mcp/mutation-envelope-parity.spec.tstests/unit/scripts/release/token-budget-gate.spec.tstests/unit/scripts/smoke-claude-plugin.spec.tstests/unit/sdk/context-intent-contracts.spec.ts
Correct the stale MCP linked-file note through pm, remove non-discriminating compaction assertions, and preserve unfinished cursor-chain acceptance as open work.
|
Final review-fix head: @greptileai please review this exact head if capacity is available. @coderabbitai full review |
|
✅ Action performedFull review finished. Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 48 minutes. |
There was a problem hiding this comment.
1 issue found across 9 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name=".agents/pm/history/pm-sf31yl.jsonl">
<violation number="1" location=".agents/pm/history/pm-sf31yl.jsonl:24">
P3: This PM history entry gains two back-to-back comment_add ops (comments/3 and comments/4) that are near-identical restatements of the same "Exact-head CodeRabbit cleanup" note, differing only in the trailing test-status phrase. This duplicates the same event in the append-only ledger and will surface as redundant noise in the item's evidence trail and any regenerated projection. Keep a single comment; drop the duplicate entry.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
Re-trigger cubic
Summary
This broad SDK and CLI delivery makes project management = context management enforceable across the agent-facing read and mutation surfaces.
PM lineage
Verification
Summary by cubic
Enforces context token budgets across CLI, SDK, and MCP with budget‑derived paging, truthful receipts, and cursor-chain amortization. Aligns MCP/SDK mutation defaults with the CLI’s lean envelope and tightens docs/tests to enforce it.
New Features
--token-budgetto list/get/search; SDK and MCP exposetokenBudget(alias--token_budget) and bump tool schema to4.3.0.declaration_feasible,result_omitted, andbudget_row_compaction; page sizes derive from the remaining budget.id,status,changed_field_count; passfullChangedFields=truefor full deltas, oridOnly=truefor IDs only.Bug Fixes
--token-budget/--token_budgethandling across CLI/SDK/MCP and scopetokenBudgetparameter descriptions correctly.idOnlythrough aggregated append; include the SDK token‑budget usage error in the generated catalog.Written for commit 1cb2c04. Summary will update on new commits.
Summary by Sourcery
Enforce context token budgets and truthful receipts across CLI, SDK, and MCP, while reducing cursor-chain overhead and aligning mutation envelopes with the CLI’s lean defaults.
New Features:
Bug Fixes:
Enhancements:
Build:
Documentation:
Tests: