Repository navigation
feat(cost): expose cycle outlook through CLI and MCP (#1138) - #1168
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (16)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
Wires the typed CycleOutlook engine (#1137) through the user surfaces. - `polylogue cost` becomes a click.Group. New `cost outlook` subcommand emits the CycleOutlook payload in JSON (canonical) and plain mode. Plain mode labels USD as API-equivalent, quota figures by basis, and surfaces QuotaPressureMissing as an explicit "not configured" row so subscription-equivalent and API-equivalent figures never collapse into a single unlabelled "cost". The legacy flat surface is preserved as `cost rollup` for the #803 pipeline. - MCP gets a new `cost_outlook(plan, method)` tool returning the same typed payload. PlanLookupError, unknown ProjectionMethod, and missing cycle_anchor_day produce typed error envelopes rather than silent fallbacks. - `Polylogue.cost_outlook(plan_name, now=None, method=...)` async method resolves the plan against `[[cost.subscription.plans]]` user overrides merged with the curated seed, lists materialized session-cost insights, folds them into per-day USD usage via the new `polylogue.cost.aggregation` helper, and projects through `build_cycle_outlook`. - Topology projection, verification catalog, and test-quality workflow renderings regenerated. MCP tool-schema witness regenerated to include cost_outlook. Closes #1138
15e4a4b to
828f478
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 15e4a4b801
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| parsed = datetime.fromisoformat(normalized) | ||
| return parsed.date().isoformat() |
There was a problem hiding this comment.
Normalize parsed timestamps to UTC before day bucketing
_parse_iso_day currently returns parsed.date() directly, so offset-aware timestamps are grouped by their local offset day instead of UTC day. For example, a session at 2026-05-01T23:30:00-07:00 is counted on 2026-05-01 here even though it is 2026-05-02 UTC. Because session_costs_to_daily_usd feeds cycle burn/projection math, this can shift usage across cycle boundaries and produce incorrect outlook totals for providers exporting non-UTC offsets. Convert the parsed datetime to UTC before extracting the date.
Useful? React with 👍 / 👎.
## Summary Two unrelated test failures had accumulated on master and were inherited into every feature branch's verify run. This PR clears both so the master baseline goes green again. Closes #1180. ## Problem Reproduced on a clean `origin/master` checkout: ``` pytest tests/unit/cli/test_check.py::TestCheckCommandSupplementary \ tests/unit/mcp/test_tool_schema_witness.py ``` 5 failures (4 + 1): - `tests/unit/cli/test_check.py::TestCheckCommandSupplementary` — `test_json_output_with_repair`, `test_repair_with_no_issues_shows_message`, `test_vacuum_with_repair`, `test_json_output_with_repair_and_vacuum_is_machine_safe` all raised `KeyError: 'message_embeddings'` from `polylogue/storage/repair.py:run_safe_repairs`. The `message_embeddings` maintenance target was added to `polylogue/maintenance/targets.py` in #1157 (typed planner contract) with `mode=REPAIR`, but no matching entry was added to `_REPAIR_HANDLERS`. `run_safe_repairs` then iterated every name from `SAFE_REPAIR_TARGETS` and crashed on the missing key. - `tests/unit/mcp/test_tool_schema_witness.py::test_mcp_tool_catalog_matches_witness` failed because the committed witness in `tests/data/witnesses/mcp-tool-schemas.json` still contained the pre-#1168 catalog. PR #1168 added `cost_outlook` to the MCP server (`polylogue/mcp/server_insight_tools.py`); the witness needed regeneration. The current registry exposes 64 tools — both `cost_outlook` and `cost_rollups`. ## Solution - `polylogue/storage/repair.py`: add `repair_message_embeddings()` as a no-op handler that records the embedding rebuild as dormant (#828). The embedding pipeline is daemon-owned and has no synchronous rebuild path, so a `doctor --repair` invocation that touches this target should report dormancy rather than crash. The catalog continues to list the target so planners and surfaces can name the dormant work. - `tests/data/witnesses/mcp-tool-schemas.json`: regenerate from `build_server(role="admin")` per the regeneration recipe in the test module docstring. No production semantics changed: the embedding stub is the smallest change that closes the crash without inventing a new rebuild contract that #828 will eventually own. ## Verification ``` pytest tests/unit/cli/test_check.py::TestCheckCommandSupplementary \ tests/unit/mcp/test_tool_schema_witness.py # => 25 passed in 10.59s (was 5 failed, 20 passed) devtools verify --quick # => "exit_code": 0 ``` Closes #1180
Summary
Wires the typed
CycleOutlookengine from #1137 (PR #1160) throughthe user surfaces: a new
polylogue cost outlookCLI subcommand, anew
cost_outlookMCP tool, and a newPolylogue.cost_outlook(...)async facade method.
Problem
AC of #1138: "cost outlook surface in CLI / MCP / web reader" and
"CLI JSON contracts are deterministic; plain output clearly labels
estimates and uncertainty". The existing
polylogue costrendered aflat per-plan rollup over
compute_usage_outlookand there was noMCP tool exposing the new typed cycle outlook (only
cost_rollupsand
session_costswere available). Subscription-equivalent andAPI-equivalent figures could collapse into one unlabelled
costnumber, and a plan without a
cycle_anchor_dayhad no way to besurfaced as "no cycle window" rather than fabricated.
Solution
polylogue/cli/commands/cost.py: convertedcostto aclick.Group. Newcost outlook --plan <name> --method {linear,trailing-7d-mean,eom-naive} --format {plain,json}rendersthe typed
CycleOutlook. JSON output is canonical and exercised bycontract tests. Plain output prefixes USD figures with
~, labelsthe USD basis as
USD (API-equivalent), labels quota figures bytheir basis (
credits/tokens/ etc.), surfacesQuotaPressureMissingasQuota pressure: not configured, andalways prints the "subscription quota math is non-authoritative"
caveat. The legacy flat rollup is preserved as
cost rollupforthe feat(insights): subscription-aware cost tracking with client-side tokenizer and per-model breakdown #803 cost-tracking pipeline.
polylogue/cli/click_command_registration.py:costregistered asa lazy group via
_GROUP_ATTRS.polylogue/mcp/server_insight_tools.py: newcost_outlook(plan, method)special tool.PlanLookupError, unknownProjectionMethod, and "no cycle anchor" surface as typed errorenvelopes (
code=not_found/invalid_argument/no_cycle_window, withtoolanddetailfields populated).polylogue/api/insights.py: newPolylogue.cost_outlook(plan_name, *, now=None, method=...)asyncmethod. Resolves plans via
polylogue.cost.plans.resolve_plan(name, user_rows=load_polylogue_config().subscription_plans), fetchesmaterialized
SessionCostInsights, folds them to daily USD usagevia the new
polylogue.cost.aggregation.session_costs_to_daily_usdhelper, and projects through
build_cycle_outlook.polylogue/cost/aggregation.py(new): pure-function bridgeaggregating
SessionCostInsight-> per-day USDDailyUsagerows.Skips rows without a parseable
created_ator with non-positivetotal_usdso coverage stays honest. Output is deterministicallysorted for stable snapshots.
cost_outlookadded toEXPECTED_TOOL_NAMES(tests/infra/mcp.py), classified as
single_objectinTOOL_CONTRACT(tests/unit/mcp/test_envelope_contracts.py),added to MCP tool-schema witness, registered in topology
projection.
Verification
Local commands actually run on this branch:
pytest tests/unit/cli/test_cost_outlook_cli.py tests/unit/mcp/test_cost_outlook_tool.py -q->13 passed.pytest tests/unit/cli/ tests/unit/mcp/ tests/unit/cost/ tests/unit/api/ -q --ignore=tests/integration->1408 passed(4 pre-existing failures in
tests/unit/cli/test_check.pyandtests/unit/cli/test_terminal_snapshots.py::test_check_output_snapshotare inherited dirty baseline unrelated to this scope; confirmed by
running them against
git stash'd HEAD).devtools verify --quick->exit_code: 0, all gates greenincluding
mypy --strict,ruff,render-all --check,verify-topology,verify-manifests,verify-witness-lifecycle.pytest tests/unit/cli/test_json_envelope_contract.py::TestCostJsonContract tests/unit/mcp/test_tool_schema_witness.py -q->5 passed(legacy contract migrated to
cost rollup --format json,MCP tool-schema witness regenerated for the new tool).
Acceptance criteria
polylogue cost outlook --plan ... --format jsonemits the fullCycleOutlookpayload deterministically; snapshot/contract testspinned in
test_cost_outlook_cli.py::TestCostOutlookJsonContract."not configured" cases surfaced explicitly
(
TestCostOutlookPlainContract).cost_outlooktool returns the same typed payload as theCLI with parameter validation; tool-contract tests in
test_cost_outlook_tool.py.into one unlabelled
costnumber on any surface (verified by bothCLI plain renderer test and MCP contract test against a mixed
credits+usdpayload).surfaces with an explicit reason (
QuotaPressureMissingserialisation,
no_cycle_windowerror envelope, plain "notconfigured" line).
devtools render-all --checkclean (CLI reference,verification catalog, topology projection, test-quality workflow
regenerated).
"Subscription quota math is non-authoritative; vendor pricing and
quotas change without notice."; CHANGELOG entry under
Unreleased.Non-goals (intentionally deferred)
(feat(reader): finish interactive reader and unified surface shell #848 etc.).
polylogue insights costpage indocs/insights.md—the new CLI subcommand is fully documented by
devtools render-cli-referenceoutput and the help text; a curated narrativepage can land as a follow-up if the renderings prove insufficient.
Closes #1138