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
6 changes: 6 additions & 0 deletions docs/quota-allocation.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,12 @@ same Agent after its latest accepted replan acknowledgement. An accepted negativ
work result can count; observation-only polls, duplicate retries, unspent
writebacks and missing settlement receipts cannot. At the threshold, the next
quota evaluation creates `periodic_review_due` through the existing replan path.
For an explicitly selected Agent, receipt qualification uses that Agent's scope
before interpreting semantic settlement fields, including during status collection
for refresh and spend. A peer's invalid semantic receipt
does not block this count; selecting the affected Agent or an unscoped history
still reports the invalid receipt. This does not rewrite receipts or relax Goal
instance ownership and shared log integrity checks.
An evidence-linked review may retain the current approach; it does not require
inventing a new plan, completing the open Todo, or declaring the Goal achieved.
Review evidence from settled work for current source and acceptance applicability
Expand Down
1 change: 1 addition & 0 deletions loopx/control_plane/status/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ def canonical_runtime_for_goal(current_goal_id: str) -> Path:
current_registry=registry,
registry_path=registry_path,
include_goal_channel_projection=include_presentation_projections,
agent_lane_id=agent_lane_id,
)
# No later projection consumes the shared status snapshot.
del todo_snapshot
Expand Down
2 changes: 2 additions & 0 deletions loopx/control_plane/work_items/attention_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ def build_attention_queue(
goal_id_filter: str | None = None,
include_stopped_goal_context: bool = False,
include_goal_channel_projection: bool = True,
agent_lane_id: str | None = None,
) -> dict[str, Any]:
"""Build the executable attention queue or a stopped-Goal archive view.

Expand Down Expand Up @@ -336,6 +337,7 @@ def build_attention_queue(
autonomous_replan_obligation_from_runs=context.autonomous_replan_obligation_from_runs,
external_progress_review=external_progress_review,
effective_turn_cadence=effective_turn_cadence_context(goal, runtime_root, registry_path=context.registry_path),
agent_lane_id=agent_lane_id,
)
item["quota"] = context.quota_status(
goal,
Expand Down
7 changes: 6 additions & 1 deletion loopx/control_plane/work_items/project_asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ def attach_active_state_project_asset_fields(
autonomous_replan_obligation_from_runs: Callable[..., dict[str, Any] | None] | None = None,
external_progress_review: dict[str, Any] | None = None,
effective_turn_cadence: dict[str, Any] | None = None,
agent_lane_id: str | None = None,
) -> dict[str, Any]:
project_asset = item.get("project_asset")
if not isinstance(project_asset, dict):
Expand Down Expand Up @@ -322,7 +323,10 @@ def attach_active_state_project_asset_fields(
shared_todos = item.get("agent_todos")
monitor_todos = {"monitor_open_items":
shared_todos.get("monitor_open_items", []) if isinstance(shared_todos, dict) else []}
agent_ids = sorted(
# Status retains shared Goal history for ownership and health checks.
# A lane caller only needs that Agent's semantic review obligations;
# peer receipts must not become a prerequisite for its settlement.
agent_ids = [agent_lane_id] if agent_lane_id is not None else sorted(
{
agent_id
for run in latest_runs or []
Expand Down Expand Up @@ -351,6 +355,7 @@ def attach_active_state_project_asset_fields(
replan_obligation = autonomous_replan_obligation_from_runs(
latest_runs or [],
agent_todos=item.get("agent_todos") if isinstance(item.get("agent_todos"), dict) else None,
agent_id=agent_lane_id,
)
if replan_obligation:
item["autonomous_replan_obligation"] = replan_obligation
Expand Down
11 changes: 7 additions & 4 deletions loopx/control_plane/work_items/replan_history_settlement.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** Replan history IO: qualify work through the existing settlement owner. */
import type { JsonObject } from "../effect_program.ts";
import { jsonObject, requireJsonObject } from "../runtime_decode.ts";
import { jsonObject, optionalNonEmptyString, requireJsonObject } from "../runtime_decode.ts";
import {
readQuotaSettlementSnapshot,
readQuotaSettlementForAdmittedOwnerFromSnapshot,
Expand All @@ -17,6 +17,7 @@ export async function projectSettledReplanHistory(value: unknown): Promise<JsonO
const source = request.settlement_source;
// Historical callers retain their units until explicitly migrated.
if (source == null) return projectReplanHistory(request);
const agentId = optionalNonEmptyString(request.agent_id, "agent_id");
const scope = requireJsonObject(source, "settlement source");
const {runtimeRoot, goalId} = validateQuotaSettlementScope(
scope.runtime_root,
Expand All @@ -40,12 +41,14 @@ export async function projectSettledReplanHistory(value: unknown): Promise<JsonO
const settlementRuns = runs.filter(raw => {
const row = jsonObject(raw);
return row !== null && typeof row.agent_id === "string" && row.agent_id !== "" &&
(agentId === null || row.agent_id === agentId) &&
typeof row.turn_id === "string" && row.turn_id !== "" &&
receiptKeys.has(JSON.stringify([row.agent_id, row.turn_id]));
});
// History rows without a matching should-run receipt cannot be qualified
// by settlement. Avoid parsing the strict quota run ledger unless at least
// one exact current-owner Turn can contribute to effective-cadence counts.
// Apply explicit Agent scope before interpreting settlement receipts, as
// the pure history owner does before counting work. Unscoped requests still
// validate all contributing Agents; a scoped read cannot repair peer data.
// Rows without a matching should-run receipt cannot contribute either.
if (settlementRuns.length === 0) {
return projectReplanHistory({...request, runs}, new Set());
}
Expand Down
4 changes: 2 additions & 2 deletions loopx/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,8 +228,6 @@
attach_dependency_blockers,
compact_todo_group as compact_todo_group,
compact_todo_item as compact_todo_item,
open_todo_items as open_todo_items,
todo_item_task_class as todo_item_task_class,
first_open_todo_text,
open_todo_items as open_todo_items,
project_asset_todo_summary,
Expand Down Expand Up @@ -1093,6 +1091,7 @@ def build_attention_queue(
current_registry: dict[str, Any] | None = None,
registry_path: Path | None = None,
include_goal_channel_projection: bool = True,
agent_lane_id: str | None = None,
) -> dict[str, Any]:
def request_active_state_todo_fields(
goal: dict[str, Any],
Expand Down Expand Up @@ -1161,6 +1160,7 @@ def request_active_state_todo_fields(
goal_id_filter=goal_id_filter,
include_stopped_goal_context=include_stopped_goal_context,
include_goal_channel_projection=include_goal_channel_projection,
agent_lane_id=agent_lane_id,
)
if runtime_root is not None:
for item in queue.get("items") or []:
Expand Down
58 changes: 58 additions & 0 deletions tests/control_plane/test_effective_turn_replan.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,64 @@
)


@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_refresh_and_spend_survive_an_unrelated_invalid_review_receipt(tmp_path, monkeypatch, provider):
isolate_sqlite_runtime(tmp_path, monkeypatch)
project, runtime, registry = _write_fixture(tmp_path, provider=provider)
rc, configured = _run_cli(registry, runtime, "configure-goal", "--goal-id", GOAL_ID,
"--execution-stride-strategy", "off", "--execution-replan-after-turns", "6", "--execute")
assert rc == 0, configured
turn = "peer-isolation-turn"
binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID,
"--todo-id", TODO_ID, "--turn-instance-id", turn]
rc, guard = _run_cli(registry, runtime, "quota", "should-run", "--codex-app", *binding)
assert rc == 0 and guard["should_run"], guard
log = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl"
original = log.read_text()
receipt = next(json.loads(line) for line in original.splitlines()
if json.loads(line)["event_id"] == guard["heartbeat_receipt"]["event_id"])
peer = "codex-peer-fixture"
peer_turn = "peer-invalid-review"
peer_effect = f"{GOAL_ID}:{peer}:{TODO_ID}:{peer_turn}"
peer_receipt = {**receipt, "event_id": "peer-invalid-receipt", "agent_id": peer,
"run_id": peer_turn, "details": {**receipt["details"],
"settlement_effect_id": peer_effect,
"semantic_replan_obligation_id": "replan-0000000000000001",
"semantic_replan_review_kind": "periodic_review_due",
"semantic_replan_review_stop_condition": None}}
with log.open("a") as stream:
stream.write(json.dumps(peer_receipt) + "\n")
index = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl"
index.parent.mkdir(parents=True, exist_ok=True)
peer_run_path = index.parent / "peer-run.json"
peer_markdown_path = index.parent / "peer-run.md"
peer_run = {"goal_id": GOAL_ID, "agent_id": peer,
"turn_instance_id": peer_turn, "classification": "state_refreshed",
"generated_at": "2026-01-01T00:00:00Z", "delivery_outcome": "outcome_progress",
"json_path": str(peer_run_path), "markdown_path": str(peer_markdown_path),
**({"goal_ref": receipt["goal_ref"]} if "goal_ref" in receipt else {})}
peer_run_path.write_text(json.dumps(peer_run))
peer_markdown_path.write_text("Synthetic peer work.\n")
with index.open("a") as stream:
stream.write(json.dumps(peer_run) + "\n")
rc, refreshed = _run_cli(registry, runtime, "refresh-state", *binding,
"--classification", "validated_progress", "--delivery-batch-scale", "implementation",
"--delivery-outcome", "outcome_progress", "--delivery-boundary", "in_flight_continuation",
"--no-global-sync", "--suppress-external-sinks", cwd=project)
assert rc == 0 and refreshed["appended"], refreshed
for _ in range(2):
rc, spent = _run_cli(registry, runtime, "quota", "spend-slot", *binding,
"--slots", "1", "--source", "heartbeat", "--execute")
assert rc == 0, json.dumps(spent)
assert _spend_run_count(runtime) == 1
assert _heartbeat_receipt_count(runtime, turn) == 1
for agent_args in ([], ["--agent-id", peer]):
rc, rejected = _run_cli(registry, runtime, "status", "--goal-id", GOAL_ID, *agent_args)
assert rc == 1 and "receipt review stop condition" in rejected["error"], rejected
final_receipts = [json.loads(line) for line in log.read_text().splitlines()]
assert receipt in final_receipts and peer_receipt in final_receipts


@pytest.mark.parametrize("threshold_override,device_count,threshold,declare_outcome", [
(None, None, 6, False), (None, None, 6, True), (2, 3, 2, False), (None, 3, 3, False),
(5, 6, 5, False), (None, 5, 5, False), (6, None, 6, False), (None, 6, 6, False),
Expand Down
47 changes: 47 additions & 0 deletions tests/control_plane_ts/quota_settlement_readback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2220,6 +2220,53 @@ test("effective cadence scopes settlement and ACKs to its admitted Goal instance
}
});

test("agent cadence does not interpret another agent's malformed semantic receipt", async () => {
const { projectSettledReplanHistory } = await import(
"../../loopx/control_plane/work_items/replan_history_settlement.ts");
const root = await fixture({writeback: true, spend: true, completion: true});
const peer = "codex-peer";
const peerTurn = "peer-turn";
const peerIdentity = settlementIdentity({goal_id: goalId, agent_id: peer,
todo_id: todoId, turn_instance_id: peerTurn});
const log = join(root, "goals", goalId, "rollout-event-log.jsonl");
const row = (agent: string, turn: string) => ({agent_id: agent, public_agent_id: agent,
monitor_agent_id: agent, turn_id: turn, classification: "state_refreshed",
generated_at: "2026-01-01T00:00:00Z", observed_at: 1,
accepted_ack: false, progress: null, monitor: {}});
const cadence = {schema_version: "replan_history_request_v0", operation: "periodic",
agent_id: agentId, monitor_agent_id: agentId, neutral_classifications: [],
stall_threshold: 2, periodic_threshold: 1, monitor_threshold: 6,
streak_threshold: 5, monitor_schema: "dead_monitor_repeat_v0",
todos: {monitors: [], advancements: [], resume: null},
settlement_source: {runtime_root: root, goal_id: goalId},
runs: [row(peer, peerTurn), row(agentId, turnId)]};
try {
const baseline = await projectSettledReplanHistory({...cadence, runs: cadence.runs.slice(1)});
assert.equal(requireJsonObject(baseline.trigger, "trigger").run_count, 1);
await appendFile(log, JSON.stringify({schema_version: "loopx_rollout_event_v0",
event_id: "malformed-peer-review", event_kind: "quota_should_run",
goal_id: goalId, agent_id: peer, run_id: peerTurn, details: {
todo_id: todoId, settlement_effect_id: peerIdentity.effect_id,
semantic_replan_obligation_id: "replan-0000000000000001",
semantic_replan_review_kind: "periodic_review_due",
semantic_replan_review_stop_condition: null,
}}) + "\n");
const originalLog = await readFile(log, "utf8");
assert.deepEqual(await projectSettledReplanHistory(cadence), baseline);
assert.equal((await projectSettledReplanHistory({...cadence,
runs: cadence.runs.slice(0, 1)})).trigger, null, "peer work cannot qualify this agent");
await assert.rejects(projectSettledReplanHistory({...cadence, agent_id: peer}),
/receipt review stop condition/, "the affected agent still sees its own invalid receipt");
await assert.rejects(projectSettledReplanHistory({...cadence, agent_id: null}),
/receipt review stop condition/, "unscoped history still validates every contributing agent");
await assert.rejects(projectSettledReplanHistory({...cadence, agent_id: 42}),
/agent_id/, "invalid scope must not silently become unscoped");
assert.equal(await readFile(log, "utf8"), originalLog, "readback cannot repair historical receipts");
} finally {
await rm(root, {recursive: true, force: true});
}
});

test("effective cadence skips settlement read without a matching should-run receipt", async () => {
const { projectSettledReplanHistory } = await import(
"../../loopx/control_plane/work_items/replan_history_settlement.ts");
Expand Down
Loading