Skip to content
Merged
36 changes: 35 additions & 1 deletion docs/project-agent-todo-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,41 @@ use `--clear-blocks-agent --global-gate`. Merely clearing scope in a multi-agent
Goal is rejected; it must not turn an ambiguous gate into a global one.

When a user gate only blocks one concrete action, add the blocked todo id with
`unblocks_todo_id=<todo_id>`. When multiple todos share the same broad
`unblocks_todo_id=<todo_id>`. If the gate was created first, its registered bound
agent can attach the initial link while the gate is open:

```bash
loopx todo update --goal-id <goal-id> --role user --todo-id <gate-id> \
--agent-id <bound-agent> --unblocks-todo-id <agent-todo-id>
```

This is an administrative provider-CAS edit, including in `hard_lease`; it does
not claim work or approve the gate. Optional note/evidence/reason may accompany
the link. The target must already exist as an Agent Todo in the same provider
snapshot and Goal, with `claimed_by` matching the gate's `bound_agent` /
`blocks_agent`. It must be active, open or blocked, not done or superseded;
completed/cancelled, archived and deferred work cannot receive this first link.
The link must also describe one decision: a gate with a `decision_scope` only
accepts a target whose `required_decision_scopes` include a scope it covers, and
a gate without one only accepts a target that requires no scoped decision (a
plain dependency link). A missing match is never read as a dependency.
A target may declare no resume condition, or exactly `todo_done:<this gate>`. Any
other condition (`todo_done:<other-id>`, `monitor_changed:<id>` even with this
gate's id, `resume_at:<time>` or `capacity_available:<capability>`) waits for
something approving this gate cannot satisfy, so it cannot receive this first link.
Preview and write reject missing, inactive or out-of-scope targets without
writing or consuming the first-link opportunity or operation ID; the same gate
and operation ID can then be used for a valid target. Existing links, gate scope,
actor bindings and explicit or unreleased lease proofs retain their ordinary
admission. Complete the linked
gate with the actual decision and evidence to consume the target's covered
decision scopes.
`todo_done:<gate-id>` checks dependency readiness only; it does not consume those
scopes. If an unlinked gate was already completed, reconcile its decision through
an explicit linked gate using the original owner evidence rather than treating
dependency completion as approval.

When multiple todos share the same broad
`action_kind`, use the schema-backed decision-scope fields instead of relying
on title/body token overlap:

Expand Down
42 changes: 40 additions & 2 deletions loopx/control_plane/coordination/todo_update_admission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import {retiredHandoffModeRejection, HANDOFF_MODE_RETIRED_REASON} from "./handoff_mode_policy.ts";
import {leaseRepositoryRejection, ownerAdministrativeRepositoryRejection} from "../work_items/task_lease_repository.ts";
import {isExploreReferenceAppend} from "../todos/field_update.ts";
import {isInactiveUserCompletionTarget} from "../todos/user_completion.ts";
import {decisionScopeRelation} from "../todos/decision_scope.ts";
import {todoDoneResumeTargetId} from "../todos/resume_condition.ts";
import {acceptanceRestoration} from "./todo_acceptance_restoration.ts";
import {monitorMutationRejection} from "./todo_monitor_cycle.ts";
import type {JsonObject} from "../effect_program.ts";
Expand Down Expand Up @@ -219,14 +222,49 @@ export function todoUpdateAdmissionRejection(
const repositoryRejection = leaseRepositoryRejection(todo, lease);
return repositoryRejection === null ? null : reject(repositoryRejection, "Evidence association must retain the completed work repository");
}
// User reminders use an administrative provider-CAS edit. Retained released
// An initial gate link is planning, not execution or an owner decision.
const boundUserGateLink = todo.role === "user" && todo.task_class === "user_gate" &&
todo.status === "open" && todo.claimed_by == null && todo.unblocks_todo_id == null &&
input.actor_agent_id !== null && todo.bound_agent === input.actor_agent_id &&
todo.blocks_agent === input.actor_agent_id &&
typeof intent.unblocks_todo_id === "string" && intent.unblocks_todo_id.length > 0 &&
Comment thread
huangruiteng marked this conversation as resolved.
Resolved
Object.keys(input.patch).every(field => field === "note") &&
input.clear_fields.every(field => field === "note") &&
Object.keys(intent).every(field => ["unblocks_todo_id", "evidence", "reason"].includes(field));
// User planning uses an administrative provider-CAS edit. Retained released
// history is not an execution grant; active/expired history needs exact
// release first. Explicit or partial proof never grants this exception.
const boundUserActionMetadata = isBoundUserActionMetadataUpdate(todo, input);
if (boundUserActionMetadata && (lease === undefined || lease.status === "released") &&
if ((boundUserActionMetadata || boundUserGateLink) && (lease === undefined || lease.status === "released") &&
input.lease_idempotency_key == null && input.lease_expected_version == null) {
try {
if (lease !== undefined) canonicalTaskLease(lease, input.goal_id, input.todo_id);
if (boundUserGateLink) {
const target = indexCoordinationProjection(head, input.goal_id).todos.get(intent.unblocks_todo_id as string);
if (target?.role !== "agent" || target.claimed_by !== todo.blocks_agent ||
target.archive_state !== "active" || isInactiveUserCompletionTarget(target)) {
return reject("user_gate_link_target_invalid",
"Initial gate link requires an active, open or blocked Agent Todo in this Goal claimed by the gate's bound/blocked agent");
}
// The link must describe one decision: a scoped gate takes only a target
// awaiting that scope; an unscoped dependency gate takes only a target
// awaiting no scoped decision. Absence of a match is not a dependency.
const relation = decisionScopeRelation(todo, target);
const awaitsScopedDecision = Array.isArray(target.required_decision_scopes) && target.required_decision_scopes.length > 0;
if (relation === null ? awaitsScopedDecision : relation.state !== "gate_covers_action") {
Comment thread
huangruiteng marked this conversation as resolved.
Resolved
return reject("user_gate_link_target_invalid",
"Initial gate link requires a target whose required decision scopes are covered by this gate's decision scope, or neither side to declare one");
}
// A target that declares any resume condition other than completion of this
// exact gate (another Todo, a Monitor change, a time or a capacity) waits for
// that; approving this gate cannot satisfy it, so it cannot take the first link.
const declared = typeof target.resume_when === "string" ? target.resume_when.trim() : "";
const waitsForThisGate = todoDoneResumeTargetId(declared) === input.todo_id;
if (declared && !waitsForThisGate) {
return reject("user_gate_link_target_invalid",
"Initial gate link requires a target that declares no resume condition other than this gate");
}
}
} catch (error) {
return reject("invalid_coordination_projection",
error instanceof Error ? error.message : "invalid retained lease facts");
Expand Down
6 changes: 6 additions & 0 deletions loopx/control_plane/todos/resume_condition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,12 @@ export function todoResumeDependencyId(value: unknown): string | null {
return spec?.kind === "todo_done" || spec?.kind === "monitor_changed" ? spec.target : null;
}

/** The Todo whose completion this condition awaits, in any stored spelling. */
export function todoDoneResumeTargetId(value: unknown): string | null {
const spec = parseResumeWhen(value);
return spec?.kind === "todo_done" ? spec.target : null;
}

export function normalizeTodoResumeWhen(value: unknown): string | null {
const request = requireJsonObject(value, "todo_resume_normalize_request");
if (request.schema_version !== TODO_RESUME_NORMALIZE_REQUEST_SCHEMA_VERSION) {
Expand Down
10 changes: 5 additions & 5 deletions loopx/control_plane/todos/user_completion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export interface UserCompletionPlan extends JsonObject {
readonly unblock_resume: ResumeReceipt | null;
readonly decision_scope_resolution: JsonObject | null;
}
const inactiveTarget = (todo: JsonObject): boolean => todo.archive_state === "archive" ||
todo.done === true || !["open", "blocked"].includes(String(todo.status || "open"));
export const isInactiveUserCompletionTarget = (todo: JsonObject): boolean => todo.archive_state === "archive" ||
todo.done === true || todo.superseded_by != null || !["open", "blocked"].includes(String(todo.status || "open"));

// Terminal admission owns whether the source may complete. In particular, a
// deferred User gate is still a legal explicit completion source even though
Expand Down Expand Up @@ -70,8 +70,8 @@ export function planUserCompletion(
const scope = gate ? normalizeTodoDecisionScope(source.decision_scope) : null;
if (!target) return {...empty, unblock_resume: {...base,
state: gate && outcome !== "approve" ? "target_or_decision_scope_not_found" : "target_not_found"}};
// A late decision must not revive completed, archived, or deferred work.
if (inactiveTarget(target)) return {...empty, unblock_resume: {...base, state: "target_not_active", status: target.status}};
// A late decision must not revive completed, archived, superseded, or deferred work.
if (isInactiveUserCompletionTarget(target)) return {...empty, unblock_resume: {...base, state: "target_not_active", status: target.status}};
const status = String(target.status || "open");
const requirements = normalizeTodoRequiredDecisionScopes(target.required_decision_scopes) ?? [];
const rawOutcomes = target.decision_scope_outcomes ?? [];
Expand Down Expand Up @@ -111,7 +111,7 @@ export function planUserCompletion(
if (status !== "blocked") return result("target_not_blocked");
if (target.task_class === "blocker") return result("explicit_blocker_repair_required");
const blockers = todos.filter(row => row.role === "user" && row.todo_id !== source.todo_id &&
row.unblocks_todo_id === id && !inactiveTarget(row)).map(row => String(row.todo_id));
row.unblocks_todo_id === id && !isInactiveUserCompletionTarget(row)).map(row => String(row.todo_id));
if (blockers.length) return result("other_user_blockers_active", {remaining_user_blocker_todo_ids: [...new Set(blockers)].sort()});
// Finishing one gate is not evidence that every independent requirement passed.
if (remaining.length || remainingOutcomes.some(item => item.outcome === "reject" || item.outcome === "cancel")) return result("decision_requirements_remaining");
Expand Down
64 changes: 64 additions & 0 deletions tests/control_plane/test_settled_monitor_user_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,70 @@ def call(*args):
assert not any(row["classification"] in {"state_refreshed", "quota_slot_spent"} for row in rows)


def test_file_gate_can_complete_before_primary_monitor_poll(tmp_path, monkeypatch):
isolate_sqlite_runtime(tmp_path, monkeypatch)
registry, runtime, _state = _write_fixture(tmp_path)
scope = "resource:action:prices_file"
gated = add_goal_todo(registry_path=registry, goal_id=GOAL_ID, role="agent",
text="Implement inventory value using the supplied prices", task_class="advancement_task",
status="blocked", claimed_by=AGENT_ID, agent_id=AGENT_ID,
required_decision_scopes=[scope])
gate = add_goal_todo(registry_path=registry, goal_id=GOAL_ID, role="user",
text="Supply inputs/prices.json", task_class="user_gate", bound_agent=AGENT_ID,
blocks_agent=AGENT_ID, unblocks_todo_id=gated["todo_id"],
decision_scope=scope, agent_id=AGENT_ID)
monitor = _add_monitor(registry, text="Observe the authorized prices file",
target_key="prices-file", next_due_at="2000-01-01T00:00:00Z")
turn = "file-gate-monitor-turn"
common = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID]
turn_args = [*common, "--runtime-profile", "generic_cli", "--turn-instance-id", turn,
"--available-capability", "network", "--available-capability", "external_evidence_poll"]
def call(*args):
return run_json_cli(*args, registry_path=registry, runtime_root=runtime)
admitted = call("quota", "should-run", *turn_args)
assert admitted["selected_todo"]["todo_id"] == monitor["todo_id"]
binding = admitted["heartbeat_receipt"]["settlement_identity"]

prices = registry.parent.parent / "inputs" / "prices.json"
prices.parent.mkdir()
prices.write_text('{"A":199}', encoding="utf-8")
observed = prices.read_text(encoding="utf-8")
assert json.loads(observed) == {"A": 199}
# Gate control is not completion of the monitor's Turn settlement Todo.
completed = call("todo", "complete", *common, "--todo-id", gate["todo_id"],
"--role", "user", "--decision-outcome", "approve",
"--evidence", f"inputs/prices.json supplied and validated: {observed}")
assert completed["completed"] is True
assert completed["decision_scope_resolution"]["state"] == "resolved"
assert completed["unblock_resume"]["state"] == "resumed"
rows = {row["todo_id"]: row for row in call("todo", "list", "--goal-id", GOAL_ID)["todos"]}
assert rows[gate["todo_id"]]["status"] == "done"
assert rows[gated["todo_id"]]["status"] == "open"
assert not rows[gated["todo_id"]].get("required_decision_scopes")
before_poll = call("quota", "should-run", *turn_args)
assert before_poll["heartbeat_receipt"]["settlement_identity"] == binding
assert before_poll["selected_todo"]["todo_id"] == monitor["todo_id"]

poll = call("quota", "monitor-poll", *turn_args, "--todo-id", monitor["todo_id"],
"--target-key", "prices-file", "--result-hash", observed, "--material-change", "--execute")
assert poll["turn_continuation"]["current_turn_settled"] is True
assert poll["turn_continuation"]["same_turn_independent_settlement_allowed"] is False
assert poll["turn_continuation"]["next_turn_required"] is True
replay = call("quota", "should-run", *turn_args)
assert replay["heartbeat_receipt"]["settlement_identity"] == binding
assert replay["selected_todo"]["todo_id"] == monitor["todo_id"]
assert replay["should_run"] is False
assert replay["interaction_contract"]["agent_channel"]["delivery_allowed"] is False
fresh_args = ["file-gate-implementation-turn" if arg == turn else arg for arg in turn_args]
fresh = call("quota", "should-run", *fresh_args)
assert fresh["selected_todo"]["todo_id"] == gated["todo_id"]
assert fresh["interaction_contract"]["agent_channel"]["delivery_allowed"] is True
index = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl"
events = [json.loads(line) for line in index.read_text(encoding="utf-8").splitlines()]
assert sum(row["classification"] == "quota_monitor_poll" for row in events) == 1
assert not any(row["classification"] in {"state_refreshed", "quota_slot_spent"} for row in events)


def _primary_monitor_fixture(
tmp_path, monkeypatch, provider, route="source", *,
resume_when=None, handoff_mode="soft_claim",
Expand Down
Loading
Loading