Repository navigation
[2734 by Claude Opus 5.5] ## Enforce per-run spend caps (cancel the run when its cost exceeds the cap) - #2758
Conversation
…nce its estimated cost reaches the cap, and its partial work is published the way a timed-out run's is. `npm run lint` and `npm run typecheck` pass, and so do about 110 affected test files (UI vitest suites included). The full suite was not run, and I couldn't exercise a real Docker agent run in this sandbox, so the stop has only been tested through the guard and in unit tests.
Where the cap comes from (highest wins)
1. `maxCostUsd` on a REST task submission or MCP `create_task`, or `--max-cost <usd>` on `propr issue implement`.
2. `limits.max_cost_usd` in `.propr/workflow.yml`. A bad value here doesn't reject the whole workflow file: it's logged and ignored. The editor schema still flags it.
3. The new `default_max_cost_usd` setting, available in Settings → Automation, `propr setting update` and MCP `update_execution_settings`.
Empty or 0 means "not set at this level", so the next level applies. A malformed or negative value is logged and treated the same way, so a typo can never cap runs at $0. I removed the unused `AgentTankConfig` type rather than reuse it.
How it's enforced
- What counts as spend: the task's recorded `llm_executions` costs plus the token usage the running agent containers have streamed so far. It's re-checked every ~10 seconds, so a run can go slightly over before it's stopped.
- The stop: the container is torn down through the same path a UI stop uses, but the run is treated like a timeout rather than a user cancellation. A user stop marks the task cancelled, which would skip publishing the partial work.
- What gets recorded: the task ends with terminal reason `cost_cap_exceeded`. It also gets a `budget.exceeded` timeline event (shown as "Spend Cap Reached"), an Inbox notification, and a short comment on the issue or PR.
- Covered runs: implementations, follow-ups, `/fix`, ultrafix cycles and reviews. Goals are unchanged.
- Retries share the budget: earlier attempts' spend counts against the cap. PR usage-limit retries get a new task ID, so they carry the earlier attempt IDs along.
- Visible in: the task header ("$5.12 / $5.00 (102.4%) capped"), the task history API, and `propr task get` (`budget` in `--json`).
- `LLM_COST_THRESHOLD_USD` still only raises alerts; the docs now say so.
Behaviours to be aware of
- Once the cap is hit, later steps that publish the partial work (commit message, PR text) can still make a few small LLM calls.
- `--max-cost` is saved against the issue in Redis for 30 days, so re-runs of that issue in that window also use it.
- The new task form in the web UI has no cap field; per-task caps come only from REST, MCP or the CLI.
Test changes you should know about
- Several existing tests replace `@propr/core` with a fixed list of exports, which broke on the new imports. I moved the pure constants and formatters into `@propr/shared` to avoid most of that.
- For the rest I edited existing tests:
- `prPublicationJob` and `prPublicationRecoveryJob` now stub the new cost-cap module.
- `planIssueHandlers.followup` gets one extra stub.
- `configRoutes.followup` expects the new setting in its deep-equal checks.
- New tests cover cap precedence, malformed values, retry arithmetic, the stop firing once with the right reason and timeline event, the workflow schema, and the CLI/UI display.
Docs are updated in `repository-workflow.md`, `metrics.md`, `execution-safety.md` (new "Spend Caps" section), the CLI docs and the CHANGELOG. `settings-locations.md` was regenerated rather than edited, because it's generated from the settings catalog. I also saved two screenshots as previews: the capped task's detail page and the new settings field.
|
/ultrafix goal=8 max=5 |
|
🔄 Ultrafix loop started (goal: 8/10, max cycles: 5) First action:
|
|
✅ AI Code Review Complete requested by @propr-dev[bot] Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR adds spend-cap configuration, live cost accounting, interruption handling, and user-facing reporting. It needs changes before merge: asynchronous accounting can falsely declare a cap exceeded, and executions that finish between checks can escape cap classification entirely. ✅ Consistent precedence — The resolver applies task, workflow, and instance caps in order, with explicit handling of zero and malformed values. ✅ Partial-work integration — This is a static review of the supplied code; no commands were run. Current-head checks show 13 neutral/skipped results and no passing, pending, or failing checks. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F1: 🔴 Execution completion can double-count spend
F2: 🔴 Final usage can bypass cap enforcement
SuggestionsThese are optional follow-ups and are not sent to S1: 🟢 Preserve historical budget configuration
ScoreThe configuration and publication integration are well developed, but two defects remain in the central enforcement lifecycle. The supplied tests do not cover these asynchronous completion paths, and current checks provide no passing validation. Score: 6/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
✅ Applied the requested follow-up changes in commit a270cf4
Summary of ChangesI fixed F1 and F2. Both cases now behave as intended, and the three new regression tests fail on the old code and pass with the fix. F1 – an execution could be counted twice (
F2 – a run could finish above its cap without the spend-cap outcome
Regression tests
Verification: Nothing visible to users changed, so there are no previews. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
…he three new regression tests fail on the old code and pass with the fix. I fixed F1 and F2. Both cases now behave as intended, and the three new regression tests fail on the old code and pass with the fix. **F1 – an execution could be counted twice** (`packages/core/src/budget/runCostGuard.ts`) - The check now copies the lists of running and finished executions in a single step, before it starts the slow pricing lookup, and uses only those copies. An execution that finishes during pricing can no longer appear in both lists. - It still reads the recorded spend first. Rows are only written after an execution finishes, so a running execution can't be counted both in recorded spend and in live usage. **F2 – a run could finish above its cap without the spend-cap outcome** - In the guard, `finish()` now returns a promise. It moves the execution to the finished list and waits for any check already running. Then it runs a fresh check that includes the final usage, and returns the stop message if the run reached its cap. Calling it twice gives the same result. The interface change is in `runCostGuardContext.ts`. - In `dockerExecutor.ts`, when the agent process exits, the executor now reads its last output line (even one with no trailing newline) and then waits for that final check before settling the result. If the cap was reached, the result goes through the same path as a run stopped mid-way: partial output marked `costCapExceeded` when the caller can publish it, otherwise `RunCostCapExceededError`. That gives the run the `cost_cap_exceeded` terminal reason, the `budget.exceeded` event and the notice. If the run was already aborted for another reason, such as a cancel, that outcome is kept. - I checked the other places that use this: Docker is the only caller of `beginExecution`, and the agents already turn `costCapExceeded` into the `cost_cap` termination. **Regression tests** - `packages/core/test/runCostCap.test.ts`: - An execution finishes while a check is still pricing its $6 of usage under a $10 cap. The run is not stopped and no exceeded event is recorded. - Usage pushes the run past its cap and the execution finishes with no check in between. The guard reports the stop message once. - `test/dockerExecutorLiveOutput.test.ts`: a fake `docker run` prints a usage line with no trailing newline and exits. The test confirms that line is seen before the final check, and that the result is `costCapExceeded` (or `RunCostCapExceededError` when partial output isn't kept). **Verification:** `npm run typecheck` and `npm run lint` pass. The guard, enforcement, Docker executor, Docker abort/ownership and task-container test files pass: 29 tests, 0 failures. I didn't run the full suite. To run the tests, I first installed dependencies with `npm ci && npm run test:prepare`; no setup files changed. Nothing visible to users changed, so there are no previews. PR: #2758 Comment by: @propr-ultrafix (ID: 0) Model: claude-opus-5-5
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR adds spend-cap configuration, execution guards, terminal reasons, and user-facing reporting. It needs changes before merge: default-model PR runs can escape live pricing, and final cost reconciliation can miss a cap crossing. ✅ Consistent cap precedence — Task, workflow, and instance caps share a resolver with explicit handling for zero, malformed values, and upper bounds. ✅ Partial-output handling — Docker execution awaits its final usage evaluation and preserves output for callers that support partial publication. ✅ Focused regression coverage — Added tests cover message deduplication, simultaneous executions, exhausted retry budgets, and usage arriving immediately before exit. This is a static review of the supplied code; no commands or tests were executed. No current-head check runs were reported. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F3: 🔴 Default-model PR runs lack live pricing
F4: 🔴 Final reconciliation drops recorded analysis spend
SuggestionsThese are optional follow-ups and are not sent to S2: 🟢 Expose live spend in task details
ScoreThe configuration and reporting integration are substantial, but two enforcement gaps undermine the central spending-limit guarantee. The focused tests need coverage for effective-model propagation and mixed recorded/live accounting. Score: 5/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
✅ Applied the requested follow-up changes in commit 8a96ac5
Summary of ChangesI fixed F3 and F4. Lint, typecheck and 260 tests across the 16 Docker-executor and spend-cap test files pass. Seven of the new assertions fail on the old code and pass with the fix: the agent-level model checks (each fails all ten agent tests), the F4 test, and the Docker-level F3 test. F3: PR runs on the default model now get priced
F4: analysis spend is no longer dropped at the final check
One race the fix can't close: if a call the guard didn't watch gets recorded in the short gap between an execution ending and that execution's own row being written, it is taken as part of that row. Spend is then undercounted by up to the smaller of the two amounts, never double-counted. Closing this would need each row matched to its execution in the database. Separate issue, not changed: Claude native goal runs ( To run the tests I installed dependencies ( 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
… 16 Docker-executor and spend-cap test files pass. Seven of the new assertions fail on the old code and pass with the fix: the agent-level model checks (each fails all ten agent tests), the F4 test, and the Docker-level F3 test. I fixed F3 and F4. Lint, typecheck and 260 tests across the 16 Docker-executor and spend-cap test files pass. Seven of the new assertions fail on the old code and pass with the fix: the agent-level model checks (each fails all ten agent tests), the F4 test, and the Docker-level F3 test. **F3: PR runs on the default model now get priced** - The Docker executor takes a new `model` option and passes it to the guard when it registers an agent container (`dockerExecutor.ts`). - Every agent passes the model it actually resolved, falling back to its configured default. That covers both implementation and analysis runs in Claude, Codex, OpenCode, Vibe and Antigravity, and the older Claude Code path in `claudeService.ts`. So a PR job with no explicit `llm` is priced even when its usage records (like Codex `turn.completed`) name no model. - Tests: - `test/analysisGitAccess.test.ts` checks that all five agents, run without a model, pass their configured default. - `test/dockerExecutorLiveOutput.test.ts` runs a fake `docker` that prints model-free Codex usage worth $3 against a $2 cap, with a guard that has no default model. The run now ends at the cap. - `test/runCostCapEnforcement.test.ts` builds a PR job without `llm`, confirms no model is set on it, and checks that the model the execution registers is the one used for pricing. **F4: analysis spend is no longer dropped at the final check** - The old final check took whichever was larger: recorded spend, or observed usage. It now adds them, without counting anything twice. - When an execution ends, the guard reads the recorded spend before that execution's own row can be written. From then on: - Spend recorded after that point is treated as the execution's own row. - Only the part of its observed usage not yet covered by that row is added on top. - Spend recorded before it ended, such as analysis, is always counted on its own. - Tests in `packages/core/test/runCostCap.test.ts`: - The requested case: $0.50 of analysis, then $1.70 of usage reported just before exit, now stops the run at $2.20. - A second test checks that once the execution's $1.70 row is written, it replaces the observed usage instead of being added to it, and that a later $0.90 analysis call pushes past the cap. That test passes on the old code too; it is there to guard the new formula. **One race the fix can't close:** if a call the guard didn't watch gets recorded in the short gap between an execution ending and that execution's own row being written, it is taken as part of that row. Spend is then undercounted by up to the smaller of the two amounts, never double-counted. Closing this would need each row matched to its execution in the database. **Separate issue, not changed:** Claude native goal runs (`claudeNativeGoal.ts`) start `docker` directly rather than through the Docker executor, so the spend guard never sees them. That isn't part of the PR-run paths these findings cover. To run the tests I installed dependencies (`npm ci` and `npm run test:prepare`), which `.propr/setup.sh` already does, so no setup changes were needed. There's nothing visual in this change, so I made no preview. PR: #2758 Comment by: @propr-ultrafix (ID: 0) Model: claude-opus-5-5
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR adds spend-cap configuration, streamed usage accounting, container cancellation, and reporting across the API, CLI, and UI. It needs changes before merge because finished-execution reconciliation can undercount actual spend. ✅ Consistent configuration precedence — Task overrides, workflow caps, and instance defaults resolve through one shared implementation. ✅ Partial-output preservation — Docker termination carries a distinct cost-cap outcome into the existing partial-publication paths, including a final usage evaluation after process exit. This is a static review of the supplied code; no commands were run. No current-head check runs were reported. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F5: 🔴 Reconcile recorded spend by execution
SuggestionsThese are optional follow-ups and are not sent to S3: 🟢 Expose live budget estimates
S4: 🟢 Add provider-shaped usage fixturesThe new tally tests exercise Claude and Codex records, while enforcement is connected to all five adapters. Fixtures from Antigravity, OpenCode, and Vibe would establish which usage records contribute during execution and catch parser drift. This is additional coverage, not a verified provider-specific defect. ScoreThe configuration and termination integration are substantial, but the accounting defect undermines the central enforcement guarantee. Validation is limited to static inspection, with no reported current-head checks. Score: 6/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
✅ Applied the requested follow-up changes in commit 3cccddd
Summary of ChangesI fixed F5. One recorded row can no longer retire more than one finished execution, so a cost whose database insert failed still counts toward the cap. The two new regressions fail on the old guard and pass with the fix. How it works now
Tests (in
Checks
Decision for you: when a per-session breakdown is available, an execution that reported a session ID is matched only to that session. If a provider ever stored a row under a different ID than it streamed, that execution would be counted twice and the run stopped early. I chose that over undercounting. Under the fallback, recorded growth that isn't really the execution's own row (such as an analysis call) can still cover it; this was already true before the change. There's no visual preview because the change has no visible effect. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
… one finished execution, so a cost whose database insert failed still counts toward the cap. The two new regressions fail on the old guard and pass with the fix. I fixed F5. One recorded row can no longer retire more than one finished execution, so a cost whose database insert failed still counts toward the cap. The two new regressions fail on the old guard and pass with the fix. **How it works now** - **Tracking the session:** while an execution streams, `RunUsageTally` notes its session ID (`session_id`, Codex `thread_id`, or the `init` `conversation_id`). It uses the same detection the executor uses when it records the session ID with the execution's row. - **Per-session totals:** `readRecordedTaskSpend` now returns the total plus a breakdown by session (`GROUP BY session_id`). `RunCostGuard` accepts either that or a plain number. - **Matching rows to executions:** in `packages/core/src/budget/runCostGuard.ts`, a finished execution with a session ID is only matched against recorded growth for that session since it ended. Spend recorded for other sessions never covers it. - **Fallback when there's no session ID or breakdown:** the remaining growth is shared out once, in the order executions finished. Each recorded dollar covers at most one execution, and any observed cost left uncovered still counts. **Tests** (in `packages/core/test/runCostCap.test.ts`) - **The F5 sequence:** a $2.50 cap with a plain-number recorded-spend stub. Executions A and B each spend $1, A's insert fails and B's succeeds, then a third execution spends $0.75. The guard now stops the run at $2.75; before the fix it saw $1.75 and let it continue. - **Session matching:** B's recorded row and an unrelated $0.20 analysis row don't cover A's failed insert. - **Session detection:** the tally picks up Claude, Codex and `init`-style session IDs. **Checks** - The cap tests, the cap-enforcement tests and the Docker live-output tests pass (26/26). - `npm run typecheck` passes, and eslint is clean on `packages/core/src/budget`. - I ran the new grouped query against an in-memory SQLite database and it returned the expected per-session sums. - The container had no `node_modules`, so I ran `npm ci` and `npm run test:prepare` first, following `.propr/setup.sh`. No setup files changed. **Decision for you:** when a per-session breakdown is available, an execution that reported a session ID is matched only to that session. If a provider ever stored a row under a different ID than it streamed, that execution would be counted twice and the run stopped early. I chose that over undercounting. Under the fallback, recorded growth that isn't really the execution's own row (such as an analysis call) can still cover it; this was already true before the change. There's no visual preview because the change has no visible effect. PR: #2758 Comment by: @propr-ultrafix (ID: 0) Model: claude-opus-5-5
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR adds spend-cap configuration, execution monitoring, interruption handling, and user-visible reporting. It needs minor changes before merge because historical retry budgets can report incorrect spending. ✅ Configuration precedence — Task overrides, repository caps, and instance defaults resolve consistently, with explicit handling of zero and malformed values. ✅ Final usage evaluation — Docker completion awaits the guard’s final evaluation, covering usage received after the last periodic check. This review used static analysis of the supplied code; no commands were run. No current-head check runs were reported. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F6: 🔴 Preserve retry spending after cache expiry
SuggestionsThese are optional follow-ups and are not sent to S5: 🟢 Test provider-native usage recordsThe new tally tests exercise Claude and Codex records, while enforcement is attached to all five agent adapters. Fixtures from OpenCode, Vibe, and Antigravity would help establish that their actual streaming formats produce increasing spend before termination. This is optional coverage; the supplied context does not establish a specific incompatible provider record. S6: 🟢 Verify the post-cap execution exemption
ScoreThe enforcement and termination integration are substantial, with focused boundary tests. The demonstrated historical budget error requires a localized correction before merge. Score: 6/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
✅ Applied the requested follow-up changes in commit ce0db59
Summary of ChangesI fixed F6. When a retry hits its spend cap, task history now keeps adding up the earlier attempts' spending even after the 90-day Redis record has expired. In the finding's example it now reports $5.20 and 104% instead of $1.20 and 24%. What changed
Tests
The new expired-Redis test and the new event test both fail on the old code and pass with the fix. These three test files pass: Limits
Environment: the workspace had no There's nothing visual to preview: the task details screen simply shows the corrected figures. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
…ow keeps adding up the earlier attempts' spending even after the 90-day Redis record has expired. In the finding's example it now reports $5.20 and 104% instead of $1.20 and 24%. I fixed F6. When a retry hits its spend cap, task history now keeps adding up the earlier attempts' spending even after the 90-day Redis record has expired. In the finding's example it now reports $5.20 and 104% instead of $1.20 and 24%. **What changed** - **The event now records the earlier attempts** (`src/jobs/runCostCap.ts`): the `budget.exceeded` event written to task history now includes the earlier attempts' task IDs (`budgetTaskIds`). It's left out when there are none, so existing events look the same. `withRunCostCap` passes the cleaned-up list (duplicates, blanks and the run's own ID removed) to the code that records the stop. - **Task history uses them as a fallback** (`packages/api/routes/taskBudget.ts`): `loadTaskBudget` now combines the task IDs from Redis and from the event before summing the recorded costs, without counting any task twice. Before, it only took them from Redis, so after expiry it counted just the retry. **Tests** - `packages/api/test/taskBudget.test.ts` (new): one test covers the finding's case: Redis returns nothing and the event carries the earlier ID, giving $5.20 / 104% / `exceeded: true`. A second test checks that IDs in both Redis and the event aren't double-counted. - `test/runCostCapEnforcement.test.ts`: a new test checks that the recorded event keeps only the cleaned-up list of earlier task IDs. The new expired-Redis test and the new event test both fail on the old code and pass with the fix. These three test files pass: `taskBudget`, `runCostCapEnforcement` and `taskHistoryRoutes`. Typecheck and lint pass for the root project and `packages/api`. I didn't run the full suite. **Limits** - **Only stopped runs are covered.** The `budget.exceeded` event is the only lasting record. If a run never hit its cap and its Redis record expires, both the cap and the earlier attempts are still lost. Covering that would mean writing a history entry for every run, which is outside F6. - **Old events stay as they were.** Events recorded before this change have no task IDs, so they still show only the retry's own spending. **Environment:** the workspace had no `node_modules`, and the provided npm cache (`PROPR_CACHE_DIR`) is read-only. I ran the install and build steps from `.propr/setup.sh` (`npm ci && npm run test:prepare`) with a temporary cache in `/tmp`. I didn't change any setup files. The ProPR image's cache location should be made writable. There's nothing visual to preview: the task details screen simply shows the corrected figures. PR: #2758 Comment by: @propr-ultrafix (ID: 0) Model: claude-opus-5-5
|
✅ AI Code Review Complete requested by @propr-ultrafix Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR adds cap configuration, streamed cost enforcement, interruption handling, and budget reporting across the API, CLI, and UI. It needs changes before merge because task details can contradict the recorded spend-cap event. ✅ Explicit precedence — Cap resolution consistently selects the task override, workflow cap, then instance default, with boundary tests. ✅ Final usage evaluation — Docker execution awaits the final budget check, including an unterminated last output record, before reporting its outcome. This review used static analysis of the supplied code; no commands or tests were run. No current-head check runs were reported. Merge blockersEvery finding below was introduced by this PR and must be resolved before merging. F7: 🔴 Preserve observed spend in task details
SuggestionsThese are optional follow-ups and are not sent to S7: 🟢 Verify continuation after enforcement
S8: 🟢 Preserve historical cap configurationResolved caps expire from Redis after 90 days, while only exceeded runs retain a durable budget event. Consider recording the resolved cap for successful runs too, so historical task details continue distinguishing an uncapped run from one that completed below its cap. This is an optional retention improvement. ScoreThe implementation has substantial targeted coverage and coherent configuration handling, but its new spend reporting loses consumption that enforcement deliberately preserves. Correct that inconsistency before merge. Score: 6/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
✅ Applied the requested follow-up changes in commit b65af81
Summary of ChangesI fixed F7: task details now report the spend that stopped a capped run, even when that run's cost rows were never saved to the database. What changed (
Other places checked: the CLI and the UI only display the New tests (
Verification
There's no visual preview because only the numbers the API returns change, not the layout. 🤖 Implementation Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
…a capped run, even when that run's cost rows were never saved to the database. I fixed F7: task details now report the spend that stopped a capped run, even when that run's cost rows were never saved to the database. **What changed** (`packages/api/routes/taskBudget.ts`) - `loadTaskBudget` now reads `spentUsd` from the `budget.exceeded` event. It only accepts a finite positive number; anything else counts as 0. - Displayed spend is now the **larger** of the event's spend and the saved total (`SUM(llm_executions.cost_usd)`). The two are never added, because both already cover the same task and its earlier attempts. Adding them would count the same spend twice once the rows are saved. - The percentage is calculated from that larger figure. In the finding's example ($5 cap, $5.20 spent, nothing saved), the API now returns `spentUsd: 5.2, percent: 104, exceeded: true` instead of `0 / 0%`. **Other places checked:** the CLI and the UI only display the `spentUsd` and `percent` the API returns, so fixing the API fixes them too. The guard itself and the event writer (`src/jobs/runCostCap.ts`) were already right: the event stores the spend the guard saw, including costs that were never saved. **New tests** (`packages/api/test/taskBudget.test.ts`) - A capped run with no saved costs reports $5.20 and 104%. - When some costs are saved, the larger figure is used. Once the saved total passes the event's figure ($5.50), the saved total wins. - An invalid `spentUsd` in the event (a string, a negative number, NaN or null) is ignored. - I changed the test helper to skip the insert when there are no rows, because SQLite fails on an empty insert. **Verification** - All 5 tests in the file pass with the fix. On the old code, the first two new tests fail and the other three pass. - `tsc --noEmit` for `packages/api` reports no errors. The root lint script doesn't cover `packages/api`, so ESLint ignored both files. - The repo's normal test runner (`scripts/run-test-suite.mjs`) timed out after 180s on this file. Redis isn't installed here, so the test's `after` cleanup (which calls `closeConnection`) never finishes. I ran the file through a temporary copy without that cleanup step, with `PROPR_DEMO_MODE=true`, and deleted the copy afterwards. To run it the normal way, Redis needs to be added to the agent image as a system package. - `node_modules` was missing, so I ran `npm ci && npm run test:prepare` first. No setup files changed. There's no visual preview because only the numbers the API returns change, not the layout. PR: #2758 Comment by: @propr-ultrafix (ID: 0) Model: claude-opus-5-5
|
|
|
/ultrafix goal=8 max=3 |
|
/fix F12 |
|
✅ Applied the requested follow-up changes in commit 22bfb60
Summary of ChangesI fixed F12. If a capped run can't read its recorded spend, it now fails before any agent container starts. Before, the failed read counted as $0, so a retry that had already used up its budget could launch again. What changed (
Same problem elsewhere: a run that starts uncapped and gets its cap later from the workflow file never had an authoritative read at start. Its first chargeable launch now goes through the strict read in Tests:
To run the tests I had to run The Gmail, Google Calendar and Google Drive connectors need to be authorized in your claude.ai connector settings before they can be used. This task didn't need them. 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
… it now fails before any agent container starts. Before, the failed read counted as $0, so a retry that had already used up its budget could launch again. I fixed F12. If a capped run can't read its recorded spend, it now fails before any agent container starts. Before, the failed read counted as $0, so a retry that had already used up its budget could launch again. **What changed** (`packages/core/src/budget/runCostGuard.ts`): - **Two kinds of read.** The guard now has a strict read that passes the error on, and a best-effort read that falls back to the last known spend. The strict one is used only where the decision is whether to start. - **`start()`:** when the run has a cap, it uses the strict read. The error reaches `withRunCostCap`, so the attempt fails through the normal failure and retry path that F11 set up, before any agent starts. A run with no cap still reads best-effort, because its earlier spend doesn't change anything yet. - **`admit()`:** it now evaluates the spend from its own strict read. Before, it called `check()`, which could fall back to a stale or zero figure. If the read fails, admission is refused. `admitCostExecution` in `dockerExecutor.ts` already passes non-cap errors on, so `executeDockerCommand` fails and the container never starts. No Docker change was needed. - **Periodic checks** and the reads taken as an execution finishes are still best-effort. A brief database error while agents run shouldn't stop them, and admission doesn't rely on those reads. **Same problem elsewhere:** a run that starts uncapped and gets its cap later from the workflow file never had an authoritative read at start. Its first chargeable launch now goes through the strict read in `admit()`, so it's covered. The issue and PR entry points both pass errors from `withRunCostCap` on to their existing failure handling, so a failed read at `start()` can't fall through to an uncapped run. **Tests:** - `packages/core/test/runCostCap.test.ts`, two new tests: - A capped run whose read fails rejects at `start()` and at `admit()`, and no stop is recorded. - A run capped after start rejects at admission when the read fails. Once reads work again, an exhausted budget is refused as before. - `test/dockerExecutorLiveOutput.test.ts`: a capped run with failing spend reads launches no container through `executeDockerCommand`. - All three new tests fail against the old guard. With the fix, 44 of 44 pass across those two files and `test/runCostCapEnforcement.test.ts`. - `npm run typecheck` and `npm run lint` pass. I didn't run the full suite. To run the tests I had to run `.propr/setup.sh` first, because dependencies weren't installed. No setup files changed. There's no visual change, so I made no previews. The Gmail, Google Calendar and Google Drive connectors need to be authorized in your claude.ai connector settings before they can be used. This task didn't need them. PR: #2758 Comment by: @integry (ID: 6009566917) Model: claude-opus-5-5
|
/review |
|
✅ AI Code Review Complete requested by @integry Posted 1 review: |
🔍 AI Code Review — codex:gpt-6-astraOverall EvaluationThe PR implements spend-cap configuration, enforcement, partial-result handling, and reporting across the intended task paths. The supplied code appears merge-ready within scope; this assessment is static, and no current-head checks were reported. ✅ Admission before execution — Exhausted budgets refuse new agent containers, and unreadable recorded spend rejects capped admission. ✅ Final usage reconciliation — Execution completion awaits a final budget check, covering usage received after the last periodic check. ✅ Partial-work handling — The new termination reason flows through existing publication and task-completion paths, with targeted tests for accounting and terminal-state behavior. Merge blockersNo merge blockers. SuggestionsThese are optional follow-ups and are not sent to S17: 🟢 Cover every provider’s usage streamThe new tally tests exercise Claude and Codex usage records, while enforcement is wired into five agent adapters. Add representative output fixtures for Antigravity, OpenCode, and Vibe, checking cumulative spend and final usage against their existing metrics parsers. This would strengthen confidence in provider coverage; the supplied context does not establish a concrete incompatible stream format. S18: 🟢 Preserve historical cap metadata
ScoreThe implementation has substantial targeted coverage and no verified merge blocker in the supplied code. Tests were not executed, as requested, and current-head validation remains unconfirmed. Score: 8/10 🤖 Review Details
Copy and edit to choose records from this review: 🤖 Review by ProPR |
|
Local verification on head
Run: |
|
✅ Applied the requested follow-up changes in commit af3b41c Summary of ChangesAll three test files now pass with the command you gave: 1.
Both stubs now export the missing function and return the workflow they receive. 2. My sandbox has no Docker, so I reproduced this by temporarily adding a stand-in "installed Docker" ahead of those paths. Tests 4 and 5 failed exactly as you reported. Test 6 ( There's no visual change, so I made no previews. 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
…ode scripts/run-test-suite.mjs test/prPublicationJob.test.ts test/prPublicationRecoveryJob.test.ts test/dockerExecutorLiveOutput.test.ts` reported "3/3 passed". `npm run typecheck` and `npm run lint` also pass. I only changed the three test files; no application code changed. All three test files now pass with the command you gave: `node scripts/run-test-suite.mjs test/prPublicationJob.test.ts test/prPublicationRecoveryJob.test.ts test/dockerExecutorLiveOutput.test.ts` reported "3/3 passed". `npm run typecheck` and `npm run lint` also pass. I only changed the three test files; no application code changed. **1. `prPublicationJob` and `prPublicationRecoveryJob`:** the stubs of `./runCostCap.js` in both tests had two problems. - They were missing `pullRequestRunCostCapTarget`, which caused the load error you saw. - Once the files loaded, three tests in `prPublicationJob` still failed. The stub `applyWorkflowCostCap` returned `undefined`, but the real one returns the workflow it's given. The job takes its workflow from that return value, so it lost it. Both stubs now export the missing function and return the workflow they receive. **2. `dockerExecutorLiveOutput`:** the spend-cap code didn't regress, and the "last record is read before the final budget check" guarantee still holds. The tests were running the wrong `docker`. Each test puts a fake `docker` on `PATH`, but the executor first looks for Docker at fixed paths (`/usr/bin/docker`, `/usr/local/bin/docker`, `/bin/docker`). On a machine with Docker installed, the real one runs instead. It fails on the made-up image and prints no usage, which gives exactly what you saw: "finish after 0 line(s)" and `costCapExceeded` undefined. My sandbox has no Docker, so I reproduced this by temporarily adding a stand-in "installed Docker" ahead of those paths. Tests 4 and 5 failed exactly as you reported. Test 6 (`a run stopped at its spend cap refuses later … containers`) failed for the same reason, so expect it to fail on your machine too. The test file now hides those fixed paths so the fake `docker` on `PATH` always runs. With the stand-in still in place, all 8 tests pass. There's no visual change, so I made no previews. PR: #2758 Comment by: @integry (ID: 6009876668) Model: claude-opus-5-5
|
/merge |
|
🔀 Resolved merge conflicts from Conflicting Files
Resolution SummaryAll 16 conflicted files are resolved and no conflict markers are left in the repository. The 13 conflicted What the conflicts were. Almost every conflict came from the same thing. This PR adds an instance setting,
Why this approach. Both features are needed, so dropping either side would break the settings list, the API responses and the tests. Neither side changed the other's logic. The only real overlap was Since only a syntax check ran, run 🤖 Resolution Details
System-triggered merge conflict resolution |
…per-run-spend-cap-20261005-2330-yv3 Automatically resolved merge conflicts after merging target branch into PR branch. Resolved conflicts in: - CHANGELOG.md - docs/docs/operations/settings-locations.md - packages/api/mcp/settingsCatalog.ts - packages/api/mcp/toolsManagement.ts - packages/api/routes/configHelpers.ts - packages/api/routes/configRoutes.ts - packages/api/routes/configRoutesSettings.ts - packages/api/routes/configSettings.ts - packages/cli/src/api/index.ts - packages/cli/src/api/settings.ts - packages/cli/src/commands/settingCommands.ts - packages/core/src/config/configManager.ts - packages/core/src/config/configManagerUltrafix.ts - propr-ui/src/components/TaskDetails/TaskStatusTable.tsx - propr-ui/src/components/TaskDetails/types.ts - test/configRoutes.followup.test.ts PR: #2758 Model: claude-opus-5-5
|
CI failed: Validate Changes Please investigate and fix this CI failure.
Failure evidence
|
Checks FailedValidation failed during setup, tests, CLI packaging, linting, or build checks. View Logs |
|
✅ Applied the requested follow-up changes in commit 638efa5 Summary of ChangesI fixed the Validate Changes failure. The step that failed was "Run Checks", on two lint warnings; the Playwright tests themselves passed. Both lints and 1. Core lint:
2. API lint: For the tests I ran the Docker executor, spend-cap and container tests plus every test file that references The change has nothing visible, so there are no previews. 🤖 Implementation Details
Undo Changes • View Task Execution 💡 ProPR Slash Commands
🤖 Generated by ProPR |
…led was "Run Checks", on two lint warnings; the Playwright tests themselves passed. Both lints and `npm run typecheck` now pass locally, and so do the 26 related test files. CI hasn't re-run on the change yet. I fixed the **Validate Changes** failure. The step that failed was "Run Checks", on two lint warnings; the Playwright tests themselves passed. Both lints and `npm run typecheck` now pass locally, and so do the 26 related test files. CI hasn't re-run on the change yet. **1. Core lint: `dockerExecutor.ts` was too long (488 counted lines, the limit is 400).** I moved three self-contained groups of code out of it into new files next to it, without changing any logic: - `dockerCostCap.ts`: the spend-cap helpers this PR added. - `dockerLiveOutputStreaming.ts`: the live-log streaming code and the ANSI-stripping helper only it uses. - `dockerContainerDetection.ts`: `detectContainerId`. `dockerExecutor.ts` now imports them. **2. API lint: `extractSettingSaves` in `packages/api/routes/configSettings.ts` was too complex (22, the limit is 20).** The `default_max_cost_usd` check this PR added pushed it over. I moved that check and the `ultrafix_ci_wait_timeout_ms` check into a new helper, `extractRunLimitSettingSaves`. Validation and error messages are unchanged. For the tests I ran the Docker executor, spend-cap and container tests plus every test file that references `configSettings`, `dockerExecutor` or `default_max_cost_usd`. Three of them failed on the first run, but that was my local setup: I had installed dependencies without building native modules. They pass after rebuilding them. The change has nothing visible, so there are no previews. PR: #2758 Comment by: @propr-dev[bot] (ID: 6013433431) Model: claude-opus-5-5
|
ℹ️ Analyzed the follow-up request by @github-actions[bot] Analysis SummaryI didn't change any code: both lint failures in this report are already fixed on the current head (
I checked this after a clean No code changes were necessary based on the current state of the branch. 🤖 Analysis Details
💡 ProPR Slash Commands
🤖 Generated by ProPR |
|
/merge |
|
🔀 Resolved merge conflicts from Conflicting Files
Resolution SummaryI resolved all 29 conflicted files and no conflict markers are left. Almost every conflict had the same cause: Checks: typecheck passes in root, core, api, cli and propr-ui. Lint passes everywhere with How each group was resolved
Changes needed to keep CI's lint passing Both parents passed lint on their own, but combining them pushed two files over limits, and CI fails on any warning:
To run these checks I installed dependencies and built the workspace packages. That only produced gitignored files. The one new tracked file is 🤖 Resolution Details
System-triggered merge conflict resolution |
…per-run-spend-cap-20261005-2330-yv3 Automatically resolved merge conflicts after merging target branch into PR branch. Resolved conflicts in: - CHANGELOG.md - docs/docs/features/propr-cli.md - packages/api/mcp/toolsManagement.ts - packages/api/routes/configHelpers.ts - packages/api/routes/configRoutesSettings.ts - packages/api/routes/configSettings.ts - packages/core/src/agents/impl/AntigravityAgent.ts - packages/core/src/agents/impl/CodexAgent.ts - packages/core/src/agents/impl/OpenCodeAgent.ts - packages/core/src/agents/impl/VibeAgent.ts - packages/core/src/agents/impl/utils/dockerResultProcessor.ts - packages/core/src/agents/termination.ts - packages/core/src/agents/types.ts - packages/core/src/claude/claudeService.ts - packages/core/src/claude/docker/dockerExecutor.ts - packages/core/src/claude/docker/dockerLiveOutputStreaming.ts - packages/core/src/index.ts - packages/core/src/queue/taskQueue.types.ts - packages/core/src/utils/github/logFiles.ts - packages/core/src/utils/workerStateManager.ts - packages/core/src/utils/workerStateManager.types.ts - packages/core/src/utils/workerStateTransition.ts - packages/shared/src/taskLifecycle.ts - propr-ui/src/api/proprTypes.ts - propr-ui/src/pages/SettingsPage/parseLoadedData.ts - propr-ui/src/pages/SettingsPage/types.ts - propr-ui/src/pages/SettingsPage/useSettingsState.ts - src/jobs/issueJob/completion.ts - src/jobs/prCommentPostExecution.ts PR: #2758 Model: claude-opus-5-5
|
/merge |
|
🔀 Resolved merge conflicts from Conflicting Files
Resolution SummaryI resolved the one merge conflict, in What the conflict was: both sides changed the same import line from
How I resolved it: I kept both sides. The import now includes everything either branch added ( Why: the two sides didn't conflict in what they do. Each one only added names used by its own code, and every one of those names is still used in the merged file. Dropping either side would leave undefined references, so combining them keeps the spend-cap work and Checks:
🤖 Resolution Details
System-triggered merge conflict resolution |
…per-run-spend-cap-20261005-2330-yv3 Automatically resolved merge conflicts after merging target branch into PR branch. Resolved conflicts in: - src/jobs/prCommentReviewJob.ts PR: #2758 Model: claude-opus-5-5
|
/merge |
|
🔀 Resolved merge conflicts from Conflicting Files
Resolution SummaryI resolved the merge conflict. What the conflict was: Both branches added a new entry at the top of the
How I resolved it: I kept both entries unchanged, with the spend-cap entry first and the pull request templates entry right after it, and removed the conflict markers. Everything below them, starting with the "Agent stall and degenerate-output watchdog" entry, is untouched. Why: The two entries describe separate features, so this is a simple text conflict, not competing logic. Both belong in the changelog, and dropping either would lose a record of shipped work. Putting the PR's entry first follows the rule of preferring the PR's intent. I left the wording of both exactly as written. Check: The 🤖 Resolution Details
System-triggered merge conflict resolution |
…per-run-spend-cap-20261005-2330-yv3 Automatically resolved merge conflicts after merging target branch into PR branch. Resolved conflicts in: - CHANGELOG.md PR: #2758 Model: claude-opus-5-5
AI Implementation Summary
Closes #2734
Branch:
2734/claude-opus-5-5-enforce-per-run-spend-cap-20261005-2330-yv3Commits: ✅ Changes committed (8abe42d)
AI Processing Completed
Execution Details:
Summary:
I've implemented per-run spend caps for #2734. A run is now stopped once its estimated cost reaches the cap, and its partial work is published the way a timed-out run's is.
npm run lintandnpm run typecheckpass, and so do about 110 affected test files (UI vitest suites included). The full suite was not run, and I couldn't exercise a real Docker agent run in this sandbox, so the stop has only been tested through the guard and in unit tests.Where the cap comes from (highest wins)
maxCostUsdon a REST task submission or MCPcreate_task, or--max-cost <usd>onpropr issue implement.limits.max_cost_usdin.propr/workflow.yml. A bad value here doesn't reject the whole workflow file: it's logged and ignored. The editor schema still flags it.default_max_cost_usdsetting, available in Settings → Automation,propr setting updateand MCPupdate_execution_settings.Empty or 0 means "not set at this level", so the next level applies. A malformed or negative value is logged and treated the same way, so a typo can never cap runs at $0. I removed the unused
AgentTankConfigtype rather than reuse it.How it's enforced
llm_executionscosts plus the token usage the running agent containers have streamed so far. It's re-checked every ~10 seconds, so a run can go slightly over before it's stopped.cost_cap_exceeded. It also gets abudget.exceededtimeline event (shown as "Spend Cap Reached"), an Inbox notification, and a short comment on the issue or PR./fix, ultrafix cycles and reviews. Goals are unchanged.propr task get(budgetin--json).LLM_COST_THRESHOLD_USDstill only raises alerts; the docs now say so.Behaviours to be aware of
--max-costis saved against the issue in Redis for 30 days, so re-runs of that issue in that window also use it.Test changes you should know about
@propr/corewith a fixed list of exports, which broke on the new imports. I moved the pure constants and formatters into@propr/sharedto avoid most of that.prPublicationJobandprPublicationRecoveryJobnow stub the new cost-cap module.planIssueHandlers.followupgets one extra stub.configRoutes.followupexpects the new setting in its deep-equal checks.Docs are updated in
repository-workflow.md,metrics.md,execution-safety.md(new "Spend Caps" section), the CLI docs and the CHANGELOG.settings-locations.mdwas regenerated rather than edited, because it's generated from the settings catalog. I also saved two screenshots as previews: the capped task's detail page and the new settings field.Detailed Logs:
bdf53b76-4295-4111-b6ab-e41fdefa08daLog files stored at:
/tmp/claude-logs/issue-2734-2026-10-06T00-19-01-791Z-conversation.json/tmp/claude-logs/issue-2734-2026-10-06T00-19-01-791Z-output.txtLatest Conversation Messages
This PR was created automatically by ProPR after processing issue #2734.
💡 Need changes?
Comment on this PR to request refinements — the AI agent monitors comments and will update the implementation based on your feedback. Keep iterating until you're satisfied!
Visual preview
Settings: default spend cap per run
The new default_max_cost_usd field under Settings → Automation → Processing (1280px).
Original unavailable: managed storage is unavailable or the upload has expired.
Task details: spend beside the run cap
A run stopped at its $5.00 cap from .propr/workflow.yml: the header shows spend/cap/percentage, the timeline shows a Spend Cap Reached event and the cost_cap_exceeded terminal reason (fixture data, 1280px).
Original unavailable: managed storage is unavailable or the upload has expired.