diff --git a/loopx/control_plane/host_adapter_settlement.py b/loopx/control_plane/host_adapter_settlement.py index 99d3a09ef7..b6f284f3c5 100644 --- a/loopx/control_plane/host_adapter_settlement.py +++ b/loopx/control_plane/host_adapter_settlement.py @@ -358,7 +358,16 @@ def _run_provider_plan( ) -> list[dict[str, str]]: outcomes: list[dict[str, str]] = [] for step in steps: - output = run_cli(list(step.args)) + args = list(step.args) + if step.step_kind == "quota_spend": + # The preceding, identity-checked writeback exposes the original + # billing source. The CLI owner still verifies the requested debit. + writeback = json.loads(outcomes[-1]["output"]) + source = _path_value(writeback, ["settlement_progress", "quota_spend_source"]) + if not isinstance(source, str) or "--source" in args: + raise RuntimeError("TypeScript host provider spend source shape mismatch") + args.extend(("--source", source)) + output = run_cli(args) outcomes.append({"step_kind": step.step_kind, "output": output}) if step.continue_when is not None and not _provider_condition_matches( output, step.continue_when diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index 10bd891ae3..b85cfa7df4 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -694,6 +694,13 @@ function spendResult( )]); } +function committedSpendReceiptSource(event: JsonObject | null): string | null { + if (event === null || !optionalString(event.event_id)) return null; + const {slots, source} = details(event); + return slots === 1 && (source === "heartbeat" || source === "visible-goal") + ? source : null; +} + function terminalResult( identity: SettlementIdentity, event: JsonObject | null, @@ -1397,8 +1404,13 @@ function readQuotaSettlementFromRequest( ? {...refreshDecision, decision: "reject", reason: "committed_writeback_payload_conflict"} : refreshDecision; + // Fully committed historical debits retain their original accounting. + // An incomplete settlement still uses the source authorized by admission. + const replaySource = settled.failure === null && spend.failure === null && noSpendKind === null + ? committedSpendReceiptSource(spendEvent) : null; const progress = settlementProgress(identityResult, writeback, spend, writebackRun, spendRun, receiptDetails.quota_spend_source ?? spendRun?.source, noSpendKind); + if (replaySource !== null) progress.quota_spend_source = replaySource; // The combined caller consumes controls and receipts after verification. // Keep original bodies by default and throughout any pending recovery, // including the same Runs carried by the four result bundles. Identity, @@ -1561,9 +1573,11 @@ async function originalSpendRejection( const recordedSource = retained?.source ?? (receipt.source === "" ? undefined : receipt.source); const fallbackSource = recordedSource === "heartbeat" || recordedSource === "visible-goal" ? recordedSource : progress.quota_spend_source; - const source = authorizedSource ?? fallbackSource; - // Every admitted CLI settlement plan authorizes one slot and the original - // source. The same check gates initial spend, receipt repair, and replay. + const replaySource = progress.state === "settled" && progress.closeout_kind == null && spendRun !== null + ? committedSpendReceiptSource(spendEvent) : null; + const source = replaySource ?? authorizedSource ?? fallbackSource; + // First debit and receipt repair must match admission. A fully receipted + // replay must match the existing debit and cannot append another charge. if (proposed.slots !== 1 || proposed.source !== source) { return settlementFailed({ kind: "quota_spend_rejected", step_kind: "quota_spend", diff --git a/loopx/control_plane/turn_driver/host_todo_completion.ts b/loopx/control_plane/turn_driver/host_todo_completion.ts index fe2e8d24e8..b444d526f8 100644 --- a/loopx/control_plane/turn_driver/host_todo_completion.ts +++ b/loopx/control_plane/turn_driver/host_todo_completion.ts @@ -277,6 +277,11 @@ function writebackContinueWhen(identity: JsonObject): JsonObject { ...exactIdentityConditions(["settlement_identity"], identity), objectAt(["settlement_result"]), nullish(["settlement_result", "failure"]), + equals(["settlement_progress", "schema_version"], "quota_settlement_progress_v0"), + any( + equals(["settlement_progress", "quota_spend_source"], "heartbeat"), + equals(["settlement_progress", "quota_spend_source"], "visible-goal"), + ), ); } @@ -365,8 +370,6 @@ function providerSteps( request.goal_id, "--slots", "1", - "--source", - "heartbeat", "--execute", "--agent-id", request.agent_id, diff --git a/tests/control_plane_ts/quota_settlement_readback.test.ts b/tests/control_plane_ts/quota_settlement_readback.test.ts index 47e74e0911..9f4e1fbec7 100644 --- a/tests/control_plane_ts/quota_settlement_readback.test.ts +++ b/tests/control_plane_ts/quota_settlement_readback.test.ts @@ -985,6 +985,43 @@ test("settlement progress preserves typed source and rejects malformed sources", } finally { await rm(root, {recursive: true, force: true}); } }); +test("a complete legacy spend replays its charged source, but partial or conflicting records do not", async (t) => { + for (const state of ["committed", "missing_receipt", "conflicting_artifact"] as const) { + await t.test(state, async () => { + const root = await fixture({writeback: true, spend: true}); + try { + const log = join(root, "goals", goalId, "rollout-event-log.jsonl"); + const index = join(root, "goals", goalId, "runs", "index.jsonl"); + const lines = (await readFile(log, "utf8")).trim().split("\n").map(line => JSON.parse(line)); + const runs = (await readFile(index, "utf8")).trim().split("\n").map(line => JSON.parse(line)); + lines.find(event => event.event_kind === "quota_should_run").details.quota_spend_source = "visible-goal"; + const receipt = lines.find(event => event.event_kind === "quota_spend"); + Object.assign(receipt.details, {slots: 1, source: "heartbeat"}); + runs.find(run => run.classification === "quota_slot_spent").quota_event = { + slots: 1, source: state === "conflicting_artifact" ? "visible-goal" : "heartbeat", + }; + const events = state === "missing_receipt" ? lines.filter(event => event !== receipt) : lines; + await writeFile(log, events.map(event => JSON.stringify(event)).join("\n") + "\n"); + await writeFile(index, runs.map(run => JSON.stringify(run)).join("\n") + "\n"); + const precheck = (source: string, slots = 1) => readQuotaSettlement(request(root, { + spend_precheck: true, spend_request: {source, slots}, + })); + + const replay = await precheck("heartbeat"); + assert.equal(Boolean(replay.spend_request_rejection), state !== "committed"); + assert.ok((await precheck("visible-goal")).spend_request_rejection); + assert.ok((await precheck("heartbeat", 2)).spend_request_rejection); + if (state !== "conflicting_artifact") { + assert.equal(requireJsonObject(replay.progress, "progress").quota_spend_source, + state === "committed" ? "heartbeat" : "visible-goal"); + } + } finally { + await rm(root, {recursive: true, force: true}); + } + }); + } +}); + test("accepted in-flight writeback closes only the exact Turn, not its Todo", async t => { const checkpoint = { schema_version: "vision_checkpoint_v0", agent_id: agentId, satisfied: true, diff --git a/tests/test_goal_mode_mcp_settlement.py b/tests/test_goal_mode_mcp_settlement.py index 9cf265aeef..eeb53887a7 100644 --- a/tests/test_goal_mode_mcp_settlement.py +++ b/tests/test_goal_mode_mcp_settlement.py @@ -456,6 +456,8 @@ def test_real_mcp_settlement_rejects_missing_writeback_then_commits_same_identit ) assert guard_rc == 0, guard assert guard["selected_todo"]["todo_id"] == todo_id # type: ignore[index] + # Exercise missing writeback with the source that the visible Host actually + # admitted. A different source should be rejected at its own boundary. premature_rc, premature = _run_cli( registry, @@ -472,7 +474,7 @@ def test_real_mcp_settlement_rejects_missing_writeback_then_commits_same_identit "--slots", "1", "--source", - "heartbeat", + "visible-goal", "--execute", ) assert premature_rc == 1 @@ -499,6 +501,7 @@ def test_real_mcp_settlement_rejects_missing_writeback_then_commits_same_identit assert settlement["lifecycle_completion"]["ok"] is True assert settlement["quota_spend"]["ok"] is True assert settlement["quota_spend"]["appended"] is True + assert settlement["quota_spend"]["source"] == "visible-goal" status_rc, status = _run_cli( registry,