Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion loopx/control_plane/host_adapter_settlement.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 17 additions & 3 deletions loopx/control_plane/quota/settlement_readback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down
7 changes: 5 additions & 2 deletions loopx/control_plane/turn_driver/host_todo_completion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
),
);
}

Expand Down Expand Up @@ -365,8 +370,6 @@ function providerSteps(
request.goal_id,
"--slots",
"1",
"--source",
"heartbeat",
"--execute",
"--agent-id",
request.agent_id,
Expand Down
37 changes: 37 additions & 0 deletions tests/control_plane_ts/quota_settlement_readback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 4 additions & 1 deletion tests/test_goal_mode_mcp_settlement.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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,
Expand Down
Loading