Skip to content

feat(cost): expose cycle outlook through CLI and MCP (#1138) - #1168

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/cost-outlook-surfaces-v2
May 17, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/cost-outlook-surfaces-v2

Conversation

@Sinity

@Sinity Sinity commented May 17, 2026

Copy link
Copy Markdown
Owner

Summary

Wires the typed CycleOutlook engine from #1137 (PR #1160) through
the user surfaces: a new polylogue cost outlook CLI subcommand, a
new cost_outlook MCP tool, and a new Polylogue.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 cost rendered a
flat per-plan rollup over compute_usage_outlook and there was no
MCP tool exposing the new typed cycle outlook (only cost_rollups
and session_costs were available). Subscription-equivalent and
API-equivalent figures could collapse into one unlabelled cost
number, and a plan without a cycle_anchor_day had no way to be
surfaced as "no cycle window" rather than fabricated.

Solution

  • polylogue/cli/commands/cost.py: converted cost to a
    click.Group. New cost outlook --plan <name> --method {linear,trailing-7d-mean,eom-naive} --format {plain,json} renders
    the typed CycleOutlook. JSON output is canonical and exercised by
    contract tests. Plain output prefixes USD figures with ~, labels
    the USD basis as USD (API-equivalent), labels quota figures by
    their basis (credits / tokens / etc.), surfaces
    QuotaPressureMissing as Quota pressure: not configured, and
    always prints the "subscription quota math is non-authoritative"
    caveat. The legacy flat rollup is preserved as cost rollup for
    the feat(insights): subscription-aware cost tracking with client-side tokenizer and per-model breakdown #803 cost-tracking pipeline.
  • polylogue/cli/click_command_registration.py: cost registered as
    a lazy group via _GROUP_ATTRS.
  • polylogue/mcp/server_insight_tools.py: new cost_outlook(plan, method) special tool. PlanLookupError, unknown
    ProjectionMethod, and "no cycle anchor" surface as typed error
    envelopes (code = not_found / invalid_argument /
    no_cycle_window, with tool and detail fields populated).
  • polylogue/api/insights.py: new
    Polylogue.cost_outlook(plan_name, *, now=None, method=...) async
    method. Resolves plans via
    polylogue.cost.plans.resolve_plan(name, user_rows=load_polylogue_config().subscription_plans), fetches
    materialized SessionCostInsights, folds them to daily USD usage
    via the new polylogue.cost.aggregation.session_costs_to_daily_usd
    helper, and projects through build_cycle_outlook.
  • polylogue/cost/aggregation.py (new): pure-function bridge
    aggregating SessionCostInsight -> per-day USD DailyUsage rows.
    Skips rows without a parseable created_at or with non-positive
    total_usd so coverage stays honest. Output is deterministically
    sorted for stable snapshots.
  • Tool wiring: cost_outlook added to EXPECTED_TOOL_NAMES
    (tests/infra/mcp.py), classified as single_object in
    TOOL_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.py and
    tests/unit/cli/test_terminal_snapshots.py::test_check_output_snapshot
    are inherited dirty baseline unrelated to this scope; confirmed by
    running them against git stash'd HEAD).
  • devtools verify --quick -> exit_code: 0, all gates green
    including 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 json emits the full
    CycleOutlook payload deterministically; snapshot/contract tests
    pinned in test_cost_outlook_cli.py::TestCostOutlookJsonContract.
  • Plain output labels estimates and uncertainty; quota basis and
    "not configured" cases surfaced explicitly
    (TestCostOutlookPlainContract).
  • MCP cost_outlook tool returns the same typed payload as the
    CLI with parameter validation; tool-contract tests in
    test_cost_outlook_tool.py.
  • Subscription-equivalent and API-equivalent fields never merge
    into one unlabelled cost number on any surface (verified by both
    CLI plain renderer test and MCP contract test against a mixed
    credits + usd payload).
  • Unknown / unpriced / estimated rows are visible in both
    surfaces with an explicit reason (QuotaPressureMissing
    serialisation, no_cycle_window error envelope, plain "not
    configured" line).
  • devtools render-all --check clean (CLI reference,
    verification catalog, topology projection, test-quality workflow
    regenerated).
  • Docs caveat: plain renderer prints
    "Subscription quota math is non-authoritative; vendor pricing and
    quotas change without notice."; CHANGELOG entry under Unreleased.

Non-goals (intentionally deferred)

Closes #1138

@coderabbitai

coderabbitai Bot commented May 17, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 43 minutes and 41 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 39510146-0655-407e-894d-48964b2e08ed

📥 Commits

Reviewing files that changed from the base of the PR and between 7261aeb and 828f478.

📒 Files selected for processing (16)
  • CHANGELOG.md
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • docs/verification-catalog.md
  • polylogue/api/insights.py
  • polylogue/cli/click_command_registration.py
  • polylogue/cli/commands/cost.py
  • polylogue/cost/aggregation.py
  • polylogue/mcp/server_insight_tools.py
  • tests/data/witnesses/mcp-tool-schemas.json
  • tests/infra/mcp.py
  • tests/unit/cli/test_cost_outlook_cli.py
  • tests/unit/cli/test_json_envelope_contract.py
  • tests/unit/mcp/test_cost_outlook_tool.py
  • tests/unit/mcp/test_envelope_contracts.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/cost-outlook-surfaces-v2

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.

❤️ Share

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

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
@Sinity
Sinity force-pushed the feature/feat/cost-outlook-surfaces-v2 branch from 15e4a4b to 828f478 Compare May 17, 2026 09:47
@Sinity
Sinity merged commit f2330c1 into master May 17, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the feature/feat/cost-outlook-surfaces-v2 branch May 17, 2026 09:47

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 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".

Comment on lines +67 to +68
parsed = datetime.fromisoformat(normalized)
return parsed.date().isoformat()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Sinity added a commit that referenced this pull request May 17, 2026
## 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
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.

feat(cost): expose cycle outlook through CLI and MCP

1 participant