[^<]+<\/a><\/h2>([^<]+)<\/p>/)?.[1] ?? "";
+ assertIncludes(listing, langSuffix === "zh" ? "记录分数" : "reported EdgeBench", "Blog catalog describes the recorded score pair scope");
+ for (const observedText of [snapshotSection, snapshotSvg, JSON.stringify(snapshot), listing]) {
+ if (/controlled|fixed Explore|holding Explore|同构|受控|固定 Explore|four.arm|四臂/i.test(observedText)) {
+ throw new Error("Reported score snapshot restored a controlled or mixed-arm claim: " + locale);
}
}
- for (const publicText of [article, twoArmSvg, JSON.stringify(audit)]) {
+ for (const publicText of [article, snapshotSvg, JSON.stringify(audit)]) {
if (/sforge/i.test(publicText)) {
throw new Error(`Internal benchmark name leaked into public context-delivery blog artifact (${locale})`);
}
@@ -466,6 +594,37 @@ async function assertClockLabelRejected(blogDir, { figure, declared, regressed }
}
}
+async function assertScoreMismatchRejected(blogDir) {
+ const temporaryRoot = await mkdtemp(join(tmpdir(), "loopx-blog-score-parity-"));
+ const fixtureBlog = join(temporaryRoot, "blog");
+ try {
+ await cp(blogDir, fixtureBlog, { recursive: true });
+ // Each mutation changes just one published representation (or its source provenance).
+ const data = "data/long-horizon-audit.json";
+ const en = "context-delivery/index.html";
+ const zh = "zh/context-delivery/index.html";
+ const svg = "images/context-delivery/stride-context-on-vs-off-en.svg";
+ for (const [path, before, after, expected] of [
+ [data, '"context_on_native": 80,', '"context_on_native": 5,', /snapshot direction or winner/],
+ [data, '"context_on_native": 80,', '"context_on_native": 81,', /table row differs.*Borden/],
+ [svg, "7,159 / 3,746", "7,159 / 3,747", /chart native example differs/],
+ [en, "33,090,430 (62.99", "13,090,430 (62.99", /table row differs.*OpenTTD/],
+ [zh, "(27.18 · 17h57m · 10 次)", "(27.18 · 17h57m · 1 次)", /table row differs.*Rust/],
+ [data, '"prior_public_ann_url": "https://github.com/', '"prior_public_ann_url": "https://example.invalid/', /immutable public sources/],
+ [data, '"direction": "lower",\n "metric_label_en": "Total cost"', '"direction": "higher",\n "metric_label_en": "Total cost"', /snapshot direction or winner/],
+ ]) {
+ const file = resolve(fixtureBlog, path);
+ const source = await readFile(file, "utf8");
+ assertIncludes(source, before, "Negative fixture must contain the original value: " + path);
+ await writeFile(file, source.replace(before, after));
+ await rejects(() => validateBilingualBlog(fixtureBlog), expected);
+ await writeFile(file, source);
+ }
+ } finally {
+ await rm(temporaryRoot, { recursive: true, force: true });
+ }
+}
+
const modulePath = fileURLToPath(import.meta.url);
if (process.argv[1] && resolve(process.argv[1]) === modulePath) {
const articleUrl = "https://loopx-project.github.io/loopx/blog/example/";
@@ -552,5 +711,6 @@ if (process.argv[1] && resolve(process.argv[1]) === modulePath) {
},
"中文主图恢复反馈口径也必须被配对标签检查拦下",
);
+ await assertScoreMismatchRejected(blogDir);
console.log(`blog-bilingual-index-smoke: ok (${articleSlugs.length} paired articles)`);
}
diff --git a/examples/coordination/remote-authority-service.ts b/examples/coordination/remote-authority-service.ts
index 45a98cab92..f4b9507dee 100644
--- a/examples/coordination/remote-authority-service.ts
+++ b/examples/coordination/remote-authority-service.ts
@@ -12,12 +12,12 @@ const port = Number(values.port);
if (!values.policy || !values.cert || !values.key || !Number.isSafeInteger(port) || port < 0 || port > 65535 ||
!process.env.LOOPX_AUTHORITY_DATABASE_URL) throw new Error("Provide policy, TLS certificate/key and service-owned database configuration");
// Validate before listening; updates are read again for each admission.
-await readRemoteAuthorityPolicy(values.policy);
+const policy = await readRemoteAuthorityPolicy(values.policy);
const pool = new Pool({connectionString: process.env.LOOPX_AUTHORITY_DATABASE_URL,
max: 8, connectionTimeoutMillis: 2000, query_timeout: 6000, idleTimeoutMillis: 10000,
statement_timeout: 5000, lock_timeout: 2000, idle_in_transaction_session_timeout: 10000});
pool.on("error", () => process.stderr.write("Authority database connection unavailable\n"));
-const service = new RemoteAuthorityService({admit: fileRemoteAuthorityAdmission(values.policy),
+const service = new RemoteAuthorityService({admit: fileRemoteAuthorityAdmission(values.policy, String(policy.schema_version)),
database: {connect: async () => {
const connection = await pool.connect();
return {query: (sql, args) => connection.query(sql, args ? [...args] : undefined),
diff --git a/examples/personal-workspace-browser/goal-workspace-m2.mjs b/examples/personal-workspace-browser/goal-workspace-m2.mjs
index ef5b6bc191..dc1ef830e9 100644
--- a/examples/personal-workspace-browser/goal-workspace-m2.mjs
+++ b/examples/personal-workspace-browser/goal-workspace-m2.mjs
@@ -286,6 +286,7 @@ async function runM2Pass({browser, collectCoverage, url}) {
const renderBudget = {coverageEnabled:collectCoverage,initialMs,expandMs,switchMs,switchSamplesMs,...lensBudget,
longTaskSupported,switchLongTasks,nodeCount:200};
console.log(JSON.stringify({m2RenderBudget:renderBudget}));
+ await verifyFocusAfterReprioritization(page, now, many[4]);
assert.equal(writes.length,0,`Rendering created effects: ${writes}`);
assert.equal(session.errors.length,0,session.errors.join('\n'));
if (!collectCoverage) assert.ok(lensBudget.withinBudget, `Loaded lens switches exceeded repeated 1s target or 2s ceiling: ${JSON.stringify({switchSamplesMs,...lensBudget})}`);
@@ -295,6 +296,40 @@ async function runM2Pass({browser, collectCoverage, url}) {
finally {await session.close();}
}
+async function verifyFocusAfterReprioritization(page, now, todo) {
+ const byOwner = now.getByRole("button", {name:"按负责人", exact:true});
+ await byOwner.click();
+ const owner = now.locator('.goal-owner-group[data-owner-id="worker-0"]');
+ const remaining = owner.locator(".goal-work-more");
+ await remaining.locator(":scope > summary").press("Enter");
+ assert.equal(await remaining.evaluate(node => node.open), false);
+
+ const row = `[data-todo-id="${todo.todo_id}"]`;
+ const leading = owner.locator(`:scope > ${row}`);
+ const moved = remaining.locator(`${row}[data-work-class="blocked"]`);
+ const refresh = page.getByRole("button", {name:"刷新状态", exact:true});
+ // Simulate a status refresh while the keyboard user remains on the page.
+ const refreshWithoutMovingFocus = () => refresh.evaluate(button => button.click());
+
+ await byOwner.focus();
+ todo.status = "blocked";
+ await refreshWithoutMovingFocus();
+ await moved.waitFor({state:"attached"});
+ assert.equal(await moved.isVisible(), false, "An unfocused task does not open its disclosure on refresh");
+ assert.equal(await byOwner.evaluate(node => document.activeElement === node), true, "Refresh leaves focus outside the task list alone");
+
+ todo.status = "open";
+ await refreshWithoutMovingFocus();
+ await leading.focus();
+ todo.status = "blocked";
+ await refreshWithoutMovingFocus();
+ await moved.waitFor({state:"attached"});
+ assert.equal(await moved.evaluate(node => document.activeElement === node), true, "The same task keeps keyboard focus after it moves");
+ await page.keyboard.press("Enter");
+ await page.waitForURL(value => value.searchParams.get("todo") === todo.todo_id);
+ await page.locator(".personal-context-drawer").waitFor();
+}
+
async function verifyRemoteSelection(browser, url) {
const snapshot = JSON.parse(await readFile(resolve(repoRoot,"examples/status.example.json"),"utf8"));
diff --git a/examples/readme-star-history-smoke.py b/examples/readme-star-history-smoke.py
index f74ed31703..de3d782f0a 100644
--- a/examples/readme-star-history-smoke.py
+++ b/examples/readme-star-history-smoke.py
@@ -101,6 +101,7 @@ def main() -> int:
readme_sections = {
ROOT / "README.md": ("## Current Status", "## Star History", "## License"),
ROOT / "README.zh-CN.md": ("## 当前状态", "## Star 趋势", "## License"),
+ ROOT / "README.ja.md": ("## 現在のステータス", "## Star の推移", "## ライセンス"),
}
for readme, sections in readme_sections.items():
text = readme.read_text(encoding="utf-8")
diff --git a/loopx/__init__.py b/loopx/__init__.py
index 2f01aed637..46099679c6 100644
--- a/loopx/__init__.py
+++ b/loopx/__init__.py
@@ -2,4 +2,4 @@
__all__ = ["__version__"]
-__version__ = "2.3.0"
+__version__ = "2.4.0"
diff --git a/loopx/capabilities/issue_fix/README.md b/loopx/capabilities/issue_fix/README.md
index 3338cccdbe..c8b4d3c8de 100644
--- a/loopx/capabilities/issue_fix/README.md
+++ b/loopx/capabilities/issue_fix/README.md
@@ -345,14 +345,11 @@ candidate so a maintainer can audit why that person was selected.
`CODEOWNERS` remains the strongest repository-native signal. Commit volume is
only evidence of familiarity; it is not proof of maintainership, availability,
-or review authority. See the [reviewer recommendation
-contract](docs/protocols/issue-fix-reviewer-recommendation-v0.md) for scoring,
-identity, and future-signal details, and the [reviewer request
-contract](docs/protocols/issue-fix-reviewer-request-v0.md) for the external-write,
+or review authority. See the [reviewer recommendation contract](docs/protocols/issue-fix-reviewer-recommendation-v0.md) for scoring,
+identity, and future-signal details, and the [reviewer request contract](docs/protocols/issue-fix-reviewer-request-v0.md) for the external-write,
idempotency, and verification rules. Secondary delivery, dedicated-bot
isolation, local-private identity mapping, and readback are defined by the
-[reviewer notification sink
-contract](docs/protocols/issue-fix-reviewer-notification-sinks-v0.md).
+[reviewer notification sink contract](docs/protocols/issue-fix-reviewer-notification-sinks-v0.md).
### 6. PR publication and public-write boundary
diff --git a/loopx/capabilities/manager_context/roundtrip.py b/loopx/capabilities/manager_context/roundtrip.py
index 3ce56200f9..8359b41340 100644
--- a/loopx/capabilities/manager_context/roundtrip.py
+++ b/loopx/capabilities/manager_context/roundtrip.py
@@ -427,24 +427,46 @@ def observe_result(result_path, reply):
]
+def _saved_answer_rows(messages, message_id, expected_turn_id):
+ matches = [row for row in messages if row.get("message_id") == message_id]
+ if len(matches) > 1:
+ raise ValueError("saved answer has conflicting message identities")
+ if not matches or matches[0].get("role") not in {"agent", "assistant"}:
+ return [], []
+ answer = matches[0]
+ turn_id = answer.get("turn_id")
+ if expected_turn_id is not None and turn_id != expected_turn_id:
+ return [], []
+ if not turn_id:
+ return [answer], [answer]
+ original = [row for row in messages if row.get("turn_id") == turn_id]
+ question = next((row for row in original if row.get("role") == "user"), None)
+ return ([question, answer] if question else [answer]), original
+
+
def project_chat_session_snapshot(root, store, session_id, *, registry,
- message_limit=None, message_cursor=None, turn_id=None,
+ message_limit=None, message_cursor=None, turn_id=None, report_message_id=None,
resume_from=None, project_history_messages=None, include_turn_error=False):
"""Project return delivery state into one existing Chat snapshot."""
turn = None
- if turn_id is not None:
+ if turn_id is not None and report_message_id is None:
if message_limit is None:
raise ValueError("a selected original Turn requires paged history")
turn = store.load_turn(session_id, turn_id)
if not turn or turn.get("session_id") != session_id or turn.get("turn_id") != turn_id:
raise ValueError("original Turn is unavailable from this Session")
- strict = message_limit is not None or resume_from is not None
+ strict = message_limit is not None or resume_from is not None or report_message_id is not None
# Read the status first: terminal completion persists its answer before
# publishing completed. An older message prefix must not appear final.
snapshot = (store.session_snapshot(session_id, strict_messages=True) if strict
else store.session_snapshot(session_id))
- if turn is not None:
+ report_context = None
+ if report_message_id is not None:
+ snapshot["messages"], report_context = _saved_answer_rows(snapshot["messages"], report_message_id, turn_id)
+ snapshot["report_message_id"] = report_message_id
+ snapshot["active_turn"] = None
+ elif turn is not None:
status = turn["status"]
snapshot["selected_turn"] = {"turn_id": turn_id, "status": status, "terminal": status in TERMINAL_TURN_STATES}
# Failure records persist the reason with the status, before appending the message.
@@ -464,7 +486,7 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
from .chat_history import page_chat_messages
page = (page_chat_messages(session_id, snapshot["messages"], limit=message_limit,
cursor=message_cursor, turn_id=turn_id) if message_limit is not None else None)
- context_messages = snapshot["messages"]
+ context_messages = snapshot["messages"] if report_context is None else report_context
if page is not None:
context_messages = context_messages[:page["message_page"]["total"]]
snapshot["messages"] = page["messages"]
@@ -475,8 +497,14 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
# Use the frozen context to choose the carrier, projecting only this page.
# A question and answer can straddle pages without duplicating a commitment
# or re-reading every off-page Turn for each page.
- snapshot["messages"] = project_collaboration(store, root, session_id, snapshot["messages"],
+ projected = project_collaboration(store, root, session_id, snapshot["messages"],
registry=registry, context_messages=context_messages)
+ if report_message_id is not None:
+ # Collaboration may include the original receipt carrier. The saved
+ # answer only exposes its precise answer and the question it displays.
+ visible_ids = {row.get("message_id") for row in snapshot["messages"]}
+ projected = [row for row in projected if row.get("message_id") in visible_ids]
+ snapshot["messages"] = projected
# Provider-owned history joins the selected page at the composition root.
# Core capabilities never import an extension projection sink.
if page is not None:
@@ -487,9 +515,13 @@ def project_chat_session_snapshot(root, store, session_id, *, registry,
def parse_chat_history_selection(query):
"""Validate one HTTP history selection before any recovery observation."""
- if (set(query) - {"message_limit", "message_cursor", "turn_id", "known_history", "task_goal_id", "task_todo_id"}
+ keys = set(query)
+ report = "report_message_id" in keys
+ if (keys - {"message_limit", "message_cursor", "turn_id", "known_history",
+ "task_goal_id", "task_todo_id", "report_message_id"}
or any(len(values) != 1 or not values[0] for values in query.values())
- or ("message_limit" not in query and set(query) & {"message_cursor", "turn_id", "known_history"})):
+ or (report and keys - {"report_message_id", "turn_id"})
+ or (not report and "message_limit" not in keys and keys & {"message_cursor", "turn_id", "known_history"})):
raise ValueError("invalid history page arguments")
limit = int(query["message_limit"][0]) if "message_limit" in query else None
if limit is not None and not 1 <= limit <= 200:
@@ -512,7 +544,8 @@ def parse_chat_history_selection(query):
raise ValueError("invalid known history proof")
parsed_basis = (basis, count, proof)
return {"message_limit": limit, "message_cursor": query.get("message_cursor", [None])[0],
- "turn_id": query.get("turn_id", [None])[0], "known_history": parsed_basis, "task_scope": task_scope}
+ "turn_id": query.get("turn_id", [None])[0], "known_history": parsed_basis, "task_scope": task_scope,
+ "report_message_id": query.get("report_message_id", [None])[0]}
def prepare_chat_history_session(store, session_id, selection, *, recover_turn):
@@ -520,7 +553,7 @@ def prepare_chat_history_session(store, session_id, selection, *, recover_turn):
task_scope = selection["task_scope"]
turn_id = selection["turn_id"]
if task_scope is None:
- if turn_id is None:
+ if turn_id is None and selection["report_message_id"] is None:
recover_turn(session_id)
return store.load_session(session_id) or {}
@@ -553,6 +586,7 @@ def read_chat_history_selection(root, store, session_id, *, registry, selection,
snapshot = project_chat_session_snapshot(root, store, session_id, registry=registry,
message_limit=selection["message_limit"], message_cursor=selection["message_cursor"],
turn_id=selection["turn_id"], project_history_messages=project_history_messages,
+ report_message_id=selection["report_message_id"],
include_turn_error=selection["task_scope"] is not None)
snapshot["messages"] = project_provider(snapshot["messages"])
if selection["message_limit"] == 200 and selection["turn_id"] is None:
diff --git a/loopx/capabilities/native_chat/queue_api.py b/loopx/capabilities/native_chat/queue_api.py
index 805fab86cb..ba4dd1d255 100644
--- a/loopx/capabilities/native_chat/queue_api.py
+++ b/loopx/capabilities/native_chat/queue_api.py
@@ -4,6 +4,7 @@
from urllib.parse import parse_qs, urlparse
from ...chat_store import CHAT_STORE_SCHEMA_VERSION
+from ...extensions.lark.private_ingress import project_private_reply_history
class ChatQueueRequestMixin:
@@ -63,7 +64,12 @@ def _session_queue(self, session_id: str) -> None:
self._session_context(session)
rows: list[dict[str, Any]] = []
for turn in store.queued_turns(session_id, strict=True, include_reserved=True):
- text = str(turn.get("message") or "")
+ # Reuse history's exact admission/source checks before truncating;
+ # a preview cannot decode a partial context envelope.
+ original = {"role": "user", "origin": turn.get("origin"),
+ "turn_id": turn["turn_id"], "text": str(turn.get("message") or "")}
+ visible = project_private_reply_history(store, session, [original])[0]
+ text = visible.get("reply_context", {}).get("source_text", original["text"])
rows.append({
"turn_id": turn["turn_id"],
"created_at": turn["created_at"],
diff --git a/loopx/chat_server.py b/loopx/chat_server.py
index ab9a4425ea..65337c4b63 100644
--- a/loopx/chat_server.py
+++ b/loopx/chat_server.py
@@ -936,7 +936,8 @@ def _session_snapshot(self, session_id: str) -> None:
media = self.server.private_media_history
contexts = getattr(self.server.runtime_controller, "project_contexts", None)
bindings = getattr(contexts, "conversation_bindings", None)
- markers = [] if selection["turn_id"] is not None else media.read(store, bindings, session)
+ scoped = selection["turn_id"] is not None or selection["report_message_id"] is not None
+ markers = [] if scoped else media.read(store, bindings, session)
payload = read_chat_history_selection(
self.server.runtime_controller.coordination_runtime_root, store, session_id,
registry=self.server.registry_path, selection=selection,
diff --git a/loopx/cli_commands/extension.py b/loopx/cli_commands/extension.py
index 14cedbb5a3..77b86ce0af 100644
--- a/loopx/cli_commands/extension.py
+++ b/loopx/cli_commands/extension.py
@@ -21,6 +21,7 @@
run_standalone_extension,
)
from ..extensions.scaffold import scaffold_extension
+from ..paths import effective_runtime_root
PrintPayload = Callable[
[dict[str, object], str, Callable[[dict[str, object]], str]],
@@ -61,10 +62,14 @@ def _render(payload: dict[str, object]) -> str:
return "\n".join(lines) + "\n"
-def _state_file(args: argparse.Namespace, runtime_root_arg: str | None) -> Path:
+def _state_file(
+ args: argparse.Namespace, runtime_root_arg: str | None, *, registry_path: Path,
+) -> Path:
override = getattr(args, "extension_state_file", None)
if override:
return Path(override).expanduser()
+ if runtime_root_arg is None:
+ runtime_root_arg = str(effective_runtime_root(registry_path, None))
return default_extension_state_file(runtime_root_arg)
@@ -201,13 +206,14 @@ def _load_json_object(path_text: str) -> dict[str, object]:
def handle_extension_command(
args: argparse.Namespace,
*,
+ registry_path: Path,
runtime_root_arg: str | None,
output_format: FormatSelector,
print_payload: PrintPayload,
) -> int | None:
if args.command != "extension":
return None
- state_file = _state_file(args, runtime_root_arg)
+ state_file = _state_file(args, runtime_root_arg, registry_path=registry_path)
try:
if args.extension_command == "init":
payload = scaffold_extension(
diff --git a/loopx/cli_commands/project_lifecycle_refresh_state.py b/loopx/cli_commands/project_lifecycle_refresh_state.py
index 0ec54e9709..ab52f3da64 100644
--- a/loopx/cli_commands/project_lifecycle_refresh_state.py
+++ b/loopx/cli_commands/project_lifecycle_refresh_state.py
@@ -822,6 +822,11 @@ def handle_refresh_state_command(
replan_obligation_id=getattr(
args, "replan_obligation_id", None
),
+ # The write may be addressed through the retained Todo while
+ # quota should-run bound this Turn to its semantic replan.
+ # Read back the immutable guard identity instead of treating
+ # that supported command shape as a second binding.
+ resolve_original_binding=True,
registry_path=registry_path,
goal_ref=goal_ref,
)
diff --git a/loopx/cli_commands/turn_run_once.py b/loopx/cli_commands/turn_run_once.py
index fa28ea033e..80e46f402f 100644
--- a/loopx/cli_commands/turn_run_once.py
+++ b/loopx/cli_commands/turn_run_once.py
@@ -4,6 +4,7 @@
from functools import partial
import sys as _sys
from collections.abc import Callable, Mapping
+from contextlib import contextmanager, nullcontext
from pathlib import Path
from typing import TYPE_CHECKING as _TYPE_CHECKING
from typing import Any
@@ -476,8 +477,29 @@ def terminal_closeout(
effect_ref: str,
) -> dict[str, object]:
require_effect_ref(effect_ref, SettlementStepKind.TERMINAL_CLOSEOUT)
+ if args.host == "codex-cli":
+ # Builtin completion has already retired the original lease.
+ # Verify the exact terminal receipt; never start another completion.
+ observed = terminal_closeout_resolver(effect_ref)
+ receipt = observed.get("payload")
+ if observed.get("kind") == "committed" and isinstance(receipt, dict):
+ return receipt
+ return {
+ "ok": False,
+ "appended": False,
+ "reason": observed.get("reason") or "Builtin terminal completion receipt is missing",
+ }
return todo_completion(result, effect_ref=effect_ref)
+ def codex_writeback(
+ result: dict[str, object], *, effect_ref: str,
+ ) -> dict[str, object]:
+ # Accountable refresh requires durable controller validation even for
+ # a predeclared terminal Todo. Other hosts keep their existing order.
+ if result.get("result_kind") == "validated_completion":
+ return completion_writeback(result, effect_ref=effect_ref)
+ return writeback(result, effect_ref=effect_ref)
+
def current_status() -> dict[str, object]:
return collect_turn_status_payload(
args,
@@ -847,6 +869,19 @@ def settlement_admission():
return request_settlement_lifetime(request_locator, settlement_identity,
registry_path=registry_path, runtime_root=runtime_root, workspace=project)
+ if args.host == "codex-cli" and goal_admission is not None:
+ request_lifetime = settlement_admission or nullcontext
+
+ @contextmanager
+ def codex_settlement_admission():
+ with request_lifetime():
+ # Independent validation can outlive the running Goal.
+ # Check the original authority before any settlement effect.
+ goal_admission.require_running(operation="codex_cli_turn_settle")
+ yield
+
+ settlement_admission = codex_settlement_admission
+
def on_managed_start_admitted() -> None:
if settlement_identity.request_subject is not None:
require_current_request_operation(request_locator, settlement_identity,
@@ -898,7 +933,8 @@ def on_managed_start_admitted() -> None:
retry_failed=bool(args.retry_failed_turn),
task_validator=task_validator,
settlement_admission=settlement_admission,
- writeback=writeback if args.execute else None,
+ writeback=(codex_writeback if args.host == "codex-cli" else writeback)
+ if args.execute else None,
completion_writeback=completion_writeback if args.execute else None,
completion_intent=completion_intent if args.execute else None,
terminal_closeout=terminal_closeout if args.execute else None,
diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py
index 6cbd890bc8..3579b126dd 100644
--- a/loopx/cli_runtime.py
+++ b/loopx/cli_runtime.py
@@ -699,7 +699,7 @@ def _dispatch_common_command(
from .cli_commands.extension import handle_extension_command
return handle_extension_command(
- args, runtime_root_arg=args.runtime_root,
+ args, registry_path=registry_path, runtime_root_arg=args.runtime_root,
output_format=output_format, print_payload=print_payload,
)
if args.command == "slash-commands":
diff --git a/loopx/control_plane/coordination/cold_source_import.ts b/loopx/control_plane/coordination/cold_source_import.ts
index 4a37736fb1..209804f008 100644
--- a/loopx/control_plane/coordination/cold_source_import.ts
+++ b/loopx/control_plane/coordination/cold_source_import.ts
@@ -234,13 +234,16 @@ export async function executeColdSourceImport(value: unknown,
try {
const input = requireJsonObject(value, "cold source import request");
const action = input.action;
+ const bindSourceRegistry = (action === "apply" || action === "readback")
+ && Object.hasOwn(input, "expected_source_registry");
+ const sourceRegistryKeys = bindSourceRegistry ? ["expected_source_registry"] : [];
if (input.schema_version !== COLD_SOURCE_IMPORT_REQUEST_SCHEMA ||
(action !== "prepare" && action !== "apply" && action !== "recover" && action !== "readback") ||
!hasExactAuthorityKeys(input, action === "prepare"
? ["schema_version", "action", "runtime_root", "goal_id", "operation_id", "projection", "source_snapshot", "target_handoff_mode", "target_provider", "source_backup"]
: action === "apply"
- ? ["schema_version", "action", "runtime_root", "goal_id", "operation_id", "expected_plan_sha256", "writers_stopped"]
- : ["schema_version", "action", "runtime_root", "goal_id", "operation_id", "expected_plan_sha256"])) {
+ ? ["schema_version", "action", "runtime_root", "goal_id", "operation_id", "expected_plan_sha256", "writers_stopped", ...sourceRegistryKeys]
+ : ["schema_version", "action", "runtime_root", "goal_id", "operation_id", "expected_plan_sha256", ...sourceRegistryKeys])) {
reject("cold_import_request_invalid");
}
const root = requireLocalAuthorityRuntimeRoot(input.runtime_root);
@@ -312,6 +315,12 @@ export async function executeColdSourceImport(value: unknown,
fence_id: `cold-import:${operation}`, import_operation_id: operation, import_plan_sha256: raw.plan_sha256};
if (prior.status === "loaded" && !same(prior.fence, fence)) reject("cold_import_fence_conflict");
const source = plan.source as ShadowRequest;
+ if (bindSourceRegistry) {
+ // The host resolves the current source before entering the effect.
+ // The immutable plan does not authorize a source the host no longer selects.
+ const registration = requireJsonObject(source.source_snapshot.registry_source, "retained registry source");
+ if (registration.path !== input.expected_source_registry) reject("source_registry_changed_retry");
+ }
const projection = requireJsonObject(plan.target_projection, "import target projection");
const identity = {operation_id: operation, projection_sha256: canonicalAuthoritySha256(projection),
receipt: {schema_version: "loopx_cold_source_import_receipt_v0", goal_id: goal,
diff --git a/loopx/control_plane/coordination/remote_authority_contract.ts b/loopx/control_plane/coordination/remote_authority_contract.ts
index d37ef5f7bb..131b35fb73 100644
--- a/loopx/control_plane/coordination/remote_authority_contract.ts
+++ b/loopx/control_plane/coordination/remote_authority_contract.ts
@@ -1,7 +1,7 @@
/** Candidate wire contract. Clients submit intentions, never authority facts. */
import type {JsonObject} from "../effect_program.ts";
import {canonicalAuthorityObject, canonicalAuthoritySha256,
- requireAuthorityStoreId} from "./authority_store_codec.ts";
+ hasExactAuthorityKeys, requireAuthorityStoreId} from "./authority_store_codec.ts";
import {POSTGRESQL_STORE_IDENTITY_PATTERN} from "./postgresql_authority_store.ts";
import {taskLeaseOperationIdentity} from "../work_items/task_lease_operation_identity.ts";
import {normalizeTodoId, normalizeGoalId, normalizeOwner} from "../work_items/task_lease_acquire.ts";
@@ -9,9 +9,11 @@ import {BARE_SHA256_PATTERN} from "../content_digest.ts";
import {parseIsoTimestamp} from "../runtime_timestamp.ts";
import {normalizeTodoResumeWhen, TODO_RESUME_NORMALIZE_REQUEST_SCHEMA_VERSION} from "../todos/resume_condition.ts";
import {normalizeTodoPriority} from "../todos/priority.ts";
+import {parseWireExactGoalRef, type WireExactGoalRef} from "../goals/acceptance_lifecycle.ts";
export const REMOTE_AUTHORITY_REQUEST = "loopx_remote_authority_request_v0";
export const REMOTE_AUTHORITY_RESPONSE = "loopx_remote_authority_response_v0";
+export const REMOTE_AUTHORITY_SCOPED_READ_RESPONSE = "loopx_remote_authority_scoped_read_response_v1";
export const REMOTE_AUTHORITY_OPERATIONS = [
"read", "claim", "progress", "renew", "release",
"complete", "block", "defer", "todo_add", "snapshot",
@@ -173,16 +175,18 @@ export function remoteAuthorityOperationId(request: RemoteAuthorityRequest, prin
request_id: requestId ?? ("request_id" in request ? request.request_id : "")})}`;
}
export function remoteAuthorityResponse(request: unknown, mode: RemoteAuthorityMode,
- payload: JsonObject): JsonObject {
- return {...payload, schema_version: REMOTE_AUTHORITY_RESPONSE,
+ payload: JsonObject, schema: typeof REMOTE_AUTHORITY_RESPONSE | typeof REMOTE_AUTHORITY_SCOPED_READ_RESPONSE = REMOTE_AUTHORITY_RESPONSE): JsonObject {
+ return {...payload, schema_version: schema,
request_sha256: canonicalAuthoritySha256({mode, request})};
}
export function remoteAuthoritySnapshotDigest(request: RemoteAuthorityScope, revision: unknown,
- todos: readonly unknown[], leases: readonly unknown[]): string {
- return canonicalAuthoritySha256({schema_version: "loopx_goal_snapshot_receipt_v0",
- tenant_id: request.tenant_id, goal_id: request.goal_id, store_identity: request.store_identity,
- provider_revision: revision, todos, leases});
+ todos: readonly unknown[], leases: readonly unknown[], goalRef?: WireExactGoalRef): string {
+ const evidence = goalRef
+ ? {schema_version: REMOTE_AUTHORITY_SCOPED_READ_RESPONSE, goal_ref: goalRef}
+ : {schema_version: "loopx_goal_snapshot_receipt_v0", provider_revision: revision};
+ return canonicalAuthoritySha256({...evidence, tenant_id: request.tenant_id,
+ goal_id: request.goal_id, store_identity: request.store_identity, todos, leases});
}
function responseRequires(condition: unknown): asserts condition {
@@ -199,8 +203,14 @@ function responseOperationId(value: unknown, request: RemoteAuthorityRequest): s
: id.startsWith("remote-task:") && BARE_SHA256_PATTERN.test(id.slice("remote-task:".length)));
return id;
}
-function responseLease(raw: unknown, request: RemoteAuthorityRequest, mutation: boolean): JsonObject {
+function responseFields(value: JsonObject, allowed: readonly string[]): void {
+ responseRequires(Object.keys(value).every(key => allowed.includes(key)));
+}
+function responseLease(raw: unknown, request: RemoteAuthorityRequest, mutation: boolean,
+ scoped: boolean = false, snapshot: boolean = false): JsonObject {
const lease = canonicalAuthorityObject(raw, "response lease");
+ if (scoped) responseFields(lease, ["owner", "status", "expires_at", "version", "lease_epoch",
+ ...(snapshot ? ["goal_id", "todo_id"] : [])]);
responseRequires(typeof lease.owner === "string" && normalizeOwner(lease.owner) === lease.owner &&
(lease.status === "active" || lease.status === "released") &&
Number.isSafeInteger(lease.version) && Number(lease.version) >= 0 &&
@@ -220,8 +230,9 @@ function responseLease(raw: unknown, request: RemoteAuthorityRequest, mutation:
return lease;
}
-function responseTodo(raw: unknown, todoId?: string): string {
+function responseTodo(raw: unknown, todoId?: string, scoped: boolean = false, snapshot: boolean = false): string {
const todo = canonicalAuthorityObject(raw, "response Todo");
+ if (scoped) responseFields(todo, ["todo_id", "status", "claimed_by", ...(snapshot ? ["role", "priority"] : [])]);
const id = normalizeTodoId(todo.todo_id);
responseRequires(todo.todo_id === id && (todoId === undefined || id === todoId));
remoteAuthorityId(todo.status, "Todo status");
@@ -231,22 +242,23 @@ function responseTodo(raw: unknown, todoId?: string): string {
return id;
}
-function responseSnapshot(value: JsonObject, request: Extract): void {
+function responseSnapshot(value: JsonObject, request: Extract,
+ goalRef?: WireExactGoalRef): void {
responseRequires(value.status === "snapshot" && value.goal_id === request.goal_id && value.store_identity === request.store_identity &&
Array.isArray(value.todos) && Array.isArray(value.leases));
- responseRevision(value.provider_revision, request);
- const todoIds = value.todos.map(todo => responseTodo(todo, request.todo_id));
+ if (!goalRef) responseRevision(value.provider_revision, request);
+ const todoIds = value.todos.map(todo => responseTodo(todo, request.todo_id, goalRef !== undefined, true));
const todoSet = new Set(todoIds);
responseRequires(todoSet.size === todoIds.length);
const leaseIds = new Set();
for (const raw of value.leases) {
- const lease = responseLease(raw, request, false);
+ const lease = responseLease(raw, request, false, goalRef !== undefined, true);
const id = normalizeTodoId(lease.todo_id);
responseRequires(lease.todo_id === id && lease.goal_id === request.goal_id && todoSet.has(id) &&
!leaseIds.has(id) && !Object.hasOwn(lease, "idempotency_key"));
leaseIds.add(id);
}
- responseRequires(value.receipt_sha256 === remoteAuthoritySnapshotDigest(request, value.provider_revision, value.todos, value.leases));
+ responseRequires(value.receipt_sha256 === remoteAuthoritySnapshotDigest(request, value.provider_revision, value.todos, value.leases, goalRef));
}
function responseCommand(raw: unknown, request: RemoteAuthorityRequest, operationId: string, historical: boolean): void {
@@ -301,9 +313,28 @@ function responseCommand(raw: unknown, request: RemoteAuthorityRequest, operatio
export function decodeRemoteAuthorityResponse(raw: unknown, request: RemoteAuthorityRequest,
mode: RemoteAuthorityMode): JsonObject {
const value = canonicalAuthorityObject(raw, "remote authority response");
- responseRequires(value.schema_version === REMOTE_AUTHORITY_RESPONSE &&
+ const scoped = value.schema_version === REMOTE_AUTHORITY_SCOPED_READ_RESPONSE;
+ responseRequires((value.schema_version === REMOTE_AUTHORITY_RESPONSE || scoped) &&
value.request_sha256 === canonicalAuthoritySha256({mode, request}));
responseRequires(typeof value.status === "string");
+ let goalRef: WireExactGoalRef | undefined;
+ if (scoped) {
+ goalRef = parseWireExactGoalRef(value.goal_ref, "scoped read Goal");
+ responseRequires(goalRef.goal_id === request.goal_id);
+ if (mode === "recover") {
+ responseRequires(request.operation !== "read" && request.operation !== "snapshot" &&
+ value.status === "found" && value.historical_only === true && value.todo_id === request.todo_id &&
+ typeof value.receipt_sha256 === "string" && BARE_SHA256_PATTERN.test(value.receipt_sha256));
+ responseRequires(hasExactAuthorityKeys(value, ["schema_version", "request_sha256", "status", "goal_ref",
+ "historical_only", "todo_id", "operation_id", "receipt_sha256"]));
+ responseOperationId(value.operation_id, request);
+ return value;
+ }
+ responseRequires(mode === "execute" && (request.operation === "read" && value.status === "found"
+ || request.operation === "snapshot" && value.status === "snapshot"));
+ const fields = value.status === "found" ? ["todo", "lease"] : ["goal_id", "store_identity", "receipt_sha256", "todos", "leases"];
+ responseRequires(hasExactAuthorityKeys(value, ["schema_version", "request_sha256", "status", "goal_ref", ...fields]));
+ }
if (["rejected", "unavailable", "ambiguous"].includes(value.status)) {
remoteAuthorityId(value.reason_code, "response reason");
responseRequires(value.status !== "ambiguous" || mode === "execute" && request.operation !== "read" && request.operation !== "snapshot");
@@ -319,12 +350,12 @@ export function decodeRemoteAuthorityResponse(raw: unknown, request: RemoteAutho
} else if (mode === "execute" && request.operation === "read") {
if (value.status !== "missing") {
responseRequires(value.status === "found");
- responseRevision(value.provider_revision, request);
- responseTodo(value.todo, request.todo_id);
- if (value.lease !== null) responseLease(value.lease, request, false);
+ if (!goalRef) responseRevision(value.provider_revision, request);
+ responseTodo(value.todo, request.todo_id, scoped);
+ if (value.lease !== null) responseLease(value.lease, request, false, scoped);
}
} else if (mode === "execute" && request.operation === "snapshot") {
- responseSnapshot(value, request);
+ responseSnapshot(value, request, goalRef);
} else {
responseRequires(mode === "execute" && request.operation !== "read" && request.operation !== "snapshot" && value.status === "result");
responseCommand(value.result, request, responseOperationId(value.operation_id, request), false);
diff --git a/loopx/control_plane/coordination/remote_authority_policy.ts b/loopx/control_plane/coordination/remote_authority_policy.ts
index 712d22a2e8..79b09459e6 100644
--- a/loopx/control_plane/coordination/remote_authority_policy.ts
+++ b/loopx/control_plane/coordination/remote_authority_policy.ts
@@ -4,30 +4,63 @@ import {createHash, timingSafeEqual} from "node:crypto";
import {open} from "node:fs/promises";
import type {JsonObject} from "../effect_program.ts";
import {BARE_SHA256_PATTERN} from "../content_digest.ts";
+import {parseWireExactGoalRef, sameExactGoalRef, type WireExactGoalRef} from "../goals/acceptance_lifecycle.ts";
+import {normalizeTodoId} from "../work_items/task_lease_acquire.ts";
import {canonicalAuthorityObject, canonicalAuthoritySha256, hasExactAuthorityKeys} from "./authority_store_codec.ts";
import {POSTGRESQL_STORE_IDENTITY_PATTERN} from "./postgresql_authority_store.ts";
-import {REMOTE_AUTHORITY_OPERATIONS, remoteAuthorityId, type RemoteAuthorityRequest} from "./remote_authority_contract.ts";
+import {REMOTE_AUTHORITY_OPERATIONS, remoteAuthorityId, remoteAuthorityOperationId,
+ type RemoteAuthorityMode, type RemoteAuthorityRequest} from "./remote_authority_contract.ts";
import type {RemoteAuthorityAdmission} from "./remote_authority_service.ts";
export const REMOTE_AUTHORITY_POLICY = "loopx_remote_authority_policy_v0";
+export const REMOTE_AUTHORITY_SCOPED_READ_POLICY = "loopx_remote_authority_scoped_read_policy_v1";
const sameScope = (a: JsonObject, b: {tenant_id: string; goal_id: string; store_identity: string}) =>
a.tenant_id === b.tenant_id && a.goal_id === b.goal_id && a.store_identity === b.store_identity;
-function object(value: unknown, keys: string[], name: string): JsonObject {
+function object(value: unknown, keys: string[], name: string, optionalKeys: string[] = []): JsonObject {
const result = canonicalAuthorityObject(value, name);
- if (!hasExactAuthorityKeys(result, keys)) throw new TypeError(`Invalid ${name}`);
+ if (!hasExactAuthorityKeys(result, [...keys, ...optionalKeys.filter(key => Object.hasOwn(result, key))])) {
+ throw new TypeError(`Invalid ${name}`);
+ }
return result;
}
export function decodeRemoteAuthorityPolicy(value: unknown): JsonObject {
const policy = object(value, ["schema_version", "scopes", "principals"], "service policy");
- if (policy.schema_version !== REMOTE_AUTHORITY_POLICY || !Array.isArray(policy.scopes) ||
+ const scoped = policy.schema_version === REMOTE_AUTHORITY_SCOPED_READ_POLICY;
+ if (!(scoped || policy.schema_version === REMOTE_AUTHORITY_POLICY) || !Array.isArray(policy.scopes) ||
!Array.isArray(policy.principals) || policy.scopes.length > 128 || policy.principals.length > 256) throw new TypeError("Invalid service policy");
const scopes = policy.scopes.map(raw => {
- const scope = object(raw, ["tenant_id", "goal_id", "store_identity", "registered_agents"], "service scope");
+ const scope = object(raw, ["tenant_id", "goal_id", "store_identity", "registered_agents",
+ ...(scoped ? ["todo_read_acl"] : [])], "service scope");
remoteAuthorityId(scope.tenant_id, "tenant"); remoteAuthorityId(scope.goal_id, "Goal");
if (typeof scope.store_identity !== "string" || !POSTGRESQL_STORE_IDENTITY_PATTERN.test(scope.store_identity) ||
!Array.isArray(scope.registered_agents) || scope.registered_agents.length === 0 || scope.registered_agents.length > 128) throw new TypeError("Invalid service scope");
scope.registered_agents.forEach(a => remoteAuthorityId(a, "registered actor"));
if (new Set(scope.registered_agents).size !== scope.registered_agents.length) throw new TypeError("Duplicate registered actor");
+ if (scoped) {
+ if (!Array.isArray(scope.todo_read_acl)) throw new TypeError("Invalid Todo read ACL");
+ const actors = new Set(scope.registered_agents), entries = new Set();
+ for (const rawEntry of scope.todo_read_acl) {
+ const entry = object(rawEntry, ["goal_ref", "todo_id", "principal_id", "actor_id"],
+ "Todo read ACL entry", ["receipt_operation_ids", "todo_origin_operation_id"]);
+ const goal = parseWireExactGoalRef(entry.goal_ref, "Todo read ACL Goal");
+ remoteAuthorityId(entry.principal_id, "ACL principal");
+ remoteAuthorityId(entry.todo_id, "ACL Todo");
+ if (goal.goal_id !== scope.goal_id || !actors.has(entry.actor_id) || normalizeTodoId(entry.todo_id) !== entry.todo_id) {
+ throw new TypeError("Invalid Todo read ACL scope");
+ }
+ const key = JSON.stringify([goal.goal_instance_id, entry.todo_id, entry.principal_id, entry.actor_id]);
+ if (entries.has(key)) throw new TypeError("Duplicate Todo read ACL entry");
+ entries.add(key);
+ if (Object.hasOwn(entry, "todo_origin_operation_id")) {
+ remoteAuthorityId(entry.todo_origin_operation_id, "Todo origin operation");
+ }
+ if (Object.hasOwn(entry, "receipt_operation_ids")) {
+ const ids = entry.receipt_operation_ids;
+ if (!Array.isArray(ids) || new Set(ids).size !== ids.length) throw new TypeError("Invalid receipt read ACL");
+ ids.forEach(id => remoteAuthorityId(id, "receipt ACL operation"));
+ }
+ }
+ }
return scope;
});
const scopeKeys = scopes.map(s => JSON.stringify([s.tenant_id, s.goal_id]));
@@ -39,12 +72,15 @@ export function decodeRemoteAuthorityPolicy(value: unknown): JsonObject {
!Array.isArray(principal.grants) || principal.grants.length > 128) throw new TypeError("Invalid principal");
const seen = new Set();
principal.grants.forEach(rawGrant => {
- const grant = object(rawGrant, ["tenant_id", "goal_id", "actor_id", "operations"], "grant");
+ const grant = object(rawGrant, ["tenant_id", "goal_id", "actor_id", "operations",
+ ...(scoped ? ["goal_ref"] : [])], "grant");
const scope = scopes.find(s => s.tenant_id === grant.tenant_id && s.goal_id === grant.goal_id);
if (!scope || !(scope.registered_agents as string[]).includes(String(grant.actor_id)) ||
!Array.isArray(grant.operations) || grant.operations.length === 0 ||
grant.operations.some(op => !REMOTE_AUTHORITY_OPERATIONS.includes(op as typeof REMOTE_AUTHORITY_OPERATIONS[number])) ||
new Set(grant.operations).size !== grant.operations.length) throw new TypeError("Invalid grant");
+ if (scoped && (parseWireExactGoalRef(grant.goal_ref, "read grant Goal").goal_id !== grant.goal_id ||
+ grant.operations.some(op => op !== "read" && op !== "snapshot"))) throw new TypeError("Invalid scoped read grant");
const key = JSON.stringify([grant.tenant_id, grant.goal_id, grant.actor_id]);
if (seen.has(key)) throw new TypeError("Duplicate grant");
seen.add(key);
@@ -58,24 +94,50 @@ export function decodeRemoteAuthorityPolicy(value: unknown): JsonObject {
}
export function remoteAuthorityPolicyAdmission(policy: JsonObject, credential: string,
- request: RemoteAuthorityRequest): RemoteAuthorityAdmission {
+ request: RemoteAuthorityRequest, mode: RemoteAuthorityMode = "execute"): RemoteAuthorityAdmission {
const digest = createHash("sha256").update(credential).digest();
const principal = (policy.principals as JsonObject[]).find(p =>
timingSafeEqual(Buffer.from(String(p.credential_sha256), "hex"), digest));
if (!principal) return {status: "rejected", reason_code: "principal_unauthenticated"};
const scope = (policy.scopes as JsonObject[]).find(s => sameScope(s, request));
+ const scoped = policy.schema_version === REMOTE_AUTHORITY_SCOPED_READ_POLICY;
+ const recoverScoped = scoped && mode === "recover";
+ const operation = recoverScoped ? "read" : request.operation;
const grant = (principal.grants as JsonObject[]).find(g => g.tenant_id === request.tenant_id &&
- g.goal_id === request.goal_id && g.actor_id === request.actor_id && (g.operations as string[]).includes(request.operation));
+ g.goal_id === request.goal_id && g.actor_id === request.actor_id && (g.operations as string[]).includes(operation));
if (!scope || !grant) return {status: "rejected", reason_code: "remote_authority_scope_denied"};
- return {status: "allowed", principal_id: String(principal.principal_id),
+ const allowed = {status: "allowed" as const, principal_id: String(principal.principal_id),
policy_revision: canonicalAuthoritySha256(policy), registered_agents: [...scope.registered_agents as string[]]};
+ if (!scoped) return allowed;
+
+ const goalRef = grant.goal_ref as WireExactGoalRef;
+ const entries = (scope.todo_read_acl as JsonObject[])
+ .filter(entry => entry.principal_id === principal.principal_id && entry.actor_id === request.actor_id &&
+ sameExactGoalRef(entry.goal_ref as WireExactGoalRef, goalRef));
+ const todoIds = entries.map(entry => String(entry.todo_id));
+ if (todoIds.length === 0 || request.todo_id !== undefined && !todoIds.includes(request.todo_id)) {
+ return {status: "rejected", reason_code: "remote_authority_scope_denied"};
+ }
+ const readScope = {goal_ref: goalRef, todo_ids: todoIds,
+ todo_origins: Object.fromEntries(entries.filter(entry => entry.todo_origin_operation_id !== undefined)
+ .map(entry => [String(entry.todo_id), String(entry.todo_origin_operation_id)]))};
+ if (!recoverScoped) return {...allowed, read_scope: readScope};
+ const id = remoteAuthorityOperationId(request, allowed.principal_id);
+ if (!entries.some(entry => entry.todo_id === request.todo_id &&
+ (entry.receipt_operation_ids as string[] | undefined)?.includes(id))) {
+ return {status: "rejected", reason_code: "remote_authority_scope_denied"};
+ }
+ return {...allowed, read_scope: {...readScope, receipt_operation_id: id}};
}
-export function fileRemoteAuthorityAdmission(path: string) {
- return async (credential: string, request: RemoteAuthorityRequest): Promise => {
+export function fileRemoteAuthorityAdmission(path: string, expectedSchema: string = REMOTE_AUTHORITY_POLICY) {
+ return async (credential: string, request: RemoteAuthorityRequest,
+ mode: RemoteAuthorityMode = "execute"): Promise => {
// A rename publishes one complete policy. Missing, malformed or unreadable
// policy fails closed; never retain a stale last-known-good grant.
- return remoteAuthorityPolicyAdmission(await readRemoteAuthorityPolicy(path), credential, request);
+ const policy = await readRemoteAuthorityPolicy(path);
+ if (policy.schema_version !== expectedSchema) throw new TypeError("Service policy schema changed; restart the listener");
+ return remoteAuthorityPolicyAdmission(policy, credential, request, mode);
};
}
diff --git a/loopx/control_plane/coordination/remote_authority_service.ts b/loopx/control_plane/coordination/remote_authority_service.ts
index 75f045e7e0..eff348b4d3 100644
--- a/loopx/control_plane/coordination/remote_authority_service.ts
+++ b/loopx/control_plane/coordination/remote_authority_service.ts
@@ -1,32 +1,36 @@
/** Authenticated task commands over the existing semantic and persistence owners. */
import type {JsonObject} from "../effect_program.ts";
import type {AuthorityStore, AuthorityStoreReadFailure} from "./authority_store.ts";
-import {canonicalAuthoritySha256} from "./authority_store_codec.ts";
+import {canonicalAuthoritySha256, parseAuthorityCursor} from "./authority_store_codec.ts";
import {PostgreSqlAuthorityService} from "./postgresql_authority_service.ts";
import type {PostgreSqlAuthorityDatabase} from "./postgresql_authority_store.ts";
import {executeCoordinationTodoClaim} from "./todo_claim.ts";
import {executeCoordinationTodoUpdate} from "./todo_update.ts";
-import {executeCoordinationTodoCreate} from "./todo_create.ts";
+import {executeCoordinationTodoCreate, COORDINATION_TODO_CREATE_RECEIPT_SCHEMA} from "./todo_create.ts";
import {executeCoordinationTodoTerminalLifecycle, type CoordinationTodoTerminalLifecycleInput} from "./todo_terminal_lifecycle.ts";
import {executeCanonicalTaskLeaseLifecycle} from "./task_lease_lifecycle.ts";
import {leaseVersion, leaseEpoch} from "../work_items/task_lease_acquire.ts";
import {TODO_DOMAIN_ITEM_SCHEMA} from "./coordination_state_contract.ts";
-import {indexCoordinationProjection, validateCoordinationTodoReadModel} from "./coordination_projection.ts";
-import {decodeRemoteAuthorityRequest, remoteAuthorityOperationId, remoteAuthorityResponse, remoteAuthoritySnapshotDigest,
+import {CoordinationProjectionRead} from "./coordination_projection.ts";
+import {GOAL_ACCEPTANCE_LIFECYCLE_OPERATION_SCHEMA, readGoalAcceptanceLifecycle, sameExactGoalRef, type WireExactGoalRef} from "../goals/acceptance_lifecycle.ts";
+import {decodeRemoteAuthorityRequest, remoteAuthorityOperationId, remoteAuthorityResponse, remoteAuthoritySnapshotDigest, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE,
type RemoteAuthorityMode, type RemoteAuthorityRequest} from "./remote_authority_contract.ts";
export type RemoteAuthorityAdmission =
- | {status: "allowed"; principal_id: string; policy_revision: string; registered_agents: readonly string[]}
+ | {status: "allowed"; principal_id: string; policy_revision: string; registered_agents: readonly string[];
+ read_scope?: {goal_ref: WireExactGoalRef; todo_ids: readonly string[];
+ todo_origins: Readonly>; receipt_operation_id?: string}}
| {status: "rejected"; reason_code: string};
export interface RemoteAuthorityDependencies {
database: PostgreSqlAuthorityDatabase;
/** One immutable, server-owned authorization decision per request. Revocation
* affects later admissions; it never lies about an already admitted commit. */
- admit(credential: string, request: RemoteAuthorityRequest): Promise;
+ admit(credential: string, request: RemoteAuthorityRequest, mode: RemoteAuthorityMode): Promise;
now?: () => Date;
}
const incarnationFailure: AuthorityStoreReadFailure = {status: "unavailable",
reason_code: "remote_authority_incarnation_changed", reason: "Rebind the authorized service scope before continuing"};
+const scopeDenied = {status: "rejected", reason_code: "remote_authority_scope_denied"} as const;
const MAX_READ_NOTE_BYTES = 4096;
/** Pin every observation and write to the admitted incarnation. The provider's
@@ -82,8 +86,9 @@ function pinnedStore(store: AuthorityStore, identity: string, admission: JsonObj
};
}
-function projectReadTodo(todo: JsonObject, includePlanning: boolean): JsonObject {
- const fields = ["todo_id", "status", "claimed_by", "note", ...(includePlanning ? ["role", "priority"] : [])];
+function projectReadTodo(todo: JsonObject, includePlanning: boolean, includeNote: boolean): JsonObject {
+ const fields = ["todo_id", "status", "claimed_by", ...(includeNote ? ["note"] : []),
+ ...(includePlanning ? ["role", "priority"] : [])];
const output = Object.fromEntries(fields.filter(field => Object.hasOwn(todo, field)).map(field => [field, todo[field]]));
if (Object.hasOwn(output, "note") && Buffer.byteLength(JSON.stringify(output.note)) > MAX_READ_NOTE_BYTES) {
delete output.note;
@@ -92,6 +97,69 @@ function projectReadTodo(todo: JsonObject, includePlanning: boolean): JsonObject
return output;
}
+function isActiveGoal(head: JsonObject, goalRef: WireExactGoalRef): boolean {
+ const lifecycle = readGoalAcceptanceLifecycle(head, goalRef.goal_id);
+ return lifecycle?.state === "active" && sameExactGoalRef(lifecycle.goal_ref, goalRef);
+}
+
+/** Reconstruct one exact committed operation through the existing checkpoint
+ * owner. Proof is bounded by the admitted head; neither current state nor a
+ * later receipt can substitute for missing historical evidence. */
+async function readScopedTransaction(store: AuthorityStore, headCursor: string,
+ goalRef: WireExactGoalRef, operationId: string) {
+ const unavailable = {status: "unavailable", reason_code: "remote_authority_read_unavailable"} as const;
+ const receipt = await store.readReceipt(operationId);
+ if (receipt.status !== "found") return receipt.status === "missing" ||
+ receipt.reason_code === "remote_authority_operation_mismatch" ? scopeDenied : unavailable;
+ const cursor = parseAuthorityCursor(receipt.cursor);
+ if (cursor > parseAuthorityCursor(headCursor) || receipt.receipts.length !== 1) return scopeDenied;
+ const offset = cursor - 1n;
+ const page = await store.scanCommitted(offset === 0n ? null : offset.toString(), 1);
+ if (page.status !== "page" || page.transactions.length !== 1) return unavailable;
+ const transaction = page.transactions[0]!;
+ const original = receipt.receipts[0]!;
+ const digest = canonicalAuthoritySha256(original);
+ if (transaction.cursor !== receipt.cursor || transaction.provider_revision !== receipt.provider_revision ||
+ transaction.operation_id !== operationId || transaction.receipts.length !== 1 ||
+ canonicalAuthoritySha256(transaction.receipts[0]) !== digest) return unavailable;
+ if (!isActiveGoal(transaction.projection, goalRef)) return scopeDenied;
+ return {status: "found" as const, original, projection: transaction.projection, digest};
+}
+
+/** The policy selects evidence, not resource ownership. Only a successful Todo
+ * creation or the trusted first bind of existing work can prove its lifetime.
+ * A claim/update, successor activation or idempotent rebind cannot relabel it. */
+function provesTodoOrigin(proof: Extract>, {status: "found"}>,
+ goalRef: WireExactGoalRef, todoId: string): boolean {
+ const read = new CoordinationProjectionRead(proof.projection, goalRef.goal_id);
+ read.validateTodoReadModel();
+ const todo = read.todoIndex.todos.get(todoId);
+ if (!todo || proof.original.goal_id !== goalRef.goal_id) return false;
+ if (proof.original.schema_version === COORDINATION_TODO_CREATE_RECEIPT_SCHEMA) {
+ return proof.original.todo_id === todoId && canonicalAuthoritySha256(proof.original.todo) === canonicalAuthoritySha256(todo);
+ }
+ const result = proof.original.result;
+ return proof.original.schema_version === GOAL_ACCEPTANCE_LIFECYCLE_OPERATION_SCHEMA &&
+ proof.original.request_sha256 === canonicalAuthoritySha256({transition: {kind: "bind_existing", goal_ref: goalRef}}) &&
+ result !== null && typeof result === "object" && !Array.isArray(result) && (result as JsonObject).changed === true;
+}
+
+/** Authorize from the current pinned head, then prove the original transaction
+ * belonged to the same Goal lifetime. Operation access stays separate from
+ * current Todo access and never returns the original execution payload. */
+async function readScopedReceipt(store: AuthorityStore, goalRef: WireExactGoalRef,
+ todoId: string, operationId: string): Promise {
+ const head = await store.loadAuthority();
+ if (head.status !== "loaded") return {status: "unavailable", reason_code: "remote_authority_read_unavailable"};
+ if (!isActiveGoal(head.head, goalRef)) return scopeDenied;
+ const current = new CoordinationProjectionRead(head.head, goalRef.goal_id);
+ current.validateTodoReadModel();
+ if (!current.todoIndex.todos.has(todoId)) return scopeDenied;
+ const proof = await readScopedTransaction(store, head.cursor, goalRef, operationId);
+ if (proof.status !== "found") return proof;
+ return {status: "found", historical_only: true, todo_id: todoId, operation_id: operationId, receipt_sha256: proof.digest};
+}
+
/** Deliberately bounded response projection: no SQL errors, paths, arbitrary
* canonical fields, workspace observations or provider credentials cross here. */
function commandResult(result: JsonObject): JsonObject {
@@ -135,9 +203,16 @@ export class RemoteAuthorityService {
return reply({status: "rejected", reason_code: "invalid_remote_authority_mode"});
}
let admission: RemoteAuthorityAdmission;
- try { admission = structuredClone(await this.#dependencies.admit(credential, request)); }
+ try { admission = structuredClone(await this.#dependencies.admit(credential, request, mode)); }
catch { return reply({status: "unavailable", reason_code: "remote_authority_policy_unavailable"}); }
if (admission.status !== "allowed") return reply(admission);
+ const isRead = request.operation === "read" || request.operation === "snapshot";
+ const readScope = admission.read_scope;
+ const allowedTodos = readScope && new Set(readScope.todo_ids);
+ const operationId = remoteAuthorityOperationId(request, admission.principal_id);
+ if (allowedTodos && (allowedTodos.size === 0 || request.todo_id && !allowedTodos.has(request.todo_id))) return reply(scopeDenied);
+ if (readScope && !isRead && (mode !== "recover" || request.todo_id === undefined ||
+ readScope.receipt_operation_id !== operationId)) return reply(scopeDenied);
// Open through the established service seam with the already authenticated
// snapshot. Never re-evaluate a different policy halfway through a request.
const service = new PostgreSqlAuthorityService({database: this.#dependencies.database,
@@ -145,7 +220,6 @@ export class RemoteAuthorityService {
authorizeTenant: () => ({status: "allowed"})});
const opened = await service.openStore({...request, credential: null});
if (opened.status !== "opened") return reply({status: "unavailable", reason_code: opened.reason_code});
- const operationId = remoteAuthorityOperationId(request, admission.principal_id);
// Explicitly reauthorizing a restored incarnation may recover old history.
// The incarnation gates current access; it is not part of business intent.
const {store_identity: admittedIdentity, ...intent} = request;
@@ -155,7 +229,13 @@ export class RemoteAuthorityService {
const store = pinnedStore(opened.store, request.store_identity, binding, operationId);
let dispatched = false;
try {
- const previous = (request.operation === "read" || request.operation === "snapshot") ? null : await store.readReceipt(operationId);
+ if (readScope && mode === "recover" && request.todo_id !== undefined) {
+ const result = await readScopedReceipt(store, readScope.goal_ref, request.todo_id, operationId);
+ return result.status === "found"
+ ? remoteAuthorityResponse(request, mode, {...result, goal_ref: readScope.goal_ref}, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE)
+ : reply(result);
+ }
+ const previous = isRead ? null : await store.readReceipt(operationId);
if (previous?.status === "found") {
const original = previous.receipts[0];
const recorded = original?.remote_admission as JsonObject | undefined;
@@ -175,22 +255,44 @@ export class RemoteAuthorityService {
if (mode === "recover") return reply({status: "missing", operation_id: operationId});
const head = await store.loadAuthority();
if (head.status !== "loaded") return reply({status: "unavailable", reason_code: "remote_authority_head_unavailable"});
- validateCoordinationTodoReadModel(head.head, request.goal_id);
- const index = indexCoordinationProjection(head.head, request.goal_id);
+ if (readScope && !isActiveGoal(head.head, readScope.goal_ref)) return reply(scopeDenied);
+ const projection = new CoordinationProjectionRead(head.head, request.goal_id);
+ projection.validateTodoReadModel();
+ const index = projection.coordinationIndex;
+ const provenTodos = readScope ? new Set() : undefined;
+ if (readScope && provenTodos) {
+ // One request-local proof per origin, shared by Todos first bound in
+ // the same transaction. Never cache authorization across admissions.
+ const proofs = new Map>>();
+ for (const id of readScope.todo_ids) {
+ if (request.todo_id && request.todo_id !== id || !index.todos.has(id)) continue;
+ const origin = readScope.todo_origins[id];
+ if (!origin) continue;
+ let proof = proofs.get(origin);
+ if (!proof) { proof = await readScopedTransaction(store, head.cursor, readScope.goal_ref, origin); proofs.set(origin, proof); }
+ if (proof.status === "unavailable") return reply(proof);
+ if (proof.status === "found" && provesTodoOrigin(proof, readScope.goal_ref, id)) provenTodos.add(id);
+ }
+ if (request.todo_id ? !provenTodos.has(request.todo_id) : provenTodos.size === 0) return reply(scopeDenied);
+ }
+ const replyRead = (payload: JsonObject) => readScope
+ ? remoteAuthorityResponse(request, mode, {...payload, goal_ref: readScope.goal_ref}, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE)
+ : reply({...payload, provider_revision: head.provider_revision});
if (request.operation === "read") {
const todo = index.todos.get(request.todo_id), lease = index.leases.get(request.todo_id);
if (!todo) return reply({status: "missing"});
- return reply({status: "found", provider_revision: head.provider_revision,
- todo: projectReadTodo(todo, false),
+ return replyRead({status: "found",
+ todo: projectReadTodo(todo, false, readScope === undefined),
lease: lease ? {...Object.fromEntries(["owner", "status", "expires_at"].filter(k => k in lease).map(k => [k, lease[k]])),
version: leaseVersion(lease), lease_epoch: leaseEpoch(lease)} : null});
}
if (request.operation === "snapshot") {
+ const visible = (id: string) => (!request.todo_id || id === request.todo_id) && (!allowedTodos || allowedTodos.has(id)) && (!provenTodos || provenTodos.has(id));
const todos = index.todo_ids
- .filter(id => !request.todo_id || id === request.todo_id)
- .map(id => projectReadTodo(index.todos.get(id)!, true));
+ .filter(visible)
+ .map(id => projectReadTodo(index.todos.get(id)!, true, readScope === undefined));
const leases = index.lease_todo_ids
- .filter(id => !request.todo_id || id === request.todo_id)
+ .filter(visible)
.map(id => {
const l = index.leases.get(id)!;
return {
@@ -199,12 +301,11 @@ export class RemoteAuthorityService {
lease_epoch: leaseEpoch(l),
};
});
- return reply({
+ return replyRead({
status: "snapshot",
- provider_revision: head.provider_revision,
store_identity: request.store_identity,
goal_id: request.goal_id,
- receipt_sha256: remoteAuthoritySnapshotDigest(request, head.provider_revision, todos, leases),
+ receipt_sha256: remoteAuthoritySnapshotDigest(request, head.provider_revision, todos, leases, readScope?.goal_ref),
todos,
leases,
});
@@ -290,6 +391,7 @@ export class RemoteAuthorityService {
expected_version: request.expected_version, ttl_seconds: request.operation === "renew" ? request.ttl_seconds : null});
return reply({status: "result", operation_id: operationId, result: commandResult(result)});
} catch {
+ if (readScope) return reply({status: "unavailable", reason_code: "remote_authority_read_unavailable"});
return reply({status: dispatched ? "ambiguous" : "unavailable", operation_id: operationId,
reason_code: dispatched ? "remote_authority_recovery_required" : "remote_authority_read_unavailable"});
}
diff --git a/loopx/control_plane/coordination/todo_lifecycle_decision.ts b/loopx/control_plane/coordination/todo_lifecycle_decision.ts
index 1a0d63bc71..dbaff1eda3 100644
--- a/loopx/control_plane/coordination/todo_lifecycle_decision.ts
+++ b/loopx/control_plane/coordination/todo_lifecycle_decision.ts
@@ -391,7 +391,17 @@ function authority(request: LifecycleDecisionRequest):
if (actor !== null) {
const rejection = registeredTodoMutationRejection(todo, actor, registered);
if (rejection !== null) return result("rejected", rejection);
- } else if (todo.claimed_by !== null || todo.bound_agent !== null ||
+ return { mode: "single_agent_compatibility", ownershipGate: "not_required" };
+ }
+ // Single-agent goals have no second agent to act for the owner, and the
+ // terminal CLI has no human owner actor, so an actorless owner decision
+ // closing an exact linked user gate uses the same override as multi-agent
+ // mode. The override requires the exact decision scope link; unlinked
+ // owned/bound/excluded records still require an accountable actor.
+ if (exactUserGateOverride(request)) {
+ return { mode: "exact_user_gate_decision_scope_override", ownershipGate: "not_required" };
+ }
+ if (todo.claimed_by !== null || todo.bound_agent !== null ||
todo.blocks_agent !== null || todo.excluded_agents.length > 0) {
// Actorless compatibility is limited to genuinely unowned Todo records;
// ownership, binding, and exclusion facts require an accountable actor.
@@ -468,6 +478,23 @@ function terminalFence(
? {...lease, active: false, status: "released"} : null,
});
}
+ // In single-agent goals there is no peer set to attribute an execution
+ // lease across, and the terminal CLI has no human owner actor: an owner
+ // decision on an exact linked user gate records a decision rather than
+ // executing work, and retires any expired lease lineage with the Todo
+ // transition. Multi-agent hard-lease goals keep their attributed-actor
+ // gate contract, registered actors keep the ordinary lease requirement, and
+ // an active holder or an explicitly supplied fence is never bypassed.
+ if (request.registered_agents.length <= 1 && request.command === "complete" &&
+ authorityMode === "exact_user_gate_decision_scope_override" &&
+ request.todo.role === "user" && request.todo.task_class === "user_gate" &&
+ request.actor_agent_id === null && !timeActive && !explicitFence) {
+ return result("apply", "terminal_fence_not_required", {
+ authority_mode: authorityMode, lease_fence: "not_required",
+ next_lease: lease?.present && lease.status !== "released"
+ ? {...lease, active: false, status: "released"} : null,
+ });
+ }
// Deferred work cannot acquire a lease. Superseding a retired wait is a
// terminal lifecycle edit, not execution, and the provider CAS retires any
// expired lease lineage together with the Todo transition.
diff --git a/loopx/control_plane/goals/acceptance_authority.ts b/loopx/control_plane/goals/acceptance_authority.ts
index d68cf6e30a..554d59b158 100644
--- a/loopx/control_plane/goals/acceptance_authority.ts
+++ b/loopx/control_plane/goals/acceptance_authority.ts
@@ -17,7 +17,7 @@ import {GOAL_ACCEPTANCE_SCHEMA, clearedGoalAcceptance, acceptanceKeys, acceptanc
resolveGoalAcceptanceDocument, projectGoalAcceptance, readGoalAcceptance, readGoalAcceptanceAuthority,
type AcceptanceDocument, type AcceptanceState, type AcceptanceVerification} from "./acceptance_contract.ts";
import { BARE_SHA256_PATTERN } from "../content_digest.ts";
-import {GOAL_ACCEPTANCE_LIFECYCLE_SCHEMA, parseGoalAcceptanceLifecycleTransition, parseWireExactGoalRef,
+import {GOAL_ACCEPTANCE_LIFECYCLE_SCHEMA, GOAL_ACCEPTANCE_LIFECYCLE_OPERATION_SCHEMA, parseGoalAcceptanceLifecycleTransition, parseWireExactGoalRef,
readGoalAcceptanceLifecycle, sameExactGoalRef, type GoalAcceptanceLifecycle,
type GoalAcceptanceLifecycleTransition, type WireExactGoalRef} from "./acceptance_lifecycle.ts";
@@ -27,7 +27,7 @@ import {projectCoreGoal} from "../work_items/replan_context.ts";
const RESULT_SCHEMA = "loopx_goal_acceptance_result_v0";
const RECEIPT_SCHEMA = "loopx_goal_acceptance_operation_v0";
-const LIFECYCLE_RECEIPT_SCHEMA = "loopx_goal_acceptance_lifecycle_operation_v0";
+const LIFECYCLE_RECEIPT_SCHEMA = GOAL_ACCEPTANCE_LIFECYCLE_OPERATION_SCHEMA;
const REQUEST_FIELDS = ["goal_id", "operation_id", "actor_agent_id", "expected_provider_revision"];
const LOCAL_FIELDS = ["runtime_root", "dry_run"];
diff --git a/loopx/control_plane/goals/acceptance_lifecycle.ts b/loopx/control_plane/goals/acceptance_lifecycle.ts
index ab4a35294d..102de76144 100644
--- a/loopx/control_plane/goals/acceptance_lifecycle.ts
+++ b/loopx/control_plane/goals/acceptance_lifecycle.ts
@@ -3,6 +3,7 @@ import {AuthorityStoreProtocolError, canonicalAuthorityObject} from "../coordina
import {parseExactGoalRef} from "./goal_instance_identity.ts";
export const GOAL_ACCEPTANCE_LIFECYCLE_SCHEMA = "loopx_goal_acceptance_lifecycle_v0";
+export const GOAL_ACCEPTANCE_LIFECYCLE_OPERATION_SCHEMA = "loopx_goal_acceptance_lifecycle_operation_v0";
export interface WireExactGoalRef extends JsonObject {
goal_id: string;
diff --git a/loopx/control_plane/quota/accounting_artifact_transaction.ts b/loopx/control_plane/quota/accounting_artifact_transaction.ts
index 54867f699d..e70a5c7bb9 100644
--- a/loopx/control_plane/quota/accounting_artifact_transaction.ts
+++ b/loopx/control_plane/quota/accounting_artifact_transaction.ts
@@ -508,13 +508,35 @@ export function resolveQuotaAccountingEffect(
return { kind: "absent" };
}
+function spendIdentityMismatch(index: JsonObject, retained: JsonObject): boolean {
+ // The spend writers retain these bindings even before commit metadata was
+ // introduced. Missing historical fields are unknown; explicit conflicts are
+ // never authenticated by a matching timestamp or billing terms.
+ return ["agent_id", "effect_ref", "turn_instance_id", "todo_id",
+ "replan_obligation_id", "settlement_identity", "goal_ref"].some(field => {
+ const expected = index[field], actual = retained[field];
+ return expected !== undefined && expected !== null && expected !== "" &&
+ actual !== undefined && actual !== null && actual !== "" &&
+ canonicalJson(expected) !== canonicalJson(actual);
+ });
+}
+
export async function readQuotaSpendEventFromRun(
runsDir: string,
run: JsonObject,
goalId: string,
): Promise {
+ const contract = contractFor("spend");
+ const indexCommit = run[contract.metadataField];
const inline = jsonObject(run.quota_event);
- if (inline) return inline;
+ if (inline && indexCommit === undefined) {
+ if (spendIdentityMismatch(run, inline)) {
+ throw new EffectRuntimeRequestError(
+ "quota spend JSON artifact identity does not match its index row",
+ );
+ }
+ return inline;
+ }
if (typeof run.json_path !== "string" || !run.json_path.trim()) return null;
let targetPath: string;
try {
@@ -550,15 +572,30 @@ export async function readQuotaSpendEventFromRun(
throw new EffectRuntimeRequestError("quota spend JSON artifact is malformed");
}
const record = requiredObject(value, "quota spend JSON artifact");
+ const artifactCommit = jsonObject(record[contract.metadataField]);
+ // The writer repeats its commit identity in the index and artifact. An
+ // in-directory file can still describe a different debit for the same Goal.
+ const commitMismatch = indexCommit !== undefined && (
+ jsonObject(indexCommit) === null || artifactCommit === null ||
+ canonicalJson(indexCommit) !== canonicalJson(artifactCommit)
+ );
+ // A historical row without a commit reference can still have an explicit
+ // Run timestamp. Preserve omitted historical fields, but reject conflicts.
+ const timestampMismatch = typeof run.generated_at === "string" && run.generated_at !== "" &&
+ typeof record.generated_at === "string" && record.generated_at !== "" &&
+ run.generated_at !== record.generated_at;
+ const event = jsonObject(record.quota_event);
if (
- record.classification !== contractFor("spend").classification ||
- (record.goal_id !== undefined && record.goal_id !== goalId)
+ record.classification !== contract.classification ||
+ (record.goal_id !== undefined && record.goal_id !== goalId) ||
+ commitMismatch || timestampMismatch || spendIdentityMismatch(run, record) ||
+ (event !== null && spendIdentityMismatch(run, event))
) {
throw new EffectRuntimeRequestError(
"quota spend JSON artifact identity does not match its index row",
);
}
- return jsonObject(record.quota_event);
+ return event;
}
export async function lookupQuotaAccountingReplay(
diff --git a/loopx/control_plane/quota/heartbeat_receipt.py b/loopx/control_plane/quota/heartbeat_receipt.py
index b228abd519..0509b87b9a 100644
--- a/loopx/control_plane/quota/heartbeat_receipt.py
+++ b/loopx/control_plane/quota/heartbeat_receipt.py
@@ -1,5 +1,4 @@
from __future__ import annotations
-from .effective_action import EffectiveAction
from collections.abc import Callable, Mapping
from pathlib import Path
@@ -12,6 +11,7 @@
rollout_event_log_path,
)
from ..todos.contract import normalize_todo_id, normalize_todo_replan_obligation_id
+from .effective_action import EffectiveAction
from .effect_program import SettlementBindingKind, SettlementIdentity
from .error_codes import HeartbeatReceiptIdentityConflictError
from .settlement_workspace_causality import (
@@ -604,10 +604,18 @@ def requalify_bound_heartbeat_receipt(
if not isinstance(qualified_details, Mapping):
raise RuntimeError("TypeScript heartbeat work qualification details missing")
event_id = str(original.get("event_id") or "")
+ receipt_revision = str(
+ qualified_details.get("settlement_receipt_revision") or ""
+ )
+ summary = (
+ "same-Turn review guard upgraded without rebinding"
+ if receipt_revision == "review_guard_upgrade"
+ else "same-Turn work admission requalified without rebinding"
+ )
corrected = build_rollout_event(
goal_id=goal_id, goal_ref=goal_ref, event_kind="quota_should_run",
agent_id=agent_id, todo_id=todo_id, run_id=turn_instance_id, status=status,
- summary="same-Turn work admission requalified without rebinding",
+ summary=summary,
source_event_id=event_id, caused_by=event_id, details=dict(qualified_details),
)
_append_rollout_event_line(log_path, corrected)
diff --git a/loopx/control_plane/quota/live_decision.py b/loopx/control_plane/quota/live_decision.py
index 4105e66a1a..fde3e9c491 100644
--- a/loopx/control_plane/quota/live_decision.py
+++ b/loopx/control_plane/quota/live_decision.py
@@ -3,12 +3,15 @@
import shlex
from collections.abc import Callable, Mapping, Sequence
+from functools import partial
from pathlib import Path
from typing import Any
from ...quota import build_quota_should_run
from ...agent_registry import load_goal_from_registry, registered_agent_ids_for_goal
+from ...command_invocation import loopx_cli_argv
from ..agent_context import project_agent_context, project_goal_agent_context
+from ..agents.identity import build_quota_agent_identity
from ..runtime.time import now_utc_iso
from ..goals.activation import goal_owner_resume_id
from ..goals.goal_frontier.fallback_source import live_fallback_authority_items
@@ -34,10 +37,13 @@
replan_obligation_id_from_packet,
)
from ..todos.contract import normalize_todo_id
+from ..scheduler.arbitration import SchedulerArbitration
from ..scheduler.execution_context import (
SchedulerExecutionContextResolution,
resolve_scheduler_execution_context,
)
+from ..scheduler.scheduler_hint import build_scheduler_hint
+from ..scheduler.state import load_app_automation_scheduler_state
from .unsettled_host_turn import (
apply_unsettled_host_turn_recovery_if_required,
apply_receipt_bound_wait_recovery,
@@ -486,6 +492,7 @@ def bind_scheduler_followup_cli_routes(
scheduler_hint = payload.get("scheduler_hint")
if not isinstance(scheduler_hint, dict):
return
+ launcher_args = loopx_cli_argv()[1:]
app_packets = [
packet
for packet_key in ("app_automation", "codex_app")
@@ -532,13 +539,13 @@ def bind_scheduler_followup_cli_routes(
}
continue
bound_cli_args = list(cli_args)
- if bound_cli_args[0] != "--registry":
- bound_cli_args = [
- "--registry",
- str(registry_path.expanduser().resolve()),
- "--runtime-root",
- str(runtime_root.expanduser().resolve()),
- *bound_cli_args,
+ # Standalone Core emits an interpreter route. Its launcher
+ # arguments must precede the CLI's global options.
+ option_index = len(launcher_args) if cli_args[:len(launcher_args)] == launcher_args else 0
+ if bound_cli_args[option_index:option_index + 1] != ["--registry"]:
+ bound_cli_args[option_index:option_index] = [
+ "--registry", str(registry_path.expanduser().resolve()),
+ "--runtime-root", str(runtime_root.expanduser().resolve()),
]
safe_turn_instance_id = str(turn_instance_id or "").strip()
if safe_turn_instance_id and "--turn-instance-id" not in bound_cli_args:
@@ -737,7 +744,7 @@ def build_live_quota_should_run_decision(
if remote_config is not None:
# Use the same hard-pause precedence and keep fresh local selection
# outside the remote route, even when a TLS read succeeds.
- return _build_remote_authority_wait_decision(
+ payload = _build_remote_authority_wait_decision(
decision_status_payload, configured_goal=registered_goal or {},
goal_id=goal_id, agent_id=agent_id, remote_config=remote_config,
registry_path=registry_path, runtime_root=runtime_root, goal_ref=goal_ref,
@@ -747,6 +754,11 @@ def build_live_quota_should_run_decision(
turn_instance_id=turn_instance_id, receipt_bound_todo_id=receipt_bound_todo_id,
receipt_bound_replan_obligation_id=receipt_bound_replan_obligation_id,
)
+ bind_scheduler_followup_cli_routes(
+ payload, registry_path=registry_path, runtime_root=runtime_root,
+ turn_instance_id=turn_instance_id, source=route_source,
+ )
+ return payload
settlement_readback = read_heartbeat_settlement(
runtime_root,
goal_id=goal_id,
@@ -831,6 +843,13 @@ def build_live_quota_should_run_decision(
goal_id=goal_id,
agent_id=agent_id,
)
+ app_scheduler_state: dict[str, Any] | None = None
+
+ def observe_app_scheduler_state(readback: Mapping[str, Any]) -> None:
+ # A later recovery wait uses the same state this decision actually read.
+ nonlocal app_scheduler_state
+ app_scheduler_state = readback.get("state")
+
payload: dict[str, Any] = build_quota_should_run(
decision_status_payload,
goal_id=goal_id,
@@ -858,6 +877,7 @@ def build_live_quota_should_run_decision(
**receipt_bound_guard_fields,
turn_instance_id=turn_instance_id,
runtime_root=runtime_root,
+ app_scheduler_state_observer=observe_app_scheduler_state,
workspace_path=workspace_path,
goal_ref=goal_ref,
authoritative_fallback_todo_items=authoritative_fallback_todo_items,
@@ -928,6 +948,14 @@ def build_live_quota_should_run_decision(
agent_id=agent_id,
current_turn_instance_id=turn_instance_id,
available_capabilities=available_capabilities,
+ project_scheduler_hint=partial(
+ build_scheduler_hint, include_detail=include_scheduler_detail,
+ scheduler_execution_context=resolved_context,
+ available_capabilities=available_capabilities,
+ codex_app_scheduler_state=app_scheduler_state,
+ codex_app_current_rrule=observed_rrule,
+ codex_app_automation_id=observed_automation_id or None,
+ ),
scheduler_execution_context=resolved_context,
goal_ref=goal_ref,
owner_action_id=goal_owner_resume_id(registered_goal),
@@ -1050,6 +1078,24 @@ def _build_remote_authority_wait_decision(
}
if goal_ref is not None:
payload["goal_ref"] = dict(goal_ref)
+
+ def project_recovery_scheduler_hint(
+ decision: dict[str, Any], *, arbitration: SchedulerArbitration,
+ ) -> dict[str, Any]:
+ decision["agent_identity"] = build_quota_agent_identity(configured_goal, agent_id=agent_id)
+ host = scheduler_context.context
+ state = None
+ if scheduler_context.ok and host is not None and host.app_automation_applicable:
+ state = load_app_automation_scheduler_state(
+ runtime_root, goal_id=goal_id, agent_id=agent_id, surface=host.host_surface.value,
+ )
+ return build_scheduler_hint(
+ decision, arbitration=arbitration, include_detail=include_scheduler_detail,
+ available_capabilities=available_capabilities, scheduler_execution_context=scheduler_context,
+ codex_app_scheduler_state=state, codex_app_current_rrule=codex_app_rrule,
+ codex_app_automation_id=codex_app_automation_id,
+ )
+
if scope_matches and not settled:
if (receipt_bound_todo_id and agent_id and turn_instance_id and readback is not None
and readback.replay_phase is ReceiptBoundReplayPhase.SETTLEMENT_PENDING):
@@ -1068,6 +1114,7 @@ def _build_remote_authority_wait_decision(
payload, registry_path=registry_path, runtime_root=runtime_root, goal_id=goal_id,
agent_id=agent_id, current_turn_instance_id=turn_instance_id,
available_capabilities=available_capabilities, scheduler_execution_context=scheduler_context,
+ project_scheduler_hint=project_recovery_scheduler_hint,
goal_ref=goal_ref,
owner_action_id=goal_owner_resume_id(configured_goal),
):
diff --git a/loopx/control_plane/quota/prior_turn_closeout.ts b/loopx/control_plane/quota/prior_turn_closeout.ts
index 9f07b8416e..dce35507da 100644
--- a/loopx/control_plane/quota/prior_turn_closeout.ts
+++ b/loopx/control_plane/quota/prior_turn_closeout.ts
@@ -30,6 +30,8 @@ export interface PriorHostTurnCloseoutCandidate extends JsonObject {
/** The Todo id or autonomous replan obligation id, per `binding_kind`. */
binding_id: string;
settlement_effect_id: string | null;
+ /** The effective guard admitted an autonomous replan under this binding. */
+ admitted_replan?: true;
/** The effective guard admitted a replan under this Todo's settlement identity. */
admitted_todo_replan?: true;
}
@@ -43,6 +45,7 @@ function candidate(
binding: HeartbeatReceiptBinding,
turnInstanceId: string,
fact: HeartbeatReceiptFact,
+ admittedReplan: boolean,
admittedTodoReplan: boolean,
): PriorHostTurnCloseoutCandidate {
return {
@@ -51,15 +54,16 @@ function candidate(
binding_kind: binding.binding_kind,
binding_id: binding.binding_id,
settlement_effect_id: binding.settlement_effect_id,
+ ...(admittedReplan ? {admitted_replan: true as const} : {}),
...(admittedTodoReplan ? {admitted_todo_replan: true as const} : {}),
};
}
/**
- * Select prior Turns eligible for closeout readback. A Todo-bound replan
- * carries the Todo settlement identity and a separate semantic obligation.
- * It did not deliver a Todo, so its closeout marker can be false. Fresh
- * admission requires a verified outstanding writeback for this binding.
+ * Select prior Turns eligible for closeout readback. An admitted replan may
+ * carry either its legacy Todo settlement identity or its autonomous-replan
+ * identity. It did not deliver a Todo, so its closeout marker can be false.
+ * Fresh admission requires a verified outstanding writeback for this binding.
* Explicit pending-closeout discovery can also find admitted replans before
* writeback, whether their settlement identity is a Todo or an obligation.
*
@@ -120,9 +124,11 @@ export function selectCloseoutCandidates(
if (binding === null) continue;
const admittedReplan = admitsAutonomousReplan(effective, fact);
const admittedTodoReplan = admittedReplan && binding.binding_kind === "todo";
- if (!fact.closeout_required && !admittedTodoReplan &&
+ if (!fact.closeout_required && !admittedReplan &&
!(includeUnwrittenReplans && admittedReplan)) continue;
- candidates.push({candidate: candidate(binding, turnInstanceId, fact, admittedTodoReplan),
+ candidates.push({candidate: candidate(
+ binding, turnInstanceId, fact, admittedReplan, admittedTodoReplan,
+ ),
requireWritebackForRecovery: !fact.closeout_required && !includeUnwrittenReplans});
}
return {candidates, turnsValidated: validated};
diff --git a/loopx/control_plane/quota/settlement_cli.py b/loopx/control_plane/quota/settlement_cli.py
index 77f179f741..6883239ab5 100644
--- a/loopx/control_plane/quota/settlement_cli.py
+++ b/loopx/control_plane/quota/settlement_cli.py
@@ -1,9 +1,9 @@
"""CLI rollout helpers for heartbeat settlement identity and receipt wiring."""
from __future__ import annotations
-from .effective_action import EffectiveAction
import argparse
+import hashlib
from collections.abc import Mapping
from pathlib import Path
@@ -12,14 +12,18 @@
normalize_todo_replan_obligation_id,
)
from ..work_items.autonomous_replan_obligation import (
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION,
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID,
+ AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION,
replan_obligation_id_from_packet,
)
from .effect_program import SettlementIdentity
+from .effective_action import EffectiveAction
from .error_codes import HeartbeatReceiptIdentityConflictError
from .heartbeat_receipt import (
heartbeat_receipt_view,
- upgrade_identityless_heartbeat_receipt,
requalify_bound_heartbeat_receipt,
+ upgrade_identityless_heartbeat_receipt,
)
from .settlement import (
QuotaSettlementReadback,
@@ -47,22 +51,38 @@ def reconcile_existing_heartbeat_receipt(
receipt = existing
receipt_status = "replayed"
receipt_appended = False
- rollout_todo_id = quota_rollout_todo_id(payload, args)
- rollout_replan_obligation_id = quota_rollout_replan_obligation_id(payload, args)
- if rollout_todo_id or rollout_replan_obligation_id:
- existing_details_value = receipt.get("details")
- existing_details = (
- existing_details_value
- if isinstance(existing_details_value, Mapping)
- else {}
- )
- existing_todo_id = normalize_todo_id(existing_details.get("todo_id"))
- existing_replan_obligation_id = normalize_todo_replan_obligation_id(
- existing_details.get("replan_obligation_id")
+ existing_details_value = receipt.get("details")
+ existing_details = (
+ existing_details_value
+ if isinstance(existing_details_value, Mapping)
+ else {}
+ )
+ existing_todo_id = normalize_todo_id(existing_details.get("todo_id"))
+ existing_replan_obligation_id = normalize_todo_replan_obligation_id(
+ existing_details.get("replan_obligation_id")
+ )
+ existing_effect_id = str(
+ existing_details.get("settlement_effect_id") or ""
+ ).strip()
+ receipt_has_bound_identity = bool(
+ (existing_todo_id or existing_replan_obligation_id)
+ and existing_effect_id
+ )
+ if receipt_has_bound_identity:
+ # A committed heartbeat receipt is the authority for this Turn's
+ # settlement identity. The current projection can rotate from Todo
+ # delivery into autonomous replan (or the reverse) while the host is
+ # interrupted, but that later projection must not rebind the original
+ # effect. Explicit retry arguments are checked below against the
+ # receipt and its retained planning selection.
+ rollout_todo_id = existing_todo_id
+ rollout_replan_obligation_id = existing_replan_obligation_id
+ else:
+ rollout_todo_id = quota_rollout_todo_id(payload, args)
+ rollout_replan_obligation_id = quota_rollout_replan_obligation_id(
+ payload, args
)
- existing_effect_id = str(
- existing_details.get("settlement_effect_id") or ""
- ).strip()
+ if rollout_todo_id or rollout_replan_obligation_id:
expected_effect_id = SettlementIdentity(
goal_id=args.goal_id,
agent_id=args.agent_id,
@@ -70,7 +90,7 @@ def reconcile_existing_heartbeat_receipt(
turn_instance_id=turn_instance_id,
replan_obligation_id=rollout_replan_obligation_id,
).effect_id
- if (existing_todo_id or existing_replan_obligation_id) and existing_effect_id:
+ if receipt_has_bound_identity:
# A fully settled Turn owns its immutable receipt regardless of a
# later explicit CLI choice. The live decision has already read
# the exact settlement and projected ``heartbeat_settled_skip``;
@@ -82,14 +102,30 @@ def reconcile_existing_heartbeat_receipt(
)
if not settled_replay:
requested_todo_id = normalize_todo_id(args.todo_id)
- if requested_todo_id and requested_todo_id != existing_todo_id:
- raise HeartbeatReceiptIdentityConflictError(
- "heartbeat receipt settlement identity conflicts with the "
- "current selected Todo: explicitly requested Todo differs"
- )
requested_replan_obligation_id = normalize_todo_replan_obligation_id(
getattr(args, "replan_obligation_id", None)
)
+ if requested_todo_id and requested_replan_obligation_id:
+ raise ValueError(
+ "quota rollout cannot bind both todo_id and "
+ "replan_obligation_id"
+ )
+ if requested_todo_id:
+ if existing_todo_id and requested_todo_id != existing_todo_id:
+ raise HeartbeatReceiptIdentityConflictError(
+ "heartbeat receipt settlement identity conflicts with the "
+ "current selected Todo: explicitly requested Todo differs"
+ )
+ if existing_replan_obligation_id:
+ retained_todo_id = normalize_todo_id(
+ existing_details.get("pending_action_selection_todo_id")
+ )
+ if requested_todo_id != retained_todo_id:
+ raise HeartbeatReceiptIdentityConflictError(
+ "heartbeat receipt settlement identity conflicts with "
+ "the retained Todo selection: explicitly requested "
+ "Todo differs"
+ )
if (
requested_replan_obligation_id
and requested_replan_obligation_id
@@ -99,32 +135,47 @@ def reconcile_existing_heartbeat_receipt(
"heartbeat receipt settlement identity conflicts with the "
"explicitly requested autonomous replan obligation"
)
- if (
- existing_todo_id != rollout_todo_id
- or existing_replan_obligation_id != rollout_replan_obligation_id
- or existing_effect_id != expected_effect_id
- ):
+ if existing_effect_id != expected_effect_id:
raise HeartbeatReceiptIdentityConflictError(
- "heartbeat receipt settlement identity conflicts with the "
- "current settlement binding: receipt="
- f"{existing_todo_id or existing_replan_obligation_id}, "
- "current="
- f"{rollout_todo_id or rollout_replan_obligation_id}"
+ "heartbeat receipt effect identity does not match its "
+ "persisted settlement binding"
)
rollout_details = quota_rollout_details(payload, args,
todo_id=rollout_todo_id, replan_obligation_id=rollout_replan_obligation_id)
rollout_details["settlement_effect_id"] = expected_effect_id
- receipt, qualified = requalify_bound_heartbeat_receipt(
- runtime_root, goal_id=args.goal_id, agent_id=args.agent_id,
- turn_instance_id=turn_instance_id, todo_id=rollout_todo_id,
- replan_obligation_id=rollout_replan_obligation_id,
- status=str(payload.get("effective_action") or payload.get("decision") or "should-run"),
- details=rollout_details,
- registry_path=Path(str(payload["registry"])) if payload.get("registry") else None,
- goal_ref=goal_ref,
+ replan_packet = (
+ payload.get("replan_action_packet")
+ if isinstance(payload.get("replan_action_packet"), Mapping)
+ else {}
+ )
+ current_replan_obligation_id = replan_obligation_id_from_packet(
+ replan_packet
)
- if qualified:
- receipt_status, receipt_appended = "upgraded", True
+ # A later frontier can rotate to a new replan identity after
+ # this Turn's historical ACK was accepted. That projection
+ # cannot requalify or replace the original receipt. Only the
+ # same open replan may append compatible review-source facts;
+ # a settlement-only packet already carries the exact evidence
+ # needed to close this immutable receipt.
+ if (
+ replan_packet.get("settlement_only") is not True
+ and (
+ not existing_replan_obligation_id
+ or current_replan_obligation_id
+ == existing_replan_obligation_id
+ )
+ ):
+ receipt, qualified = requalify_bound_heartbeat_receipt(
+ runtime_root, goal_id=args.goal_id, agent_id=args.agent_id,
+ turn_instance_id=turn_instance_id, todo_id=rollout_todo_id,
+ replan_obligation_id=rollout_replan_obligation_id,
+ status=str(payload.get("effective_action") or payload.get("decision") or "should-run"),
+ details=rollout_details,
+ registry_path=Path(str(payload["registry"])) if payload.get("registry") else None,
+ goal_ref=goal_ref,
+ )
+ if qualified:
+ receipt_status, receipt_appended = "upgraded", True
else:
rollout_details = quota_rollout_details(
payload,
@@ -411,24 +462,51 @@ def quota_rollout_details(
replan_packet = payload.get("replan_action_packet")
obligation = payload.get("autonomous_replan_obligation")
if semantic_replan_obligation_id and isinstance(obligation, Mapping) and obligation.get("obligation_id") == semantic_replan_obligation_id:
- from ..work_items.replan_semantics_codec import project_replan_semantics
from ...rollout_event_log import _safe_details
+ from ..work_items.replan_semantics_codec import project_replan_semantics
source = project_replan_semantics({"operation": "receipt_review_source",
"agent_id": getattr(args, "agent_id", None),
"obligation": {key: value for key, value in obligation.items() if key != "replan_context"}})
review = source["review_source"]
if isinstance(review, Mapping):
- # Retain the original stop clause only when the existing public
- # metadata serializer preserves it exactly. Unsafe/lossy sources
- # keep legacy strict recovery; never truncate a governing clause.
+ # Retain a short public stop clause verbatim. A longer clause can
+ # still preserve its semantic identity through a digest, but only
+ # when the public metadata serializer accepts the entire source
+ # without private markers or whitespace normalization. Unsafe or
+ # otherwise lossy sources keep legacy strict recovery.
try:
safe = _safe_details({"semantic_replan_review_kind": review["kind"],
"semantic_replan_review_stop_condition": review["stop_condition"]})
except ValueError:
safe = {}
- if safe.get("semantic_replan_review_stop_condition") == review["stop_condition"]:
+ stop_condition = review.get("stop_condition")
+ if safe.get("semantic_replan_review_stop_condition") == stop_condition:
details.update(safe)
+ elif (
+ safe.get("semantic_replan_review_kind") == review.get("kind")
+ and isinstance(stop_condition, str)
+ and len(stop_condition) > 240
+ and " ".join(stop_condition.split()) == stop_condition
+ ):
+ stop_details = {
+ "semantic_replan_review_kind": safe["semantic_replan_review_kind"],
+ # Older readers require the scalar stop field. Keep them
+ # fail-closed on this path while a current reader verifies
+ # the full clause through its digest (and known contract,
+ # when available).
+ "semantic_replan_review_stop_condition": (
+ AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION
+ ),
+ "semantic_replan_review_stop_condition_sha256": hashlib.sha256(
+ stop_condition.encode("utf-8")
+ ).hexdigest(),
+ }
+ if stop_condition == AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION:
+ stop_details["semantic_replan_review_stop_contract_id"] = (
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID
+ )
+ details.update(stop_details)
receipt = payload.get("heartbeat_receipt")
capability_guard = (replan_packet.get("capability_guard") if isinstance(replan_packet, Mapping) else None) or (
receipt.get("semantic_replan_capability_guard") if isinstance(receipt, Mapping) else None
diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts
index e0b3f977b5..f3064dbf36 100644
--- a/loopx/control_plane/quota/settlement_readback.ts
+++ b/loopx/control_plane/quota/settlement_readback.ts
@@ -1,6 +1,7 @@
-import { readReceiptLogSnapshot } from "../runtime/receipt_log_snapshot.ts";
+import { createHash } from "node:crypto";
import { isAbsolute, join } from "node:path";
+import { readReceiptLogSnapshot } from "../runtime/receipt_log_snapshot.ts";
import {
heartbeatReceiptsFromEvents,
readGoalRolloutEventSnapshot,
@@ -21,6 +22,7 @@ import {
type SettlementResult,
} from "../effect_program.ts";
import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts";
+import { BARE_SHA256_PATTERN } from "../content_digest.ts";
import { hasMonitorPollTransaction } from "./monitor_poll_commit.ts";
import { readQuotaSpendEventFromRun } from "./accounting_artifact_transaction.ts";
import {
@@ -43,6 +45,7 @@ import {
isCapabilityRetirementWriteback,
receiptBoundMonitorPhase,
receiptBoundReplayPhase,
+ type ReceiptBoundReplayPhase,
} from "./settlement_phase.ts";
import { isTurnScopedSettlementOutcome } from "../work_items/delivery_outcome.ts";
import {
@@ -72,6 +75,11 @@ import {
import { refreshExternalDelivery } from "./refresh_external_delivery.ts";
import { BLOCKED_WAIT_REQUEST_SCHEMA, prepareBlockedWait, RECEIPT_BOUND_WAIT_REQUEST_SCHEMA, projectReceiptBoundWait, isMonitorUnavailableWait } from "./blocked_wait.ts";
import {nativeChildReportAdmission} from "../capabilities/native_child_admission.ts";
+import {
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION,
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID,
+ AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION,
+} from "../work_items/replan_semantics.ts";
import {
parseQuotaAccountingOwner,
quotaOwnerOwnsProjection,
@@ -134,6 +142,19 @@ interface ResultBundle extends JsonObject {
payload: JsonObject;
}
+interface MatchedSpendRecords {
+ run: JsonObject | null;
+ receipt: JsonObject | null;
+ admissionSource?: unknown;
+}
+
+interface SpendTerms {
+ slots: unknown;
+ source: unknown;
+}
+
+const ORIGINAL_TURN_SPEND_SLOTS = 1;
+
type SettlementProgressState = "identity_required" | "writeback_required" |
"writeback_receipt_required" | "spend_required" | "spend_receipt_required" | "settled";
@@ -514,7 +535,8 @@ export function projectSemanticReplanGuard(
): JsonObject {
const hasCapability = ["semantic_replan_capability_id", "semantic_replan_gap_id", "semantic_replan_frontier_revision"]
.some(field => Object.hasOwn(receiptDetails, field));
- const hasReview = ["semantic_replan_review_kind", "semantic_replan_review_stop_condition"]
+ const hasReview = ["semantic_replan_review_kind", "semantic_replan_review_stop_condition",
+ "semantic_replan_review_stop_condition_sha256", "semantic_replan_review_stop_contract_id"]
.some(field => Object.hasOwn(receiptDetails, field));
if (hasCapability && hasReview) throw new EffectRuntimeRequestError(
"a review source cannot replace a capability guard", "malformed_settlement_state");
@@ -545,14 +567,40 @@ export function projectSemanticReplanGuard(
);
}
const reviewKind = hasReview ? requireNonEmptyString(receiptDetails.semantic_replan_review_kind, "receipt review kind") : null;
- const stop = hasReview ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_condition, "receipt review stop condition") : null;
+ const stop = Object.hasOwn(receiptDetails, "semantic_replan_review_stop_condition")
+ ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_condition, "receipt review stop condition") : null;
+ const stopDigest = Object.hasOwn(receiptDetails, "semantic_replan_review_stop_condition_sha256")
+ ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_condition_sha256,
+ "receipt review stop condition digest") : null;
+ const stopContractId = Object.hasOwn(receiptDetails, "semantic_replan_review_stop_contract_id")
+ ? requireNonEmptyString(receiptDetails.semantic_replan_review_stop_contract_id,
+ "receipt review stop contract id") : null;
+ if (hasReview && stop === null && stopDigest === null) throw new EffectRuntimeRequestError(
+ "a receipt review requires a stop condition or digest", "malformed_settlement_state");
if (stop && stop.length > 240) throw new EffectRuntimeRequestError(
"receipt review stop condition exceeds scalar metadata bounds", "malformed_settlement_state");
+ if (stopDigest !== null && !BARE_SHA256_PATTERN.test(stopDigest)) throw new EffectRuntimeRequestError(
+ "receipt review stop condition digest is malformed", "malformed_settlement_state");
+ if (stopContractId !== null &&
+ (stopContractId !== AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID || stopDigest === null ||
+ createHash("sha256").update(AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, "utf8").digest("hex") !== stopDigest)) {
+ throw new EffectRuntimeRequestError(
+ "receipt review stop contract does not match its digest", "malformed_settlement_state");
+ }
+ if (stop !== null && stopDigest !== null &&
+ stop !== AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION &&
+ createHash("sha256").update(stop, "utf8").digest("hex") !== stopDigest) {
+ throw new EffectRuntimeRequestError(
+ "receipt review stop condition digest does not match its value", "malformed_settlement_state");
+ }
return {
schema_version: SEMANTIC_REPLAN_GUARD_SCHEMA,
scope: "turn_guard",
selected_obligation_id: selectedObligationId,
- ...(hasReview ? {selected_review_source: {kind: reviewKind, stop_condition: stop}} : {}),
+ ...(hasReview ? {selected_review_source: {kind: reviewKind,
+ ...(stop === null ? {} : {stop_condition: stop}),
+ ...(stopDigest === null ? {} : {stop_condition_sha256: stopDigest}),
+ ...(stopContractId === null ? {} : {stop_contract_id: stopContractId})}} : {}),
...(hasCapability ? {
selected_capability_guard: decodeCapabilityGuard({schema_version: "semantic_replan_capability_guard_v0",
capability_id: receiptDetails.semantic_replan_capability_id, gap_id: receiptDetails.semantic_replan_gap_id,
@@ -561,6 +609,48 @@ export function projectSemanticReplanGuard(
};
}
+/** Upgrade a legacy bound review receipt without changing its Turn identity.
+ *
+ * Older receipts retained the selected replan obligation but not the review
+ * source that proves a regenerated frontier still represents the same duty.
+ * The correction is append-only: the caller serializes the returned details
+ * under the receipt-log lock. It is admitted only while closeout has not
+ * started and both the old and current guards select this exact binding.
+ */
+function requalifyHeartbeatReceipt(
+ heartbeatReceipt: JsonObject,
+ currentDetails: JsonObject,
+ identity: SettlementIdentity,
+ replayPhase: ReceiptBoundReplayPhase,
+ closeoutStarted: boolean,
+): JsonObject {
+ const work = heartbeatWorkRequalification(
+ heartbeatReceipt,
+ currentDetails,
+ identity,
+ replayPhase,
+ closeoutStarted,
+ );
+ if (work.append === true || replayPhase !== "open" || closeoutStarted ||
+ identity.binding_kind !== "autonomous_replan") return work;
+
+ const originalDetails = details(heartbeatReceipt);
+ const originalGuard = projectSemanticReplanGuard(originalDetails);
+ const currentGuard = projectSemanticReplanGuard(currentDetails);
+ if (originalGuard.selected_obligation_id !== identity.replan_obligation_id ||
+ currentGuard.selected_obligation_id !== identity.replan_obligation_id ||
+ originalGuard.selected_review_source != null ||
+ currentGuard.selected_review_source == null) return work;
+
+ const upgraded = {...originalDetails};
+ for (const field of ["semantic_replan_review_kind", "semantic_replan_review_stop_condition",
+ "semantic_replan_review_stop_condition_sha256", "semantic_replan_review_stop_contract_id"]) {
+ if (currentDetails[field] !== undefined) upgraded[field] = currentDetails[field]!;
+ }
+ upgraded.settlement_receipt_revision = "review_guard_upgrade";
+ return {append: true, details: upgraded};
+}
+
function decodeCapabilityGuard(value: unknown): JsonObject {
const guard = jsonObject(value);
if (!guard || guard.schema_version !== "semantic_replan_capability_guard_v0"
@@ -920,13 +1010,24 @@ function resolveIdentity(
const fact = heartbeatReceiptFactFromEvent(guard);
const originalTodoId = normalizeTodoId(fact.todo_id);
const originalReplanId = normalizeReplanObligationId(fact.replan_obligation_id);
+ const retainedTodoId = normalizeTodoId(
+ details(guard).pending_action_selection_todo_id,
+ );
if (!originalTodoId && !originalReplanId && !requestSubject) {
return failedIdentity("the original Turn guard has no settlement binding", "receipt_unbound");
}
- if ((request.todo_id !== null && (todoId === null || todoId !== originalTodoId)) ||
+ const requestedTodoMatchesOriginal = request.todo_id === null ||
+ (todoId !== null && (
+ todoId === originalTodoId ||
+ (originalReplanId !== null && todoId === retainedTodoId)
+ ));
+ if (!requestedTodoMatchesOriginal ||
(request.replan_obligation_id !== null &&
(replanObligationId === null || replanObligationId !== originalReplanId))) {
- return failedIdentity("requested binding differs from the original Turn guard", "identity_mismatch");
+ return failedIdentity(
+ "settlement binding does not match: requested binding differs from the original Turn guard",
+ "identity_mismatch",
+ );
}
todoId = originalTodoId;
replanObligationId = originalReplanId;
@@ -1206,6 +1307,7 @@ function readQuotaSettlementFromRequest(
request: ReadbackRequest,
snapshot: QuotaSettlementReadbackSnapshot,
nameOwedPriorTurn = true,
+ matchedSpend?: MatchedSpendRecords,
): JsonObject {
if (
snapshot.runtimeRoot !== request.runtime_root ||
@@ -1292,6 +1394,11 @@ function readQuotaSettlementFromRequest(
identity,
);
const spendEvent = findStepEvent(events, identity, "quota_spend");
+ if (matchedSpend) {
+ matchedSpend.run = spendRun;
+ matchedSpend.receipt = spendEvent;
+ matchedSpend.admissionSource = receiptDetails.quota_spend_source;
+ }
const completionEvent = findStepEvent(events, identity, "todo_complete");
const supersedeEvent = findStepEvent(events, identity, "todo_supersede");
const closeoutStarted = [writebackRun, writebackEvent, spendRun, spendEvent, completionEvent, supersedeEvent]
@@ -1441,7 +1548,7 @@ function readQuotaSettlementFromRequest(
closeoutStarted, normalizeReplanObligationId(semanticReplanGuard.selected_obligation_id),
),
...(request.heartbeat_reentry_guard === null ? {} : {
- heartbeat_reentry_qualification: heartbeatWorkRequalification(heartbeatReceipt,
+ heartbeat_reentry_qualification: requalifyHeartbeatReceipt(heartbeatReceipt,
request.heartbeat_reentry_guard, identity, replayPhase, closeoutStarted),
}),
};
@@ -1511,9 +1618,33 @@ export async function readQuotaSettlement(value: unknown): Promise {
return await withOwner(
request.owner,
async () => {
+ const matchedSpend: MatchedSpendRecords = {run: null, receipt: null};
const result = readQuotaSettlementFromRequest(request,
- await readQuotaSettlementSnapshot(request.runtime_root, request.goal_id));
+ await readQuotaSettlementSnapshot(request.runtime_root, request.goal_id), true, matchedSpend);
const identity = jsonObject(jsonObject(jsonObject(result.identity)?.result)?.value);
+ const receipt = spendReceiptTerms(matchedSpend.receipt);
+ // Only exact readback opens its matched debit artifact. Check its
+ // identity even when the receipt is missing or omits billing terms.
+ // Snapshot readers for history and guard discovery use the bounded index.
+ const retained = matchedSpend.run !== null
+ ? await readQuotaSpendEventFromRun(join(request.runtime_root, "goals", request.goal_id, "runs"),
+ matchedSpend.run, request.goal_id)
+ : null;
+ const ledger = {slots: retained?.slots ?? undefined, source: retained?.source ?? undefined};
+ let conflict = spendTermsConflict(ledger, receipt);
+ if (retained === null && matchedSpend.run !== null && matchedSpend.receipt !== null) {
+ // An index row identifies the original debit, but does not provide its
+ // terms. Check explicit receipt terms against the matching admission.
+ const source = matchedSpend.admissionSource ?? undefined;
+ conflict = spendTermsConflict(
+ {slots: ORIGINAL_TURN_SPEND_SLOTS, source}, receipt, "the original Turn admission",
+ ) ?? (source === undefined && receipt.source !== undefined
+ ? "the original Turn admission has no verifiable billing source for the quota spend receipt"
+ : null);
+ }
+ if (conflict !== null && spendRequest === null) {
+ throw new EffectRuntimeRequestError(conflict, "malformed_settlement_state");
+ }
if (identity && request.refresh_retry &&
jsonObject(result.refresh_recovery)?.decision !== "reject" &&
isTurnScopedSettlementOutcome(request.refresh_retry.delivery_outcome,
@@ -1529,49 +1660,68 @@ export async function readQuotaSettlement(value: unknown): Promise {
// only its receipts and whether a spend Run already needs receipt repair.
const settlement = requireJsonObject(result.settlement, "quota settlement bundle");
const outcome = requireJsonObject(settlement.result, "quota settlement result");
- const spendRun = jsonObject(result.spend_run);
- const spendRejection = spendRequest && identity
- ? await originalSpendRejection(request, result, spendRequest, spendRun)
- : null;
+ const rejection = conflict === null
+ ? spendRequest && identity ? originalSpendRejection(result, spendRequest, ledger, receipt) : null
+ : rejectedSpend(conflict);
return {
schema_version: result.schema_version,
found: true,
identity: result.identity,
settlement: {...settlement, result: {...outcome, value: null}},
progress: result.progress,
- spend_run_present: spendRun !== null,
- ...(spendRejection === null ? {} : {spend_request_rejection: bundle(spendRejection)}),
+ spend_run_present: matchedSpend.run !== null,
+ ...(rejection === null ? {} : {spend_request_rejection: bundle(rejection)}),
};
},
);
}
-async function originalSpendRejection(
- request: ReadbackRequest, readback: JsonObject, proposed: JsonObject,
- spendRun: JsonObject | null,
-): Promise | null> {
+function spendReceiptTerms(event: JsonObject | null): SpendTerms {
+ const {slots, source} = event === null ? {} : details(event);
+ // Older rollout envelopes and repaired receipts can omit billing terms.
+ return {
+ slots: slots == null || slots === "" ? undefined : slots,
+ source: source == null || source === "" ? undefined : source,
+ };
+}
+
+function spendTermsConflict(
+ recorded: SpendTerms,
+ receipt: SpendTerms,
+ description = "the recorded debit",
+): string | null {
+ for (const field of ["slots", "source"] as const) {
+ if (recorded[field] !== undefined && receipt[field] !== undefined && recorded[field] !== receipt[field]) {
+ return `${description} and quota spend receipt disagree on ${field}`;
+ }
+ }
+ return null;
+}
+
+function rejectedSpend(reason: string): SettlementResult {
+ return settlementFailed({kind: "quota_spend_rejected", step_kind: "quota_spend", reason});
+}
+
+function originalSpendRejection(
+ readback: JsonObject, proposed: JsonObject,
+ ledger: SpendTerms, receipt: SpendTerms,
+): SettlementResult | null {
const progress = requireJsonObject(readback.progress, "quota settlement progress");
const guard = jsonObject(readback.heartbeat_receipt);
const authorizedSource = guard ? details(guard).quota_spend_source : null;
// Older ledgers can have a rollout receipt but no readable artifact. Keep
// their receipt facts available and never repair an already mismatched debit.
const spendEvent = jsonObject(readback.spend_event);
- const receipt = spendEvent ? details(spendEvent) : {};
- const retained = spendRun === null ? null : await readQuotaSpendEventFromRun(
- join(request.runtime_root, "goals", request.goal_id, "runs"), spendRun, request.goal_id,
- );
- const recordedSlots = retained?.slots ?? (receipt.slots === "" ? undefined : receipt.slots);
- const recordedSource = retained?.source ?? (receipt.source === "" ? undefined : receipt.source);
+ const spendRun = jsonObject(readback.spend_run);
+ const recordedSlots = ledger.slots ?? receipt.slots;
+ const recordedSource = ledger.source ?? 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.
- if (proposed.slots !== 1 || proposed.source !== source) {
- return settlementFailed({
- kind: "quota_spend_rejected", step_kind: "quota_spend",
- reason: `original Turn settlement requires --slots 1 --source ${String(source)}`,
- });
+ if (proposed.slots !== ORIGINAL_TURN_SPEND_SLOTS || proposed.source !== source) {
+ return rejectedSpend(`original Turn settlement requires --slots ${ORIGINAL_TURN_SPEND_SLOTS} --source ${String(source)}`);
}
const slotsConflict = recordedSlots !== undefined && recordedSlots !== proposed.slots;
const sourceConflict = recordedSource !== undefined && recordedSource !== source;
@@ -1579,10 +1729,7 @@ async function originalSpendRejection(
// debit needs the original charge facts before we can certify its receipt.
const unverifiableRepair = spendRun !== null && spendEvent === null &&
(recordedSlots === undefined || recordedSource === undefined);
- return slotsConflict || sourceConflict || unverifiableRepair ? settlementFailed({
- kind: "quota_spend_rejected", step_kind: "quota_spend",
- reason: unverifiableRepair
+ return slotsConflict || sourceConflict || unverifiableRepair ? rejectedSpend(unverifiableRepair
? "the recorded debit has no verifiable billing terms for receipt repair"
- : "the recorded debit differs from the original Turn settlement plan",
- }) : null;
+ : "the recorded debit differs from the original Turn settlement plan") : null;
}
diff --git a/loopx/control_plane/quota/should_run.py b/loopx/control_plane/quota/should_run.py
index 1f85af9df8..962f4540e7 100644
--- a/loopx/control_plane/quota/should_run.py
+++ b/loopx/control_plane/quota/should_run.py
@@ -194,6 +194,7 @@ def _attach_quota_should_run_envelope(
def _app_scheduler_state_read_observer(
direct_sources: dict[str, dict[str, Any]],
+ observe_state: Callable[[Mapping[str, Any]], None] | None,
) -> Callable[[Mapping[str, Any]], None]:
def record(readback: Mapping[str, Any]) -> None:
previous = direct_sources.get("app_scheduler_state", {})
@@ -211,6 +212,8 @@ def record(readback: Mapping[str, Any]) -> None:
item_count=item_count,
unreadable_count=unreadable_count,
)
+ if observe_state is not None:
+ observe_state(readback)
return record
@@ -577,6 +580,7 @@ def build_quota_should_run(
goal_ref: Mapping[str, object] | None = None,
authoritative_fallback_todo_items: FallbackTodoSource = None,
replan_explore_reader: Callable[[str, str | None], Mapping[str, Any] | None] | None = None,
+ app_scheduler_state_observer: Callable[[Mapping[str, Any]], None] | None = None,
) -> dict[str, Any]:
safe_goal_id = str(goal_id or "").strip()
direct_sources: dict[str, dict[str, Any]] = {}
@@ -687,7 +691,7 @@ def build_quota_should_run(
runtime_root=runtime_root,
goal_ref=goal_ref,
scheduler_state_read_observer=_app_scheduler_state_read_observer(
- direct_sources
+ direct_sources, app_scheduler_state_observer,
),
)
_apply_missing_state_health_guidance(
diff --git a/loopx/control_plane/quota/unsettled_host_turn.py b/loopx/control_plane/quota/unsettled_host_turn.py
index 44ee6885f7..eda16f9d2c 100644
--- a/loopx/control_plane/quota/unsettled_host_turn.py
+++ b/loopx/control_plane/quota/unsettled_host_turn.py
@@ -22,6 +22,7 @@
EffectRuntimeResponseAmbiguous,
effect_runtime_result,
)
+from ..scheduler.arbitration import SchedulerArbitration
from ..scheduler.execution_context import SchedulerExecutionContextResolution
from ..agents.agent_scope_frontier import AgentScopeFrontierAction
from ..todos.todo_semantics import todo_item_task_class
@@ -410,6 +411,7 @@ def apply_unsettled_host_turn_recovery_if_required(
agent_id: str | None,
current_turn_instance_id: str | None,
available_capabilities: list[str] | None,
+ project_scheduler_hint: Callable[..., dict[str, Any]],
scheduler_execution_context: (
Mapping[str, Any] | SchedulerExecutionContextResolution | None
),
@@ -432,9 +434,14 @@ def apply_unsettled_host_turn_recovery_if_required(
)
if verdict is None:
return False
- return _apply_recovery_projection(payload, verdict=verdict, registry_path=registry_path, runtime_root=runtime_root,
+ arbitration = _apply_recovery_projection(
+ payload, verdict=verdict, registry_path=registry_path, runtime_root=runtime_root,
current_turn_instance_id=current_turn_instance_id, available_capabilities=available_capabilities,
- scheduler_execution_context=scheduler_execution_context)
+ scheduler_execution_context=scheduler_execution_context,
+ )
+ if verdict["recovery"].get("state") == "attention_required":
+ payload["scheduler_hint"] = project_scheduler_hint(payload, arbitration=arbitration)
+ return True
def apply_receipt_bound_wait_recovery(
@@ -525,7 +532,7 @@ def _apply_recovery_projection(
payload: dict[str, Any], *, verdict: Mapping[str, Any], registry_path: Path, runtime_root: Path,
current_turn_instance_id: str | None, available_capabilities: list[str] | None,
scheduler_execution_context: Mapping[str, Any] | SchedulerExecutionContextResolution | None,
-) -> bool:
+) -> SchedulerArbitration:
recovery = verdict["recovery"]
obligation = verdict["obligation"]
attention = recovery.get("state") == "attention_required"
@@ -614,11 +621,4 @@ def _apply_recovery_projection(
cli_channel["spend_allowed_now"] = obligation.get("spend_allowed_now") is True
cli_channel["recovery_ref"] = "$.unsettled_host_turn_recovery"
payload["interaction_contract"] = interaction_contract
- if attention:
- from ..scheduler.scheduler_hint import build_scheduler_hint
-
- payload["scheduler_hint"] = build_scheduler_hint(
- payload, arbitration=arbitration, scheduler_execution_context=scheduler_execution_context,
- available_capabilities=available_capabilities,
- )
- return True
+ return arbitration
diff --git a/loopx/control_plane/quota/unsettled_host_turn_recovery.ts b/loopx/control_plane/quota/unsettled_host_turn_recovery.ts
index 8bb66871c0..890054f1e3 100644
--- a/loopx/control_plane/quota/unsettled_host_turn_recovery.ts
+++ b/loopx/control_plane/quota/unsettled_host_turn_recovery.ts
@@ -335,6 +335,12 @@ function decodeCandidate(value: unknown): PriorHostTurnCloseoutCandidate {
);
}
const settlementEffectId = optionalHeartbeatString(raw.settlement_effect_id);
+ if (raw.admitted_replan !== undefined &&
+ (raw.admitted_replan !== true || settlementEffectId === null)) {
+ throw new EffectRuntimeRequestError(
+ "prior host Turn recovery candidate has an invalid autonomous replan fact",
+ );
+ }
if (raw.admitted_todo_replan !== undefined &&
(raw.admitted_todo_replan !== true || bindingKind !== "todo" || settlementEffectId === null)) {
throw new EffectRuntimeRequestError(
@@ -350,6 +356,11 @@ function decodeCandidate(value: unknown): PriorHostTurnCloseoutCandidate {
binding_kind: bindingKind,
binding_id: bindingId,
settlement_effect_id: settlementEffectId,
+ ...(
+ raw.admitted_replan === true || raw.admitted_todo_replan === true
+ ? {admitted_replan: true as const}
+ : {}
+ ),
...(raw.admitted_todo_replan === true ? {admitted_todo_replan: true as const} : {}),
};
}
@@ -506,9 +517,10 @@ function recoveryObligation(
*
* The accepted closeout order is policy: a validated settlement wins, then an
* exactly committed monitor-poll closeout, then a typed lifecycle transition.
- * For a Todo-bound autonomous replan, a verified writeback keeps its debit
- * obligation even when the Todo has changed. Ordinary lifecycle closeouts
- * retain their existing meaning.
+ * For an admitted autonomous replan, a verified writeback keeps its debit
+ * obligation under either the legacy Todo binding or the canonical replan
+ * obligation binding. Ordinary lifecycle closeouts retain their existing
+ * meaning.
*/
export function reduceUnsettledHostTurnRecovery(value: unknown): JsonObject {
const request = requireJsonObject(value, "prior host Turn recovery request");
@@ -553,7 +565,7 @@ export function reduceUnsettledHostTurnRecovery(value: unknown): JsonObject {
};
}
- const replanSpendOwed = selected.admitted_todo_replan === true && awaitingQuotaSpend(missingReceipts);
+ const replanSpendOwed = selected.admitted_replan === true && awaitingQuotaSpend(missingReceipts);
const lifecycleCloseout = replanSpendOwed ? null : acceptedLifecycleCloseout(todo);
if (lifecycleCloseout !== null) {
return {
diff --git a/loopx/control_plane/runtime/checkpoint_artifacts.ts b/loopx/control_plane/runtime/checkpoint_artifacts.ts
index afc6bffd56..d2ea3977ba 100644
--- a/loopx/control_plane/runtime/checkpoint_artifacts.ts
+++ b/loopx/control_plane/runtime/checkpoint_artifacts.ts
@@ -3,11 +3,11 @@
* Native sessions, canonical state adoption and evaluator opportunities retain owners.
*/
import {createHash} from "node:crypto";
-import {createReadStream} from "node:fs";
+import {constants, createReadStream} from "node:fs";
import {chmod, copyFile, lstat, mkdir, mkdtemp, open, readFile, readdir, rm} from "node:fs/promises";
import {dirname, isAbsolute, join, resolve, sep} from "node:path";
import type {JsonObject} from "../effect_program.ts";
-import {jsonObject, requireJsonObject, requireNonEmptyString} from "../runtime_decode.ts";
+import {jsonObject, parseJsonSource, parsedSourceNumberTokens, requireJsonObject, requireNonEmptyString} from "../runtime_decode.ts";
import {canonicalAuthoritySha256, hasExactAuthorityKeys} from "../coordination/authority_store_codec.ts";
import {snapshotSqliteDatabase} from "../coordination/sqlite_backup.ts";
import {durableWriteJson, publishNewDirectory} from "../effect_runtime_io.ts";
@@ -15,6 +15,7 @@ import {settlementIdentity} from "../effect_program.ts";
import {normalizeHeartbeatReplanObligationId, normalizeHeartbeatTodoId} from "../quota/heartbeat_receipt_identity.ts";
import {EffectRuntimeConflictError, EffectRuntimeRequestError} from "../effect_runtime_errors.ts";
import {EffectiveAction} from "../quota/effective_action.generated.ts";
+import {MAX_LOCAL_SNAPSHOT_BYTES} from "../effect_runtime_snapshot.ts";
import {BARE_SHA256_PATTERN} from "../content_digest.ts";
import {checkpointRetentionPlan} from "./checkpoint_retention.ts";
@@ -249,6 +250,144 @@ async function verify(root: string, expected: unknown): Promise {
// guard, a no-write reread, or the selection hop that appended its binding.
// A pending/failed/uncommitted view is not an admitted identity.
const ADMITTED_RECEIPT_STATUSES: ReadonlySet = new Set(["committed", "replayed", "upgraded"]);
+function checkpointReplanIntent(quota: JsonObject, goal: string, agent: string, turn: string): JsonObject {
+ // A refused handoff should retain its causal mismatch diagnosis.
+ const mismatch = () => new EffectRuntimeRequestError("checkpoint replan does not match the current admitted identity");
+ if (quota.ok !== true || quota.goal_id !== goal) throw new EffectRuntimeRequestError("checkpoint requires a matching current quota readback");
+ if (quota.effective_action !== EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED) {
+ return {capture: false, reason: "no_fresh_replan", execution_authority_granted: false};
+ }
+ const packet = requireJsonObject(quota.replan_action_packet, "checkpoint replan packet");
+ const id = normalizeHeartbeatReplanObligationId(packet.obligation_id);
+ const receipt = requireJsonObject(quota.heartbeat_receipt, "checkpoint heartbeat receipt");
+ // The replan owner marks receipt-owned follow-through with settlement_only.
+ // These packets carry the original writer's response, not a new research node.
+ const settlementOnly = packet.settlement_only === true;
+ if (packet.schema_version !== "replan_action_packet_v0" ||
+ typeof packet.decision !== "string" || packet.decision.trim() === "" ||
+ (!settlementOnly && packet.decision !== "replan_required") ||
+ !id || !ADMITTED_RECEIPT_STATUSES.has(receipt.status as string) || receipt.turn_instance_id !== turn) {
+ throw mismatch();
+ }
+ const semanticReplan = normalizeHeartbeatReplanObligationId(receipt.semantic_replan_obligation_id);
+ const closeoutPending = receipt.closeout_required === true;
+ if (!closeoutPending && !settlementOnly && receipt.settlement_identity === undefined && receipt.settlement_binding_owed === true) {
+ // The original guard owns the semantic node before the Agent chooses
+ // work. An inert pre-decision capture does not invent that later work's
+ // causal settlement identity or grant permission to execute it.
+ const actor = requireJsonObject(quota.agent_identity, "checkpoint source Agent");
+ requireNonEmptyString(receipt.event_id, "checkpoint committed guard event");
+ if (actor.agent_id !== agent || actor.registered !== true || semanticReplan !== id) {
+ throw mismatch();
+ }
+ return {capture: true, obligation_id: id, execution_authority_granted: false};
+ }
+ const identity = requireJsonObject(receipt.settlement_identity, "checkpoint settlement identity");
+ const todo = normalizeHeartbeatTodoId(identity.todo_id);
+ const boundReplan = normalizeHeartbeatReplanObligationId(identity.replan_obligation_id);
+ if ((todo !== null && boundReplan !== null) ||
+ identity.goal_id !== goal || identity.agent_id !== agent || identity.turn_instance_id !== turn ||
+ identity.effect_id !== settlementIdentity({goal_id: goal, agent_id: agent, todo_id: todo,
+ replan_obligation_id: boundReplan, turn_instance_id: turn}).effect_id) {
+ throw mismatch();
+ }
+ // A replay can expose the next obligation while this Turn still owes its
+ // original Todo settlement. Release that response to its writer; it is not
+ // a new capture boundary and must not interrupt the pending closeout.
+ if (closeoutPending) return {capture: false, reason: "turn_closeout_pending", execution_authority_granted: false};
+ if (settlementOnly) {
+ if (semanticReplan !== id || (boundReplan !== null && boundReplan !== id)) {
+ throw mismatch();
+ }
+ return {capture: false, reason: "turn_closeout_pending", execution_authority_granted: false};
+ }
+ if (todo ? boundReplan !== null || semanticReplan !== id : boundReplan !== id) {
+ throw mismatch();
+ }
+ return {capture: true, obligation_id: id, settlement_effect_id: identity.effect_id,
+ execution_authority_granted: false};
+}
+
+function hasReplanAnnotation(value: unknown): boolean {
+ // Historical JSON notes used empty values for absence. Keep that selection
+ // rule here; a declared held member still requires verification below.
+ if (!value) return false;
+ return typeof value !== "object" || Object.keys(value).length > 0;
+}
+
+async function readPendingReplanBasis(root: string, manifest: JsonObject): Promise {
+ const metadata = requireJsonObject(manifest.point_metadata, "checkpoint point metadata");
+ const operator = jsonObject(metadata.operator_metadata);
+ const pending = hasReplanAnnotation(metadata.replan) ? metadata.replan : operator?.replan;
+ if (!hasReplanAnnotation(pending) && metadata.held_decision_component_id === undefined) return null;
+ const intent = requireJsonObject(pending, "checkpoint pending replan");
+ const id = metadata.held_decision_component_id;
+ if (typeof id !== "string" || !components(manifest.components).some(entry => entry.id === id)) {
+ throw new EffectRuntimeRequestError("restored replan point lacks its original pending packet");
+ }
+ const expected = requireNonEmptyString(metadata.decision_sha256, "checkpoint pending packet digest");
+ if (!BARE_SHA256_PATTERN.test(expected)) {
+ throw new EffectRuntimeRequestError("checkpoint pending packet digest is invalid");
+ }
+ const path = join(root, "components", id);
+ await physical(path);
+ const entry = await lstat(path);
+ const witness = requireJsonObject(manifest.artifact_witness, "checkpoint artifact witness")[id];
+ const sealed = Array.isArray(witness) && witness.length === 1 ? jsonObject(witness[0]) : null;
+ if (!entry.isFile() || !sealed || sealed.kind !== "file" || sealed.path !== "") {
+ throw new EffectRuntimeRequestError("checkpoint pending packet must be a regular sealed member");
+ }
+ if (entry.size <= 0 || entry.size > MAX_LOCAL_SNAPSHOT_BYTES) {
+ throw new EffectRuntimeRequestError("checkpoint pending packet size is outside the local source budget");
+ }
+ if (sealed.sha256 !== expected || sealed.size !== entry.size) {
+ throw new EffectRuntimeRequestError("checkpoint pending packet digest differs");
+ }
+ const file = await open(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
+ let raw: Buffer;
+ try {
+ const observed = await file.stat();
+ if (!observed.isFile() || observed.dev !== entry.dev || observed.ino !== entry.ino || observed.size !== entry.size) {
+ throw new EffectRuntimeRequestError("checkpoint pending packet changed while opening");
+ }
+ raw = Buffer.alloc(entry.size);
+ let offset = 0;
+ while (offset < raw.length) {
+ const {bytesRead} = await file.read(raw, offset, raw.length - offset, offset);
+ if (bytesRead === 0) break;
+ offset += bytesRead;
+ }
+ if (offset !== raw.length || (await file.stat()).size !== raw.length) {
+ throw new EffectRuntimeRequestError("checkpoint pending packet changed while reading");
+ }
+ } finally {
+ await file.close();
+ }
+ const actual = createHash("sha256").update(raw).digest("hex");
+ if (actual !== expected) {
+ throw new EffectRuntimeRequestError("checkpoint pending packet digest differs");
+ }
+ let parsed: ReturnType;
+ try { parsed = parseJsonSource(new TextDecoder("utf-8", {fatal: true}).decode(raw)); }
+ catch { throw new EffectRuntimeRequestError("checkpoint pending packet is not valid UTF-8 JSON"); }
+ const quota = requireJsonObject(parsed.value, "checkpoint quota readback");
+ // Only this sealed historical reader permits an unversioned decision. A
+ // complete carrier, including malformed version/binding fields, is checked.
+ if (Object.hasOwn(quota, "schema_version") || Object.hasOwn(quota, "contract_binding")) {
+ const {requireCompleteTurnDecision} = await import("../quota/turn_envelope.ts");
+ requireCompleteTurnDecision(quota, parsedSourceNumberTokens(quota, parsed.numbers));
+ }
+ const source = requireJsonObject(metadata.loopx_state, "checkpoint source Goal/Agent");
+ const receipt = requireJsonObject(quota.heartbeat_receipt, "checkpoint heartbeat receipt");
+ const observed = checkpointReplanIntent(quota, requireNonEmptyString(source.goal_id, "checkpoint goal"),
+ requireNonEmptyString(source.agent_id, "checkpoint agent"),
+ requireNonEmptyString(receipt.turn_instance_id, "checkpoint Turn"));
+ if (observed.capture !== true || canonicalAuthoritySha256(observed) !== canonicalAuthoritySha256(intent)) {
+ throw new EffectRuntimeRequestError("restored original replan binding differs");
+ }
+ return {intent: observed, decision_sha256: actual, decision_path: path};
+}
+
export async function checkpointArtifacts(value: unknown): Promise {
const request = requireJsonObject(value, "checkpoint artifacts request");
if (request.action === "retention_plan") {
@@ -341,77 +480,27 @@ export async function checkpointArtifacts(value: unknown): Promise {
execution_authority_granted: false};
}
if (request.action === "select_replan") {
- // Typed refusals keep their reason through the runtime boundary, so a
- // refused handoff is diagnosable instead of an opaque internal failure.
- const mismatch = () => new EffectRuntimeRequestError("checkpoint replan does not match the current admitted identity");
if (!hasExactAuthorityKeys(request, ["action", "quota", "goal_id", "agent_id", "turn_instance_id"])) {
throw new Error("checkpoint replan selection fields are invalid");
}
- const quota = requireJsonObject(request.quota, "checkpoint quota readback");
- const goal = requireNonEmptyString(request.goal_id, "checkpoint goal");
- const agent = requireNonEmptyString(request.agent_id, "checkpoint agent");
- const turn = requireNonEmptyString(request.turn_instance_id, "checkpoint Turn");
- if (quota.ok !== true || quota.goal_id !== goal) throw new EffectRuntimeRequestError("checkpoint requires a matching current quota readback");
- if (quota.effective_action !== EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED) {
- return {capture: false, reason: "no_fresh_replan", execution_authority_granted: false};
- }
- const packet = requireJsonObject(quota.replan_action_packet, "checkpoint replan packet");
- const id = normalizeHeartbeatReplanObligationId(packet.obligation_id);
- const receipt = requireJsonObject(quota.heartbeat_receipt, "checkpoint heartbeat receipt");
- // The replan owner marks receipt-owned follow-through with settlement_only.
- // These packets carry the original writer's response, not a new research node.
- const settlementOnly = packet.settlement_only === true;
- if (packet.schema_version !== "replan_action_packet_v0" ||
- typeof packet.decision !== "string" || packet.decision.trim() === "" ||
- (!settlementOnly && packet.decision !== "replan_required") ||
- !id || !ADMITTED_RECEIPT_STATUSES.has(receipt.status as string) || receipt.turn_instance_id !== turn) {
- throw mismatch();
- }
- const semanticReplan = normalizeHeartbeatReplanObligationId(receipt.semantic_replan_obligation_id);
- const closeoutPending = receipt.closeout_required === true;
- if (!closeoutPending && !settlementOnly && receipt.settlement_identity === undefined && receipt.settlement_binding_owed === true) {
- // The original guard owns the semantic node before the Agent chooses
- // work. An inert pre-decision capture does not invent that later work's
- // causal settlement identity or grant permission to execute it.
- const actor = requireJsonObject(quota.agent_identity, "checkpoint source Agent");
- requireNonEmptyString(receipt.event_id, "checkpoint committed guard event");
- if (actor.agent_id !== agent || actor.registered !== true || semanticReplan !== id) {
- throw mismatch();
- }
- return {capture: true, obligation_id: id, execution_authority_granted: false};
- }
- const identity = requireJsonObject(receipt.settlement_identity, "checkpoint settlement identity");
- const todo = normalizeHeartbeatTodoId(identity.todo_id);
- const boundReplan = normalizeHeartbeatReplanObligationId(identity.replan_obligation_id);
- if ((todo !== null && boundReplan !== null) ||
- identity.goal_id !== goal || identity.agent_id !== agent || identity.turn_instance_id !== turn ||
- identity.effect_id !== settlementIdentity({goal_id: goal, agent_id: agent, todo_id: todo,
- replan_obligation_id: boundReplan, turn_instance_id: turn}).effect_id) {
- throw mismatch();
- }
- // A replay can expose the next obligation while this Turn still owes its
- // original Todo settlement. Release that response to its writer; it is not
- // a new capture boundary and must not interrupt the pending closeout.
- if (closeoutPending) return {capture: false, reason: "turn_closeout_pending", execution_authority_granted: false};
- if (settlementOnly) {
- if (semanticReplan !== id || (boundReplan !== null && boundReplan !== id)) {
- throw mismatch();
- }
- return {capture: false, reason: "turn_closeout_pending", execution_authority_granted: false};
- }
- if (todo ? boundReplan !== null || semanticReplan !== id : boundReplan !== id) {
- throw mismatch();
- }
- return {capture: true, obligation_id: id, settlement_effect_id: identity.effect_id,
- execution_authority_granted: false};
+ return checkpointReplanIntent(requireJsonObject(request.quota, "checkpoint quota readback"),
+ requireNonEmptyString(request.goal_id, "checkpoint goal"),
+ requireNonEmptyString(request.agent_id, "checkpoint agent"),
+ requireNonEmptyString(request.turn_instance_id, "checkpoint Turn"));
}
if (request.action === "read_basis") {
- if (!hasExactAuthorityKeys(request, ["action", "root", "expected_sha256"])) throw new Error("checkpoint basis fields are invalid");
+ const keys = ["action", "root", "expected_sha256"];
+ if (Object.hasOwn(request, "include_pending_replan")) keys.push("include_pending_replan");
+ if (!hasExactAuthorityKeys(request, keys) ||
+ (Object.hasOwn(request, "include_pending_replan") && request.include_pending_replan !== true)) {
+ throw new EffectRuntimeRequestError("checkpoint basis fields are invalid");
+ }
const root = absolute(request.root, "checkpoint root");
const manifest = await readReviewedManifest(root, request.expected_sha256);
// This reads a digest-bound declaration after admission's full member
// verification. It does not claim current integrity of every component.
return {point_metadata: manifest.point_metadata, components: manifest.components,
+ ...(request.include_pending_replan === true ? {pending_replan: await readPendingReplanBasis(root, manifest)} : {}),
integrity_verified: false, execution_authority_granted: false};
}
const fields = request.action === "probe" ? ["action", "components"] :
diff --git a/loopx/control_plane/status/collection.py b/loopx/control_plane/status/collection.py
index 7ddd538a4b..8d65923da3 100644
--- a/loopx/control_plane/status/collection.py
+++ b/loopx/control_plane/status/collection.py
@@ -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
diff --git a/loopx/control_plane/turn_driver/codex_cli.py b/loopx/control_plane/turn_driver/codex_cli.py
index dd4d453b5e..e2433070b0 100644
--- a/loopx/control_plane/turn_driver/codex_cli.py
+++ b/loopx/control_plane/turn_driver/codex_cli.py
@@ -58,6 +58,7 @@
CODEX_STDIO_MCP_SERVER_SCHEMA_VERSION = "codex_stdio_mcp_server_v0"
CODEX_CLI_RESULT_KINDS = (
"validated_progress",
+ "validated_completion",
"repair_required",
"replan_required",
"user_action_required",
@@ -395,7 +396,7 @@ def _render_prompt(request: Mapping[str, Any], *, checked: Mapping[str, Any] | N
("Use task_context for the admitted work. Its interaction_contract.agent_channel carries work_context, required_reads and primary_action; the outer adapter retains the complete original source and Core effect instructions. " if complete else ("Use turn_authority as the verified authority for this Turn. " if staged else "Use the TurnEnvelope as the source of truth. "))
+ "Read work_context and remaining required_reads before primary_action; do not repeat fulfilled reads; perform work only when its contract allows it. The selected Todo summary is not its full requirements, and completing that work does not prove Goal completion.",
"Do not write LoopX state, spend quota, or apply scheduler changes; the adapter owns those effects.",
- "Return only the schema-constrained result. For validated_progress, repair_required, or replan_required, fill every material field with public-safe evidence.",
+ "Return only the schema-constrained result. Use validated_completion when the selected Todo's full requirements are met; the adapter runs its declared completion validation and durably completes it before accountable writeback. Use validated_progress for partial work; progress alone never completes a Todo. Neither result proves Goal closure. For validated_progress, validated_completion, repair_required, or replan_required, fill every material field with public-safe evidence.",
"For those material results, preserve the actual delivery_batch_scale and delivery_outcome selected from the signed execution_profile's work and outcome requirements. Return work_evidence and validation_evidence as separate non-empty arrays of short public-safe strings; name the artifact or observed work in the first and the independent command or readback in the second. For legacy requests without execution_profile, use null when evidence is not supplied. For stop results, set both evidence fields to null.",
"For those material results, set path_delta_mode=material_replan and result_kind=replan_required only when this Turn changes a prior assumption, route, scope, acceptance rule, or stops prior work; then provide a complete bounded agent vision packet with goal_path_delta_v0 in agent_vision_json and leave vision_unchanged_reason empty.",
"For routine continuation, retry, successor creation, or no-change replanning, explicitly set path_delta_mode=unchanged. Reuse the current checkpoint with vision_unchanged_reason and empty agent_vision_json, or record new progress/completion evidence in a fresh agent_vision_json packet with path_delta.outcome continue or no_change and empty vision_unchanged_reason.",
diff --git a/loopx/control_plane/work_items/attention_queue.py b/loopx/control_plane/work_items/attention_queue.py
index fb9976b9b9..a9c21a41e7 100644
--- a/loopx/control_plane/work_items/attention_queue.py
+++ b/loopx/control_plane/work_items/attention_queue.py
@@ -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.
@@ -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,
diff --git a/loopx/control_plane/work_items/autonomous_replan_ack.py b/loopx/control_plane/work_items/autonomous_replan_ack.py
index a9a8ecb81f..2c16a75ccc 100644
--- a/loopx/control_plane/work_items/autonomous_replan_ack.py
+++ b/loopx/control_plane/work_items/autonomous_replan_ack.py
@@ -310,12 +310,15 @@ def _source_run(
def _expected_todo_receipt(
run: dict[str, Any], events: list[dict[str, Any]], *,
- goal_id: str, agent_id: str, turn_instance_id: str,
+ goal_id: str, agent_id: str, turn_instance_id: str, obligation_id: str,
) -> tuple[str, str]:
- """Todo settlement identity for this ACK, filled from its heartbeat receipt.
+ """Todo command identity for this ACK, filled from its heartbeat receipt.
A historical index can omit the Todo and effect. The turn's existing
- quota receipt still has that exact identity. An empty side is not a match.
+ quota receipt still has that exact identity. A replan-bound receipt keeps
+ the admitted Todo as its pending action selection; that retained selection
+ may address the writeback without replacing the receipt's obligation.
+ An empty or differently bound side is not a match.
"""
identity = run.get("settlement_identity")
@@ -333,7 +336,15 @@ def _expected_todo_receipt(
):
continue
details = _event_details(event)
- todo = todo or _binding_text(event.get("todo_id") or details.get("todo_id"))
+ receipt_replan = _binding_text(details.get("replan_obligation_id"))
+ retained_todo = (
+ _binding_text(details.get("pending_action_selection_todo_id"))
+ if receipt_replan == obligation_id
+ else ""
+ )
+ todo = todo or _binding_text(
+ event.get("todo_id") or details.get("todo_id") or retained_todo
+ )
effect = effect or _binding_text(details.get("settlement_effect_id"))
return todo, effect
@@ -366,7 +377,8 @@ def _writeback_event_is_bound(
if not event_todo or not event_effect:
return False
expected_todo, expected_effect = _expected_todo_receipt(
- run, events, goal_id=goal_id, agent_id=agent_id, turn_instance_id=turn_instance_id)
+ run, events, goal_id=goal_id, agent_id=agent_id,
+ turn_instance_id=turn_instance_id, obligation_id=obligation_id)
return bool(
expected_todo and expected_effect
and event_todo == expected_todo and event_effect == expected_effect
diff --git a/loopx/control_plane/work_items/autonomous_replan_obligation.py b/loopx/control_plane/work_items/autonomous_replan_obligation.py
index c79451204e..0023ae799f 100644
--- a/loopx/control_plane/work_items/autonomous_replan_obligation.py
+++ b/loopx/control_plane/work_items/autonomous_replan_obligation.py
@@ -27,6 +27,18 @@
MAX_AUTONOMOUS_REPLAN_TRIGGERS = 3
AUTONOMOUS_REPLAN_STALL_THRESHOLD = 2
+AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID = "autonomous_replan_default_v0"
+AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION = (
+ "stop only the affected path when required access, destructive git, production actions, "
+ "or owner-only decisions exceed existing user authority. Keep authorized private reads "
+ "within their storage and publication boundaries; do not expose credentials or disclose "
+ "private material beyond that authority. Continue independent authorized replan work "
+ "while honoring explicit stops"
+)
+AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION = (
+ "stop this replan path until a compatible reader validates its digest-bound "
+ "review guard"
+)
REPLAN_NOVELTY_POLICY_SCHEMA_VERSION = "replan_evidence_delivery_policy_v0"
TODO_LIFECYCLE_SETTLEMENT_RESOLUTION_MODE = "todo_lifecycle_settlement"
REPLAN_NOVELTY_GUIDANCE = (
@@ -642,13 +654,7 @@ def build_autonomous_replan_obligation(
else ["keep", "split", "add", "retire", "ask_decision"]
),
todo_actions=todo_actions[:3],
- stop_condition=(
- "stop only the affected path when required access, destructive git, production actions, "
- "or owner-only decisions exceed existing user authority. Keep authorized private reads "
- "within their storage and publication boundaries; do not expose credentials or disclose "
- "private material beyond that authority. Continue independent authorized replan work "
- "while honoring explicit stops"
- ),
+ stop_condition=AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION,
recommended_action=recommended_action,
agent_id=replan_agent_id,
extra_fields=extra_fields,
diff --git a/loopx/control_plane/work_items/interaction_contract.py b/loopx/control_plane/work_items/interaction_contract.py
index 73070b5732..7bc65511b2 100644
--- a/loopx/control_plane/work_items/interaction_contract.py
+++ b/loopx/control_plane/work_items/interaction_contract.py
@@ -13,6 +13,8 @@
import typing
from collections.abc import Collection, Mapping
+from ...install_contract import render_host_cli_command
+
from ..agents.agent_scope_frontier import AgentScopeFrontierAction, agent_scope_frontier_action as _agent_scope_frontier_action
from ..agents.capability_gate import runtime_capabilities_for_cli_projection
from ..agents.workspace_guard import delivery_workspace_refresh_hint
@@ -47,7 +49,7 @@
normalize_todo_replan_obligation_id,
)
from ..todos.todo_semantics import todo_item_task_class
-from ..todos.user_gate import has_only_open_user_actions, open_todo_count
+from ..todos.user_gate import has_only_open_user_actions, open_todo_count, open_user_gate_todo_items
from ..todos.write_hint import build_capability_resolution_writeback_actions
from .autonomous_replan_obligation import (
build_autonomous_replan_cli_actions,
@@ -463,6 +465,17 @@ def _due_monitor_cli_actions(
]
+# Observation is evidence, never an owner decision: no completion command is projected.
+# Keep the text free of quote characters; consumers shlex-split every action.
+MONITOR_USER_GATE_NOTICE = (
+ "A Monitor observation never completes or approves a User gate. Do not pass the id or claim proof "
+ "of this Turn to a gate completion, and do not attach evidence to a gate through todo update. "
+ "Record the observation with the poll below and yield. Work that may continue on an observed change "
+ "without an owner decision belongs in the successor of that poll (--material-change with "
+ "--next-agent-todo), not behind a User gate."
+)
+
+
def _turn_scoped_cli_settlement_context(
payload: dict[str, Any],
*,
@@ -633,7 +646,7 @@ def _selection_recovery_command(
def _render_replan_successor_closeout_guard(
*, settlement_plan: Mapping[str, Any] | None,
- scheduler_args: str, typed_quota_guard: str, settlement_args: str,
+ scheduler_args: str, typed_quota_guard: str,
) -> str | None:
"""Render this host's guard for an existing TS-owned pure replan identity."""
if not scheduler_args or not settlement_plan:
@@ -642,7 +655,11 @@ def _render_replan_successor_closeout_guard(
if not isinstance(identity, Mapping) or identity.get("binding_kind") != "autonomous_replan":
# Todo-bound replans retain their distinct closeout path.
return None
- return typed_quota_guard + settlement_args
+ # The receipt recovers the obligation; should-run accepts only its Turn.
+ return render_host_cli_command([
+ *shlex.split(typed_quota_guard),
+ "--turn-instance-id", str(identity["turn_instance_id"]),
+ ])
def _deferred_resume_continuation(
@@ -1019,7 +1036,7 @@ def _admitted_interaction_next_cli_actions(
),
successor_closeout_guard=_render_replan_successor_closeout_guard(
settlement_plan=settlement_plan, scheduler_args=scheduler_args,
- typed_quota_guard=typed_quota_guard, settlement_args=settlement_args,
+ typed_quota_guard=typed_quota_guard,
),
)
return _terminal_cli_actions(
@@ -1396,7 +1413,7 @@ def _build_interaction_cli_channel(
registry_path=registry_path,
)
)
- channel = {
+ channel: dict[str, Any] = {
"next_cli_actions": _admitted_interaction_next_cli_actions(
payload,
mode=mode,
@@ -1436,6 +1453,10 @@ def _build_interaction_cli_channel(
work_lane = payload.get("work_lane_contract")
if not isinstance(work_lane, Mapping):
work_lane = {}
+ if primary_monitor is not None and turn_instance_id and open_user_gate_todo_items(payload.get("user_todo_summary")):
+ # Keep the Monitor instruction first; the notice precedes the poll it qualifies.
+ actions = channel["next_cli_actions"]
+ channel["next_cli_actions"] = [*actions[:1], MONITOR_USER_GATE_NOTICE, *actions[1:]]
auxiliary_monitor = work_lane.get("auxiliary_monitor_poll")
if not isinstance(auxiliary_monitor, Mapping):
auxiliary_monitor = None
diff --git a/loopx/control_plane/work_items/project_asset.py b/loopx/control_plane/work_items/project_asset.py
index 7b07aa09ee..44dc44bc65 100644
--- a/loopx/control_plane/work_items/project_asset.py
+++ b/loopx/control_plane/work_items/project_asset.py
@@ -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):
@@ -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 []
@@ -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
diff --git a/loopx/control_plane/work_items/replan_history_settlement.ts b/loopx/control_plane/work_items/replan_history_settlement.ts
index b09652f49e..be0578ff4b 100644
--- a/loopx/control_plane/work_items/replan_history_settlement.ts
+++ b/loopx/control_plane/work_items/replan_history_settlement.ts
@@ -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,
@@ -17,6 +17,7 @@ export async function projectSettledReplanHistory(value: unknown): Promise {
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());
}
diff --git a/loopx/control_plane/work_items/replan_semantics.ts b/loopx/control_plane/work_items/replan_semantics.ts
index 748e4ca126..3431e4b1a7 100644
--- a/loopx/control_plane/work_items/replan_semantics.ts
+++ b/loopx/control_plane/work_items/replan_semantics.ts
@@ -1,4 +1,5 @@
import type { JsonObject } from "../effect_program.ts";
+import { createHash } from "node:crypto";
import { BARE_SHA256_PATTERN } from "../content_digest.ts";
import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts";
import { optionalNonEmptyString, requireJsonObject, requireNonEmptyString } from "../runtime_decode.ts";
@@ -35,7 +36,17 @@ const ACCEPTANCE_HOLD_TRIGGERS = new Set(["goal_acceptance_stale", "goal_accepta
// These review kinds carry no evidence window, capability or lifecycle duty.
// A vision gap dominates the ordinary outcome gap's discharge policy, so the
// same scalar receipt can retain a mixed review after its work links change.
-const SCALAR_REVIEW_KINDS = new Set(["goal_outcome_uncovered", "vision_acceptance_gap"]);
+const SCALAR_REVIEW_KINDS = new Set(["goal_outcome_uncovered", "vision_acceptance_gap", "monitor_no_change_streak"]);
+const RECONSTRUCTIBLE_REVIEW_KINDS = new Set([...SCALAR_REVIEW_KINDS, "periodic_review_due"]);
+export const AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID = "autonomous_replan_default_v0";
+export const AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION =
+ "stop only the affected path when required access, destructive git, production actions, " +
+ "or owner-only decisions exceed existing user authority. Keep authorized private reads " +
+ "within their storage and publication boundaries; do not expose credentials or disclose " +
+ "private material beyond that authority. Continue independent authorized replan work " +
+ "while honoring explicit stops";
+export const AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION =
+ "stop this replan path until a compatible reader validates its digest-bound review guard";
const EXTERNAL_REVIEW_TRIGGERS = new Set(["external_progress_review_drift"]);
export const FRESH_PATH_DISPOSITIONS = new Set(["continue", "no_change", "replan"]);
const PROGRESS_CLI_ARGS = "--progress-result-class --progress-surface-id --progress-hypothesis-id --progress-probe-kind --progress-evidence-id ";
@@ -76,6 +87,20 @@ function triggerKinds(obligation: JsonObject): string[] {
const triggers = Array.isArray(obligation.triggers) ? obligation.triggers : [];
return triggers.map(trigger => String(object(trigger).kind ?? "").trim());
}
+function receiptReviewKind(obligation: JsonObject): string | null {
+ const kinds = triggerKinds(obligation);
+ if (!kinds.length) return null;
+ if (kinds.every(kind => SCALAR_REVIEW_KINDS.has(kind))) {
+ // Preserve the current frontier's precedence, including Monitor-only
+ // reviews, when selecting a scalar or digest-backed receipt source.
+ return ["vision_acceptance_gap", "goal_outcome_uncovered", "monitor_no_change_streak"]
+ .find(kind => kinds.includes(kind)) ?? null;
+ }
+ // A single current review can be revalidated by its kind and complete stop
+ // contract without pretending that an old context is current. Mixed duties
+ // retain their source-specific recovery instead of collapsing to one label.
+ return kinds.length === 1 ? kinds[0] : null;
+}
function isExternalReview(obligation: JsonObject): boolean {
return triggerKinds(obligation).some(kind => EXTERNAL_REVIEW_TRIGGERS.has(kind));
}
@@ -389,6 +414,44 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject {
// writeback. The exact receipt retains its typed kind, never raw task prose
// or an old decision context. Other duties keep their canonical owners.
const review = object(request.receipt_review);
+ const reviewKind = typeof review.kind === "string" ? review.kind : "";
+ const reviewStop = typeof review.stop_condition === "string"
+ ? review.stop_condition : null;
+ const reviewDigest = typeof review.stop_condition_sha256 === "string"
+ ? review.stop_condition_sha256 : "";
+ const reviewContractId = typeof review.stop_contract_id === "string"
+ ? review.stop_contract_id : "";
+ const reviewContractStop = reviewContractId === AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID &&
+ BARE_SHA256_PATTERN.test(reviewDigest) &&
+ createHash("sha256").update(AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, "utf8").digest("hex") === reviewDigest
+ ? AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION : null;
+ const currentReviewKind = current === null ? null : receiptReviewKind(current);
+ const currentStop = current === null || typeof current.stop_condition !== "string"
+ ? null : current.stop_condition;
+ if (request.guard_scoped && current !== null && currentReviewKind === reviewKind &&
+ currentStop !== null && (currentStop === reviewStop ||
+ (BARE_SHA256_PATTERN.test(reviewDigest) &&
+ createHash("sha256").update(currentStop, "utf8").digest("hex") === reviewDigest)) &&
+ current.schema_version === "autonomous_replan_obligation_v0" && current.required === true &&
+ typeof request.agent_id === "string" && request.agent_id.trim() &&
+ current.agent_id === request.agent_id && current.resolution_mode == null &&
+ current.capability_guard == null) {
+ // The frontier regenerated the review identity while its kind and complete
+ // stop contract stayed unchanged. Preserve the receipt's settlement id,
+ // but retain the current obligation and context so recovery never claims
+ // that an old context snapshot is still current.
+ const rebound: JsonObject = {...current, obligation_id: selected,
+ selection_binding: "heartbeat_receipt"};
+ if (current.obligation_id !== selected) {
+ // The current context and its delivery receipt were derived under the
+ // regenerated frontier id. Returning them under the old settlement id
+ // would create an internally inconsistent packet. The quota context
+ // owner reattaches a fresh context from current status after this typed
+ // identity projection; no historical context snapshot is replayed.
+ delete rebound.replan_context;
+ }
+ return {obligation: rebound};
+ }
if (request.guard_scoped && SCALAR_REVIEW_KINDS.has(String(review.kind)) &&
typeof review.stop_condition === "string" && review.stop_condition.trim() && review.stop_condition.length <= 240 &&
typeof request.agent_id === "string" && request.agent_id.trim()) {
@@ -397,6 +460,14 @@ function preserveReceiptBoundObligation(request: JsonObject): JsonObject {
stop_condition: review.stop_condition,
triggers: [{kind: review.kind}], selection_binding: "heartbeat_receipt"}};
}
+ if (request.guard_scoped && current === null &&
+ RECONSTRUCTIBLE_REVIEW_KINDS.has(reviewKind) && reviewContractStop !== null &&
+ typeof request.agent_id === "string" && request.agent_id.trim()) {
+ return {obligation: {schema_version: "autonomous_replan_obligation_v0",
+ required: true, obligation_id: selected, agent_id: request.agent_id,
+ stop_condition: reviewContractStop,
+ triggers: [{kind: reviewKind}], selection_binding: "heartbeat_receipt"}};
+ }
throw new EffectRuntimeRequestError(
"heartbeat receipt settlement identity conflicts with the current autonomous replan obligation",
"heartbeat_receipt_identity_conflict",
@@ -547,24 +618,22 @@ export function projectReplanSemantics(value: unknown): JsonObject {
if (request.operation === "receipt_bound_obligation") return preserveReceiptBoundObligation(request);
const obligation = requireJsonObject(request.obligation, "obligation");
if (request.operation === "receipt_review_source") {
- const kinds = triggerKinds(obligation);
const triggers = Array.isArray(obligation.triggers) ? obligation.triggers : [];
- // Plain vision/outcome reviews share a scalar receipt source. Other mixed,
- // restricted, lifecycle and capability obligations must retain their
+ const kind = receiptReviewKind(obligation);
+ // A simple review stores only its kind and complete stop contract. Other
+ // mixed, restricted, lifecycle and capability obligations must retain
// source-specific evidence and discharge rules through their own owners.
return {review_source: obligation.schema_version === "autonomous_replan_obligation_v0" &&
- obligation.required === true && kinds.length > 0 &&
+ obligation.required === true && kind !== null &&
obligation.trigger_count === triggers.length &&
typeof request.agent_id === "string" && request.agent_id.trim() &&
obligation.agent_id === request.agent_id &&
- kinds.every(kind => SCALAR_REVIEW_KINDS.has(kind)) &&
obligation.resolution_mode == null && obligation.capability_guard == null &&
strings(obligation.satisfying_semantic_outcomes).length === 0 &&
obligation.progress_baseline == null && obligation.progress_window == null &&
triggers.every(trigger => object(trigger).progress_baseline == null && object(trigger).progress_window == null) &&
- typeof obligation.stop_condition === "string" && obligation.stop_condition.trim() && obligation.stop_condition.length <= 240
- ? {kind: kinds.includes("vision_acceptance_gap") ? "vision_acceptance_gap" : "goal_outcome_uncovered",
- stop_condition: obligation.stop_condition} : null};
+ typeof obligation.stop_condition === "string" && obligation.stop_condition.trim()
+ ? {kind, stop_condition: obligation.stop_condition} : null};
}
if (request.operation === "transition_eligibility") {
return {allowed: !requiresStrideDecision(obligation, request.stride_strategy)};
@@ -574,6 +643,19 @@ export function projectReplanSemantics(value: unknown): JsonObject {
if (request.operation === "requirements") {
const strideControl = strideControlContract(object(obligation.replan_context), obligation.obligation_id);
const writeback = writebackProjection(required, externalReview, strideControl !== null);
+ if (required.includes("coverage_backed_no_followup")) {
+ writeback.writeback_contract = {...object(writeback.writeback_contract),
+ no_followup_requirements: {
+ cli_args: ["--progress-result-class", "no_followup", "--progress-coverage-scope-id", "",
+ "--progress-evidence-id", "",
+ "--agent-vision-json", ""],
+ vision_fields: {state: "no_followup", "path_delta.outcome": "stop"},
+ preserve: ["vision_patch"],
+ rule: "Use verified scope coverage and the vision_authoring path_delta fields with evidence_refs. " +
+ "Retain the current complete vision_patch: changing durable fields requires outcome=replan and cannot be combined with stop. " +
+ "Write back and spend with the original settlement_plan identity, not a later obligation.",
+ }};
+ }
if (requiresStrideDecision(obligation)) {
const contract = object(writeback.writeback_contract);
writeback.cli_semantic_args = VISION_CLI_ARGS;
diff --git a/loopx/extensions/lark/private_conversations.py b/loopx/extensions/lark/private_conversations.py
index 8ec48634ef..0adb10bf31 100644
--- a/loopx/extensions/lark/private_conversations.py
+++ b/loopx/extensions/lark/private_conversations.py
@@ -33,7 +33,7 @@
from ...control_plane.collaboration import conversation_reply_context
from ...control_plane.content_digest import BARE_SHA256_PATTERN
from ...control_plane.effect_runtime import effect_runtime_request_scope
-from ...file_lock import exclusive_file_lock
+from ...file_lock import exclusive_file_lock, try_exclusive_file_lock
from ...presentation.markdown import markdown_scalar
from ...presentation.renderers.conversation_status_markdown import render_conversation_status
from .conversation_identity import identity_ref, lark_private_source
@@ -41,7 +41,9 @@
from .event_collector_runtime import enrich_lark_event_reply_context
from .goal_channel_transport import call, json_payload, lark_args, lark_provider_mention_identities, record_event_timing
from .identity_shapes import LARK_APP_ID_PATTERN as APP_ID_PATTERN, LARK_MESSAGE_ID_PATTERN
-from .inbox_reply import _message, reply_lark_event_inbox, update_lark_inbox_reply, verify_lark_inbox_reply
+from .inbox_reply import (
+ SourceAuthorityVerifier, _message, reply_lark_event_inbox, update_lark_inbox_reply, verify_lark_inbox_reply,
+)
from .manager_context import manager_failure_reply
from .inbox_reactions import (_reconcile_outbound_input_reactions,
mark_lark_event_inbox_processing, mark_lark_event_inbox_received)
@@ -1262,6 +1264,7 @@ def _feedback(self, path: Path, record: dict[str, Any], *, inbox: Callable[[], P
def _deliver(self, path: Path, record: dict[str, Any], phase: str, text: str, *, inbox: Callable[[], Path],
edit_only: bool = False, authorization_check: Callable[[], bool] | None = None,
+ source_authority_verifier: SourceAuthorityVerifier | None = None,
reply_placement: str | None = None, delivery_id: str | None = None,
finalize_source: bool = True, image_attachments: list[dict[str, Any]] | None = None,
historical_source_check: Callable[[], bool] | None = None) -> bool:
@@ -1276,9 +1279,8 @@ def _deliver(self, path: Path, record: dict[str, Any], phase: str, text: str, *,
if historical_source_check is not None and phase != "answer_images.historical":
raise ValueError("historical source verification requires a media repair")
phase = presentation_phase(record, phase)
- source_authority = partial(self._source_authority, record)
- if kind == "answer_images":
- source_authority = partial(source_authority, expected_text=record["event"]["content"])
+ expected_text = record["event"]["content"] if kind == "answer_images" else None
+ source_authority = source_authority_verifier or partial(self._source_authority, record, expected_text=expected_text)
phase_state = record["deliveries"].get(phase, {})
if phase_state.get("verified"):
return True
@@ -1289,10 +1291,12 @@ def _deliver(self, path: Path, record: dict[str, Any], phase: str, text: str, *,
text = _presentation_text(text)
if phase_state.get("text") not in (None, text):
raise ValueError("delivery content changed after an attempt")
- if image_attachments and (authorization_check is None or edit_only
- or not ((kind == "web" and reply_placement == "chat_root")
+ if image_attachments and (edit_only
+ or not ((kind == "web" and reply_placement == "chat_root"
+ and (authorization_check is not None or source_authority_verifier is not None))
or (kind == "answer_images" and record["event"].get("chat_type") == "p2p"
- and record["source"].get("private_human_message") is True))):
+ and record["source"].get("private_human_message") is True
+ and authorization_check is not None))):
raise ValueError("Image projection requires its original private outbox")
record_event_timing(record["profile"], record["event"]["message_id"], "delivery_started")
config = inbox()
@@ -1318,8 +1322,9 @@ def verified_source() -> bool:
def image_authorized() -> bool:
# A provider read can overlap Stop, Close, or an edit to the old reply.
- return authorization_check is not None and (provider_images_current() and authorization_check()
- if kind == "answer_images" else authorization_check() and verified_source())
+ if kind == "answer_images":
+ return provider_images_current() and authorization_check is not None and authorization_check()
+ return (authorization_check is None or authorization_check()) and verified_source()
image_keys = ()
if image_attachments:
@@ -2114,11 +2119,17 @@ def _reconcile_web_projection(self, path: Path) -> int:
for message in messages) else "delivered"
_atomic_write_json(path, row)
return 0
- def authorized() -> bool:
+ def authorized_source(profile: str, chat_id: str, message_id: str) -> tuple[str | None, bool]:
+ # Check the original provider source first. The fresh App
+ # grant and canonical body checks then cover any changes
+ # during that read, both before preview and before dispatch.
+ name, verified = self._source_authority(row, profile, chat_id, message_id)
+ if not name or not verified:
+ return None, False
try:
- return pending in self._web_projection_messages(row)
+ return name, pending in self._web_projection_messages(row)
except (OSError, ValueError, KeyError):
- return False
+ return None, False
who = "你" if pending["role"] == "user" else "LoopX"
text = f"**{who}(App)**\n\n{pending['text']}"
if self.reaction_feedback and pending["role"] == "user":
@@ -2127,7 +2138,7 @@ def authorized() -> bool:
row["deliveries"].setdefault("web." + pending["message_id"], {}).setdefault("feedback", {})
_atomic_write_json(path, row)
delivered = self._deliver(path, row, "web." + pending["message_id"], text,
- inbox=lambda: self._inbox(row), authorization_check=authorized,
+ inbox=lambda: self._inbox(row), source_authority_verifier=authorized_source,
reply_placement="chat_root", delivery_id=self._web_projection_delivery_id(row, pending), finalize_source=False,
image_attachments=pending.get("attachments"))
if delivered:
@@ -2140,18 +2151,17 @@ def authorized() -> bool:
return 0
def reconcile_app_feedback(self) -> int:
- """Reconcile optional reactions independently of the body outbox.
-
- The live service reserves at most one existing reply worker for this
- pass. A slow reaction must never own the body-delivery fence or prevent
- a later canonical answer from reaching the same audience.
- """
+ """Reconcile optional reactions independently of the body outbox."""
if not self.reaction_feedback:
return 0
for path in sorted((self.root / "web-projections").glob("*.json")):
with exclusive_file_lock(path.with_suffix(".feedback"), operation="reconcile_web_input_feedback"):
try:
- with exclusive_file_lock(path, operation="read_web_input_feedback"):
+ # Leave a busy body outbox for the next feedback pass so
+ # independent Sessions can still acknowledge their inputs.
+ with try_exclusive_file_lock(path, operation="read_web_input_feedback") as lock:
+ if lock is None:
+ continue
row = self._read_web_projection_journal(path)
except (OSError, ValueError):
continue
@@ -2176,7 +2186,11 @@ def reconcile_app_feedback(self) -> int:
self._web_projection_feedback(row, message)
if "feedback" not in phase or phase["feedback"] == prior_feedback:
continue
- with exclusive_file_lock(path, operation="record_web_input_feedback"):
+ # The reaction has its own receipt. Defer writeback when
+ # a body worker acquired the journal during provider I/O.
+ with try_exclusive_file_lock(path, operation="record_web_input_feedback") as lock:
+ if lock is None:
+ continue
try:
current = self._read_web_projection_journal(path)
except (OSError, ValueError):
diff --git a/loopx/global_todos.py b/loopx/global_todos.py
index 71103af9b1..11aa3d97f7 100644
--- a/loopx/global_todos.py
+++ b/loopx/global_todos.py
@@ -4,6 +4,10 @@
from pathlib import Path
from typing import Any
+from .control_plane.goals.contract_health import (
+ CONTRACT_ERROR_DIAGNOSTIC_SCHEMA_VERSION,
+ contract_error_views,
+)
from .control_plane.projection_envelope_facts import (
render_projection_envelope_markdown,
seal_projection_envelope,
@@ -392,10 +396,50 @@ def _deduplicate_todos(
return list(deduplicated.values())
+def _scoped_status_failure(
+ status_payload: dict[str, Any],
+) -> tuple[set[str], set[str]] | None:
+ registry = as_dict(status_payload.get("global_registry"))
+ contract = as_dict(status_payload.get("contract"))
+ diagnostics = contract.get("error_diagnostics")
+ if (
+ registry.get("available") is not True
+ or registry.get("ok") is not True
+ or contract.get("ok") is not False
+ or contract.get("global_errors")
+ or not isinstance(diagnostics, list)
+ or not diagnostics
+ or not all(
+ isinstance(row, dict)
+ and row.get("schema_version") == CONTRACT_ERROR_DIAGNOSTIC_SCHEMA_VERSION
+ for row in diagnostics
+ )
+ ):
+ return None
+ views = contract_error_views(diagnostics)
+ if (
+ views["global_errors"]
+ or views["errors"] != contract.get("errors")
+ or len(views["error_diagnostics"]) != len(diagnostics)
+ ):
+ return None
+ failed_goals = set(views["goal_errors"])
+ registered_goals = {
+ row["id"]
+ for row in as_list(as_dict(status_payload.get("run_history")).get("goals"))
+ if isinstance(row, dict) and row.get("registry_member") is True
+ and isinstance(row.get("id"), str) and row["id"]
+ }
+ if not failed_goals or not failed_goals <= registered_goals:
+ return None
+ return registered_goals, failed_goals
+
+
def _queue_goal_ids(
status_payload: dict[str, Any],
*,
scan_limit: int,
+ eligible_goals: set[str] | None = None,
) -> tuple[list[str], int]:
queue = as_dict(status_payload.get("attention_queue"))
unique_goal_ids: list[str] = []
@@ -412,6 +456,12 @@ def _queue_goal_ids(
reported_count = max(0, int(queue.get("item_count") or 0))
except (TypeError, ValueError):
reported_count = 0
+ # A degraded status queue can include a synthetic contract warning in
+ # place of the failed Goal. Only the observed registry can name read scopes.
+ if eligible_goals is not None:
+ eligible = [goal_id for goal_id in unique_goal_ids if goal_id in eligible_goals]
+ reported_count -= len(unique_goal_ids) - len(eligible)
+ unique_goal_ids = eligible
available_count = max(len(unique_goal_ids), reported_count)
return unique_goal_ids[:scan_limit], available_count
@@ -426,6 +476,7 @@ def _todos_envelope(
goal_scan_omitted: int,
shown_count: int,
available_count: int,
+ failed_status_goals: set[str] | None = None,
) -> dict[str, Any]:
global_registry = as_dict(status_payload.get("global_registry"))
status_envelope = as_dict(status_payload.get("projection_envelope"))
@@ -467,7 +518,13 @@ def _todos_envelope(
omitted.append(
{"reason": "attention_goals_not_scanned", "count": goal_scan_omitted}
)
- if status_payload and status_payload.get("ok") is not True:
+ if failed_status_goals:
+ omitted.append({
+ "reason": "status_unavailable",
+ "count": len(failed_status_goals),
+ "refs": [_redact_text(goal_id, limit=120) for goal_id in sorted(failed_status_goals)[:8]],
+ })
+ elif status_payload and status_payload.get("ok") is not True:
omitted.append({"reason": "status_unavailable", "count": 1})
queue = status_payload.get("attention_queue")
queue_read = isinstance(queue, dict) and isinstance(queue.get("items"), list)
@@ -516,7 +573,7 @@ def _todos_envelope(
"scope": "global",
"expected_count": expected,
"included_count": (
- max(0, expected - excluded - goal_scan_omitted)
+ max(0, expected - excluded - goal_scan_omitted - len(failed_status_goals or ()))
if expected is not None
else 0
),
@@ -554,21 +611,27 @@ def build_global_todos(
limit=scan_limit,
)
status_read_at = now_utc_iso()
- if status_payload.get("ok") is not True:
+ status_ok = status_payload.get("ok") is True
+ scoped_failure = None if status_ok else _scoped_status_failure(status_payload)
+ registered_goals, failed_status_goals = scoped_failure or (set(), set())
+ goal_ids, available_goal_count = _queue_goal_ids(
+ status_payload,
+ scan_limit=scan_limit,
+ eligible_goals=registered_goals - failed_status_goals if scoped_failure else None,
+ )
+ if not status_ok and (scoped_failure is None or not goal_ids):
return build_global_todos_error(
"Global status source unavailable.",
status_payload=status_payload,
status_read_at=status_read_at,
)
-
- goal_ids, available_goal_count = _queue_goal_ids(
- status_payload,
- scan_limit=scan_limit,
- )
- warnings: list[dict[str, Any]] = []
+ warnings = [
+ _warning("quota_unavailable", goal_id=goal_id, detail="The Goal's status contract check failed.")
+ for goal_id in sorted(failed_status_goals)
+ ]
classified: list[dict[str, Any]] = []
quota_read_at = now_utc_iso()
- quota_unavailable = 0
+ quota_unavailable = len(failed_status_goals)
for goal_id in goal_ids:
quota_payloads, was_unavailable = _quotas_for_goal(
status_payload,
@@ -655,6 +718,7 @@ def build_global_todos(
goal_scan_omitted=max(0, available_goal_count - len(goal_ids)),
shown_count=returned_count,
available_count=matched_count,
+ failed_status_goals=failed_status_goals,
),
"omissions": [
(
diff --git a/loopx/paths.py b/loopx/paths.py
index 9a5a41cf5a..84dc5eb3cd 100644
--- a/loopx/paths.py
+++ b/loopx/paths.py
@@ -236,8 +236,9 @@ def default_runtime_route() -> dict[str, object]:
recommended_action = None
if status == "conflict":
recommended_action = (
- "Select one registry with --registry/--runtime-root; "
- "inspect both roots before migration."
+ "Use --registry alone with a concrete registry file that declares its runtime "
+ "to follow the registered Goal sources. Use --runtime-root for an explicit "
+ "single-runtime operation. Inspect both roots before migration."
)
elif status == "invalid":
recommended_action = (
@@ -271,10 +272,7 @@ def select_default_runtime_root() -> Path:
if route["target_registry_exists"] and route["legacy_registry_exists"]
else "Both default LoopX runtime roots contain state."
)
- raise ValueError(
- f"{conflict} Select an explicit --registry and "
- "--runtime-root; resolve the route conflict before using implicit defaults."
- )
+ raise ValueError(f"{conflict} {route['recommended_action']}")
if route["status"] == "invalid":
raise ValueError(str(route["recommended_action"]))
return Path(str(route["selected_runtime_root"]))
diff --git a/loopx/presentation/goal_storage_api.py b/loopx/presentation/goal_storage_api.py
index 10630b6e1b..77017193fa 100644
--- a/loopx/presentation/goal_storage_api.py
+++ b/loopx/presentation/goal_storage_api.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import hashlib
+from contextlib import ExitStack
import json
import os
import re
@@ -13,7 +14,7 @@
from ..control_plane.effect_runtime import effect_runtime_result
from ..control_plane.coordination.local_authority_shadow_projection import source_effect_runtime_result
-from ..file_lock import exclusive_file_lock, write_json_atomic
+from ..file_lock import exclusive_cross_runtime_file_lock, exclusive_file_lock, write_json_atomic
CHAT_GOAL_STORAGE_PATH = "/api/chat/goal-storage"
@@ -119,6 +120,53 @@ def _storage_send(self, result: dict[str, Any], goal_id: str, preview_id: str |
payload["preview_id"] = preview_id
self._send_json(payload, status=200 if result.get("ok") else 409)
+ def _storage_source_registry(
+ self, goal_id: str, registry: dict[str, Any], goal: dict[str, Any], root: Path,
+ *, registry_path: Path | None = None,
+ ) -> Path:
+ invoked = registry_path if registry_path is not None else Path(self.server.registry_path).resolve()
+ if not goal.get("source_registry"):
+ return invoked
+
+ from ..control_plane.runtime.runtime_projection_route import resolve_goal_source_runtime_route
+
+ route = resolve_goal_source_runtime_route(
+ registry_path=invoked, registry=registry, goal_id=goal_id,
+ )
+ # A Chat runtime can be bound directly to the source behind a global
+ # index. Keep the host's runtime scope and existing same-root plans.
+ if (route["routed_to_source_registry"]
+ and route["invoked_runtime_root"] != str(root)
+ and route["source_runtime_root"] == str(root)):
+ return Path(route["source_registry"])
+ return invoked
+
+ def _storage_cold_snapshot(
+ self, goal_id: str, registry: dict[str, Any], goal: dict[str, Any],
+ root: Path, source_registry: Path,
+ ) -> tuple[Path, dict[str, object], dict[str, object]]:
+ from ..control_plane.coordination.authority_source_capture import build_runtime_shadow_source_snapshot
+ from ..control_plane.goals.state_resolution import resolve_goal_state
+ from ..control_plane.projects.registry_codec import load_project_registry
+ from ..registry import find_registry_goal
+
+ if source_registry != Path(self.server.registry_path).resolve():
+ registry = load_project_registry(source_registry)
+ selected_goal = find_registry_goal(registry, goal_id)
+ if selected_goal is None:
+ raise ValueError("registered Goal source changed")
+ goal = selected_goal
+ _, project, state = resolve_goal_state(
+ registry=registry, goal_id=goal_id, project_override=None, state_file_override=None,
+ )
+ if project is None:
+ raise ValueError("registered project is required")
+ projection, snapshot = build_runtime_shadow_source_snapshot(
+ goal=goal, runtime_root=root, state_path=state, registry_path=source_registry,
+ include_all_archived_todos=True,
+ )
+ return project, projection, snapshot
+
def _storage_inspect(self) -> None:
try:
query = parse_qs(urlparse(self.path).query, keep_blank_values=True)
@@ -133,18 +181,14 @@ def _storage_inspect(self) -> None:
result = self._storage_owner(goal_id, action="migration-readback")
current = result.get("current")
if result.get("ok") and isinstance(current, dict) and current.get("canonical") is False:
- from ..control_plane.coordination.local_authority_shadow_projection import source_effect_runtime_result
- from ..control_plane.coordination.authority_source_capture import build_runtime_shadow_source_snapshot
- from ..state_refresh import resolve_goal_state
-
- _, _, state_path = resolve_goal_state(registry=registry, goal_id=goal_id,
- project_override=None, state_file_override=None)
- projection, snapshot = build_runtime_shadow_source_snapshot(goal=goal,
- runtime_root=self.server.runtime_root, state_path=state_path,
- registry_path=self.server.registry_path, include_all_archived_todos=True)
+ root = self.server.runtime_root.resolve()
+ source_registry = self._storage_source_registry(goal_id, registry, goal, root)
+ _, projection, snapshot = self._storage_cold_snapshot(
+ goal_id, registry, goal, root, source_registry,
+ )
result = source_effect_runtime_result("coordination.source.inspect_storage", {
"schema_version": "loopx_cold_source_inspection_request_v0",
- "runtime_root": str(self.server.runtime_root.expanduser().absolute()),
+ "runtime_root": str(root),
"goal_id": goal_id, "projection": projection, "source_snapshot": snapshot,
})
_, saved = self._storage_preview_read(self._storage_preview_path(goal_id), goal_id)
@@ -274,20 +318,12 @@ def _storage_import(self, *, action: str) -> None:
request: dict[str, Any] = {"schema_version": "loopx_cold_source_import_request_v0",
"action": action, "runtime_root": str(root), "goal_id": goal_id, "operation_id": operation}
if action == "prepare":
- from ..control_plane.goals.state_resolution import resolve_goal_state
- from ..control_plane.coordination.authority_source_capture import build_runtime_shadow_source_snapshot
from ..control_plane.coordination.cold_source_backup import create_cold_source_backup
- _, project, state = resolve_goal_state(registry=registry, goal_id=goal_id,
- project_override=None, state_file_override=None)
- if project is None:
- raise ValueError("registered project is required")
- # Source capture witnesses physical filenames. Give backup IO
- # the same registry route so directory aliases cannot split
- # its saved member map from the source's byte witness.
- registry_path = Path(self.server.registry_path).resolve()
- projection, snapshot = build_runtime_shadow_source_snapshot(goal=goal, runtime_root=root,
- state_path=state, registry_path=registry_path, include_all_archived_todos=True)
+ registry_path = self._storage_source_registry(goal_id, registry, goal, root)
+ project, projection, snapshot = self._storage_cold_snapshot(
+ goal_id, registry, goal, root, registry_path,
+ )
source_paths = [
Path(snapshot["state_path"]), Path(snapshot["registry_source"]["path"]),
*(Path(item["path"]) for item in snapshot["evidence_files"]),
@@ -304,7 +340,30 @@ def _storage_import(self, *, action: str) -> None:
request["writers_stopped"] = body["writers_stopped"]
path = self._storage_preview_path(goal_id)
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
- with exclusive_file_lock(path):
+ with exclusive_file_lock(path), ExitStack() as source_lock:
+ if action == "apply":
+ from ..registry import find_registry_goal, load_registry
+
+ invoked = Path(self.server.registry_path).resolve()
+ source_lock.enter_context(exclusive_cross_runtime_file_lock(
+ invoked, operation="cold_source_import",
+ ))
+ # A global index selects the source but is not in the
+ # typed cutover's source locks. Re-read its mapping under
+ # the registry writer's lock and retain it through Apply.
+ registry = load_registry(invoked)
+ current_goal = find_registry_goal(registry, goal_id)
+ if current_goal is None:
+ raise ValueError("registered Goal source changed")
+ selected = self._storage_source_registry(
+ goal_id, registry, current_goal, root, registry_path=invoked,
+ )
+ request["expected_source_registry"] = str(selected)
+ if selected == invoked:
+ # The typed owner locks this same file and verifies
+ # its immutable plan witness before fencing. Do not
+ # hold a second process's lock across that call.
+ source_lock.close()
if action == "readback":
known, saved = os.path.lexists(path), None
else:
diff --git a/loopx/quota.py b/loopx/quota.py
index 68f27bd509..0c8bbfbfb6 100644
--- a/loopx/quota.py
+++ b/loopx/quota.py
@@ -1088,6 +1088,7 @@ def build_quota_should_run(
workspace_path: Path | None = None,
goal_ref: Mapping[str, object] | None = None,
authoritative_fallback_todo_items: FallbackTodoSource = None,
+ app_scheduler_state_observer: Callable[[Mapping[str, Any]], None] | None = None,
) -> dict[str, Any]:
from .control_plane.quota.should_run import (
build_quota_should_run as _build_quota_should_run,
@@ -1134,6 +1135,7 @@ def read_explore_context(read_goal_id: str, read_agent_id: str | None) -> dict[s
goal_ref=goal_ref,
authoritative_fallback_todo_items=authoritative_fallback_todo_items,
replan_explore_reader=read_explore_context,
+ app_scheduler_state_observer=app_scheduler_state_observer,
)
@@ -1835,12 +1837,15 @@ def spend_quota_slot(
),
}
if settlement_readback.spend_run_present:
+ # The precheck verified these terms against the retained debit.
+ # Carry them to the existing receipt writer without charging again.
return {
"ok": True,
"mode": "spend-slot",
"dry_run": not execute,
"appended": False,
"receipt_repair_required": bool(execute),
+ **spend_request,
"goal_id": safe_goal_id,
"agent_id": identity.agent_id,
"todo_id": identity.todo_id,
diff --git a/loopx/state_refresh.py b/loopx/state_refresh.py
index 99d790f275..2859286fa8 100644
--- a/loopx/state_refresh.py
+++ b/loopx/state_refresh.py
@@ -888,6 +888,13 @@ def refresh_state_run(
goal_ref=goal_ref,
source_admission=source_admission,
borrow_source_admission=source_admission is not None,
+ # refresh-state closes the exact admitted Turn. A semantic
+ # replan may retain ``--todo-id`` as its planning selection
+ # while the immutable settlement identity is the replan
+ # obligation recorded by quota should-run. Resolve that
+ # original receipt binding, while the read model still rejects
+ # a different Todo or obligation.
+ resolve_original_binding=True,
refresh_retry=(refresh_retry_request := {
"checkpoint_read_context_id": checkpoint_read_context_id,
"external_delivery": external_delivery,
diff --git a/loopx/status.py b/loopx/status.py
index c64de931c4..cbb5528f2f 100644
--- a/loopx/status.py
+++ b/loopx/status.py
@@ -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,
@@ -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],
@@ -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 []:
diff --git a/man/loopx.1 b/man/loopx.1
index fe854fe8d1..5a3c418659 100644
--- a/man/loopx.1
+++ b/man/loopx.1
@@ -1,4 +1,4 @@
-.TH LOOPX 1 "" "LoopX 2.3.0" "User Commands"
+.TH LOOPX 1 "" "LoopX 2.4.0" "User Commands"
.SH NAME
loopx \- control-plane helper for long-running agent work
.SH SYNOPSIS
diff --git a/packages/dsh-loopx-plugin/src/driver.ts b/packages/dsh-loopx-plugin/src/driver.ts
index 5f144538cf..bdafac88a7 100644
--- a/packages/dsh-loopx-plugin/src/driver.ts
+++ b/packages/dsh-loopx-plugin/src/driver.ts
@@ -1011,6 +1011,7 @@ export class LoopXContinuationDriver {
private async evaluate(state: DriverState): Promise {
if (!this.ready(state)) return false
+ const session = state.agent.session
const startedAt = performance.now()
let stage: AdmissionStage = 'maintenance-slot'
let admissionSignal: AbortSignal | undefined
@@ -1056,6 +1057,9 @@ export class LoopXContinuationDriver {
if (!waitingForIdle && state.controller === controller) state.controller = undefined
}
+ // Cancellation can land after the maintenance callback has built its plan.
+ if (admissionSignal?.aborted || state.agent.session !== session) return false
+
if (plan.kind === 'wait') {
if (plan.schedulerToken !== undefined) state.schedulerToken = plan.schedulerToken
if (plan.unchangedPolls !== undefined) state.unchangedPolls = plan.unchangedPolls
diff --git a/packages/dsh-loopx-plugin/tests/driver.spec.ts b/packages/dsh-loopx-plugin/tests/driver.spec.ts
index 19e11c9443..537e78776d 100644
--- a/packages/dsh-loopx-plugin/tests/driver.spec.ts
+++ b/packages/dsh-loopx-plugin/tests/driver.spec.ts
@@ -2340,6 +2340,49 @@ describe('GoalBar exact-Session Driver bridge', () => {
await driver.dispose()
})
+ it.each([
+ { plan: 'queue', shouldRun: true, interruption: 'Pause' },
+ { plan: 'wait', shouldRun: false, interruption: 'Pause' },
+ { plan: 'queue', shouldRun: true, interruption: 'maintenance cancellation' },
+ { plan: 'wait', shouldRun: false, interruption: 'maintenance cancellation' },
+ ])('discards a $plan plan returned after $interruption', async ({ shouldRun, interruption }) => {
+ const fixture = runnerFixture({ shouldRun, waitMinutes: 5 })
+ const clock = schedulerClock()
+ const host = fakeAgent()
+ const driver = new LoopXContinuationDriver({
+ runner: fixture.runner,
+ isLiveAgent: () => true,
+ retryDelaysMs: [0, 0],
+ clock,
+ })
+ const capture = { agent: host.agent, session: host.agent.session }
+ vi.spyOn(host.agent, 'runMaintenance').mockImplementationOnce(async task => {
+ const maintenance = new AbortController()
+ const plan = await task(maintenance.signal)
+ if (interruption === 'Pause') {
+ await expect(driver.cancelQueued(capture)).resolves.toEqual({ kind: 'applied' })
+ } else {
+ maintenance.abort()
+ }
+ return plan
+ })
+ try {
+ driver.observeAgent(host.agent)
+ host.appendEvent(userSkillInvocationEvent())
+ const interrupted = await driver.evaluateActivatedSession(capture)
+ expect(host.nextTurn).toHaveLength(0)
+ expect(clock.timers).toHaveLength(0)
+ expect(interrupted).toEqual({ kind: 'unavailable', reason: 'evaluation_unavailable' })
+
+ await expect(driver.evaluateActivatedSession(capture)).resolves.toEqual({ kind: 'applied' })
+ expect(fixture.quotaCalls).toHaveLength(2)
+ expect(host.nextTurn).toHaveLength(shouldRun ? 1 : 0)
+ expect(clock.timers).toHaveLength(shouldRun ? 0 : 1)
+ } finally {
+ await driver.dispose()
+ }
+ })
+
it('Pause removes only the captured Session scheduled continuation', async () => {
const fixture = runnerFixture({ shouldRun: false, waitMinutes: 5 })
const first = fakeAgent()
diff --git a/pyproject.toml b/pyproject.toml
index fdc6cddab9..623d084858 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "loopx"
-version = "2.3.0"
+version = "2.4.0"
description = "A Loop Engineering control plane for long-running agent goals (requires Node.js 22.22.3+)."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/scripts/ci/impact_plan.py b/scripts/ci/impact_plan.py
index 4992b47e26..596d01def9 100644
--- a/scripts/ci/impact_plan.py
+++ b/scripts/ci/impact_plan.py
@@ -9,7 +9,7 @@
import subprocess
SCHEMA = "loopx_ci_job_plan_v1"
-ROOT_DOCS = {"README.md", "README.zh-CN.md", "CHANGELOG.md", "CONTRIBUTING.md"}
+ROOT_DOCS = {"README.md", "README.zh-CN.md", "README.ja.md", "CHANGELOG.md", "CONTRIBUTING.md"}
POLICY_PATHS = ("scripts/ci/impact_plan.py", "scripts/ci/review_gate.py", ".github/workflows/python-tests.yml")
OUTPUTS = ("core_tests", "backend_tests", "python_tests", "stage2c_tests", "presentation_tests")
PRESENTATION_ROOTS = ("apps/presentation/dashboard/src/", "apps/presentation/dashboard/public/", "loopx/web/chat/")
diff --git a/scripts/ci/test_impact_plan.py b/scripts/ci/test_impact_plan.py
index f52b2353ce..6001700e01 100644
--- a/scripts/ci/test_impact_plan.py
+++ b/scripts/ci/test_impact_plan.py
@@ -28,6 +28,14 @@ def test_presentation_and_docs_union(self):
"apps/presentation/dashboard/public/icon.svg"):
self.assertEqual(candidate([Change(status, path), Change("M", "docs/design.md")])[0], "presentation")
+ def test_root_readme_locales_are_documents(self):
+ readmes = ("README.md", "README.zh-CN.md", "README.ja.md")
+ for path in readmes:
+ for status in ("A", "M", "D"):
+ with self.subTest(path=path, status=status):
+ self.assertEqual(candidate([Change(status, path)])[0], "docs")
+ self.assertEqual(candidate([Change("M", path) for path in readmes])[0], "docs")
+
def test_one_shared_unknown_prompt_test_or_dependency_forces_full(self):
for path in ("loopx/cli.py", "loopx/control_plane/goals/vision_checkpoint.ts",
"loopx/claude_goal_mode/commands/loopx.md", "tests/test_ui.py",
diff --git a/skills/loopx-self-repair/references/repair-patterns.md b/skills/loopx-self-repair/references/repair-patterns.md
index 99e2de3f79..9a8765a4ba 100644
--- a/skills/loopx-self-repair/references/repair-patterns.md
+++ b/skills/loopx-self-repair/references/repair-patterns.md
@@ -126,7 +126,7 @@ teaches a reusable control-plane lesson.
| `normal_no_user_todo_misflagged` | `action_required=false` and user open count is zero, but the agent reports a state projection fault. | quota payload and user todo summary. | Rule over-applied the "todo not projected" fallback. | Allow "无用户待办/无需通知"; update heartbeat/prompt smoke if needed. |
| `todo_no_followup_global_terminal_overreach` | A completed scoped Todo records `done + no_followup`, but `refresh-state --repair-delta-kind no_followup` becomes `replan_noop` because unrelated advancement or long-running monitor Todos remain open. | rejected repair-delta claim, complete Agent Todo projection, scoped Todo metadata, and the latest local no-follow-up completion. | The repair-delta validator reused Goal-level terminal-frontier completeness to validate a Todo-local closure. | Keep Goal `terminal_no_followup` strict, but validate repair-delta no-follow-up against the latest scoped completed Todo in a complete parser projection; reject other-agent, continuation-required, malformed, or truncated evidence and keep the emitted Todo evidence bounded. Cover the real CLI path with an open monitor regression. |
| `terminal_settlement_ordering_gap` | Final Todo completion succeeds, then the matching refresh or spend is rejected because the Goal is already terminal; different hosts may expose different closeout orders or retry the material effect. | Typed settlement plan and effect identity, Todo completion event, accountable refresh and spend receipts, Turn journal phase prefix, and host task-body projection. | Final `no_followup` was modeled like ordinary pre-settlement Todo completion even though it mutates Goal terminal state and activates the strict no-more-spend guard. | Keep Goal terminal guards strict. Treat ordinary successor completion as Todo lifecycle work, but make final `no_followup` a conditional post-spend terminal closeout under the same effect identity. Require matching writeback and spend receipts at the mutation boundary, prove the closeout event itself carries `no_followup`, and journal it so closeout-only retry cannot repeat writeback or spend. Cover CLI, visible Goal, Codex App, Turn driver, adapter order, failure short-circuit, and replay. |
-| `receipt_bound_lifecycle_source_gap` | A lifecycle review is admitted, then closing the original Todo through its settled Turn makes same-review reentry fail with an identity conflict; a blocked refresh may commit without a qualified replan ACK. | Exact original completion identity and closeout receipt, admitted review identity/time, canonical Todo readback, typed blocked observation and writeback/debit receipts. | Lifecycle reconstruction recognized only the completion-key reentry form; writeback could treat a missing selected source like an unrelated future obligation. | Reuse the canonical completion-recovery vocabulary for both legal paths and retain exact actor, identity and timestamp checks. Revalidate every selected replan through the shared owner before writeback. For an already committed unqualified blocked observation with no debit, permit only an exact additive checkpoint requalification; preserve the original run and all receipt history, reject payload changes or later superseding vision, and never infer acceptance or erase a committed debit. |
+| `receipt_bound_lifecycle_source_gap` | An admitted lifecycle or Monitor review loses its live source after Todo closeout, so same-Turn guard reentry or refresh fails with an identity conflict; a blocked refresh may commit without a qualified replan ACK. | Exact original completion identity and closeout receipt, admitted review identity/time, canonical Todo readback, typed observation and writeback/debit receipts. | Lifecycle reconstruction recognized only the completion-key reentry form; scalar receipts omitted Monitor review sources; writeback could treat a missing selected source like an unrelated future obligation. | Reuse the canonical completion-recovery vocabulary for both legal paths and retain exact actor, identity and timestamp checks. Retain unqualified Monitor review kinds and their stop conditions through the existing scalar receipt source; lifecycle closeout alone never discharges the required semantic review or authorizes debit. Revalidate every selected replan through the shared owner before writeback. For an already committed unqualified blocked observation with no debit, permit only an exact additive checkpoint requalification; preserve the original run and all receipt history, reject payload changes or later superseding vision, and never infer acceptance or erase a committed debit. |
| `host_settlement_source_projection_gap` | A visible Goal host packet requires `source=visible-goal` without an explicit Turn receipt, but the nested interaction contract tells the agent to spend as `heartbeat` and binds the currently selected Todo. The command can fail after Todo completion or misattribute interactive usage. | Host runtime profile, canonical host quota commands, interaction-contract CLI actions, selected Todo lifecycle order, and the failed spend preview. | The generic interaction projection hard-coded heartbeat accounting and selected-Todo binding instead of deriving the accounting route from the scheduler execution context. | Route spend actions from the typed runtime profile. Native Goal runtimes preserve `source=visible-goal` and host-level attribution; heartbeat automation keeps its Todo- and Turn-bound settlement plan. Cover the exact CLI actions for each native Goal profile and retain the heartbeat regression. |
| `visible_goal_settlement_replan_attribution_gap` | An accountable visible-Goal delivery writeback moves the frontier into capability or control-plane repair; the following unbound spend is recorded against the new repair state with no Todo, Turn, effect, or delivery-workspace causality, and an exact retry cannot replay the committed effect. | Newest same-Agent accountable run, its complete nested settlement identity, top-level Todo/Turn fields, original heartbeat receipt, delivery-workspace causality, current quota frontier, spend classification, and retry run count. | The unbound visible-Goal path used the mutable current frontier as settlement authority and did not recover the completed delivery identity; commit classification also represented eligible, repair, and delivery semantics as overlapping booleans, allowing a later repair projection to overwrite attribution. | Allow unbound recovery only for visible-Goal spend from the newest fully typed same-Agent accountable run; require its top-level and nested identities to match the TypeScript-generated settlement payload and revalidate the original heartbeat receipt. Preserve Todo/Turn/effect/workspace causality, write the CLI receipt under the recovered Turn, and reduce commit semantics to one closed TypeScript disposition where proven delivery completion precedes later frontier repair. Cover missing/legacy identity, capability and control-plane replan, and exact one-run replay. |
| `runtime_capability_user_gate_overreach` | A missing launcher/runtime capability such as `network` becomes `capability_gate.action=ask_owner`, `requires_user_action=true`, or a user notification even though no credential, protected access, or production authority is needed. | quota `capability_gate`, heartbeat `--available-capability` inputs, launcher/runtime observations, interaction contract user channel. | Capability availability and permission authority were collapsed into one owner-held class. | Keep runtime provisioning gaps in the agent repair lane, require truthful runtime observation before declaring availability, and reserve `ask_owner` for credentials or protected/production authority. Cover all-blocked and mixed-capability cases with capability-gate and monitor smokes. |
diff --git a/tests/control_plane/test_canonical_handoff_invariants.py b/tests/control_plane/test_canonical_handoff_invariants.py
index 1159645ece..88b10abc4d 100644
--- a/tests/control_plane/test_canonical_handoff_invariants.py
+++ b/tests/control_plane/test_canonical_handoff_invariants.py
@@ -58,6 +58,7 @@ def _write_workspace(
*,
handoff_mode: str | None = None,
lifecycle_authority: list[dict[str, Any]] | None = None,
+ registered_agents: list[str] | None = None,
) -> tuple[Path, Path]:
repo = tmp_path / "repo"
repo.mkdir(exist_ok=True)
@@ -76,7 +77,11 @@ def _write_workspace(
)
coordination: dict[str, Any] = {
"agent_model": "peer_v1",
- "registered_agents": [AGENT_A, AGENT_B, ORCHESTRATOR],
+ "registered_agents": (
+ [AGENT_A, AGENT_B, ORCHESTRATOR]
+ if registered_agents is None
+ else list(registered_agents)
+ ),
}
if lifecycle_authority is not None:
coordination["todo_lifecycle_authority"] = lifecycle_authority
@@ -777,6 +782,75 @@ def test_exact_user_gate_completion_preserves_execution_fence(
assert result["decision_scope_resolution"]["state"] == "resolved"
+@pytest.mark.parametrize("mode", ["soft_claim", "hard_lease"])
+@pytest.mark.parametrize(
+ "agents",
+ [[AGENT_A], [AGENT_A, AGENT_B, ORCHESTRATOR]],
+ ids=["single-agent", "multi-agent"],
+)
+def test_owner_closes_exact_user_gate_without_an_agent_actor(
+ tmp_path, canonical_workspace, mode, agents
+):
+ """The owner who is not registered as an agent can close a single-agent gate.
+
+ A single-agent goal has no second agent to act for the owner, and the
+ terminal CLI has no human owner actor. Multi-agent hard-lease goals retain
+ their attributed-actor execution fence contract when no actor is named.
+ """
+ registry, state = canonical_workspace(
+ tmp_path, handoff_mode=mode, registered_agents=agents
+ )
+ target, gate = _add_exact_user_gate_pair(registry)
+ unlinked = add_goal_todo(
+ registry_path=registry,
+ goal_id=GOAL_ID,
+ role="user",
+ text="Confirm one unlinked owner decision.",
+ task_class="user_gate",
+ blocks_agent=AGENT_A,
+ )
+ before, display = _snapshot(registry), state.read_bytes()
+ with pytest.raises(LocalCoordinationAuthorityRejection) as error:
+ _terminal(
+ registry,
+ unlinked["todo_id"],
+ role="user",
+ decision_outcome="approve",
+ agent_id=None,
+ )
+ assert error.value.code == "actor_required"
+ _unchanged(registry, state, before, display)
+
+ if mode == "hard_lease" and len(agents) > 1:
+ with pytest.raises(LocalCoordinationAuthorityRejection) as error:
+ _terminal(
+ registry,
+ gate["todo_id"],
+ role="user",
+ decision_outcome="approve",
+ agent_id=None,
+ )
+ assert error.value.code == "handoff_mode_requires_lease"
+ _unchanged(registry, state, before, display)
+ return
+
+ result = _terminal(
+ registry,
+ gate["todo_id"],
+ role="user",
+ decision_outcome="approve",
+ agent_id=None,
+ )
+ assert (
+ result["mutation_authority"]["authority_mode"]
+ == "exact_user_gate_decision_scope_override"
+ )
+ assert result["task_lease_fence"]["lease_fence"] == "not_required"
+ assert _agent_todo(state, gate["todo_id"])["status"] == "done"
+ assert not _agent_todo(state, target["todo_id"]).get("required_decision_scopes")
+ assert result["decision_scope_resolution"]["state"] == "resolved"
+
+
def test_bound_user_action_completes_without_gate_or_execution_claim(
tmp_path, canonical_workspace
):
diff --git a/tests/control_plane/test_chat_cold_source_import.py b/tests/control_plane/test_chat_cold_source_import.py
index af755f0892..a72a5601f3 100644
--- a/tests/control_plane/test_chat_cold_source_import.py
+++ b/tests/control_plane/test_chat_cold_source_import.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import http.client
+from concurrent.futures import ThreadPoolExecutor
import json
import subprocess
import socket
@@ -32,7 +33,18 @@ def cold_api(tmp_path, monkeypatch, request, source_modules_present):
# of this same set before the cold receiver is copied.
(receiver / "loopx" / name).unlink(missing_ok=True)
registry = tmp_path / "project/.loopx/registry.json"
- if request.param:
+ if request.param in ("global-source", "global-source-race"):
+ # Keep Chat bound to the source runtime, but invoke it through the
+ # global registry whose own runtime holds the machine index.
+ global_root = tmp_path / "machine-runtime"
+ global_root.mkdir()
+ payload = json.loads(registry.read_text())
+ payload["common_runtime_root"] = str(global_root)
+ payload["registry_role"] = "global-local"
+ payload["goals"][0]["source_registry"] = str(registry)
+ registry = global_root / "registry.global.json"
+ registry.write_text(json.dumps(payload))
+ elif request.param:
# The configured registry may live outside conventional Goal folders.
# Only its explicit backup member can cover this observed source.
external = tmp_path / "project/source-registry.json"
@@ -53,14 +65,33 @@ def cold_api(tmp_path, monkeypatch, request, source_modules_present):
staged_ready = ready.with_suffix('.tmp')
staged_ready.write_text(json.dumps({'port': port, 'package': loopx.__file__}), encoding='utf-8')
staged_ready.replace(ready)
+if len(sys.argv) > 5:
+ import time
+ import loopx.presentation.goal_storage_api as storage
+ original_effect = storage.source_effect_runtime_result
+ def paused_import(operation, payload, **kwargs):
+ pause = runtime / 'pause-apply'
+ if (operation == 'coordination.cold_source.import'
+ and payload.get('action') == 'apply' and pause.exists()):
+ pause.with_suffix('.selected').write_text(payload['expected_source_registry'])
+ deadline = time.monotonic() + 20
+ while not pause.with_suffix('.resume').exists():
+ if time.monotonic() >= deadline:
+ raise TimeoutError('test did not resume its paused Apply')
+ time.sleep(.01)
+ return original_effect(operation, payload, **kwargs)
+ storage.source_effect_runtime_result = paused_import
serve_chat(registry_path=registry, runtime_root_override=runtime,
scan_roots=[Path(json.loads(registry.read_text())['goals'][0]['repo'])], host='127.0.0.1', port=port,
goal_id='cold', open_browser=False, verbose=False)
"""
+ server_arguments = [str(registry), str(runtime), str(ready), str(requested_port)]
+ if request.param == "global-source-race":
+ server_arguments.append("pause")
error_path = tmp_path / "server-errors.txt"
error_stream = error_path.open("w")
server = subprocess.Popen([sys.executable, "-u", "-c", script,
- str(registry), str(runtime), str(ready), str(requested_port)], cwd=tmp_path,
+ *server_arguments], cwd=tmp_path,
env={**env, "LOOPX_USAGE_PING": "0"}, stdout=subprocess.DEVNULL, stderr=error_stream)
def execute(script):
@@ -78,7 +109,7 @@ def restart():
server.wait(timeout=10)
ready.unlink()
server = subprocess.Popen([sys.executable, "-u", "-c", script,
- str(registry), str(runtime), str(ready), str(requested_port)], cwd=tmp_path,
+ *server_arguments], cwd=tmp_path,
env={**env, "LOOPX_USAGE_PING": "0"}, stdout=subprocess.DEVNULL, stderr=error_stream)
port = wait_ready()
@@ -166,7 +197,7 @@ def test_cold_http_preview_reload_confirm_original_recovery(cold_api, provider):
assert observed["operation_id"] == plan["operation_id"]
assert not observed["legacy_writer_fenced"] and not observed["current"]["canonical"]
assert state.read_bytes() == original
- assert not list(runtime.rglob("writer-fence.json"))
+ assert not list(runtime.rglob("legacy-writer-fence-*.json"))
code, refused = call("apply", {**saved, "writers_stopped": False})
assert code == 409 and refused["reason_code"] == "cold_import_operator_stop_confirmation_required"
code, applied = call("apply", {**saved, "writers_stopped": True})
@@ -213,6 +244,110 @@ def action(kind, parameters, key):
assert read() == later
+@pytest.mark.parametrize("cold_api", ["global-source"], indirect=True)
+def test_cold_http_binds_global_mirror_to_the_registered_source(cold_api):
+ call, read, state, body, runtime, registry, _, restart = cold_api
+ original_state = state.read_bytes()
+ original_mirror = registry.read_bytes()
+ mirror = json.loads(original_mirror)
+ source = runtime.parent / "project/.loopx/registry.json"
+
+ code, observed = call()
+ assert code == 200 and observed["current"]["canonical"] is False, observed
+ assert observed["cold_source"]["active_todo_count"] == 1
+ plan = prepare(call, handoff_mode="soft_claim")
+ saved = carrier(plan)
+ assert plan["coordination_source_backup_verified"] is True
+ assert plan["source_inventory"]["archived_todo_count"] == 1
+ restart()
+ code, pending = call()
+ assert code == 200 and pending["pending_preview"] == saved
+ assert call("recover", saved)[1]["status"] == "prepared"
+ code, refused = call("apply", {**saved, "writers_stopped": False})
+ assert code == 409 and refused["reason_code"] == "cold_import_operator_stop_confirmation_required"
+
+ # The saved plan still has an intact source file, the same Goal and the
+ # same target store. An explicit rebinding must still invalidate Apply.
+ other_registry = source.with_name("other-registry.json")
+ other_registry.write_bytes(source.read_bytes())
+ mirror["goals"][0]["source_registry"] = str(other_registry)
+ registry.write_text(json.dumps(mirror))
+ code, refused = call("apply", {**saved, "writers_stopped": True})
+ assert code == 409 and refused["reason_code"] == "source_registry_changed_retry"
+ assert not list(runtime.rglob("legacy-writer-fence-*.json"))
+
+ registry.write_bytes(original_mirror)
+ code, applied = call("apply", {**saved, "writers_stopped": True})
+ assert code == 200 and applied["status"] == "applied", applied
+ assert applied["current"]["provider"] == "sqlite"
+ assert applied["execution_authority_granted"] is False
+ assert next(row["text"] for row in read()["todos"] if row["todo_id"] == "todo_current") == body
+ assert state.read_bytes() == original_state
+ assert not list(registry.parent.rglob("legacy-writer-fence-*.json"))
+
+
+@pytest.mark.parametrize("cold_api", ["global-source-race"], indirect=True)
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_cold_http_source_rebind_is_ordered_with_cutover(cold_api, provider):
+ from loopx.control_plane.coordination.legacy_writer_fence import legacy_coordination_writer_fence_path
+ from loopx.file_lock import exclusive_cross_runtime_file_lock
+ from loopx.global_registry import GlobalRegistryReduction, mutate_global_registry
+
+ call, read, state, body, runtime, registry, _, _ = cold_api
+ plan = prepare(call, provider, handoff_mode="soft_claim")
+ original = state.read_bytes()
+ source = runtime.parent / "project/.loopx/registry.json"
+ replacement = source.with_name("replacement-registry.json")
+ replacement.write_bytes(source.read_bytes())
+ pause = runtime / "pause-apply"
+ pause.touch()
+
+ def rebind():
+ def reduce(payload):
+ payload["goals"][0]["source_registry"] = str(replacement)
+ return GlobalRegistryReduction(payload, {"bound": "replacement"})
+ return mutate_global_registry(registry, "test-source-rebind", reduce)
+
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ applying = pool.submit(call, "apply", {**carrier(plan), "writers_stopped": True})
+ deadline = time.monotonic() + 15
+ try:
+ while not pause.with_suffix(".selected").exists():
+ assert not applying.done(), applying.result() if applying.done() else None
+ assert time.monotonic() < deadline, "Apply did not reach its effect boundary"
+ time.sleep(.01)
+ assert pause.with_suffix(".selected").read_text() == str(source)
+ # This is the existing registry writer's actual cross-runtime lock,
+ # not a sleep-based guess that the competing thread is blocked.
+ serialized = False
+ try:
+ with exclusive_cross_runtime_file_lock(registry, timeout_seconds=0):
+ pass
+ except TimeoutError:
+ serialized = True
+ if serialized:
+ writer = pool.submit(rebind)
+ else:
+ rebind()
+ finally:
+ pause.with_suffix(".resume").touch()
+ code, result = applying.result(timeout=90)
+ fence = legacy_coordination_writer_fence_path(runtime_root=runtime, goal_id="cold")
+ if serialized:
+ assert code == 200 and result["status"] == "applied", result
+ assert writer.result(timeout=10)["wrote"]
+ assert fence.exists()
+ assert next(row["text"] for row in read()["todos"] if row["todo_id"] == "todo_current") == body
+ else:
+ # A writer that commits first invalidates the old selected source.
+ # The original bug returned applied and fenced that old source.
+ assert code == 409, {"response": result, "legacy_fence_exists": fence.exists()}
+ assert result["authority_changed"] is False and not fence.exists()
+ assert call()[1]["current"]["canonical"] is False
+ assert state.read_bytes() == original
+ assert json.loads(registry.read_text())["goals"][0]["source_registry"] == str(replacement)
+
+
def test_cold_http_changed_source_backup_and_untrusted_inputs(cold_api):
call, read, state, _, runtime, _, _, _ = cold_api
plan = prepare(call)
@@ -227,7 +362,7 @@ def test_cold_http_changed_source_backup_and_untrusted_inputs(cold_api):
state.write_text(state.read_text() + "\nChanged after preview\n")
code, refused = call("apply", {**saved, "writers_stopped": True})
assert code == 409 and refused["reason_code"] == "source_changed_retry", refused
- assert not list(runtime.rglob("writer-fence.json"))
+ assert not list(runtime.rglob("legacy-writer-fence-*.json"))
fresh = prepare(call)
archives = list((runtime / "backups/cold-import").glob(f"*{fresh['operation_id']}*.tar.gz"))
@@ -236,7 +371,7 @@ def test_cold_http_changed_source_backup_and_untrusted_inputs(cold_api):
code, refused = call("apply", {**carrier(fresh), "writers_stopped": True})
assert code == 409 and refused["reason_code"] == "cold_import_backup_changed", refused
assert call()[1]["current"]["canonical"] is False
- assert not list(runtime.rglob("writer-fence.json"))
+ assert not list(runtime.rglob("legacy-writer-fence-*.json"))
@pytest.mark.parametrize("provider", ["file", "sqlite"])
@@ -292,7 +427,7 @@ def test_registered_runtime_alias_import_preserves_original_operation(cold_api,
plan = prepare(call, provider)
saved = carrier(plan)
assert call("recover", saved)[1]["status"] == "prepared"
- assert not list(runtime.rglob("writer-fence.json"))
+ assert not list(runtime.rglob("legacy-writer-fence-*.json"))
assert call("apply", {**saved, "writers_stopped": False})[0] == 409
code, applied = call("apply", {**saved, "writers_stopped": True})
assert code == 200 and applied["status"] == "applied", applied
@@ -329,8 +464,8 @@ def test_registered_runtime_alias_retarget_rejects_without_import(cold_api, prov
before = state.read_bytes()
code, refused = call("apply", {**carrier(plan), "writers_stopped": True})
assert code == 409 and refused["reason_code"] == "shadow_source_runtime_root_mismatch", refused
- assert not list(runtime.rglob("writer-fence.json"))
- assert not list(other.rglob("writer-fence.json"))
+ assert not list(runtime.rglob("legacy-writer-fence-*.json"))
+ assert not list(other.rglob("legacy-writer-fence-*.json"))
assert state.read_bytes() == before
diff --git a/tests/control_plane/test_checkpoint_restore_capture.py b/tests/control_plane/test_checkpoint_restore_capture.py
index 310a06502a..4c08087b34 100644
--- a/tests/control_plane/test_checkpoint_restore_capture.py
+++ b/tests/control_plane/test_checkpoint_restore_capture.py
@@ -1,10 +1,12 @@
"""A restored fork needs a current, settled semantic decision before recapture."""
import copy
+import hashlib
+import json
import pytest
from loopx.control_plane.effect_program import SettlementIdentity
-from loopx.control_plane.effect_runtime import effect_runtime_result
+from loopx.control_plane.effect_runtime import EffectRuntimeRemoteError, effect_runtime_result
def test_nonrestored_conversation_has_no_completed_checkpoint_review(tmp_path):
@@ -78,12 +80,175 @@ def test_readonly_participant_capture_and_limited_basis_read(tmp_path):
basis = effect_runtime_result("runtime.checkpoint_artifacts", {"action": "read_basis", "root": str(unit),
"expected_sha256": captured["sha256"]})
assert basis["integrity_verified"] is False and basis["execution_authority_granted"] is False
- from loopx.control_plane.effect_runtime import EffectRuntimeRemoteError
with pytest.raises(EffectRuntimeRemoteError):
effect_runtime_result("runtime.checkpoint_artifacts", {"action": "verify", "root": str(unit),
"expected_sha256": captured["sha256"]})
+@pytest.mark.parametrize("location", ["root", "operator"])
+@pytest.mark.parametrize("note", [None, {}, False, [], 0, ""])
+def test_empty_replan_annotations_keep_the_ordinary_restore_path(tmp_path, monkeypatch, location, note):
+ from types import SimpleNamespace
+ from benchmark.runtime.checkpoint import parse_checkpoint_request
+ from benchmark.runtime.checkpoint_continuation import restored_capture_gate, restored_checkpoint_review
+ from benchmark.runtime.checkpoint_session_refresh import prepare_session_refresh
+
+ source = tmp_path / "code"
+ source.write_text("retained work")
+ unit = tmp_path / "point"
+ request = parse_checkpoint_request(json.dumps({
+ "destination": str(unit), "components": [{"id": "code", "source_path": str(source)}],
+ "point_metadata": {"replan": note},
+ }).encode())
+ metadata = {"loopx_state": {"goal_id": "checkpoint-source", "agent_id": "worker"},
+ "operator_metadata": request["point_metadata"]}
+ if location == "root":
+ metadata["replan"] = metadata["operator_metadata"].pop("replan")
+ components = request["components"]
+ probe = effect_runtime_result("runtime.checkpoint_artifacts", {"action": "probe", "components": components})
+ captured = effect_runtime_result("runtime.checkpoint_artifacts", {
+ "action": "capture", "components": components, "destination": str(unit),
+ "point_metadata": metadata, "expected_source_sha256": probe["source_sha256"],
+ }, retry_safe=False)
+ assert effect_runtime_result("runtime.checkpoint_artifacts", {
+ "action": "verify", "root": str(unit), "expected_sha256": captured["sha256"],
+ })["integrity_verified"]
+ before = {path.relative_to(unit): path.read_bytes() for path in unit.rglob("*") if path.is_file()}
+ binding = {"session_id": "retained-session", "checkpoint_artifact_sha256": captured["sha256"],
+ "checkpoint_artifact_root": str(unit)}
+ env = {"LOOPX_RUNTIME_ROOT": str(tmp_path / "runtime"), "LOOPX_GOAL_ID": "checkpoint-source",
+ "LOOPX_AGENT_ID": "worker", "LOOPX_WAKE_LOG_DIR": str(tmp_path / "wakes")}
+ monkeypatch.setattr("benchmark.runtime.checkpoint_continuation.load_codex_cli_session",
+ lambda *args, **kwargs: binding)
+ monkeypatch.setattr("benchmark.runtime.sessions.BenchmarkSessionWake",
+ lambda *args: SimpleNamespace(session_id=binding["session_id"]))
+ review = restored_checkpoint_review(env)
+ gate = restored_capture_gate(env)
+ assert review["semantic_review_accepted"] is False
+ assert gate["capture_allowed"] is False # Ordinary recovery still requires a current settled review.
+ assert review["instructions"] == gate["instructions"]
+ assert "This source has no retained pending replan packet." in gate["instructions"]
+ declaration = tmp_path / "warm-start.json"
+ declaration.write_text(json.dumps({
+ "root": str(unit), "sha256": captured["sha256"], "fresh_replan": True,
+ "goal_id": "checkpoint-source", "agent_id": "worker",
+ }))
+ resets = []
+ session = SimpleNamespace(session_id=binding["session_id"], binding=binding,
+ prepare_checkpoint_refresh=lambda *args, **kwargs: resets.append((args, kwargs)))
+ with pytest.raises(ValueError, match="fresh replan requires the original pending decision boundary"):
+ prepare_session_refresh({**env, "LOOPX_WARM_START": str(declaration),
+ "LOOPX_ITERATION_CONTEXT": "resume"}, session, tmp_path)
+ assert resets == [] # Empty advice cannot authorize a fresh pending-replan treatment.
+ basis = effect_runtime_result("runtime.checkpoint_artifacts", {
+ "action": "read_basis", "root": str(unit), "expected_sha256": captured["sha256"],
+ "include_pending_replan": True,
+ })
+ assert basis["pending_replan"] is None and basis["execution_authority_granted"] is False
+ assert {path.relative_to(unit): path.read_bytes() for path in unit.rglob("*") if path.is_file()} == before
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_sealed_pending_basis_reuses_original_guard_and_rejects_replacements(tmp_path, monkeypatch, provider):
+ from loopx.control_plane.quota.turn_envelope import compose_turn_decision
+ from benchmark.runtime.checkpoint_continuation import restored_checkpoint_review
+ from benchmark.runtime.checkpoint_session_refresh import prepare_session_refresh
+ from types import SimpleNamespace
+ from test_replan_successor_guard_reentry import AGENT, GOAL, TURN, _fixture
+
+ call, runtime, _ = _fixture(tmp_path, monkeypatch, provider)
+ original = call("quota", "should-run", "--runtime-profile", "generic_cli", "--goal-id", GOAL,
+ "--agent-id", AGENT, "--turn-instance-id", TURN,
+ "--decision-output-dir", str(tmp_path / "original"))
+ assert original["effective_action"] == "autonomous_replan_required"
+ retained = tmp_path / "original" / "decision.json"
+ source_bytes = retained.read_bytes()
+ source = json.loads(source_bytes)
+ identity = source["heartbeat_receipt"]["settlement_identity"]
+ runs = runtime / "goals" / GOAL / "runs" / "index.jsonl"
+ original_runs = runs.read_bytes()
+ pending = {"capture": True, "obligation_id": identity["replan_obligation_id"],
+ "settlement_effect_id": identity["effect_id"], "execution_authority_granted": False}
+ complete = compose_turn_decision({**source, "future_observation": {"exact": 2**53 + 1, "decimal": 1.0}})
+ packet = tmp_path / "held-decision.json"
+ packet.touch(mode=0o600)
+ evidence = [{"id": "held_decision", "source_path": str(packet)}]
+
+ def seal(name, payload, *, wanted=pending, decision_digest=None, operator_fallback=False):
+ raw = json.dumps(payload, ensure_ascii=False).encode()
+ packet.write_bytes(raw)
+ digest = hashlib.sha256(raw).hexdigest()
+ request = {"action": "capture", "components": evidence, "destination": str(tmp_path / name),
+ "point_metadata": {"held_decision_component_id": "held_decision", "loopx_state": {
+ "goal_id": GOAL, "agent_id": AGENT}, "replan": wanted, "decision_sha256": decision_digest or digest},
+ "expected_source_sha256": effect_runtime_result("runtime.checkpoint_artifacts", {
+ "action": "probe", "components": evidence})["source_sha256"]}
+ if operator_fallback:
+ request["point_metadata"].update(replan=False, operator_metadata={"replan": wanted})
+ sealed = effect_runtime_result("runtime.checkpoint_artifacts", request, retry_safe=False)
+ return {"action": "read_basis", "root": request["destination"], "expected_sha256": sealed["sha256"],
+ "include_pending_replan": True}, digest
+
+ for name, payload in (("historical", source), ("complete", complete), ("operator-fallback", source)):
+ request, digest = seal(name, payload, operator_fallback=name == "operator-fallback")
+ selected = effect_runtime_result("runtime.checkpoint_artifacts", request)
+ assert selected["pending_replan"] == {"intent": pending, "decision_sha256": digest,
+ "decision_path": str(tmp_path / name / "components" / "held_decision")}
+ assert not selected["integrity_verified"] and not selected["execution_authority_granted"]
+
+ # Exercise both actual receivers with a sealed source and an already
+ # admitted native binding. Only the external native transport is fake.
+ binding = {"session_id": "synthetic-session", "checkpoint_artifact_sha256": request["expected_sha256"],
+ "checkpoint_artifact_root": request["root"]}
+ declaration = tmp_path / "warm-start.json"
+ declaration.write_text(json.dumps({"root": request["root"], "sha256": request["expected_sha256"],
+ "goal_id": GOAL, "agent_id": AGENT, "fresh_replan": True}))
+ partial = tmp_path / "context-refresh" / "pre-replan.json"
+ partial.parent.mkdir(exist_ok=True)
+ partial.touch() # Recovery of a lost external reply must not re-admit.
+ env = {"LOOPX_RUNTIME_ROOT": str(runtime), "LOOPX_GOAL_ID": GOAL, "LOOPX_AGENT_ID": AGENT,
+ "LOOPX_WARM_START": str(declaration), "LOOPX_ITERATION_CONTEXT": "resume",
+ "LOOPX_WAKE_LOG_DIR": str(tmp_path / "wakes")}
+ observations = []
+ session = SimpleNamespace(**binding, binding=binding, prepare_checkpoint_refresh=lambda *args, **kw:
+ observations.append((args, kw)))
+ with monkeypatch.context() as m:
+ m.setattr("benchmark.runtime.checkpoint_continuation.load_codex_cli_session", lambda *a, **kw: binding)
+ m.setattr("benchmark.runtime.sessions.BenchmarkSessionWake", lambda *a: session)
+ notice = prepare_session_refresh(env, session, tmp_path)
+ assert "BEFORE a pending replan" in notice and observations == [(
+ (None, partial, tmp_path / "stdout.jsonl"),
+ {"pre_replan_basis": {"pending_replan": pending, "decision_sha256": digest}},
+ )]
+ review = restored_checkpoint_review(env)
+ assert not review["semantic_review_accepted"]
+ assert selected["pending_replan"]["decision_path"] in review["instructions"]
+
+ for name, payload, wanted, expected in (
+ ("tampered", {**complete, "future_observation": {"exact": 2**53}}, pending, "integrity mismatch"),
+ ("unknown", {**complete, "schema_version": "unknown"}, pending, "unsupported complete Turn decision version"),
+ ("wrong-intent", source, {**pending, "obligation_id": "replan-" + "b" * 16}, "binding differs"),
+ ("missing-intent", source, None, "checkpoint pending replan must be an object"),
+ ("empty-intent", source, {}, "checkpoint pending replan must be an object"),
+ ("false-intent", source, False, "checkpoint pending replan must be an object"),
+ ):
+ request, _ = seal(name, payload, wanted=wanted)
+ with pytest.raises(EffectRuntimeRemoteError, match=expected):
+ effect_runtime_result("runtime.checkpoint_artifacts", request)
+
+ request, _ = seal("wrong-member", source, decision_digest="a" * 64)
+ with pytest.raises(EffectRuntimeRemoteError, match="packet digest differs"):
+ effect_runtime_result("runtime.checkpoint_artifacts", request)
+ request, _ = seal("replaced-member", source)
+ member = tmp_path / "replaced-member" / "components" / "held_decision"
+ saved = member.read_bytes()
+ member.write_bytes(b" " + saved[1:]) # Same size as the sealed file.
+ with pytest.raises(EffectRuntimeRemoteError, match="packet digest differs"):
+ effect_runtime_result("runtime.checkpoint_artifacts", request)
+ assert retained.read_bytes() == source_bytes
+ assert runs.read_bytes() == original_runs
+
+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("cited", [False, True])
def test_successor_review_needs_checkpoint_linked_settlement(tmp_path, monkeypatch, provider, cited):
diff --git a/tests/control_plane/test_cli_program_route.py b/tests/control_plane/test_cli_program_route.py
index 3a5adbfb94..e2d0f51f6e 100644
--- a/tests/control_plane/test_cli_program_route.py
+++ b/tests/control_plane/test_cli_program_route.py
@@ -132,28 +132,66 @@ def run(argv, *, expected_code=0):
assert guard["decision"] == "run", guard
identity = guard["heartbeat_receipt"]["settlement_identity"]
assert identity["todo_id"] == cli.TODO_ID and identity["turn_instance_id"] == cli.TURN_ID
- commands = {s["kind"]: s["command_template"] for s in channel["settlement_plan"]["ordered_steps"]}
- for command in [*channel["next_cli_actions"], *commands.values()]:
+ plan = channel["settlement_plan"]
+ steps = {step["kind"]: step for step in plan["ordered_steps"]}
+ commands = [step["command_template"] for step in steps.values() if step["owner"] == "agent"]
+ for command in [*channel["next_cli_actions"], *commands]:
assert shlex.split(command)[0] == program
for read in guard["interaction_contract"]["agent_channel"].get("required_reads", []):
assert shlex.split(read["command"])[0] != "loopx"
- refresh = commands["durable_writeback"].replace("", "validated_progress")
- refresh = refresh.replace("", "implementation").replace("", "outcome_progress")
- refreshed = run([
+ refresh = (
+ steps["durable_writeback"]["command_template"]
+ .replace("", "validated_progress")
+ .replace("", "implementation")
+ .replace("", "outcome_progress")
+ )
+ refresh_argv = [
*shlex.split(refresh), "--vision-state", "vision_on_track",
"--vision-summary", "Continue eligible work.",
"--vision-acceptance", "The original runtime settles its selected work once.",
"--no-global-sync", "--suppress-external-sinks",
- ])
+ ]
+ spend_step = steps["quota_spend"]
+ if handoff_mode == "hard_lease":
+ assert plan["schema_version"] == "quota_settlement_plan_v2"
+ assert spend_step["owner"] == "runtime"
+ assert "command_template" not in spend_step
+ assert all("spend-slot" not in shlex.split(action) for action in channel["next_cli_actions"])
+ assert {"--settle-turn", "--settlement-receipt"} <= set(refresh_argv)
+ else:
+ assert spend_step["owner"] == "agent"
+
+ refreshed = run(refresh_argv)
assert refreshed["vision_checkpoint"]["satisfied"]
- owed = refreshed["settlement_owed"]["command"]
- assert shlex.split(owed)[0] == program
- first, replay = run(shlex.split(owed)), run(shlex.split(owed))
+ if handoff_mode == "hard_lease":
+ assert refreshed["settlement_result"]["ok"]
+ receipts = refreshed["settlement_result"]["receipts"]
+ assert [receipt["step_kind"] for receipt in receipts] == [
+ "validation", "durable_writeback", "quota_spend",
+ ]
+ assert all(
+ receipt["effect_id"] == identity["effect_id"] and receipt["status"] == "committed"
+ for receipt in receipts
+ )
+ assert refreshed["quota_spend"]["appended"]
+ first = refreshed
+ settle_argv = refresh_argv
+ else:
+ assert cli._spend_run_count(runtime) == 0
+ settle_argv = shlex.split(refreshed["settlement_owed"]["command"])
+ assert settle_argv[0] == program
+ first = run(settle_argv)
assert first["settlement_progress"]["state"] == "settled" and first["appended"]
+ assert cli._spend_run_count(runtime) == 1
+ replay = run(settle_argv)
assert replay["idempotent_replay"] and not replay["appended"]
assert first["settlement_identity"] == identity
+ if handoff_mode == "hard_lease":
+ assert replay["settlement_identity"] == identity
+ assert replay["settlement_result"] == first["settlement_result"]
assert cli._spend_run_count(runtime) == 1
+ assert cli._classification_count(runtime, "validated_progress") == 1
if lease:
released = run([
*prefix, "task-lease", "release", "--goal-id", cli.GOAL_ID,
diff --git a/tests/control_plane/test_effective_turn_replan.py b/tests/control_plane/test_effective_turn_replan.py
index 0e449180e8..03fba2571b 100644
--- a/tests/control_plane/test_effective_turn_replan.py
+++ b/tests/control_plane/test_effective_turn_replan.py
@@ -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),
diff --git a/tests/control_plane/test_monitor_gate_handoff.py b/tests/control_plane/test_monitor_gate_handoff.py
new file mode 100644
index 0000000000..541c21620e
--- /dev/null
+++ b/tests/control_plane/test_monitor_gate_handoff.py
@@ -0,0 +1,104 @@
+"""A due Monitor is told that its observation cannot complete a User gate."""
+from __future__ import annotations
+
+import json
+
+import pytest
+from canonical_authority_fixture import isolate_sqlite_runtime
+
+from loopx.control_plane.testing.canary_harness import run_json_cli, run_json_cli_result
+from loopx.control_plane.work_items.interaction_contract import MONITOR_USER_GATE_NOTICE
+from tests.control_plane.test_monitor_followthrough_contract import (
+ AGENT_ID,
+ GOAL_ID,
+ _write_fixture,
+)
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_monitor_observation_never_projects_gate_completion(tmp_path, tmp_path_factory, monkeypatch, provider):
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ registry, runtime, state = _write_fixture(tmp_path_factory.mktemp("g") / "a b", provider=provider,
+ handoff_mode="hard_lease")
+
+ def cli(*args):
+ return run_json_cli(*args, registry_path=registry, runtime_root=runtime)
+
+ def rejected(*args):
+ rc, result = run_json_cli_result(*args, registry_path=registry, runtime_root=runtime)
+ assert rc == 1 and result["ok"] is False, result
+ return result
+
+ def actions(guard):
+ return guard["interaction_contract"]["cli_channel"]["next_cli_actions"]
+
+ actor = ("--goal-id", GOAL_ID, "--agent-id", AGENT_ID)
+ scope = (*actor, "--runtime-profile", "generic_cli")
+ monitor_args = ("todo", "add", "--goal-id", GOAL_ID, "--role", "agent", "--task-class", "continuous_monitor",
+ "--claimed-by", AGENT_ID, "--target-key", "prices-input", "--cadence", "1m",
+ "--expires-at", "2099-01-01T00:00:00Z", "--next-due-at", "2000-01-01T00:00:00Z",
+ "--text", "Observe inputs/prices.json once when due.")
+ monitor = cli(*monitor_args)["todo_id"]
+ claim = cli("todo", "claim", *actor, "--todo-id", monitor, "--claimed-by", AGENT_ID)
+ # Without an open User gate the projection is unchanged.
+ plain = cli("quota", "should-run", *scope, "--turn-instance-id", "no-gate")
+ assert plain["selected_todo"]["todo_id"] == monitor
+ assert MONITOR_USER_GATE_NOTICE not in actions(plain)
+
+ work = cli("todo", "add", "--goal-id", GOAL_ID, "--role", "agent", "--task-class", "advancement_task",
+ "--claimed-by", AGENT_ID, "--status", "blocked",
+ "--text", "Compute value from the supplied prices.")["todo_id"]
+ gate = cli("todo", "add", *actor, "--role", "user", "--task-class", "user_gate",
+ "--unblocks-todo-id", work, "--text", "Provide inputs/prices.json.")["todo_id"]
+ # An unrelated owner decision for the same agent must never receive an approval recipe either.
+ release = cli("todo", "add", *actor, "--role", "user", "--task-class", "user_gate",
+ "--decision-scope", "production:goal:release", "--text", "Approve the release.")["todo_id"]
+
+ guard = cli("quota", "should-run", *scope, "--turn-instance-id", "no-gate")
+ assert guard["selected_todo"]["todo_id"] == monitor
+ projected = actions(guard)
+ assert "condition unmet" in projected[0]
+ assert projected[1] == MONITOR_USER_GATE_NOTICE
+ # The notice never points an observation at a gate, linked or unrelated.
+ assert "pending user action" not in MONITOR_USER_GATE_NOTICE and "report" not in MONITOR_USER_GATE_NOTICE
+ commands = [action for action in projected if action.startswith("loopx ")]
+ assert len(commands) == 1 and " quota monitor-poll " in commands[0], projected
+ assert not any("todo complete" in action or "--decision-outcome" in action for action in projected)
+ assert gate not in " ".join(projected) and release not in " ".join(projected)
+
+ price_file = state.parents[3] / "inputs" / "prices.json"
+ price_file.parent.mkdir()
+ price_file.write_text('{"A":199}', encoding="utf-8")
+ poll = cli("quota", "monitor-poll", *scope, "--turn-instance-id", "no-gate", "--todo-id", monitor,
+ "--target-key", "prices-input", "--result-hash", "prices-present", "--material-change",
+ "--use-current-task-lease", "--execute")
+ assert poll["material_change"] is True
+ assert poll["turn_continuation"]["current_turn_settled"] is True
+ # The two attempts the notice rules out stay rejected by their existing owners.
+ denied = rejected("todo", "complete", *actor, "--role", "user", "--todo-id", gate,
+ "--turn-instance-id", "no-gate", "--decision-outcome", "approve", "--evidence", "Actual input observed")
+ assert "settlement binding does not match the original quota guard" in denied["error"]
+ denied = rejected("todo", "update", *actor, "--todo-id", gate, "--evidence", "Actual input observed")
+ assert denied["error_code"] == "handoff_mode_requires_lease"
+ rows = {row["todo_id"]: row for row in cli("todo", "list", "--goal-id", GOAL_ID)["todos"]}
+ assert rows[gate]["status"] == "open" and rows[release]["status"] == "open"
+ assert rows[work]["status"] == "blocked"
+
+ # A later unchanged check still carries the notice and still offers no completion.
+ cli("todo", "update", *actor, "--todo-id", monitor, "--claim-operation-id", claim["claim_operation_id"],
+ "--next-due-at", "2000-01-01T00:00:00Z")
+ unchanged = cli("quota", "should-run", *scope, "--turn-instance-id", "unchanged-monitor")
+ assert unchanged["selected_todo"]["todo_id"] == monitor
+ assert MONITOR_USER_GATE_NOTICE in actions(unchanged)
+ assert not any("todo complete" in action for action in actions(unchanged))
+
+ # The owner's own decision remains the only route, and resumes the linked work for a fresh Turn.
+ completed = cli("todo", "complete", *actor, "--role", "user", "--todo-id", gate,
+ "--decision-outcome", "approve", "--evidence", "Owner confirmed the supplied prices")
+ assert completed["unblock_resume"]["state"] == "resumed"
+ rows = {row["todo_id"]: row for row in cli("todo", "list", "--goal-id", GOAL_ID)["todos"]}
+ assert rows[work]["status"] == "open" and rows[release]["status"] == "open"
+ 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"] == "quota_slot_spent" for row in events)
diff --git a/tests/control_plane/test_monitor_replan_closeout.py b/tests/control_plane/test_monitor_replan_closeout.py
new file mode 100644
index 0000000000..da2c312ce1
--- /dev/null
+++ b/tests/control_plane/test_monitor_replan_closeout.py
@@ -0,0 +1,94 @@
+"""Closing a Monitor cannot orphan the review Turn which admitted its closeout."""
+from __future__ import annotations
+
+import json
+import shlex
+from pathlib import Path
+
+import pytest
+
+from loopx.control_plane.testing.quota_fixtures import quota_todo_item
+from test_replan_successor_guard_reentry import AGENT, GOAL, TURN, _fixture
+
+
+def _guard(call, turn: str = TURN):
+ return call("quota", "should-run", "--goal-id", GOAL, "--agent-id", AGENT,
+ "--runtime-profile", "generic_cli", "--turn-instance-id", turn)
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize("first", ["guard", "writeback"])
+def test_monitor_closeout(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, first: str) -> None:
+ monitor = quota_todo_item(
+ todo_id="todo_monitor", title="Observe the external gate", archive_state="active",
+ task_class="continuous_monitor", claimed_by=AGENT, action_kind="monitor",
+ target_key="external-gate", cadence="30m", consecutive_no_change="5",
+ next_due_at="2099-01-01T00:00:00Z", expires_at="2099-01-02T00:00:00Z",
+ )
+ call, _, index = _fixture(tmp_path, monkeypatch, provider, initial_todos=[monitor])
+ # Only the live Monitor's current streak admits this review, not run history.
+ index.write_text("")
+ state = tmp_path / "project" / "ACTIVE_GOAL_STATE.md"
+ state.write_text(state.read_text() + "\n## User Todo / Owner Review Reading Queue\n")
+ admitted = _guard(call)
+ assert admitted["decision"] == "autonomous_replan_required"
+ assert admitted["autonomous_replan_obligation"]["triggers"][0]["kind"] == "monitor_no_change_streak"
+ identity = admitted["heartbeat_receipt"]["settlement_identity"]
+ assert identity["binding_kind"] == "autonomous_replan"
+ actions = admitted["interaction_contract"]["cli_channel"]["next_cli_actions"]
+
+ claim = call("todo", "claim", "--goal-id", GOAL, "--todo-id", monitor["todo_id"],
+ "--agent-id", AGENT, "--claimed-by", AGENT)
+ completed = call("todo", "complete", "--goal-id", GOAL, "--todo-id", monitor["todo_id"],
+ "--agent-id", AGENT, "--claim-operation-id", claim["claim_operation_id"],
+ "--evidence", "The declared external gate is covered.", "--no-follow-up")
+ assert completed["ok"] is True
+ listed = call("todo", "list", "--goal-id", GOAL, "--todo-id", monitor["todo_id"], "--include-archived")
+ assert listed["todo"]["status"] == "done"
+
+ if first == "guard":
+ pending = _guard(call)
+ assert pending["heartbeat_receipt"]["settlement_identity"] == identity
+ assert pending["autonomous_replan_obligation"]["obligation_id"] == identity["replan_obligation_id"]
+ assert pending["normal_delivery_allowed"] is False
+
+ # A lifecycle transition is not itself the semantic review or a debit.
+ premature = call(*shlex.split(actions[1])[1:], expected_code=1)
+ assert premature.get("appended") is not True
+ vision = tmp_path / "vision.json"
+ vision.write_text(json.dumps({
+ "schema_version": "goal_vision_replan_contract_v0", "state": "no_followup",
+ "vision_patch": {"acceptance_summary": "The independently accepted source outcome is covered."},
+ "path_delta": {"schema_version": "goal_path_delta_v0", "outcome": "stop",
+ "prior_assumption": "The external gate still needs observation.",
+ "observed_reality": "The declared gate is covered and no successor remains.",
+ "retained": ["the independently accepted source contract"],
+ "evidence_refs": ["evidence:gate-coverage"]},
+ }))
+ refresh = shlex.split(actions[0])[1:]
+ values = {
+ "--progress-result-class": "no_followup", "--progress-surface-id": "gate-coverage",
+ "--progress-hypothesis-id": "covered-gate", "--progress-probe-kind": "closeout-review",
+ "--progress-evidence-id": "evidence:gate-coverage",
+ }
+ for flag, value in values.items():
+ refresh[refresh.index(flag) + 1] = value
+ refreshed = call(*refresh, "--agent-vision-json", str(vision),
+ "--progress-coverage-scope-id", "external-gate", "--progress-coverage-complete",
+ "--no-global-sync", "--suppress-external-sinks")
+ assert refreshed["settlement_progress"]["state"] == "spend_required"
+ pending = _guard(call)
+ assert pending["heartbeat_receipt"]["settlement_identity"] == identity
+ assert pending["settlement_progress"]["state"] == "spend_required"
+ spend = pending["interaction_contract"]["cli_channel"]["next_cli_actions"]
+ assert len(spend) == 1
+ spent = call(*shlex.split(spend[0])[1:])
+ assert spent["appended"] is True
+ assert spent["settlement_progress"]["state"] == "settled"
+ assert call(*shlex.split(spend[0])[1:])["appended"] is False
+ assert _guard(call)["effective_action"] == "heartbeat_settled_skip"
+ next_turn = _guard(call, "turn-after-monitor-review")
+ assert next_turn["ok"] is True
+ assert next_turn["effective_action"] == "terminal_no_followup"
+ rows = [json.loads(line) for line in index.read_text().splitlines()]
+ assert sum(row.get("classification") == "quota_slot_spent" for row in rows) == 1
diff --git a/tests/control_plane/test_quota_settlement.py b/tests/control_plane/test_quota_settlement.py
index 79e0a6d664..ed2651f365 100644
--- a/tests/control_plane/test_quota_settlement.py
+++ b/tests/control_plane/test_quota_settlement.py
@@ -41,6 +41,7 @@
from loopx.control_plane.quota.error_codes import (
HeartbeatReceiptIdentityConflictError,
)
+from loopx.control_plane.quota.effective_action import EffectiveAction
from loopx.control_plane.quota.turn_envelope import quota_action_signature_document
from loopx.control_plane.scheduler.execution_context import (
SchedulerRuntimeProfile,
@@ -255,6 +256,22 @@ def test_selected_todo_suppresses_stale_replan_packet_binding() -> None:
assert quota_rollout_replan_obligation_id(payload, args) is None
+def test_current_replan_preserves_explicit_planning_selection_gate() -> None:
+ obligation_id = "replan-0000000000000001"
+ payload = {
+ "effective_action": EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED.value,
+ "selected_todo": {"todo_id": TODO_ID},
+ "action_portfolio": {
+ "selection_policy": {"requires_explicit_turn_binding": True},
+ },
+ "replan_action_packet": {"obligation_id": obligation_id},
+ }
+ args = SimpleNamespace(todo_id=None, replan_obligation_id=None)
+
+ assert quota_rollout_todo_id(payload, args) is None
+ assert quota_rollout_replan_obligation_id(payload, args) is None
+
+
def test_explicit_replan_binding_survives_newly_selected_todo() -> None:
obligation_id = "replan-0000000000000001"
payload = {"selected_todo": {"todo_id": TODO_ID}}
diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py
index 6bb924e7c4..7c98cd6960 100644
--- a/tests/control_plane/test_quota_settlement_cli.py
+++ b/tests/control_plane/test_quota_settlement_cli.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import hashlib
import json
import os
import shlex
@@ -737,6 +738,200 @@ def _bind_selected_replan_guard(
return bound
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_existing_todo_receipt_precedes_later_replan_projection(
+ tmp_path: Path,
+ provider: str,
+) -> None:
+ """A later replan cannot replace an admitted Todo settlement identity."""
+
+ project, runtime, registry = _write_fixture(tmp_path)
+ _configure_read_only_todo(project)
+ _initialize_fixture_authority(project, runtime, provider=provider)
+ turn = "turn-existing-todo-before-later-replan"
+ guard = (
+ "quota",
+ "should-run",
+ "--codex-app",
+ "--goal-id",
+ GOAL_ID,
+ "--agent-id",
+ AGENT_ID,
+ "--turn-instance-id",
+ turn,
+ )
+
+ first_rc, first = _run_cli(registry, runtime, *guard)
+ assert first_rc == 0, first
+ original = first["heartbeat_receipt"]["settlement_identity"]
+ assert original["todo_id"] == TODO_ID
+ assert original.get("replan_obligation_id") is None
+
+ _append_surface_only_runs(
+ runtime,
+ count=AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD,
+ )
+ replay_rc, replay = _run_cli(registry, runtime, *guard)
+
+ assert replay_rc == 0, replay
+ assert replay["heartbeat_receipt"]["settlement_identity"] == original
+ assert (
+ replay["interaction_contract"]["cli_channel"]["settlement_plan"][
+ "identity"
+ ]
+ == original
+ )
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_same_explicit_todo_retry_preserves_original_identity(
+ tmp_path: Path,
+ provider: str,
+) -> None:
+ """Retrying the retained planning choice reuses the admitted replan."""
+
+ project, runtime, registry = _write_fixture(tmp_path)
+ _configure_selected_todo_replan_fixture(project, registry, stride_strategy="off")
+ _initialize_git_checkout(project)
+ _initialize_fixture_authority(project, runtime, provider=provider)
+ turn = "turn-same-explicit-todo-replan-retry"
+ guard = (
+ "quota",
+ "should-run",
+ "--codex-app",
+ "--goal-id",
+ GOAL_ID,
+ "--agent-id",
+ AGENT_ID,
+ "--turn-instance-id",
+ turn,
+ "--todo-id",
+ SELECTED_REPLAN_TODO_ID,
+ )
+
+ first_rc, first = _run_cli(registry, runtime, *guard)
+ replay_rc, replay = _run_cli(registry, runtime, *guard)
+
+ assert first_rc == 0, first
+ original = first["heartbeat_receipt"]["settlement_identity"]
+ assert original["todo_id"] == SELECTED_REPLAN_TODO_ID
+ assert replay_rc == 0, replay
+ assert replay["heartbeat_receipt"]["settlement_identity"] == original
+ assert (
+ replay["interaction_contract"]["cli_channel"]["settlement_plan"][
+ "identity"
+ ]
+ == original
+ )
+
+ conflict_args = list(guard)
+ conflict_args[-1] = ALTERNATIVE_TODO_ID
+ conflict_rc, conflict = _run_cli(registry, runtime, *conflict_args)
+ assert conflict_rc == 1, conflict
+ assert conflict["error_code"] == "heartbeat_receipt_identity_conflict"
+ receipt_events = _heartbeat_receipt_events(runtime, turn)
+ assert receipt_events
+ assert {
+ event["details"]["settlement_effect_id"] for event in receipt_events
+ } == {original["effect_id"]}
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_todoless_replan_upgrades_legacy_review_guard(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str,
+) -> None:
+ """A legacy review receipt gains its source without rebinding the Turn."""
+ if provider == "sqlite":
+ from canonical_authority_fixture import isolate_sqlite_runtime
+
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ project, runtime, registry = _write_fixture(tmp_path)
+ state = project / f".codex/goals/{GOAL_ID}/ACTIVE_GOAL_STATE.md"
+ state.write_text(
+ state.read_text().split("## Agent Todo")[0].replace(
+ "status: active-read-only", "status: active"
+ ) + "## Agent Todo\n\n"
+ )
+ registry_value = json.loads(registry.read_text())
+ registry_value["goals"][0]["status"] = "active"
+ registry.write_text(json.dumps(registry_value))
+ _initialize_fixture_authority(project, runtime, provider=provider)
+ _append_surface_only_runs(runtime, count=AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD)
+
+ def call(*args: str, expected_code: int = 0) -> dict[str, Any]:
+ code, result = _run_cli(registry, runtime, *args)
+ assert code == expected_code, result
+ return result
+
+ call("configure-goal", "--goal-id", GOAL_ID,
+ "--execution-replan-after-todos", "5", "--execute")
+
+ turn = "turn-todoless-replan-review-upgrade"
+ guard = ("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID,
+ "--agent-id", AGENT_ID, "--turn-instance-id", turn)
+ first = call(*guard)
+ assert first["effective_action"] == "autonomous_replan_required"
+ identity = first["heartbeat_receipt"]["settlement_identity"]
+ assert identity["binding_kind"] == "autonomous_replan"
+ assert identity["replan_obligation_id"] == first["replan_action_packet"]["obligation_id"]
+ original = _heartbeat_receipt_events(runtime, turn)[0]
+ expected_kind = original["details"]["semantic_replan_review_kind"]
+
+ # Simulate a receipt written before review-source retention existed. The
+ # exercised repair below is append-only; only this fixture setup removes
+ # fields from its synthetic legacy input.
+ log = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl"
+ events = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()]
+ for event in events:
+ if event.get("event_id") != original["event_id"]:
+ continue
+ for field in ("semantic_replan_review_kind",
+ "semantic_replan_review_stop_condition",
+ "semantic_replan_review_stop_condition_sha256",
+ "semantic_replan_review_stop_contract_id"):
+ event["details"].pop(field, None)
+ log.write_text("\n".join(json.dumps(event) for event in events) + "\n", encoding="utf-8")
+
+ replay = call(*guard)
+ assert replay["heartbeat_receipt"]["settlement_identity"] == identity
+ repaired = _heartbeat_receipt_events(runtime, turn)
+ assert len(repaired) == 2
+ assert repaired[1]["causality"]["caused_by"] == original["event_id"]
+ assert repaired[1]["details"]["settlement_receipt_revision"] == "review_guard_upgrade"
+ assert repaired[1]["details"]["semantic_replan_review_kind"] == expected_kind
+ assert (
+ repaired[1]["details"].get("semantic_replan_review_stop_condition")
+ or repaired[1]["details"].get("semantic_replan_review_stop_condition_sha256")
+ )
+
+ # A new completed Turn rotates the periodic frontier obligation id while the
+ # review kind and full stop contract remain the same. A fresh dry-run
+ # exposes that raw id; replay of the admitted Turn retains its old identity
+ # and adopts the current context.
+ index = runtime / "goals" / GOAL_ID / "runs" / "index.jsonl"
+ with index.open("a", encoding="utf-8") as handle:
+ handle.write(json.dumps({"generated_at": "2026-08-13T01:00:00+00:00",
+ "goal_id": GOAL_ID, "classification": "surface_only_progress",
+ "agent_id": AGENT_ID, "progress_scope": "agent_lane",
+ "delivery_outcome": "surface_only"}) + "\n")
+ receipt_bytes = log.read_bytes()
+ log.unlink()
+ try:
+ probe = call("quota", "should-run", "--codex-app", "--goal-id", GOAL_ID,
+ "--agent-id", AGENT_ID, "--dry-run")
+ finally:
+ log.write_bytes(receipt_bytes)
+ assert probe["replan_action_packet"]["obligation_id"] != identity["replan_obligation_id"]
+ assert probe["autonomous_replan_obligation"]["stop_condition"] == (
+ first["autonomous_replan_obligation"]["stop_condition"]
+ )
+ replay = call(*guard)
+ assert replay["heartbeat_receipt"]["settlement_identity"] == identity
+ assert replay["autonomous_replan_obligation"]["obligation_id"] == identity["replan_obligation_id"]
+ assert len(_heartbeat_receipt_events(runtime, turn)) == 2
+
+
def _initialize_git_checkout(project: Path) -> None:
subprocess.run(
["git", "init", "--quiet"],
@@ -7721,21 +7916,33 @@ def refine(document: dict[str, Any], operation: str) -> dict[str, Any]:
def test_receipt_review_does_not_persist_private_or_lossy_stop_clauses() -> None:
from argparse import Namespace
from loopx.control_plane.quota.settlement_cli import quota_rollout_details
+ from loopx.control_plane.work_items.autonomous_replan_obligation import (
+ AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION,
+ )
obligation = {"schema_version": "autonomous_replan_obligation_v0", "required": True,
"agent_id": AGENT_ID, "obligation_id": "replan-1111111111111111",
- "trigger_count": 1, "triggers": [{"kind": "goal_outcome_uncovered"}]}
- for stop, retained in [("Stop at owner-only decisions.", True),
- ("Stop if Authorization: example is required.", False),
- ("Stop before\nowner-only decisions.", False), ("s" * 241, False)]:
+ "trigger_count": 1, "triggers": [{"kind": "periodic_review_due"}]}
+ for stop, retention in [("Stop at owner-only decisions.", "full"),
+ ("Stop if " + "Author" + "ization: example is required.", "none"),
+ ("Stop before\nowner-only decisions.", "none"), ("s" * 241, "digest")]:
details = quota_rollout_details({"autonomous_replan_obligation": {**obligation, "stop_condition": stop},
"replan_action_packet": {"obligation_id": obligation["obligation_id"]}},
Namespace(quota_command="should-run", agent_id=AGENT_ID), todo_id=None)
- assert ("semantic_replan_review_kind" in details) is retained
- if retained:
+ assert ("semantic_replan_review_kind" in details) is (retention != "none")
+ if retention == "full":
assert details["semantic_replan_review_stop_condition"] == stop
+ assert "semantic_replan_review_stop_condition_sha256" not in details
+ elif retention == "digest":
+ assert details["semantic_replan_review_stop_condition_sha256"] == hashlib.sha256(
+ stop.encode("utf-8")
+ ).hexdigest()
+ assert details["semantic_replan_review_stop_condition"] == (
+ AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION
+ )
else:
assert "semantic_replan_review_stop_condition" not in details
+ assert "semantic_replan_review_stop_condition_sha256" not in details
@pytest.mark.parametrize("provider", ["file", "sqlite"])
diff --git a/tests/control_plane/test_refresh_settle_turn.py b/tests/control_plane/test_refresh_settle_turn.py
index 5c3d86da21..4941264756 100644
--- a/tests/control_plane/test_refresh_settle_turn.py
+++ b/tests/control_plane/test_refresh_settle_turn.py
@@ -169,6 +169,229 @@ def fail_child(argv, **kwargs):
assert replay["idempotent_replay"] and _spend_run_count(runtime) == 1
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_exact_spend_and_combined_replay_reject_disagreeing_billing_terms(tmp_path, monkeypatch, provider):
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ project, runtime, registry = _write_fixture(tmp_path)
+ _initialize_fixture_authority(project, runtime, provider=provider)
+ binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID,
+ "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID]
+ rc, guard = _run_cli(registry, runtime, "quota", "should-run", "--codex-app", *binding, cwd=project)
+ assert rc == 0, guard
+ original = guard["heartbeat_receipt"]["settlement_identity"]
+ refresh = ["refresh-state", *binding, "--classification", "verified_billing_replay",
+ "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress",
+ "--delivery-boundary", "in_flight_continuation", "--no-global-sync", "--suppress-external-sinks"]
+ combined = [*refresh, "--settle-turn", "--settlement-receipt"]
+ spend = ["quota", "spend-slot", *binding, "--execute"]
+ debit = [*spend, "--slots", "1", "--source", "heartbeat"]
+ rc, delivery = _run_cli(registry, runtime, *refresh, cwd=project)
+ assert rc == 0 and delivery["settlement_progress"]["state"] == "spend_required", delivery
+ for slots, source in (("2", "heartbeat"), ("1", "visible-goal")):
+ rc, wrong = _run_cli(registry, runtime, *spend, "--slots", slots, "--source", source, cwd=project)
+ assert rc != 0 and not wrong["ok"] and not wrong["appended"], wrong
+ assert _spend_run_count(runtime) == 0
+
+ rc, settled = _run_cli(registry, runtime, *combined, cwd=project)
+ assert rc == 0 and settled["settlement_progress"]["state"] == "settled", settled
+ assert settled["settlement_identity"]["effect_id"] == original["effect_id"]
+ log = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl"
+ index = log.parent / "runs" / "index.jsonl"
+ receipt_log = log.read_text(encoding="utf-8")
+ initial_index = index.read_bytes()
+ debit_record, = (record for line in initial_index.splitlines()
+ if (record := json.loads(line))["classification"] == "quota_slot_spent")
+ artifact = Path(debit_record["json_path"])
+ assert artifact.resolve().is_relative_to(runtime.resolve())
+ for field, bad_value in ((None, None), ("slots", 2), ("source", "visible-goal"),
+ ("missing", None), ("legacy_empty", ""), ("legacy_empty", None),
+ ("missing_artifact", None), ("missing", None), ("legacy_empty", None),
+ ("slots", 2), ("source", "visible-goal"),
+ ("unknown_admission_source", None), ("unknown_legacy_terms", None)):
+ rows = [json.loads(line) for line in receipt_log.splitlines()]
+ receipt, = (row for row in rows if row["event_kind"] == "quota_spend" and row["agent_id"] == AGENT_ID)
+ details = receipt["details"]
+ assert details["settlement_effect_id"] == original["effect_id"]
+ assert details["slots"] == 1 and details["source"] == "heartbeat"
+ if field == "missing":
+ details.pop("slots")
+ details.pop("source")
+ elif field == "legacy_empty":
+ details.update(slots=bad_value, source=bad_value)
+ elif field == "missing_artifact":
+ artifact.rename(tmp_path / "legacy-unavailable-spend.json")
+ elif field in ("unknown_admission_source", "unknown_legacy_terms"):
+ admission, = (row for row in rows if row["event_kind"] == "quota_should_run")
+ assert admission["details"].pop("quota_spend_source") == "heartbeat"
+ if field == "unknown_legacy_terms":
+ details.pop("slots")
+ details.pop("source")
+ elif field is not None:
+ details[field] = bad_value
+ log.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
+ before = log.read_bytes()
+ missing_artifact = not artifact.exists()
+ # A caller cannot make a conflicting source valid by supplying that
+ # same source on replay once only the index and receipt remain.
+ commands = (combined, debit) if missing_artifact else (debit, combined)
+ if field == "source" and missing_artifact:
+ commands += ((*spend, "--slots", "1", "--source", bad_value),)
+ for command in commands:
+ rc, replay = _run_cli(registry, runtime, *command, cwd=project)
+ if field in ("slots", "source", "unknown_admission_source"):
+ assert rc != 0 and not replay["ok"], replay
+ basis = "original Turn admission" if missing_artifact else "recorded debit"
+ diagnostic = replay.get("reason") or replay.get("error") or ""
+ expected = ("original Turn admission has no verifiable billing source"
+ if field == "unknown_admission_source"
+ else f"{basis} and quota spend receipt disagree on {field}")
+ assert expected in diagnostic, replay
+ assert replay.get("settlement_progress", {}).get("state") != "settled", replay
+ assert not replay.get("settlement_owed"), replay
+ else:
+ assert rc == 0 and replay["ok"] and replay["idempotent_replay"], replay
+ assert replay["settlement_identity"]["effect_id"] == original["effect_id"]
+ assert not replay.get("appended"), replay
+ assert log.read_bytes() == before and index.read_bytes() == initial_index
+ assert _heartbeat_receipt_count(runtime, TURN_ID) == 1 and _spend_run_count(runtime) == 1
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize("repair_entry", ["spend", "refresh"])
+def test_missing_spend_receipt_preserves_the_original_debit(tmp_path, monkeypatch, provider, repair_entry):
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ project, runtime, registry = _write_fixture(tmp_path)
+ _initialize_fixture_authority(project, runtime, provider=provider)
+ binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID,
+ "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID]
+ rc, guard = _run_cli(registry, runtime, "quota", "should-run", "--codex-app", *binding, cwd=project)
+ assert rc == 0, guard
+ original = guard["heartbeat_receipt"]["settlement_identity"]
+ combined = ["refresh-state", *binding, "--classification", "verified_billing_repair",
+ "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress",
+ "--delivery-boundary", "in_flight_continuation", "--no-global-sync", "--suppress-external-sinks",
+ "--settle-turn", "--settlement-receipt"]
+ debit = ["quota", "spend-slot", *binding, "--slots", "1", "--source", "heartbeat", "--execute"]
+ rc, settled = _run_cli(registry, runtime, *combined, cwd=project)
+ assert rc == 0 and settled["settlement_progress"]["state"] == "settled", settled
+
+ log = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl"
+ index = log.parent / "runs" / "index.jsonl"
+ original_index = index.read_bytes()
+ debit_record, = (row for line in original_index.splitlines()
+ if (row := json.loads(line))["classification"] == "quota_slot_spent")
+ artifact = Path(debit_record["json_path"])
+ original_artifact = artifact.read_bytes()
+ records = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()]
+ receipt, = (row for row in records if row["event_kind"] == "quota_spend")
+ retained = [row for row in records if row is not receipt]
+ log.write_text("".join(json.dumps(row) + "\n" for row in retained), encoding="utf-8")
+
+ rc, repaired = _run_cli(registry, runtime, *(debit if repair_entry == "spend" else combined), cwd=project)
+ assert rc == 0 and repaired["ok"], repaired
+ assert repaired["settlement_progress"]["state"] == "settled", repaired
+ assert repaired["settlement_identity"]["effect_id"] == original["effect_id"]
+ assert not repaired.get("settlement_owed"), repaired
+ recovered_log = log.read_bytes()
+ after = [json.loads(line) for line in recovered_log.splitlines()]
+ assert [row for row in after if row["event_kind"] != "quota_spend"] == retained
+ recovered, = (row for row in after if row["event_kind"] == "quota_spend")
+ assert recovered["details"]["settlement_effect_id"] == original["effect_id"]
+ assert recovered["details"]["slots"] == receipt["details"]["slots"] == 1
+ assert recovered["details"]["source"] == receipt["details"]["source"] == "heartbeat"
+ for command in (debit, combined):
+ rc, replay = _run_cli(registry, runtime, *command, cwd=project)
+ assert rc == 0 and replay["ok"] and replay["idempotent_replay"], replay
+ assert replay["settlement_identity"]["effect_id"] == original["effect_id"]
+ assert not replay.get("appended") and not replay.get("settlement_owed"), replay
+ assert log.read_bytes() == recovered_log
+ assert index.read_bytes() == original_index and artifact.read_bytes() == original_artifact
+ assert _heartbeat_receipt_count(runtime, TURN_ID) == 1 and _spend_run_count(runtime) == 1
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize("artifact_format", ["current", "legacy"])
+def test_exact_spend_and_refresh_reject_another_turns_debit_file(
+ tmp_path, monkeypatch, provider, artifact_format,
+):
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ project, runtime, registry = _write_fixture(tmp_path)
+ _initialize_fixture_authority(project, runtime, provider=provider)
+ commands, identities = {}, {}
+ for turn in (TURN_ID, f"{TURN_ID}-second"):
+ 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, cwd=project)
+ assert rc == 0 and guard["should_run"], guard
+ identities[turn] = guard["heartbeat_receipt"]["settlement_identity"]
+ combined = ["refresh-state", *binding, "--classification", "verified_debit_identity",
+ "--delivery-batch-scale", "implementation", "--delivery-outcome", "outcome_progress",
+ "--delivery-boundary", "in_flight_continuation", "--no-global-sync", "--suppress-external-sinks",
+ "--settle-turn", "--settlement-receipt"]
+ spend = ["quota", "spend-slot", *binding, "--slots", "1", "--source", "heartbeat", "--execute", "--verbose"]
+ rc, settled = _run_cli(registry, runtime, *combined, cwd=project)
+ assert rc == 0 and settled["settlement_progress"]["state"] == "settled", settled
+ assert settled["settlement_identity"] == identities[turn]
+ commands[turn] = (combined, spend)
+
+ log = runtime / "goals" / GOAL_ID / "rollout-event-log.jsonl"
+ index = log.parent / "runs" / "index.jsonl"
+ rows = [json.loads(line) for line in index.read_bytes().splitlines()]
+ target, sibling = (row for row in rows if row["classification"] == "quota_slot_spent")
+ assert target["settlement_identity"] == identities[TURN_ID]
+ assert sibling["settlement_identity"] == identities[f"{TURN_ID}-second"]
+ artifacts = [Path(row["json_path"]) for row in (target, sibling)]
+ if artifact_format == "legacy":
+ # The historical Python writer retained Turn/effect bindings, but no
+ # commit metadata. Equal timestamps must not authenticate another Turn.
+ for row, path in zip((target, sibling), artifacts):
+ record = json.loads(path.read_bytes())
+ row.pop("quota_spend_commit")
+ record.pop("quota_spend_commit")
+ row["generated_at"] = record["generated_at"] = "2026-11-01T12:00:00Z"
+ path.write_text(json.dumps(record) + "\n", encoding="utf-8")
+ index.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
+ original_artifacts = [path.read_bytes() for path in artifacts]
+ assert [(json.loads(data)["quota_event"]["slots"], json.loads(data)["quota_event"]["source"])
+ for data in original_artifacts] == [(1, "heartbeat"), (1, "heartbeat")]
+ original_index = index.read_bytes()
+ original_log = log.read_bytes()
+ target["json_path"] = sibling["json_path"]
+ index.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8")
+ redirected_index = index.read_bytes()
+
+ for receipt_kind in ("current", "legacy", "missing"):
+ if receipt_kind != "current":
+ retained = []
+ for line in original_log.splitlines():
+ row = json.loads(line)
+ if row["event_kind"] == "quota_spend" and row["run_id"] == TURN_ID:
+ if receipt_kind == "missing":
+ continue
+ row["details"].pop("slots")
+ row["details"].pop("source")
+ retained.append(row)
+ log.write_text("".join(json.dumps(row) + "\n" for row in retained), encoding="utf-8")
+ before = log.read_bytes()
+ for command in commands[TURN_ID]:
+ rc, rejected = _run_cli(registry, runtime, *command, cwd=project)
+ assert rc != 0 and not rejected["ok"], rejected
+ reason = (rejected.get("verbose_debug", {}).get("error")
+ or rejected.get("error") or rejected.get("reason") or "")
+ assert "quota spend JSON artifact identity does not match its index row" in reason, rejected
+ assert rejected.get("settlement_progress", {}).get("state") != "settled", rejected
+ assert log.read_bytes() == before and index.read_bytes() == redirected_index
+ assert _spend_run_count(runtime) == 2
+
+ assert [path.read_bytes() for path in artifacts] == original_artifacts
+ index.write_bytes(original_index)
+ rc, recovered = _run_cli(registry, runtime, *commands[TURN_ID][0], cwd=project)
+ assert rc == 0 and recovered["settlement_progress"]["state"] == "settled", recovered
+ assert recovered["settlement_identity"] == identities[TURN_ID]
+ assert _spend_run_count(runtime) == 2 and index.read_bytes() == original_index
+
+
+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_receipt_capture_failure_keeps_committed_receipts_and_exact_retry(tmp_path, monkeypatch, provider):
isolate_sqlite_runtime(tmp_path, monkeypatch)
diff --git a/tests/control_plane/test_replan_successor_guard_reentry.py b/tests/control_plane/test_replan_successor_guard_reentry.py
index fd5586492a..48508cd15a 100644
--- a/tests/control_plane/test_replan_successor_guard_reentry.py
+++ b/tests/control_plane/test_replan_successor_guard_reentry.py
@@ -2,7 +2,9 @@
from __future__ import annotations
import json
+import os
import shlex
+import shutil
import subprocess
import sys
from pathlib import Path
@@ -107,6 +109,124 @@ def _add(call, obligation_id: str):
"--operation-id", "periodic-source-successor", "--replan-obligation-id", obligation_id)
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_projected_successor_closeout_guard_executes_original_turn(tmp_path, monkeypatch, provider):
+ from loopx.command_invocation import loopx_cli_route
+ from loopx.control_plane.scheduler.execution_context import scheduler_execution_context_for_runtime_profile
+ from loopx.control_plane.work_items.interaction_contract import interaction_next_cli_actions
+ from loopx.control_plane.work_items.progress_observation import build_replan_action_packet
+
+ call, _, _ = _fixture(tmp_path, monkeypatch, provider)
+ original = _guard(call)
+ identity = original["heartbeat_receipt"]["settlement_identity"]
+ # Exercise the existing bounded-research successor projection over a real guard.
+ original["replan_action_packet"] = build_replan_action_packet(
+ original["autonomous_replan_obligation"], goal_id=GOAL, agent_id=AGENT,
+ bounded_research_frontier={"selected_gap": {
+ "successor_summary": "Independently verify the source artifact",
+ "successor_binding": {"action_kind": "validate", "target_key": "independent-source-artifact"},
+ }},
+ )
+ cli = Path(sys.executable).parent / ("loopx.exe" if os.name == "nt" else "loopx")
+ with loopx_cli_route(str(cli)):
+ actions = interaction_next_cli_actions(
+ original, mode="autonomous_replan", capability_reentry_resolved=True,
+ settlement_plan=original["interaction_contract"]["cli_channel"]["settlement_plan"],
+ scheduler_execution_context=scheduler_execution_context_for_runtime_profile("codex_app_heartbeat"),
+ runtime_root=original["runtime_root"], registry_path=str(tmp_path / "registry.json"),
+ turn_instance_id=TURN,
+ )
+ command = actions[1]
+ tokens = shlex.split(command)
+ if os.name == "nt":
+ assert tokens.pop(0) == "&"
+ _add(call, identity["replan_obligation_id"])
+ result = subprocess.run(
+ [*tokens, "--context-delivery", "off"],
+ capture_output=True, text=True, timeout=60,
+ )
+ reread = json.loads(result.stdout)
+ assert result.returncode == 0, reread.get("error") or reread.get("reason") or reread
+ assert reread["heartbeat_receipt"]["settlement_identity"] == identity
+ assert reread["replan_action_packet"]["settlement_only"] is True
+ if os.name == "nt":
+ shell = shutil.which("pwsh") or shutil.which("powershell")
+ assert shell is not None
+ result = subprocess.run(
+ [shell, "-NoProfile", "-Command", command + "; exit $LASTEXITCODE"],
+ capture_output=True, text=True, timeout=60,
+ env={**os.environ, "PATH": str(Path(sys.executable).parent) + os.pathsep + os.environ["PATH"]},
+ )
+ native = read_cli_policy_payload(result.stdout, returncode=result.returncode)
+ assert result.returncode == 0, native
+ assert native["heartbeat_receipt"]["settlement_identity"] == identity
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+def test_projected_terminal_replan_fields_execute_without_guessed_flags(tmp_path, monkeypatch, provider):
+ from copy import deepcopy
+ from loopx.install_contract import render_host_cli_command
+
+ call, _, index = _fixture(tmp_path, monkeypatch, provider, future_monitor=False)
+ call("configure-goal", "--goal-id", GOAL, "--execution-stride-strategy", "off", "--execute")
+ # The complete delivery has no remaining Todo; retain its accepted mainline.
+ rows = [json.loads(row) for row in index.read_text().splitlines()]
+ vision = deepcopy(next(row["agent_vision"] for row in rows if "agent_vision" in row))
+ original = _guard(call)
+ identity = original["heartbeat_receipt"]["settlement_identity"]
+ contract = original["replan_action_packet"]["writeback_contract"]
+ context = original["autonomous_replan_obligation"]["replan_context"]
+ assert context["evidence"]
+ for row in context["evidence"]:
+ read = row.get("read_action") or context["evidence_read_action_template"].replace("{evidence_ref}", row["evidence_ref"])
+ detail = call(*shlex.split(read)[1:])
+ assert detail["evidence"]["evidence_ref"] == row["evidence_ref"]
+ terminal = contract["no_followup_requirements"]
+ assert terminal["cli_args"] == ["--progress-result-class", "no_followup",
+ "--progress-coverage-scope-id", "", "--progress-evidence-id", "",
+ "--agent-vision-json", ""]
+ assert terminal["vision_fields"] == {"state": "no_followup", "path_delta.outcome": "stop"}
+ assert "vision_patch" in terminal["preserve"]
+ vision["state"] = terminal["vision_fields"]["state"]
+ vision["path_delta"] = {
+ "schema_version": "goal_path_delta_v0", "outcome": terminal["vision_fields"]["path_delta.outcome"],
+ "prior_assumption": "The bounded source scope could need more work.",
+ "observed_reality": "Independent validation covers the complete source scope.",
+ "stopped": ["Repeated source checks"], "evidence_refs": ["validation:complete-source"],
+ }
+ path = tmp_path / "author's terminal.json"
+ path.write_text(json.dumps(vision), encoding="utf-8")
+ command = next(action for action in original["interaction_contract"]["cli_channel"]["next_cli_actions"]
+ if "refresh-state" in action)
+ argv = shlex.split(command)
+ # Replace only the caller-authored values in the projected template.
+ argv[argv.index("--agent-vision-json") + 1] = str(path)
+ values = {"": str(path), "": "scope:complete-source",
+ "": "validation:complete-source"}
+ for flag, value in zip(terminal["cli_args"][::2], terminal["cli_args"][1::2], strict=True):
+ if flag in argv:
+ argv[argv.index(flag) + 1] = values.get(value, value)
+ else:
+ argv.extend([flag, values.get(value, value)])
+ argv.extend(["--no-global-sync", "--suppress-external-sinks"])
+ if os.name == "nt":
+ shell = shutil.which("pwsh") or shutil.which("powershell")
+ assert shell is not None
+ # Exercise the native shell, including a quoted executable and apostrophe.
+ argv[0] = str(Path(sys.executable).parent / "loopx.exe")
+ invocation = [shell, "-NoProfile", "-Command", render_host_cli_command(argv) + "; exit $LASTEXITCODE"]
+ else:
+ invocation = [sys.executable, "-m", "loopx.cli", *argv[1:]]
+ result = subprocess.run(invocation, capture_output=True, text=True, timeout=60)
+ written = json.loads(result.stdout)
+ assert result.returncode == 0, json.dumps(written, ensure_ascii=False)
+ assert written["settlement_identity"] == identity
+ assert written["autonomous_replan_ack"]["semantic_delta"]["satisfying_outcomes"] == ["coverage_backed_no_followup"]
+ spent = call(*shlex.split(written["settlement_owed"]["command"])[1:])
+ assert spent["settlement_progress"]["state"] == "settled"
+ assert call(*shlex.split(written["settlement_owed"]["command"])[1:])["idempotent_replay"] is True
+
+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("context_delivery", ["off", "on"])
def test_successor_cli_reads_policy_with_context_delivery(
diff --git a/tests/control_plane/test_replan_writeback_projection.py b/tests/control_plane/test_replan_writeback_projection.py
index 96258b7975..ecff0fda03 100644
--- a/tests/control_plane/test_replan_writeback_projection.py
+++ b/tests/control_plane/test_replan_writeback_projection.py
@@ -155,7 +155,7 @@ def test_declared_outcomes_not_trigger_name_determine_writeback_input() -> None:
def test_guarded_successor_guidance_closes_original_turn_before_stopping(profile: str) -> None:
payload = {"replan_action_packet": {"writeback_contract": {"successor_command": "loopx todo add"}}}
binding = "--replan-obligation-id replan-1111111111111111 --turn-instance-id turn-original"
- guard = f"loopx --format json quota should-run {profile} --goal-id example --agent-id agent-example {binding}"
+ guard = f"loopx --format json quota should-run {profile} --goal-id example --agent-id agent-example --turn-instance-id turn-original"
actions = build_autonomous_replan_cli_actions(
payload, goal_id="example", settlement_args=f" {binding}",
scoped_cli_args=" --agent-id agent-example", quota_spend_action="spend-bound-turn",
@@ -243,10 +243,11 @@ def test_successor_guard_entrypoint_retains_host_and_only_pure_replan_binding(
tokens = shlex.split(actions[1])
assert tokens[tokens.index("--runtime-root") + 1] == "/tmp/public-safe-replan-runtime"
assert tokens[tokens.index("--turn-instance-id") + 1] == "turn-original"
- assert tokens[tokens.index("--replan-obligation-id") + 1] == identity["replan_obligation_id"]
+ assert "--replan-obligation-id" not in tokens
assert tokens[tokens.index("--agent-id") + 1] == "agent-example"
assert "--todo-id" not in tokens
- assert render_scheduler_execution_args(scheduler_execution_context=context).strip() in actions[1]
+ for arg in shlex.split(render_scheduler_execution_args(scheduler_execution_context=context)):
+ assert arg in tokens
assert "do not execute or select its successor" in actions[2]
diff --git a/tests/control_plane/test_runtime_projection_explicit_route.py b/tests/control_plane/test_runtime_projection_explicit_route.py
index eaf9b56171..f011810cd8 100644
--- a/tests/control_plane/test_runtime_projection_explicit_route.py
+++ b/tests/control_plane/test_runtime_projection_explicit_route.py
@@ -137,6 +137,41 @@ def unexpected_read():
) == [root]
+def test_default_conflict_guides_status_to_each_registered_goal_source(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys,
+):
+ current, _legacy = _conflicting_default_roots(tmp_path, monkeypatch)
+ registry, _source_runtime, _state = promoted_create_fixture(tmp_path / "source")
+ source_payload = json.loads(registry.read_bytes())
+ source_payload["goals"][0].update(
+ domain="software", adapter={"kind": "read_only_project_map_v0", "status": "connected-read-only"},
+ )
+ registry.write_text(json.dumps(source_payload), encoding="utf-8")
+ global_registry = _declare_target(current, registry)
+ global_payload = json.loads(global_registry.read_bytes())
+ global_payload["common_runtime_root"] = str(current)
+ global_registry.write_text(json.dumps(global_payload), encoding="utf-8")
+ monkeypatch.delenv("LOOPX_REGISTRY", raising=False)
+ monkeypatch.chdir(tmp_path)
+
+ args = ["--format", "json", "status", "--goal-id", DEFAULT_CONFLICT_GOAL]
+ with pytest.raises(SystemExit, match="Both default LoopX runtime roots") as conflict:
+ main(args)
+ assert main(["--registry", str(global_registry), *args]) == 0
+ status = json.loads(capsys.readouterr().out)
+ assert status["ok"] is True and status["contract"]["errors"] == []
+
+ assert main(["--registry", str(global_registry), "--runtime-root", str(current), *args]) == 1
+ forced = json.loads(capsys.readouterr().out)
+ assert forced.get("error_code") == "canonical_authority_required", forced
+ assert forced["authority_read"]["goal_id"] == DEFAULT_CONFLICT_GOAL
+
+ advice = paths.default_runtime_route()["recommended_action"]
+ assert "Use --registry alone" in advice
+ assert "explicit single-runtime" in advice
+ assert str(conflict.value).endswith(advice)
+
+
@pytest.mark.parametrize("missing_path_key", ["json_path", "markdown_path"])
def test_route_projection_with_missing_artifact_is_not_current(
tmp_path: Path,
diff --git a/tests/control_plane/test_scheduler_fallback_hint.py b/tests/control_plane/test_scheduler_fallback_hint.py
index 2c20e5eeed..1ef74314e8 100644
--- a/tests/control_plane/test_scheduler_fallback_hint.py
+++ b/tests/control_plane/test_scheduler_fallback_hint.py
@@ -1,8 +1,12 @@
from __future__ import annotations
+import sys
from datetime import datetime, timezone
from pathlib import Path
+import pytest
+
+from loopx.command_invocation import loopx_cli_route
from loopx.control_plane.heartbeat.rules import (
SCHEDULER_HINT_APPLICATION_RULE,
SCHEDULER_HINT_COMPACT_RULE,
@@ -345,12 +349,16 @@ def test_fallback_hint_keeps_a_concrete_projected_turn(tmp_path: Path) -> None:
assert fallback["route_binding"]["turn_instance_bound"] is False
-def test_scheduler_followup_routes_preserve_turn_lineage(tmp_path: Path) -> None:
+@pytest.mark.parametrize("launcher", [(), ("-I", "-m", "loopx.entrypoint")])
+def test_scheduler_followup_routes_preserve_turn_lineage(
+ tmp_path: Path, launcher: tuple[str, ...],
+) -> None:
payload = {
"scheduler_hint": {
"app_automation": {
"ack_hint": {
"cli_args": [
+ *launcher,
"quota",
"scheduler-ack-current",
"--execute",
@@ -359,6 +367,7 @@ def test_scheduler_followup_routes_preserve_turn_lineage(tmp_path: Path) -> None
},
"failure_hint": {
"cli_args": [
+ *launcher,
"quota",
"scheduler-fail-current",
"--execute",
@@ -369,16 +378,23 @@ def test_scheduler_followup_routes_preserve_turn_lineage(tmp_path: Path) -> None
}
turn_instance_id = "turn-scheduler-followup-001"
- bind_scheduler_followup_cli_routes(
- payload,
- registry_path=tmp_path / "registry.json",
- runtime_root=tmp_path / "runtime",
- turn_instance_id=turn_instance_id,
- )
+ with loopx_cli_route(None, default_argv=[sys.executable, *launcher]):
+ bind_scheduler_followup_cli_routes(
+ payload,
+ registry_path=tmp_path / "registry.json",
+ runtime_root=tmp_path / "runtime",
+ turn_instance_id=turn_instance_id,
+ )
app_automation = payload["scheduler_hint"]["app_automation"]
for hint_name in ("ack_hint", "failure_hint"):
hint = app_automation[hint_name]
+ assert hint["cli_args"][:len(launcher) + 5] == [
+ *launcher,
+ "--registry", str((tmp_path / "registry.json").resolve()),
+ "--runtime-root", str((tmp_path / "runtime").resolve()),
+ "quota",
+ ]
assert hint["cli_args"][-3:] == [
"--turn-instance-id",
turn_instance_id,
diff --git a/tests/control_plane/test_turn_host_context_delivery.py b/tests/control_plane/test_turn_host_context_delivery.py
index 7b8435015a..c71b6a9299 100644
--- a/tests/control_plane/test_turn_host_context_delivery.py
+++ b/tests/control_plane/test_turn_host_context_delivery.py
@@ -145,11 +145,13 @@ def test_captured_context_reaches_actual_host_without_readmission(tmp_path, monk
# The current producer's own immutable capture is the transport oracle;
# the original long task and optional context remain independent inputs.
detail = actual["detail_ref"]["captured_decision"]
- assert json.loads(Path(detail["path"]).read_text()) == actual["work_contract"]
- assert actual["work_contract"] == plan["work_contract"]
- assert "Validate the complete acceptance: " + "preserve original evidence; " * 180 in json.dumps(actual["work_contract"])
+ delivered_work = json.loads(Path(detail["path"]).read_text())
+ assert delivered_work == plan["work_contract"]
+ assert actual["source_decision_hash"] == plan["source_decision_hash"]
+ assert "work_contract" not in actual
+ assert "Validate the complete acceptance: " + "preserve original evidence; " * 180 in json.dumps(delivered_work)
assert "turn_envelope" not in actual and "turn_authority" not in actual
- delivered_context = actual["work_contract"]["interaction_contract"].get("agent_context")
+ delivered_context = delivered_work["interaction_contract"].get("agent_context")
assert delivered_context == context
if context:
assert "detail_ref" not in delivered_context
@@ -234,7 +236,8 @@ def test_bound_replan_reaches_actual_host_with_original_evidence(tmp_path, monke
prompt_path = project / "received.txt"
prompt = prompt_path.read_text()
actual, _ = json.JSONDecoder().raw_decode(prompt.split("Turn request:\n", 1)[1])
- assert actual["work_contract"] == plan["work_contract"]
+ assert actual["source_decision_hash"] == plan["source_decision_hash"]
+ assert "work_contract" not in actual
# This Goal body is a pending original read, exercised below; a complete
# contract does not require every retained source to be inline.
assert "turn_envelope" not in actual and "turn_authority" not in actual
diff --git a/tests/control_plane/test_unmigrated_goal_reads.py b/tests/control_plane/test_unmigrated_goal_reads.py
index f7720c3b5f..6d4d5a52b0 100644
--- a/tests/control_plane/test_unmigrated_goal_reads.py
+++ b/tests/control_plane/test_unmigrated_goal_reads.py
@@ -11,6 +11,8 @@
from loopx.control_plane.coordination.legacy_writer_fence import (
legacy_coordination_writer_fence_path,
)
+from loopx.control_plane.testing.canary_harness import run_json_cli_result
+from canonical_authority_fixture import initialize_canonical_source_fixture, isolate_sqlite_runtime
from test_cold_source_import_cli import canonical_todos, workspace
@@ -66,6 +68,66 @@ def test_ordinary_cli_refuses_unmigrated_goal_without_importing_it(
assert not (runtime / "authority").exists()
+def test_global_todos_retains_healthy_lanes_with_a_stopped_unmigrated_goal(tmp_path, monkeypatch):
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ runtime = tmp_path / "runtime"
+ runtime.mkdir()
+ registry = runtime / "registry.global.json"
+ goals = []
+ state_by_goal = {}
+ for goal_id in ("ready", "stopped"):
+ project = tmp_path / goal_id
+ project.mkdir()
+ state = project / "ACTIVE_GOAL_STATE.md"
+ state.write_text(
+ "---\nstatus: active\nowner_mode: goal\n---\n\n"
+ "## Agent Todo\n\n- [ ] Verify the registered work.\n"
+ f" \n"
+ )
+ goal = {
+ "id": goal_id, "repo": str(project), "state_file": state.name, "status": "active",
+ "domain": "software", "adapter": {"kind": "read_only_project_map_v0", "status": "connected-read-only"},
+ "coordination": {"registered_agents": ["agent-a"]},
+ }
+ if goal_id == "stopped":
+ goal["activation"] = {
+ "schema_version": "loopx_goal_activation_v1", "state": "stopped",
+ "updated_at": "2026-01-01T00:00:00Z", "actor_kind": "owner", "reason": "Stop this fixture.",
+ }
+ else:
+ initialize_canonical_source_fixture(runtime, goal_id, state_path=state, provider="sqlite")
+ goals.append(goal)
+ state_by_goal[goal_id] = state
+ registry.write_text(json.dumps({
+ "schema_version": "0.1", "registry_role": "global-local",
+ "common_runtime_root": str(runtime), "goals": goals,
+ }))
+ original = registry.read_bytes(), state_by_goal["stopped"].read_bytes()
+
+ code, status = run_json_cli_result("status", registry_path=registry)
+ assert code == 1 and status["ok"] is False
+ assert [(e["goal_id"], e["code"]) for e in status["contract"]["error_diagnostics"]] == [
+ ("stopped", "canonical_authority_required"),
+ ]
+ assert any(row["goal_id"] == "loopx-contract" for row in status["attention_queue"]["items"])
+
+ code, observed = run_json_cli_result("global-todos", registry_path=registry)
+ assert code == 0 and observed["ok"] is True, observed
+ assert {(todo["goal_id"], todo["todo_id"]) for todo in observed["todos"]} == {("ready", "todo_ready")}
+ assert [(row["goal_id"], row["reason_code"]) for row in observed["source_warnings"]] == [
+ ("stopped", "quota_unavailable"),
+ ]
+ envelope = observed["projection_envelope"]
+ assert envelope["complete"] is False
+ assert envelope["coverage"]["expected_count"] == 2
+ assert envelope["coverage"]["included_count"] == 1
+ quota = next(row for row in envelope["sources"] if row["source_id"] == "goal_quota")
+ assert (quota["read_status"], quota["item_count"], quota["unreadable_count"]) == ("read", 1, 1)
+ assert (registry.read_bytes(), state_by_goal["stopped"].read_bytes()) == original
+ assert not legacy_coordination_writer_fence_path(runtime_root=runtime, goal_id="stopped").exists()
+
+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_explicit_import_retains_full_source_and_enables_ordinary_reads(
tmp_path, monkeypatch, provider,
diff --git a/tests/control_plane/test_unsettled_recovery_admission_bound.py b/tests/control_plane/test_unsettled_recovery_admission_bound.py
index 2f1dad56b7..e75dfefa25 100644
--- a/tests/control_plane/test_unsettled_recovery_admission_bound.py
+++ b/tests/control_plane/test_unsettled_recovery_admission_bound.py
@@ -1,4 +1,5 @@
"""Recovery admissions are bounded per original debt, never treated as spend."""
+import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Barrier
@@ -41,13 +42,20 @@ def test_unchanged_recovery_waits_then_accepts_progress_or_owner_resume(
# Repeating a committed recovery identity is not a fresh admission.
rc, replay = _run_cli(registry, runtime, *guard, "--turn-instance-id", "recovery-2")
assert rc == 0 and replay["should_run"] is True, replay
- for turn in ("wait-1", "wait-2"):
- rc, wait = _run_cli(registry, runtime, *guard, "--turn-instance-id", turn)
+ for turn, detail in (("wait-1", ()), ("wait-2", ("--include-detail", "scheduler"))):
+ rc, wait = _run_cli(registry, runtime, *guard, "--turn-instance-id", turn, *detail)
assert rc == 0 and wait["should_run"] is False, wait
assert wait["reason_code"] == "unsettled_recovery_admission_limit"
assert wait["unsettled_host_turn_recovery"]["state"] == "attention_required"
assert wait["unsettled_host_turn_recovery"]["admissions_without_progress"] == 3
- assert wait["scheduler_hint"]["action"] != "run_now"
+ hint = wait["scheduler_hint"]
+ assert hint["action"] == "backoff_waiting_for_user"
+ if detail:
+ scheduler = hint["cold_path_detail"]["local_scheduler"]
+ assert scheduler["recommended_interval_minutes"] > 0
+ assert hint["unchanged_poll"]["limits"]["local_scheduler"] == 3
+ else:
+ assert "cold_path_detail" not in hint
channel = wait["interaction_contract"]["agent_channel"]
assert channel["must_attempt"] is False and channel["delivery_allowed"] is False
assert wait["interaction_contract"]["cli_channel"]["spend_allowed_now"] is False
@@ -108,6 +116,89 @@ def test_unchanged_recovery_waits_then_accepts_progress_or_owner_resume(
assert _spend_run_count(runtime) == 0
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize("remote_binding", [False, True])
+def test_recovery_wait_keeps_observed_app_schedule_and_acknowledgement(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, provider: str, remote_binding: bool,
+) -> None:
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ project, runtime, registry = _write_fixture(tmp_path, provider=provider)
+ codex_home = tmp_path / "codex"
+ monkeypatch.setenv("CODEX_HOME", str(codex_home))
+ monkeypatch.setenv("CODEX_THREAD_ID", "recovery-thread")
+ automation = codex_home / "automations" / "recovery-heartbeat" / "automation.toml"
+ automation.parent.mkdir(parents=True)
+
+ def set_host_rrule(rrule: str) -> None:
+ automation.write_text(
+ 'version = 1\nid = "recovery-heartbeat"\nkind = "heartbeat"\n'
+ 'name = "Recovery schedule fixture"\nstatus = "ACTIVE"\n'
+ f'prompt = "Advance `{GOAL_ID}` from active state. Agent: `{AGENT_ID}`."\n'
+ f'rrule = "{rrule}"\ntarget_thread_id = "recovery-thread"\n',
+ encoding="utf-8",
+ )
+
+ def guard(turn: str, *extra: str) -> dict:
+ rc, result = _run_cli(
+ registry, runtime, "quota", "should-run", "--codex-app",
+ "--goal-id", GOAL_ID, "--agent-id", AGENT_ID,
+ "--turn-instance-id", turn, *extra, cwd=project,
+ )
+ assert rc == 0, result
+ return result
+
+ matching_rrule = "FREQ=MINUTELY;INTERVAL=30"
+ short_rrule = "FREQ=MINUTELY;INTERVAL=3"
+ set_host_rrule(matching_rrule)
+ original = guard("owed-original", "--todo-id", TODO_ID)
+ assert original["heartbeat_receipt"]["closeout_required"]
+ for index in range(3):
+ assert guard(f"recovery-{index}")["should_run"]
+
+ if remote_binding:
+ # A local recovery receipt still owns closeout after the Goal opts into
+ # the remote route. This fixture has no remote credentials or endpoint.
+ document = json.loads(registry.read_text(encoding="utf-8"))
+ goal, = (goal for goal in document["goals"] if goal["id"] == GOAL_ID)
+ goal["remote_authority"] = {"enabled": True}
+ registry.write_text(json.dumps(document), encoding="utf-8")
+
+ wait = guard("matching-wait", "--include-detail", "scheduler")
+ assert wait["should_run"] is False
+ assert wait["reason_code"] == "unsettled_recovery_admission_limit"
+ hint = wait["scheduler_hint"]
+ assert hint["cold_path_detail"]["local_scheduler"]["recommended_interval_minutes"] == 30
+ app = hint["app_automation"]
+ backoff = app["stateful_backoff"]
+ assert backoff["host_observation"]["current_rrule"] == matching_rrule
+ assert backoff["host_observation"]["status"] == "matches_recommended"
+ assert backoff["apply_needed"] is False and backoff["ack_needed"] is True
+ assert app["host_action"] == "ack_observed_rrule_without_update"
+ ack_hint = app["ack_hint"]
+ assert ack_hint["route_binding"]["turn_instance_bound"] is True
+ assert ack_hint["args"]["turn_instance_id"] == "matching-wait"
+ host_config = automation.read_bytes()
+ rc, ack = _run_cli(registry, runtime, *ack_hint["cli_args"], cwd=project)
+ assert rc == 0 and ack["scheduler_state_mutated"] is True, ack
+ assert automation.read_bytes() == host_config
+
+ replay = guard("matching-wait")
+ assert replay["heartbeat_receipt"]["event_id"] == wait["heartbeat_receipt"]["event_id"]
+ app = replay["scheduler_hint"]["app_automation"]
+ backoff = app["stateful_backoff"]
+ assert backoff["apply_needed"] is False and backoff["ack_needed"] is False
+ assert app["host_action"] == "none"
+ assert "cold_path_detail" not in replay["scheduler_hint"]
+
+ set_host_rrule(short_rrule)
+ drifted = guard("drifted-wait")["scheduler_hint"]["app_automation"]
+ assert drifted["stateful_backoff"]["host_observation"]["current_rrule"] == short_rrule
+ assert drifted["stateful_backoff"]["host_observation"]["status"] == "drift_detected"
+ assert drifted["host_action"] == "update_current_heartbeat_rrule"
+ assert drifted["recommended_rrule"] == matching_rrule
+ assert _spend_run_count(runtime) == 0
+
+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
@pytest.mark.parametrize("intermediate_guard", [False, True])
def test_owner_resume_survives_controller_lifecycle(
diff --git a/tests/control_plane_ts/quota_settlement_readback.test.ts b/tests/control_plane_ts/quota_settlement_readback.test.ts
index 47e74e0911..9a50f9f0dc 100644
--- a/tests/control_plane_ts/quota_settlement_readback.test.ts
+++ b/tests/control_plane_ts/quota_settlement_readback.test.ts
@@ -35,6 +35,11 @@ import {
preflightPriorHostTurnCloseout,
} from "../../loopx/control_plane/quota/unsettled_host_turn_recovery.ts";
import { requireJsonObject } from "../../loopx/control_plane/runtime_decode.ts";
+import {
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION,
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID,
+ AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION,
+} from "../../loopx/control_plane/work_items/replan_semantics.ts";
const goalId = "settlement-goal";
const agentId = "codex-settlement";
@@ -94,9 +99,36 @@ test("recorded review source retains its stop clause under the exact selected gu
semantic_replan_review_stop_condition: "Stop at owner-only decisions."};
assert.deepEqual(projectSemanticReplanGuard(details).selected_review_source, {
kind: details.semantic_replan_review_kind, stop_condition: details.semantic_replan_review_stop_condition});
+ const digest = createHash("sha256").update(details.semantic_replan_review_stop_condition, "utf8").digest("hex");
+ assert.deepEqual(projectSemanticReplanGuard({semantic_replan_obligation_id: details.semantic_replan_obligation_id,
+ semantic_replan_review_kind: details.semantic_replan_review_kind,
+ semantic_replan_review_stop_condition_sha256: digest}).selected_review_source, {
+ kind: details.semantic_replan_review_kind, stop_condition_sha256: digest});
+ assert.deepEqual(projectSemanticReplanGuard({...details,
+ semantic_replan_review_stop_condition_sha256: digest}).selected_review_source, {
+ kind: details.semantic_replan_review_kind,
+ stop_condition: details.semantic_replan_review_stop_condition,
+ stop_condition_sha256: digest});
+ const defaultDigest = createHash("sha256").update(
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, "utf8").digest("hex");
+ assert.deepEqual(projectSemanticReplanGuard({
+ semantic_replan_obligation_id: details.semantic_replan_obligation_id,
+ semantic_replan_review_kind: "periodic_review_due",
+ semantic_replan_review_stop_condition: AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION,
+ semantic_replan_review_stop_condition_sha256: defaultDigest,
+ semantic_replan_review_stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID,
+ }).selected_review_source, {
+ kind: "periodic_review_due",
+ stop_condition: AUTONOMOUS_REPLAN_DIGEST_COMPATIBILITY_STOP_CONDITION,
+ stop_condition_sha256: defaultDigest,
+ stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID,
+ });
for (const patch of [{semantic_replan_obligation_id: ""},
{semantic_replan_obligation_id: undefined}, {semantic_replan_review_kind: undefined},
{semantic_replan_review_stop_condition: undefined}, {semantic_replan_review_stop_condition: "s".repeat(241)},
+ {semantic_replan_review_stop_condition_sha256: "bad"},
+ {semantic_replan_review_stop_condition_sha256: "0".repeat(64)},
+ {semantic_replan_review_stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID},
{semantic_replan_capability_id: "explore"}]) {
assert.throws(() => projectSemanticReplanGuard({...details, ...patch}));
}
@@ -1967,6 +1999,44 @@ test("rejects a guard bound to another Todo", async () => {
);
});
+test("a retained Todo selects its original replan guard without rebinding it", async () => {
+ const obligation = "replan-0000000000000001";
+ const bound = settlementIdentity({
+ goal_id: goalId,
+ agent_id: agentId,
+ todo_id: null,
+ replan_obligation_id: obligation,
+ turn_instance_id: turnId,
+ });
+ const runtimeRoot = await fixture();
+ try {
+ const log = join(runtimeRoot, "goals", goalId, "rollout-event-log.jsonl");
+ const events = (await readFile(log, "utf8")).trim().split("\n")
+ .map(line => JSON.parse(line));
+ Object.assign(events[0].details, {
+ todo_id: "",
+ replan_obligation_id: obligation,
+ settlement_effect_id: bound.effect_id,
+ pending_action_selection_todo_id: todoId,
+ semantic_replan_obligation_id: obligation,
+ });
+ await writeFile(log, events.map(event => JSON.stringify(event)).join("\n") + "\n");
+
+ const result = await readQuotaSettlement(request(runtimeRoot, {
+ resolve_original_binding: true,
+ }));
+ assert.deepEqual((result.identity as any).result.value, settlementIdentityPayload(bound));
+
+ const mismatch = await readQuotaSettlement(request(runtimeRoot, {
+ todo_id: "todo_other",
+ resolve_original_binding: true,
+ }));
+ assert.equal((mismatch.identity as any).result.failure.kind, "identity_mismatch");
+ } finally {
+ await rm(runtimeRoot, {recursive: true, force: true});
+ }
+});
+
test("rejects dual Todo and replan bindings before reading settlement facts", async () => {
const runtimeRoot = await fixture({
writeback: true,
@@ -2220,6 +2290,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");
diff --git a/tests/control_plane_ts/quota_void_commit.test.ts b/tests/control_plane_ts/quota_void_commit.test.ts
index 9f1e9592ba..b70c4abc99 100644
--- a/tests/control_plane_ts/quota_void_commit.test.ts
+++ b/tests/control_plane_ts/quota_void_commit.test.ts
@@ -304,6 +304,81 @@ test("target lookup falls back to the bounded legacy JSON artifact", async (t) =
assert.equal((event.after as Record).spent_slots, 1);
});
+test("void does not use another debit's artifact even at the same timestamp", async (t) => {
+ const fixture = await targetFixture(t, { inline: false, slots: 4 });
+ const record = JSON.parse(await readFile(fixture.targetJsonPath, "utf8"));
+ const commit = { schema_version: "quota_spend_commit_receipt_v0", effect_id: "original-debit",
+ request_digest: `sha256:${"a".repeat(64)}` };
+ const index = JSON.parse(fixture.indexContent);
+ const otherDebit = `${JSON.stringify({ ...record,
+ quota_spend_commit: { ...commit, effect_id: "another-debit" } })}\n`;
+ assert.equal(index.generated_at, record.generated_at);
+ await writeFile(fixture.targetJsonPath, otherDebit, "utf8");
+
+ for (const inline of [false, true]) {
+ const retainedIndex = `${JSON.stringify({ ...index, quota_spend_commit: commit,
+ ...(inline ? { quota_event: record.quota_event } : {}) })}\n`;
+ await writeFile(fixture.indexPath, retainedIndex, "utf8");
+ await assert.rejects(
+ async () => evaluateQuotaVoidCommit(await request(fixture, { execute: false })),
+ /quota spend JSON artifact identity does not match its index row/,
+ );
+ assert.equal(await readFile(fixture.indexPath, "utf8"), retainedIndex);
+ }
+ assert.equal(await readFile(fixture.targetJsonPath, "utf8"), otherDebit);
+});
+
+test("legacy debit bindings must agree in the index, artifact and event", async (t) => {
+ const fixture = await targetFixture(t, { inline: false });
+ const record = JSON.parse(await readFile(fixture.targetJsonPath, "utf8"));
+ const index = JSON.parse(fixture.indexContent);
+ // Each identity was persisted by the legacy writer independently of its
+ // timestamp. Exercise both artifact locations through the actual void path.
+ const bindings = {
+ agent_id: ["agent-a", "agent-b"],
+ effect_ref: ["debit-a", "debit-b"],
+ turn_instance_id: ["turn-a", "turn-b"],
+ todo_id: ["todo-a", "todo-b"],
+ replan_obligation_id: ["replan-a", "replan-b"],
+ settlement_identity: [{ effect_id: "turn-a" }, { effect_id: "turn-b" }],
+ };
+ for (const [field, [original, other]] of Object.entries(bindings)) {
+ for (const nested of [false, true]) {
+ const retainedIndex = `${JSON.stringify({ ...index, [field]: original })}\n`;
+ await writeFile(fixture.indexPath, retainedIndex);
+ const conflict = nested
+ ? { ...record, quota_event: { ...record.quota_event, [field]: other } }
+ : { ...record, [field]: other };
+ const artifact = `${JSON.stringify(conflict)}\n`;
+ await writeFile(fixture.targetJsonPath, artifact);
+ await assert.rejects(
+ async () => evaluateQuotaVoidCommit(await request(fixture, { execute: false })),
+ /quota spend JSON artifact identity does not match its index row/,
+ );
+ assert.equal(await readFile(fixture.indexPath, "utf8"), retainedIndex);
+ assert.equal(await readFile(fixture.targetJsonPath, "utf8"), artifact);
+ if (nested) {
+ const inlineIndex = JSON.stringify({ ...index, [field]: original,
+ quota_event: conflict.quota_event });
+ await writeFile(fixture.indexPath, inlineIndex);
+ await assert.rejects(
+ async () => evaluateQuotaVoidCommit(await request(fixture, { execute: false })),
+ /quota spend JSON artifact identity does not match its index row/,
+ );
+ assert.equal(await readFile(fixture.indexPath, "utf8"), inlineIndex);
+ await writeFile(fixture.indexPath, retainedIndex);
+ }
+ }
+ // Omitted or empty historical identity fields remain compatible. An
+ // explicit conflict is stronger evidence than a matching timestamp.
+ for (const absent of [undefined, null, ""]) {
+ await writeFile(fixture.targetJsonPath, JSON.stringify({ ...record, [field]: absent }));
+ const result = await evaluateQuotaVoidCommit(await request(fixture, { execute: false }));
+ assert.equal(result.status, "preview");
+ }
+ }
+});
+
test("legacy index rows without goal identity use the requested goal", async (t) => {
const fixture = await targetFixture(t, { inline: false });
const indexRecord = JSON.parse(fixture.indexContent) as Record;
diff --git a/tests/control_plane_ts/remote_authority.integration.test.ts b/tests/control_plane_ts/remote_authority.integration.test.ts
index 23c1cf5205..96436bc47c 100644
--- a/tests/control_plane_ts/remote_authority.integration.test.ts
+++ b/tests/control_plane_ts/remote_authority.integration.test.ts
@@ -21,10 +21,12 @@ import {authorityProjectionFixture} from "./authority_projection_fixture.ts";
import {resolveTestPython} from "../../scripts/test-python.mjs";
import {registerRemoteAuthorityModeConformance} from "./remote_authority_mode_conformance.ts";
import {registerRemoteAuthorityLifecycleConformance} from "./remote_authority_lifecycle_conformance.ts";
+import {registerRemoteAuthorityReadAclConformance} from "./remote_authority_read_acl_conformance.ts";
const connectionString = process.env.LOOPX_TEST_POSTGRES_URL;
registerRemoteAuthorityModeConformance(connectionString);
registerRemoteAuthorityLifecycleConformance(connectionString);
+registerRemoteAuthorityReadAclConformance(connectionString);
test("quota CLI verifies the exact remote binding and never grants local execution", {skip: !connectionString}, async t => {
const fixture = await postgresRemoteFixture(t, connectionString!);
await fixture.seed(["todo_gateway_probe"], {todo_gateway_probe: "private-synthetic-note"});
diff --git a/tests/control_plane_ts/remote_authority.test.ts b/tests/control_plane_ts/remote_authority.test.ts
index e65dae3eb3..0c4d8012d7 100644
--- a/tests/control_plane_ts/remote_authority.test.ts
+++ b/tests/control_plane_ts/remote_authority.test.ts
@@ -9,7 +9,7 @@ import {tmpdir} from "node:os";
import {join} from "node:path";
import type {JsonObject} from "../../loopx/control_plane/effect_program.ts";
import {decodeRemoteAuthorityRequest, decodeRemoteAuthorityResponse, remoteAuthorityOperationId,
- remoteAuthorityResponse} from "../../loopx/control_plane/coordination/remote_authority_contract.ts";
+ remoteAuthorityResponse, remoteAuthoritySnapshotDigest, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE} from "../../loopx/control_plane/coordination/remote_authority_contract.ts";
import {canonicalAuthoritySha256} from "../../loopx/control_plane/coordination/authority_store_codec.ts";
import {decodeRemoteAuthorityPolicy, remoteAuthorityPolicyAdmission, readRemoteAuthorityPolicy} from "../../loopx/control_plane/coordination/remote_authority_policy.ts";
import {RemoteAuthorityService} from "../../loopx/control_plane/coordination/remote_authority_service.ts";
@@ -76,6 +76,66 @@ test("missing-lease release responses require explicit no-op evidence", () => {
}
});
+test("scoped read responses require their Goal reference and exclude global authority metadata", () => {
+ const {request_id: _, ...scope} = claimRequest("a");
+ const request = decodeRemoteAuthorityRequest({...scope, operation: "read"});
+ const goal_ref = {goal_id: request.goal_id, goal_instance_id: "ginst_" + "a".repeat(32)};
+ const payload = {status: "found", goal_ref, todo: {todo_id: request.todo_id, status: "open"}, lease: null};
+ const wrap = (value: JsonObject) => remoteAuthorityResponse(request, "execute", value, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE);
+ assert.deepEqual(decodeRemoteAuthorityResponse(wrap(payload), request, "execute"), wrap(payload));
+ for (const invalid of [
+ {...payload, goal_ref: {goal_id: request.goal_id}},
+ {...payload, goal_ref: {...goal_ref, goal_id: "other-goal"}},
+ {...payload, provider_revision: `${request.store_identity}:2`},
+ {...payload, cursor: "2"},
+ ]) assert.throws(() => decodeRemoteAuthorityResponse(wrap(invalid), request, "execute"));
+});
+
+test("scoped response nested records reject fields outside their read projection", () => {
+ const {request_id: _, ...scope} = claimRequest("a");
+ const goal_ref = {goal_id: scope.goal_id, goal_instance_id: "ginst_" + "a".repeat(32)};
+ const todo = {todo_id: scope.todo_id, status: "open", claimed_by: "actor-a"};
+ const lease = {owner: "actor-a", status: "active", expires_at: "2099-01-01T00:00:00Z", version: 1, lease_epoch: 1};
+ const read = decodeRemoteAuthorityRequest({...scope, operation: "read"});
+ const snapshot = decodeRemoteAuthorityRequest({...scope, operation: "snapshot"});
+ const wrap = (request: typeof read, payload: JsonObject) => remoteAuthorityResponse(request, "execute",
+ {...payload, goal_ref}, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE);
+ const found = (row: JsonObject, held: JsonObject) => wrap(read, {status: "found", todo: row, lease: held});
+ const snap = (row: JsonObject, held: JsonObject) => wrap(snapshot, {status: "snapshot", goal_id: scope.goal_id,
+ store_identity: scope.store_identity, todos: [row], leases: [held],
+ receipt_sha256: remoteAuthoritySnapshotDigest(snapshot, undefined, [row], [held], goal_ref)});
+ const snapshotTodo = {...todo, role: "agent", priority: "P1"};
+ const snapshotLease = {...lease, goal_id: scope.goal_id, todo_id: scope.todo_id};
+ assert.deepEqual(decodeRemoteAuthorityResponse(found(todo, lease), read, "execute"), found(todo, lease));
+ assert.deepEqual(decodeRemoteAuthorityResponse(snap(snapshotTodo, snapshotLease), snapshot, "execute"), snap(snapshotTodo, snapshotLease));
+ for (const field of ["note", "note_omitted", "text", "idempotency_key", "provider_revision", "cursor", "unknown"]) {
+ const value = field === "note_omitted" ? true : "must-not-cross-the-read-boundary";
+ assert.throws(() => decodeRemoteAuthorityResponse(found({...todo, [field]: value}, lease), read, "execute"), `read Todo ${field}`);
+ assert.throws(() => decodeRemoteAuthorityResponse(found(todo, {...lease, [field]: value}), read, "execute"), `read lease ${field}`);
+ // A matching digest cannot authorize extra fields in a scoped snapshot.
+ assert.throws(() => decodeRemoteAuthorityResponse(snap({...snapshotTodo, [field]: value}, snapshotLease), snapshot, "execute"), `snapshot Todo ${field}`);
+ assert.throws(() => decodeRemoteAuthorityResponse(snap(snapshotTodo, {...snapshotLease, [field]: value}), snapshot, "execute"), `snapshot lease ${field}`);
+ }
+ const trusted = remoteAuthorityResponse(read, "execute", {status: "found", provider_revision: `${scope.store_identity}:3`,
+ todo: {...todo, note: "trusted v0 note"}, lease: {...lease, idempotency_key: "trusted-v0-key"}});
+ assert.deepEqual(decodeRemoteAuthorityResponse(trusted, read, "execute"), trusted);
+});
+
+test("scoped historical receipt responses expose proof for the original Todo without its execution payload", () => {
+ const request = claimRequest("a");
+ const goal_ref = {goal_id: request.goal_id, goal_instance_id: "ginst_" + "a".repeat(32)};
+ const payload = {status: "found", historical_only: true, goal_ref, todo_id: request.todo_id,
+ operation_id: remoteAuthorityOperationId(request, "principal-a"), receipt_sha256: "d".repeat(64)};
+ const wrap = (value: JsonObject) => remoteAuthorityResponse(request, "recover", value, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE);
+ assert.deepEqual(decodeRemoteAuthorityResponse(wrap(payload), request, "recover"), wrap(payload));
+ for (const invalid of [
+ {...payload, todo_id: "todo_other"},
+ {...payload, historical_only: false},
+ {...payload, result: {lease: {idempotency_key: "out-of-scope"}}},
+ {...payload, cursor: "2"},
+ ]) assert.throws(() => decodeRemoteAuthorityResponse(wrap(invalid), request, "recover"));
+});
+
test("invalid policy cannot silently broaden or retain grants", async t => {
for (const mutate of [(p: ReturnType) => p.principals.push(p.principals[0]),
(p: ReturnType) => p.scopes.push(p.scopes[0]),
diff --git a/tests/control_plane_ts/remote_authority_fixture.ts b/tests/control_plane_ts/remote_authority_fixture.ts
index 93125f5136..892ebbf116 100644
--- a/tests/control_plane_ts/remote_authority_fixture.ts
+++ b/tests/control_plane_ts/remote_authority_fixture.ts
@@ -88,6 +88,7 @@ export async function postgresRemoteFixture(t: TestContext, connectionString: st
await setup.query(`GRANT CONNECT ON DATABASE ${name} TO ${role}`);
await setup.query(`GRANT USAGE ON SCHEMA loopx_control_plane TO ${role}`);
await setup.query(`GRANT SELECT ON loopx_control_plane.authority_store_metadata TO ${role}`);
+ await setup.query(`GRANT SELECT ON loopx_control_plane.authority_checkpoints TO ${role}`);
await setup.query(`GRANT SELECT, INSERT, UPDATE ON loopx_control_plane.authority_heads TO ${role}`);
await setup.query(`GRANT SELECT, INSERT ON loopx_control_plane.authority_commits,
loopx_control_plane.authority_events, loopx_control_plane.authority_receipts TO ${role}`);
@@ -102,7 +103,7 @@ export async function postgresRemoteFixture(t: TestContext, connectionString: st
});
}
const policyPath = join(tls.root, "policy.json");
- async function writePolicy(policy = servicePolicy()) {
+ async function writePolicy(policy: unknown = servicePolicy()) {
await writeFile(`${policyPath}.next`, JSON.stringify(policy), {mode: 0o600});
await rename(`${policyPath}.next`, policyPath);
}
diff --git a/tests/control_plane_ts/remote_authority_read_acl_conformance.ts b/tests/control_plane_ts/remote_authority_read_acl_conformance.ts
new file mode 100644
index 0000000000..fe4260876e
--- /dev/null
+++ b/tests/control_plane_ts/remote_authority_read_acl_conformance.ts
@@ -0,0 +1,277 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {createServer} from "node:https";
+import type {AddressInfo} from "node:net";
+import type {JsonObject} from "../../loopx/control_plane/effect_program.ts";
+import {transitionGoalAcceptanceLifecycle} from "../../loopx/control_plane/goals/acceptance_authority.ts";
+import type {GoalAcceptanceLifecycleTransition} from "../../loopx/control_plane/goals/acceptance_lifecycle.ts";
+import {prepareCoordinationProjectionCommit} from "../../loopx/control_plane/coordination/coordination_projection.ts";
+import {TODO_DOMAIN_ITEM_SCHEMA} from "../../loopx/control_plane/coordination/coordination_state_contract.ts";
+import {executeCoordinationTodoCreate} from "../../loopx/control_plane/coordination/todo_create.ts";
+import {REMOTE_AUTHORITY_REQUEST, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE,
+ remoteAuthorityOperationId, remoteAuthoritySnapshotDigest} from "../../loopx/control_plane/coordination/remote_authority_contract.ts";
+import {REMOTE_AUTHORITY_SCOPED_READ_POLICY} from "../../loopx/control_plane/coordination/remote_authority_policy.ts";
+import {claimRequest, postgresRemoteFixture, serviceIdentity, servicePolicy} from "./remote_authority_fixture.ts";
+
+export function registerRemoteAuthorityReadAclConformance(connectionString: string | undefined) {
+ test("remote read ACL pins the Goal lifetime and projects only the caller's resources", {skip: !connectionString}, async t => {
+ const fixture = await postgresRemoteFixture(t, connectionString!);
+ const goal_id = "goal-one";
+ const a = {goal_id, goal_instance_id: "ginst_" + "a".repeat(32)};
+ const b = {goal_id, goal_instance_id: "ginst_" + "b".repeat(32)};
+ const {scopes, principals} = servicePolicy();
+ const policy = {schema_version: REMOTE_AUTHORITY_SCOPED_READ_POLICY,
+ scopes: scopes.map(scope => ({...scope, todo_read_acl: [
+ {goal_ref: a, todo_id: "todo_visible", principal_id: "principal-a", actor_id: "actor-a",
+ todo_origin_operation_id: "bind-first-goal"},
+ {goal_ref: b, todo_id: "todo_next", principal_id: "principal-b", actor_id: "actor-b",
+ todo_origin_operation_id: "create-successor-todo"},
+ // A new grant must not relabel retained predecessor resources.
+ {goal_ref: b, todo_id: "todo_visible", principal_id: "principal-b", actor_id: "actor-b",
+ todo_origin_operation_id: "bind-first-goal"},
+ ]})),
+ principals: principals.map((principal, index) => ({...principal, grants: principal.grants.map(grant => ({
+ ...grant, goal_ref: index === 0 ? a : b, operations: ["read", "snapshot"],
+ }))})),
+ };
+ await fixture.seed(["todo_visible", "todo_hidden"], {todo_visible: "unqualified source text", todo_hidden: "private hidden note"});
+ const legacy = await fixture.start();
+ const originalClaim = claimRequest("a", "todo_visible");
+ assert.equal((await fixture.client(legacy.endpoint, "a", originalClaim)).code, 0);
+ assert.equal((await fixture.client(legacy.endpoint, "b", claimRequest("b", "todo_hidden"))).code, 0);
+ await legacy.stop();
+ await fixture.writePolicy(policy);
+ const service = await fixture.start();
+ const scope = (actor: "a" | "b") => ({schema_version: REMOTE_AUTHORITY_REQUEST, goal_id,
+ tenant_id: "tenant-one", actor_id: `actor-${actor}`, store_identity: serviceIdentity} as const);
+ const snapshot = (actor: "a" | "b", todo_id?: string) =>
+ fixture.client(service.endpoint, actor, {...scope(actor), operation: "snapshot", ...(todo_id ? {todo_id} : {})});
+ const read = (actor: "a" | "b", todo_id: string) =>
+ fixture.client(service.endpoint, actor, {...scope(actor), operation: "read", todo_id});
+ function denied(response: Awaited>) {
+ assert.equal(response.code, 1);
+ assert.equal(response.value.status, "rejected");
+ assert.equal(response.value.reason_code, "remote_authority_scope_denied");
+ assert.deepEqual(Object.keys(response.value).sort(), ["reason_code", "request_sha256", "schema_version", "status"]);
+ }
+ async function transition(operation_id: string, step: GoalAcceptanceLifecycleTransition, expected = "applied") {
+ const result = await transitionGoalAcceptanceLifecycle(fixture.store, {
+ goal_id, actor_agent_id: null, operation_id, transition: step,
+ });
+ assert.equal(result.status, expected);
+ }
+
+ const unbound = await fixture.store.loadAuthority();
+ denied(await read("a", "todo_visible"));
+ denied(await snapshot("a"));
+ assert.deepEqual(await fixture.store.loadAuthority(), unbound);
+ await transition("bind-first-goal", {kind: "bind_existing", goal_ref: a});
+ const head = await fixture.store.loadAuthority();
+ assert.equal(head.status, "loaded");
+ if (head.status !== "loaded") throw new Error("Missing fixture head");
+
+ const visible = await read("a", "todo_visible");
+ assert.equal(visible.code, 0);
+ assert.equal(visible.value.schema_version, REMOTE_AUTHORITY_SCOPED_READ_RESPONSE);
+ assert.deepEqual(visible.value.goal_ref, a);
+ assert.deepEqual(visible.value.todo, {todo_id: "todo_visible", status: "open", claimed_by: "actor-a"});
+ assert.equal((visible.value.lease as JsonObject).owner, "actor-a");
+ assert(!("idempotency_key" in (visible.value.lease as JsonObject)));
+ const first = await snapshot("a");
+ assert.equal(first.code, 0);
+ assert.deepEqual(first.value.goal_ref, a);
+ for (const field of ["todos", "leases"]) {
+ assert.deepEqual((first.value[field] as JsonObject[]).map(row => row.todo_id), ["todo_visible"]);
+ }
+ assert(!Object.hasOwn(first.value, "provider_revision"));
+ assert(!JSON.stringify(first.value).includes("unqualified source text"));
+ await t.test("TLS CLI rejects nested disclosure even with correlation and a recomputed snapshot digest", async () => {
+ let reply: JsonObject = visible.value;
+ const proxy = createServer({key: fixture.key, cert: fixture.cert}, (incoming, outgoing) => {
+ incoming.resume(); outgoing.setHeader("Content-Type", "application/json"); outgoing.end(JSON.stringify(reply));
+ });
+ await new Promise(resolve => proxy.listen(0, "127.0.0.1", resolve));
+ try {
+ const endpoint = `https://127.0.0.1:${(proxy.address() as AddressInfo).port}`;
+ const request = {...scope("a"), operation: "read" as const, todo_id: "todo_visible"};
+ assert.equal((await fixture.client(endpoint, "a", request)).code, 0);
+ for (const [record, field] of [["todo", "note"], ["lease", "idempotency_key"]]) {
+ reply = {...visible.value, [record!]: {...visible.value[record!] as JsonObject, [field!]: "private-response-marker"}};
+ const rejected = await fixture.client(endpoint, "a", request);
+ assert.equal(rejected.code, 1); assert.equal(rejected.value.status, "unavailable");
+ assert(!JSON.stringify(rejected.value).includes("private-response-marker"));
+ }
+ const snapshotRequest = {...scope("a"), operation: "snapshot" as const};
+ for (const [collection, field] of [["todos", "note"], ["leases", "idempotency_key"]]) {
+ reply = structuredClone(first.value);
+ (reply[collection!] as JsonObject[])[0]![field!] = "private-response-marker";
+ reply.receipt_sha256 = remoteAuthoritySnapshotDigest(snapshotRequest, undefined,
+ reply.todos as JsonObject[], reply.leases as JsonObject[], a);
+ const rejected = await fixture.client(endpoint, "a", snapshotRequest);
+ assert.equal(rejected.code, 1); assert.equal(rejected.value.status, "unavailable");
+ assert(!JSON.stringify(rejected.value).includes("private-response-marker"));
+ }
+ reply = first.value;
+ assert.equal((await fixture.client(endpoint, "a", snapshotRequest)).code, 0);
+ } finally { await new Promise(resolve => proxy.close(() => resolve())); }
+ });
+ for (const origin of [undefined, "missing-origin-operation", remoteAuthorityOperationId(originalClaim, "principal-a")]) {
+ await fixture.writePolicy({...policy, scopes: policy.scopes.map(s => ({...s,
+ todo_read_acl: s.todo_read_acl.map(entry => ({...entry, todo_origin_operation_id: origin}))}))});
+ denied(await read("a", "todo_visible"));
+ denied(await snapshot("a"));
+ }
+ await fixture.writePolicy(policy);
+ denied(await read("a", "todo_hidden"));
+ denied(await read("a", "todo_missing"));
+ denied(await snapshot("a", "todo_hidden"));
+ denied(await snapshot("b"));
+ denied(await fixture.client(service.endpoint, "a", {...scope("b"), operation: "snapshot"}));
+ denied(await fixture.client(service.endpoint, "a", originalClaim));
+ denied(await fixture.client(service.endpoint, "a", originalClaim, true));
+ assert.deepEqual(await fixture.store.loadAuthority(), head);
+
+ const hidden = (head.head.todos as JsonObject[]).find(todo => todo.todo_id === "todo_hidden")!;
+ assert.equal((await fixture.store.commitAuthority(prepareCoordinationProjectionCommit({
+ goal_id, projection: head.head, expected_provider_revision: head.provider_revision, operation_id: "change-hidden-todo",
+ mutations: [{kind: "todo_upsert", todo: {...hidden, note: "different private hidden note"}}],
+ }))).status, "applied");
+ assert.deepEqual((await snapshot("a")).value, first.value);
+
+ await fixture.writePolicy({...policy, scopes: policy.scopes.map(s => ({...s,
+ todo_read_acl: s.todo_read_acl.filter(entry => entry.principal_id !== "principal-a")}))});
+ denied(await snapshot("a"));
+ await fixture.writePolicy(servicePolicy());
+ const downgrade = await snapshot("a");
+ assert.equal(downgrade.value.status, "unavailable");
+ assert.equal(downgrade.value.reason_code, "remote_authority_policy_unavailable");
+ await fixture.writePolicy(policy);
+ assert.deepEqual((await snapshot("a")).value, first.value);
+
+ await transition("retire-first-goal", {kind: "retire", goal_ref: a});
+ denied(await snapshot("a"));
+ await transition("activate-second-goal", {kind: "activate_successor", retired_goal_ref: a, goal_ref: b});
+ const added = await executeCoordinationTodoCreate(fixture.store, {
+ goal_id, actor_agent_id: "actor-b", registered_agents: ["actor-a", "actor-b"],
+ operation_id: "create-successor-todo", dry_run: false, now: new Date(),
+ todo: {schema_version: TODO_DOMAIN_ITEM_SCHEMA, todo_id: "todo_next", role: "agent",
+ status: "open", done: false, archive_state: "active", text: "Second lifetime task"},
+ });
+ assert.equal(added.status, "applied");
+ const successor = await fixture.store.loadAuthority();
+ denied(await snapshot("a"));
+ denied(await read("a", "todo_visible"));
+ denied(await read("a", "todo_next"));
+ denied(await read("b", "todo_visible"));
+ const second = await snapshot("b");
+ assert.equal(second.code, 0);
+ assert.deepEqual(second.value.goal_ref, b);
+ assert.deepEqual((second.value.todos as JsonObject[]).map(todo => todo.todo_id), ["todo_next"]);
+ assert.deepEqual(second.value.leases, []);
+ assert.equal((await read("b", "todo_next")).code, 0);
+ assert.deepEqual(await fixture.store.loadAuthority(), successor);
+ await transition("bind-current-again", {kind: "bind_existing", goal_ref: b}, "no_change");
+ for (const origin of ["activate-second-goal", "bind-current-again", "create-successor-todo"]) {
+ await fixture.writePolicy({...policy, scopes: policy.scopes.map(s => ({...s,
+ todo_read_acl: s.todo_read_acl.map(entry => entry.goal_ref === b && entry.todo_id === "todo_visible"
+ ? {...entry, todo_origin_operation_id: origin} : entry)}))});
+ denied(await read("b", "todo_visible"));
+ assert.deepEqual(((await snapshot("b")).value.todos as JsonObject[]).map(todo => todo.todo_id), ["todo_next"]);
+ }
+ });
+
+ test("scoped receipt recovery proves the original Goal lifetime and current exact operation access", {skip: !connectionString}, async t => {
+ const fixture = await postgresRemoteFixture(t, connectionString!);
+ const goal_id = "goal-one";
+ const a = {goal_id, goal_instance_id: "ginst_" + "a".repeat(32)};
+ const b = {goal_id, goal_instance_id: "ginst_" + "b".repeat(32)};
+ const unboundClaim = claimRequest("a", "todo_legacy");
+ const boundClaim = claimRequest("a", "todo_bound");
+ const missingClaim = claimRequest("a", "todo_bound", "never-committed");
+ const id = (request: typeof boundClaim) => remoteAuthorityOperationId(request, "principal-a");
+ async function transition(operation_id: string, step: GoalAcceptanceLifecycleTransition) {
+ const result = await transitionGoalAcceptanceLifecycle(fixture.store, {goal_id, actor_agent_id: null,
+ operation_id, transition: step});
+ assert.equal(result.status, "applied");
+ }
+
+ await fixture.seed(["todo_legacy", "todo_bound", "todo_hidden"]);
+ const legacy = await fixture.start();
+ assert.equal((await fixture.client(legacy.endpoint, "a", unboundClaim)).code, 0);
+ await transition("bind-receipt-goal", {kind: "bind_existing", goal_ref: a});
+ assert.equal((await fixture.client(legacy.endpoint, "a", boundClaim)).code, 0);
+ const original = await fixture.client(legacy.endpoint, "a", boundClaim, true);
+ assert.equal(original.code, 0);
+ assert("cursor" in original.value);
+ assert("lease" in (original.value.result as JsonObject));
+ await legacy.stop();
+
+ // Read an earlier receipt after the authority has crossed a checkpoint.
+ // This uses the normal journal and keeps the original receipt intact.
+ for (let sequence = 0; sequence < 64; sequence++) {
+ const head = await fixture.store.loadAuthority();
+ if (head.status !== "loaded") throw new Error("Missing fixture head");
+ const hidden = (head.head.todos as JsonObject[]).find(todo => todo.todo_id === "todo_hidden")!;
+ const result = await fixture.store.commitAuthority(prepareCoordinationProjectionCommit({
+ goal_id, projection: head.head, expected_provider_revision: head.provider_revision,
+ operation_id: `append-receipt-fixture-${sequence}`,
+ mutations: [{kind: "todo_upsert", todo: {...hidden, note: `Hidden fixture update ${sequence}`}}],
+ }));
+ assert.equal(result.status, "applied");
+ }
+ function policy(goalRef: typeof a, allowed: readonly string[], operations = ["read", "snapshot"]) {
+ const {scopes, principals} = servicePolicy();
+ return {schema_version: REMOTE_AUTHORITY_SCOPED_READ_POLICY,
+ scopes: scopes.map(scope => ({...scope, todo_read_acl: [
+ {goal_ref: goalRef, todo_id: "todo_bound", principal_id: "principal-a", actor_id: "actor-a",
+ todo_origin_operation_id: "bind-receipt-goal", receipt_operation_ids: allowed},
+ {goal_ref: goalRef, todo_id: "todo_legacy", principal_id: "principal-a", actor_id: "actor-a",
+ receipt_operation_ids: [id(unboundClaim), id(boundClaim)]},
+ ]})),
+ principals: principals.slice(0, 1).map(principal => ({...principal, grants: principal.grants.map(grant =>
+ ({...grant, goal_ref: goalRef, operations}))})),
+ };
+ }
+ await fixture.writePolicy(policy(a, [id(boundClaim), id(missingClaim)]));
+ const service = await fixture.start();
+ const recover = (request: typeof boundClaim) => fixture.client(service.endpoint, "a", request, true);
+ function denied(result: Awaited>) {
+ assert.equal(result.code, 1);
+ assert.equal(result.value.status, "rejected");
+ assert.equal(result.value.reason_code, "remote_authority_scope_denied");
+ assert.deepEqual(Object.keys(result.value).sort(), ["reason_code", "request_sha256", "schema_version", "status"]);
+ }
+ const current = await fixture.store.loadAuthority();
+ const allowed = await recover(boundClaim);
+ assert.equal(allowed.code, 0);
+ assert.deepEqual(allowed.value, {
+ schema_version: REMOTE_AUTHORITY_SCOPED_READ_RESPONSE, status: "found", historical_only: true,
+ todo_id: boundClaim.todo_id, goal_ref: a, operation_id: original.value.operation_id,
+ receipt_sha256: original.value.receipt_sha256, request_sha256: original.value.request_sha256,
+ });
+ denied(await recover(unboundClaim));
+ denied(await recover(missingClaim));
+ denied(await recover({...boundClaim, todo_id: unboundClaim.todo_id}));
+ denied(await fixture.client(service.endpoint, "a", boundClaim)); // Execute stays outside the read grant.
+ await fixture.writePolicy(policy(a, []));
+ denied(await recover(boundClaim));
+ const currentTodo = await fixture.client(service.endpoint, "a", {
+ operation: "read", schema_version: REMOTE_AUTHORITY_REQUEST, tenant_id: boundClaim.tenant_id,
+ goal_id, actor_id: boundClaim.actor_id, store_identity: serviceIdentity, todo_id: boundClaim.todo_id,
+ });
+ assert.equal(currentTodo.code, 0);
+ await fixture.writePolicy(policy(a, [id(boundClaim)], ["snapshot"]));
+ denied(await recover(boundClaim));
+ assert.deepEqual(await fixture.store.loadAuthority(), current);
+
+ await fixture.writePolicy(policy(a, [id(boundClaim)]));
+ await transition("retire-receipt-goal", {kind: "retire", goal_ref: a});
+ denied(await recover(boundClaim));
+ await transition("activate-next-receipt-goal", {kind: "activate_successor", retired_goal_ref: a, goal_ref: b});
+ const successor = await fixture.store.loadAuthority();
+ denied(await recover(boundClaim)); // Stale credential.
+ await fixture.writePolicy(policy(b, [id(boundClaim)]));
+ denied(await recover(boundClaim)); // Current ACL cannot reassign a receipt from A to B.
+ assert.deepEqual(await fixture.store.loadAuthority(), successor);
+ });
+}
diff --git a/tests/control_plane_ts/replan_semantics.test.ts b/tests/control_plane_ts/replan_semantics.test.ts
index 274fa81016..47d5960f41 100644
--- a/tests/control_plane_ts/replan_semantics.test.ts
+++ b/tests/control_plane_ts/replan_semantics.test.ts
@@ -1,6 +1,12 @@
import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
import test from "node:test";
-import { projectReplanSemantics, requiredSemanticOutcomes } from "../../loopx/control_plane/work_items/replan_semantics.ts";
+import {
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION,
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID,
+ projectReplanSemantics,
+ requiredSemanticOutcomes,
+} from "../../loopx/control_plane/work_items/replan_semantics.ts";
test("capability evidence is not a default exit or a generic progress claim", () => {
for (const outcome of ["capability_evidence_observed", "capability_duty_retired"]) {
@@ -175,7 +181,7 @@ test("an open Vision reconstruction must come from the exact scoped receipt sour
}
});
-test("only plain vision and outcome reviews have a scalar receipt source", () => {
+test("scalar and digest review sources exclude evidence windows and restricted duties", () => {
const source = {schema_version: "autonomous_replan_obligation_v0", required: true,
obligation_id: "replan-1111111111111111", agent_id: "reviewer", trigger_count: 1,
stop_condition: "Stop at owner-only decisions.",
@@ -184,9 +190,11 @@ test("only plain vision and outcome reviews have a scalar receipt source", () =>
const request = {operation: "receipt_review_source", agent_id: "reviewer", obligation: source};
assert.deepEqual(projectReplanSemantics(request), {review_source: {
kind: "goal_outcome_uncovered", stop_condition: source.stop_condition}});
+ assert.deepEqual(projectReplanSemantics({...request, obligation: {...source,
+ stop_condition: "s".repeat(241), triggers: [{kind: "periodic_review_due"}]}}), {review_source: {
+ kind: "periodic_review_due", stop_condition: "s".repeat(241)}});
for (const patch of [{required: false}, {schema_version: "unknown"}, {agent_id: "another-agent"},
{triggers: []}, {trigger_count: 2}, {trigger_count: undefined},
- {triggers: [{kind: "periodic_review_due"}]},
{triggers: [{kind: "goal_outcome_uncovered"}, {kind: "external_progress_review_drift"}]},
{trigger_count: 2, triggers: [{kind: "vision_acceptance_gap"}, {kind: "periodic_review_due"}]},
{trigger_count: 2, triggers: [{kind: "vision_acceptance_gap"}, {kind: "external_progress_review_drift"}]},
@@ -195,13 +203,66 @@ test("only plain vision and outcome reviews have a scalar receipt source", () =>
{progress_baseline: {}}, {progress_window: []},
{triggers: [{kind: "goal_outcome_uncovered", progress_baseline: {}}]},
{triggers: [{kind: "goal_outcome_uncovered", progress_window: []}]},
- {stop_condition: null}, {stop_condition: "s".repeat(241)},
+ {stop_condition: null},
{resolution_mode: "todo_lifecycle_settlement"},
{capability_guard: {schema_version: "semantic_replan_capability_guard_v0"}}]) {
assert.deepEqual(projectReplanSemantics({...request, obligation: {...source, ...patch}}), {review_source: null});
}
});
+test("a digest-bound review keeps its receipt id across equivalent frontier regeneration", () => {
+ const originalId = "replan-1111111111111111";
+ const currentId = "replan-2222222222222222";
+ const stop = "Review current acceptance evidence before changing the route. ".repeat(6).trim();
+ const digest = createHash("sha256").update(stop, "utf8").digest("hex");
+ const current = {schema_version: "autonomous_replan_obligation_v0", required: true,
+ obligation_id: currentId, agent_id: "reviewer", trigger_count: 1,
+ triggers: [{kind: "periodic_review_due"}], stop_condition: stop,
+ replan_context: {context_id: "latest-review-context"}};
+ const request = {operation: "receipt_bound_obligation", guard_scoped: true,
+ replay_phase: "open", selected_obligation_id: originalId, agent_id: "reviewer",
+ current_obligation: current, transition_candidates: [], receipt_review: {
+ kind: "periodic_review_due", stop_condition_sha256: digest}};
+ const recovered = projectReplanSemantics(request).obligation as JsonObject;
+ assert.equal(recovered.obligation_id, originalId);
+ assert.equal(recovered.stop_condition, stop);
+ assert.equal(recovered.replan_context, undefined,
+ "the caller must rebuild current context under the retained settlement id");
+ assert.equal(recovered.selection_binding, "heartbeat_receipt");
+ for (const patch of [
+ {receipt_review: {...request.receipt_review, kind: "vision_acceptance_gap"}},
+ {receipt_review: {...request.receipt_review, stop_condition_sha256: "0".repeat(64)}},
+ {current_obligation: {...current, stop_condition: `${stop} changed`}},
+ {current_obligation: {...current, triggers: [{kind: "goal_outcome_uncovered"}]}},
+ {current_obligation: {...current, agent_id: "another-agent"}},
+ ]) {
+ assert.throws(() => projectReplanSemantics({...request, ...patch}), /identity conflicts/);
+ }
+});
+
+test("a canonical periodic review reconstructs after its live frontier disappears", () => {
+ const originalId = "replan-1111111111111111";
+ const digest = createHash("sha256").update(
+ AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION, "utf8").digest("hex");
+ const request = {operation: "receipt_bound_obligation", guard_scoped: true,
+ replay_phase: "open", selected_obligation_id: originalId, agent_id: "reviewer",
+ current_obligation: null, transition_candidates: [], receipt_review: {
+ kind: "periodic_review_due", stop_condition_sha256: digest,
+ stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID}};
+ assert.deepEqual(projectReplanSemantics(request).obligation, {
+ schema_version: "autonomous_replan_obligation_v0", required: true,
+ obligation_id: originalId, agent_id: "reviewer",
+ stop_condition: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION,
+ triggers: [{kind: "periodic_review_due"}], selection_binding: "heartbeat_receipt"});
+ for (const receipt_review of [
+ {...request.receipt_review, stop_condition_sha256: "0".repeat(64)},
+ {...request.receipt_review, stop_contract_id: "unknown"},
+ {...request.receipt_review, kind: "external_progress_review_drift"},
+ ]) {
+ assert.throws(() => projectReplanSemantics({...request, receipt_review}), /identity conflicts/);
+ }
+});
+
test("mixed vision/outcome recovery preserves the dominant policy without discharging review", () => {
for (const triggers of [[{kind: "vision_acceptance_gap"}],
[{kind: "goal_outcome_uncovered"}, {kind: "vision_acceptance_gap"}],
@@ -228,6 +289,63 @@ test("mixed vision/outcome recovery preserves the dominant policy without discha
}
});
+test("Monitor lifecycle changes retain the admitted review without discharging it", () => {
+ const kind = "monitor_no_change_streak";
+ const source = {schema_version: "autonomous_replan_obligation_v0", required: true,
+ obligation_id: "replan-1111111111111111", agent_id: "reviewer", trigger_count: 1,
+ triggers: [{kind, todo_id: "todo_monitor", run_count: 5, threshold: 5}],
+ stop_condition: "Stop at owner-only decisions."};
+ const review = projectReplanSemantics({operation: "receipt_review_source", agent_id: "reviewer",
+ obligation: source}).review_source;
+ assert.deepEqual(review, {kind, stop_condition: source.stop_condition});
+ const request = {operation: "receipt_bound_obligation", guard_scoped: true,
+ replay_phase: "open", selected_obligation_id: source.obligation_id, current_obligation: null,
+ transition_candidates: [], agent_id: "reviewer", receipt_review: review};
+ const recovered = projectReplanSemantics(request).obligation as JsonObject;
+ assert.equal(recovered.obligation_id, source.obligation_id);
+ assert.equal(recovered.selection_binding, "heartbeat_receipt");
+ assert.deepEqual(recovered.triggers, [{kind}]);
+ assert.deepEqual(requiredSemanticOutcomes(recovered), requiredSemanticOutcomes(source));
+ assert.equal(projectReplanSemantics({operation: "qualify", obligation: recovered}).accepted, false);
+ assert.equal(projectReplanSemantics({operation: "qualify", obligation: recovered,
+ observation_delta: {delta_kinds: ["new_surface"]}}).accepted, true);
+ assert.throws(() => projectReplanSemantics({...request, guard_scoped: false}), /identity conflicts/);
+ for (const restriction of [{progress_baseline: {}}, {progress_window: []},
+ {capability_guard: {}}, {resolution_mode: "todo_lifecycle_settlement"},
+ {satisfying_semantic_outcomes: ["new_runnable_successor"]}]) {
+ assert.equal(projectReplanSemantics({operation: "receipt_review_source", agent_id: "reviewer",
+ obligation: {...source, ...restriction}}).review_source, null);
+ }
+});
+
+test("Monitor receipt recovery preserves mixed-review precedence and the complete stop contract", () => {
+ const monitor = {kind: "monitor_no_change_streak", todo_id: "todo_monitor", run_count: 5, threshold: 5};
+ const cases: [JsonObject[], string, boolean][] = [
+ [[monitor], "monitor_no_change_streak", true],
+ [[monitor, {kind: "goal_outcome_uncovered"}], "goal_outcome_uncovered", true],
+ [[monitor, {kind: "vision_acceptance_gap"}], "vision_acceptance_gap", false],
+ [[{kind: "vision_acceptance_gap"}, monitor], "vision_acceptance_gap", false],
+ ];
+ for (const [triggers, kind, acceptsProgress] of cases) {
+ const source = {schema_version: "autonomous_replan_obligation_v0", required: true,
+ obligation_id: "replan-1111111111111111", agent_id: "reviewer",
+ trigger_count: triggers.length, triggers, stop_condition: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONDITION};
+ assert.deepEqual(projectReplanSemantics({operation: "receipt_review_source", agent_id: "reviewer",
+ obligation: source}).review_source, {kind, stop_condition: source.stop_condition});
+ const recovered = projectReplanSemantics({operation: "receipt_bound_obligation", guard_scoped: true,
+ replay_phase: "open", selected_obligation_id: source.obligation_id, agent_id: "reviewer",
+ current_obligation: null, transition_candidates: [], receipt_review: {kind,
+ stop_condition_sha256: createHash("sha256").update(source.stop_condition, "utf8").digest("hex"),
+ stop_contract_id: AUTONOMOUS_REPLAN_DEFAULT_STOP_CONTRACT_ID}}).obligation as JsonObject;
+ assert.equal(recovered.obligation_id, source.obligation_id);
+ assert.equal(recovered.stop_condition, source.stop_condition);
+ assert.deepEqual(recovered.triggers, [{kind}]);
+ assert.equal(projectReplanSemantics({operation: "qualify", obligation: recovered}).accepted, false);
+ assert.equal(projectReplanSemantics({operation: "qualify", obligation: recovered,
+ observation_delta: {delta_kinds: ["new_surface"]}}).accepted, acceptsProgress);
+ }
+});
+
test("a recorded outcome review survives work-link refinement without cached context or discharge", () => {
const id = "replan-1111111111111111";
const request = {operation: "receipt_bound_obligation", guard_scoped: true,
@@ -341,6 +459,21 @@ test("no-followup cannot hide an inconsistent vision behind another accepted out
assert.equal(valid.accepted, true);
});
+test("terminal input projection supplies coverage and vision without widening restricted exits", () => {
+ const result = projectReplanSemantics({operation: "requirements", obligation});
+ const contract = result.writeback_contract as JsonObject;
+ const terminal = contract.no_followup_requirements as JsonObject;
+ assert.deepEqual(terminal.cli_args, ["--progress-result-class", "no_followup",
+ "--progress-coverage-scope-id", "", "--progress-evidence-id", "",
+ "--agent-vision-json", ""]);
+ assert.deepEqual(terminal.vision_fields, {state: "no_followup", "path_delta.outcome": "stop"});
+ assert.deepEqual(terminal.preserve, ["vision_patch"]);
+ const restricted = projectReplanSemantics({operation: "requirements", obligation: {
+ ...obligation, satisfying_semantic_outcomes: ["new_concrete_blocker"],
+ }});
+ assert.equal((restricted.writeback_contract as JsonObject).no_followup_requirements, undefined);
+});
+
test("external progress review: renamed identifiers discharge only behind new evidence; the plan may stand on evidence", () => {
const review = {triggers: [{kind: "external_progress_review_drift", model_authority: "none"}]};
const projection = projectReplanSemantics({operation: "requirements", obligation: review});
diff --git a/tests/control_plane_ts/todo_terminal_decision.test.ts b/tests/control_plane_ts/todo_terminal_decision.test.ts
index 553a066ef9..a3e25a9900 100644
--- a/tests/control_plane_ts/todo_terminal_decision.test.ts
+++ b/tests/control_plane_ts/todo_terminal_decision.test.ts
@@ -349,6 +349,199 @@ test("exact linked user gate decision scope does not invent Agent authority", ()
assert.equal(mismatch.code, "actor_required");
});
+test("single-agent goals consult the exact user gate override for owner decisions", () => {
+ const scope = {kind: "direction", granularity: "action", scope_key: "release"};
+ const gate = {
+ todo_id: "todo_gate",
+ status: "open",
+ role: "user",
+ task_class: "user_gate",
+ claimed_by: null,
+ excluded_agents: [],
+ bound_agent: "agent-a",
+ blocks_agent: null,
+ decision_scope: scope,
+ required_decision_scopes: [],
+ unblocks_todo_id: "todo_target",
+ };
+ const target = {
+ ...request().todo as object,
+ todo_id: "todo_target",
+ required_decision_scopes: [scope],
+ };
+ // Single registered agent: an owner decision (no agent actor) closing the
+ // exact linked gate must use the override instead of failing actor admission.
+ const accepted = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ todo: gate,
+ decision_target: target,
+ actor_agent_id: null,
+ decision_outcome: "approve",
+ }));
+ assert.equal(accepted.outcome, "apply");
+ assert.equal(accepted.authority_mode, "exact_user_gate_decision_scope_override");
+
+ // Without the exact scope link the override does not fire: the ownership
+ // facts still require an accountable actor.
+ const unlinked = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ todo: gate,
+ decision_target: { ...target, required_decision_scopes: [] },
+ actor_agent_id: null,
+ decision_outcome: "approve",
+ }));
+ assert.equal(unlinked.outcome, "rejected");
+ assert.equal(unlinked.code, "actor_required");
+
+ // Registered actors keep ordinary single-agent compatibility, while
+ // unregistered or excluded actors remain rejected even when the scope link
+ // matches.
+ const viaActor = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ todo: gate,
+ decision_target: target,
+ actor_agent_id: "agent-a",
+ decision_outcome: "approve",
+ }));
+ assert.equal(viaActor.outcome, "apply");
+ assert.equal(viaActor.authority_mode, "single_agent_compatibility");
+
+ const unregistered = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ todo: gate,
+ decision_target: target,
+ actor_agent_id: "bogus",
+ decision_outcome: "approve",
+ }));
+ assert.equal(unregistered.outcome, "rejected");
+ assert.equal(unregistered.code, "actor_not_registered");
+
+ const excluded = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ todo: { ...gate, excluded_agents: ["agent-a"] },
+ decision_target: target,
+ actor_agent_id: "agent-a",
+ decision_outcome: "approve",
+ }));
+ assert.equal(excluded.outcome, "rejected");
+ assert.equal(excluded.code, "actor_excluded");
+});
+
+test("actorless owner gate decisions do not require an execution lease", () => {
+ const scope = {kind: "direction", granularity: "action", scope_key: "release"};
+ const gate = {
+ todo_id: "todo_gate",
+ status: "open",
+ role: "user",
+ task_class: "user_gate",
+ claimed_by: null,
+ excluded_agents: [],
+ bound_agent: null,
+ blocks_agent: "agent-a",
+ decision_scope: scope,
+ required_decision_scopes: [],
+ unblocks_todo_id: "todo_target",
+ };
+ const target = {
+ ...request().todo as object,
+ todo_id: "todo_target",
+ required_decision_scopes: [scope],
+ };
+ // A single-agent hard-lease goal has no peer set or agent actor to hold a
+ // lease for an owner decision: the gate records a decision, it does not execute work.
+ const owner = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ handoff_mode: "hard_lease",
+ todo: gate,
+ decision_target: target,
+ actor_agent_id: null,
+ decision_outcome: "approve",
+ }));
+ assert.equal(owner.outcome, "apply");
+ assert.equal(owner.authority_mode, "exact_user_gate_decision_scope_override");
+ assert.equal(owner.lease_fence, "not_required");
+ assert.equal(owner.next_lease, null);
+
+ // A registered actor keeps the ordinary lease requirement: the owner
+ // exception never widens an agent's execution admission.
+ const actor = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ handoff_mode: "hard_lease",
+ todo: gate,
+ decision_target: target,
+ actor_agent_id: "agent-a",
+ decision_outcome: "approve",
+ }));
+ assert.equal(actor.outcome, "rejected");
+ assert.equal(actor.code, "handoff_mode_requires_lease");
+ assert.equal(actor.lease_fence, "required");
+
+ // Any expired lease lineage is retired together with the Todo transition,
+ // while an active holder or explicit lease fence is never bypassed.
+ const expiredLease = {
+ present: true,
+ active: false,
+ status: "active",
+ owner: "agent-a",
+ idempotency_key: "old-lease",
+ version: 2,
+ lease_epoch: 1,
+ write_scopes: [],
+ };
+ const retired = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ handoff_mode: "hard_lease",
+ todo: gate,
+ decision_target: target,
+ lease: expiredLease,
+ actor_agent_id: null,
+ decision_outcome: "approve",
+ }));
+ assert.equal(retired.outcome, "apply");
+ assert.equal(retired.lease_fence, "not_required");
+ assert.equal(retired.next_lease?.status, "released");
+
+ const activeHolder = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ handoff_mode: "hard_lease",
+ todo: gate,
+ decision_target: target,
+ lease: { ...expiredLease, active: true },
+ actor_agent_id: null,
+ decision_outcome: "approve",
+ }));
+ assert.equal(activeHolder.outcome, "rejected");
+ assert.equal(activeHolder.code, "lease_fence_required");
+
+ const explicitFence = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a"],
+ handoff_mode: "hard_lease",
+ todo: gate,
+ decision_target: target,
+ actor_agent_id: null,
+ decision_outcome: "approve",
+ lease_idempotency_key: "stale-key",
+ }));
+ assert.equal(explicitFence.outcome, "rejected");
+ assert.equal(explicitFence.code, "handoff_mode_requires_lease");
+
+ // Multi-agent hard-lease goals preserve their attributed-actor contract
+ // even when auto-acquire is enabled for the gate.
+ for (const allowAuto of [false, true]) {
+ const multiAgent = evaluateCoordinationTodoTerminalDecision(request({
+ registered_agents: ["agent-a", "agent-b"],
+ handoff_mode: "hard_lease",
+ allow_user_gate_auto_acquire: allowAuto,
+ todo: gate,
+ decision_target: target,
+ actor_agent_id: null,
+ decision_outcome: "approve",
+ }));
+ assert.equal(multiAgent.outcome, "rejected");
+ assert.equal(multiAgent.code, "handoff_mode_requires_lease");
+ }
+});
+
test("hard-lease terminal transition releases the exact owned generation", () => {
const lease = {
present: true,
diff --git a/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts b/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts
index 4bd8ef4448..edff1eface 100644
--- a/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts
+++ b/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts
@@ -508,6 +508,38 @@ test("an admitted Todo-bound replan without verified writeback does not hold a l
}
});
+test("an admitted obligation-bound replan without verified writeback does not hold a later guard", async () => {
+ const turn = "turn-replan";
+ const replanId = `replan-${"c".repeat(16)}`;
+ const identity = settlementIdentity({
+ goal_id: GOAL,
+ agent_id: AGENT,
+ replan_obligation_id: replanId,
+ turn_instance_id: turn,
+ });
+ const runtime = await runtimeWith([
+ receipt(turn, {
+ replan_obligation_id: replanId,
+ semantic_replan_obligation_id: replanId,
+ settlement_effect_id: identity.effect_id,
+ closeout_required: false,
+ ok: true,
+ should_run: true,
+ interaction_mode: "autonomous_replan",
+ must_attempt_work: true,
+ delivery_allowed: false,
+ quiet_noop_allowed: false,
+ }),
+ ]);
+ try {
+ const result = await preflight(runtime.root);
+ assert.equal(result.status, "none");
+ assert.equal(result.reason, "no_prior_turn_requires_closeout");
+ } finally {
+ await runtime.close();
+ }
+});
+
test("the current Turn, other goals, other agents, and other event kinds are ignored", async () => {
const runtime = await runtimeWith([
receipt("current-turn", closeoutRequired("current-turn", "todo_current")),
@@ -1096,6 +1128,71 @@ test("an autonomous replan binding recovers without a Todo binding", async () =>
}
});
+test("an admitted obligation-bound replan with writeback resumes its original debit", async () => {
+ const turn = "turn-replan-writeback";
+ const replanId = `replan-${"d".repeat(16)}`;
+ const identity = settlementIdentity({
+ goal_id: GOAL,
+ agent_id: AGENT,
+ replan_obligation_id: replanId,
+ turn_instance_id: turn,
+ });
+ const runtime = await runtimeWith([
+ receipt(turn, {
+ replan_obligation_id: replanId,
+ semantic_replan_obligation_id: replanId,
+ settlement_effect_id: identity.effect_id,
+ closeout_required: false,
+ ok: true,
+ should_run: true,
+ interaction_mode: "autonomous_replan",
+ must_attempt_work: true,
+ delivery_allowed: false,
+ quiet_noop_allowed: false,
+ }),
+ {
+ schema_version: "loopx_rollout_event_v0",
+ event_id: "event-replan-writeback",
+ event_kind: "refresh_state",
+ goal_id: GOAL,
+ agent_id: AGENT,
+ run_id: turn,
+ details: {settlement_effect_id: identity.effect_id},
+ },
+ ]);
+ try {
+ const runsRoot = join(runtime.root, "goals", GOAL, "runs");
+ await mkdir(runsRoot, {recursive: true});
+ await writeFile(join(runsRoot, "index.jsonl"), `${JSON.stringify({
+ classification: "state_refreshed",
+ delivery_outcome: "outcome_progress",
+ goal_id: GOAL,
+ agent_id: AGENT,
+ replan_obligation_id: replanId,
+ turn_instance_id: turn,
+ settlement_identity: identity,
+ })}\n`);
+
+ const result = await preflight(runtime.root);
+ const candidate = candidateFrom(result);
+ assert.equal(candidate.binding_kind, "autonomous_replan");
+ assert.equal(candidate.binding_id, replanId);
+ assert.equal(candidate.admitted_replan, true);
+ assert.deepEqual(result.missing_receipts, ["quota_spend_receipt"]);
+
+ const verdict = reduce(
+ candidate,
+ result.missing_receipts as string[],
+ READ_TODO(null),
+ );
+ assert.equal(verdict.status, "recovery_required");
+ assert.equal((verdict.recovery as JsonObject).repair, "resume_prior_turn");
+ assert.equal((verdict.obligation as JsonObject).repair, "resume_prior_turn");
+ } finally {
+ await runtime.close();
+ }
+});
+
test("candidate bindings are revalidated before any verdict", async () => {
assert.throws(
() => reduce({
diff --git a/tests/extensions/test_extension_readiness_contexts.py b/tests/extensions/test_extension_readiness_contexts.py
index c714edcb13..b59b265229 100644
--- a/tests/extensions/test_extension_readiness_contexts.py
+++ b/tests/extensions/test_extension_readiness_contexts.py
@@ -7,6 +7,8 @@
import subprocess
import sys
+import pytest
+
from tests.control_plane import test_refresh_external_delivery as settlement_fixtures
from tests.control_plane.test_quota_settlement_cli import AGENT_ID, GOAL_ID, TODO_ID, TURN_ID
from loopx.extensions.lark.goal_channel_contracts import (
@@ -139,6 +141,113 @@ def test_legacy_single_proof_is_read_only_then_migrated_by_real_doctor(tmp_path:
assert extension_status(state_file=state_file)["extensions"][0]["doctor_verified"]
+@pytest.mark.parametrize("selection", ["registry", "environment"])
+def test_real_extension_cli_follows_selected_registry_with_conflicting_defaults(
+ tmp_path: Path, selection: str,
+) -> None:
+ home = tmp_path / "home"
+ defaults = [home / ".loopx", home / ".codex" / "loopx"]
+ for root in defaults:
+ root.mkdir(parents=True)
+ (root / "preserve.txt").write_text("existing independent state")
+ project = tmp_path / "project"
+ registry = project / ".loopx" / "registry.json"
+ registry.parent.mkdir(parents=True)
+ registry.write_text(json.dumps({"goals": [], "common_runtime_root": "selected state"}))
+ runtime = project / "selected state"
+ context = tmp_path / "unrelated working directory"
+ context.mkdir()
+ (context / f"{MODULE}.py").write_text("raise SystemExit(0)\n")
+ manifest = _manifest(tmp_path / "extension.toml")
+ repo = Path(__file__).resolve().parents[2]
+ environment = {
+ key: value for key, value in os.environ.items()
+ if not key.startswith(("LOOPX_", "PYTHON", "CODEX_"))
+ }
+ environment.update(
+ HOME=str(home), PYTHONPATH=os.pathsep.join((str(context), str(repo))),
+ LOOPX_USAGE_PING="0", DO_NOT_TRACK="1",
+ )
+ prefix = [sys.executable, "-c", "from loopx.entrypoint import main; raise SystemExit(main())",
+ "--format", "json"]
+
+ def run(*args: str, env: dict | None = None) -> dict:
+ result = subprocess.run(
+ [*prefix, *args], cwd=context, env=env or environment,
+ capture_output=True, text=True, timeout=30,
+ )
+ assert result.returncode == 0, result.stderr
+ return json.loads(result.stdout)
+
+ installed = run("--runtime-root", str(runtime), "extension", "install",
+ "--manifest", str(manifest), "--execute")
+ assert installed["doctor"]["verified"] is True
+ state = runtime / "extensions" / "state.json"
+ before = state.read_bytes()
+ route = ["--registry", str(registry)] if selection == "registry" else []
+ selected_env = {**environment, "LOOPX_REGISTRY": str(registry)}
+ listed = run(*route, "extension", "list", env=selected_env if not route else None)
+ assert [item["id"] for item in listed["extensions"]] == [EXTENSION_ID]
+ assert listed["extensions"][0]["doctor_verified"] is True
+ assert state.read_bytes() == before
+ checked = run(*route, "extension", "doctor", "--all-enabled", "--execute",
+ env=selected_env if not route else None)
+ assert checked["status"] == "ready" and checked["verified_count"] == 1
+ for root in defaults:
+ assert sorted(path.name for path in root.iterdir()) == ["preserve.txt"]
+ assert (root / "preserve.txt").read_text() == "existing independent state"
+
+
+@pytest.mark.parametrize("override", ["runtime-root", "state-file"])
+def test_real_extension_cli_explicit_storage_does_not_open_unused_registry(
+ tmp_path: Path, override: str,
+) -> None:
+ registry = tmp_path / "unreadable-registry.json"
+ registry.write_text("not registry JSON")
+ state = tmp_path / "selected" / "extensions" / "state.json"
+ state.parent.mkdir(parents=True)
+ state.write_text(json.dumps({"schema_version": "loopx_extension_state_v0", "extensions": {}}))
+ prefix = ["--runtime-root", str(state.parent.parent)] if override == "runtime-root" else []
+ suffix = ["--state-file", str(state)] if override == "state-file" else []
+ environment = {key: value for key, value in os.environ.items()
+ if not key.startswith(("LOOPX_", "PYTHON", "CODEX_"))}
+ environment.update(LOOPX_USAGE_PING="0", DO_NOT_TRACK="1",
+ PYTHONPATH=str(Path(__file__).resolve().parents[2]))
+ before = {path: path.read_bytes() for path in (registry, state)}
+ result = subprocess.run(
+ [sys.executable, "-c", "from loopx.entrypoint import main; raise SystemExit(main())",
+ "--format", "json", "--registry", str(registry), *prefix,
+ "extension", "list", *suffix],
+ cwd=tmp_path, env=environment, capture_output=True, text=True, timeout=30,
+ )
+ assert result.returncode == 0, result.stderr
+ assert json.loads(result.stdout)["extensions"] == []
+ assert {path: path.read_bytes() for path in before} == before
+
+
+def test_real_extension_cli_does_not_choose_between_conflicting_defaults(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ for relative in (".loopx", ".codex/loopx"):
+ root = home / relative
+ root.mkdir(parents=True)
+ (root / "preserve.txt").write_text("independent state")
+ environment = {key: value for key, value in os.environ.items()
+ if not key.startswith(("LOOPX_", "PYTHON", "CODEX_"))}
+ environment.update(HOME=str(home), LOOPX_USAGE_PING="0", DO_NOT_TRACK="1",
+ PYTHONPATH=str(Path(__file__).resolve().parents[2]))
+ before = {str(path.relative_to(home)): path.read_bytes()
+ for path in home.rglob("*") if path.is_file()}
+ result = subprocess.run(
+ [sys.executable, "-c", "from loopx.entrypoint import main; raise SystemExit(main())",
+ "--format", "json", "extension", "doctor", "--all-enabled", "--execute"],
+ cwd=tmp_path, env=environment, capture_output=True, text=True, timeout=30,
+ )
+ assert result.returncode != 0
+ assert "Both default LoopX runtime roots contain state" in result.stderr
+ assert {str(path.relative_to(home)): path.read_bytes()
+ for path in home.rglob("*") if path.is_file()} == before
+
+
settlement_session = settlement_fixtures.session
diff --git a/tests/test_codex_turn_completion.py b/tests/test_codex_turn_completion.py
new file mode 100644
index 0000000000..614cebc3de
--- /dev/null
+++ b/tests/test_codex_turn_completion.py
@@ -0,0 +1,512 @@
+"""Builtin completion uses the real Todo validator and canonical lease fence."""
+
+from __future__ import annotations
+
+import contextlib
+import io
+import json
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from loopx.capabilities.native_chat.steward_turn import StewardTurnHost
+from loopx.cli import build_parser, main
+from loopx.cli_commands import turn_run_once
+from loopx.cli_commands.turn import handle_turn_command
+from loopx.control_plane.todos.mutation_api import add_goal_todo
+from loopx.control_plane.turn_driver.codex_cli import codex_cli_result_schema
+from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime
+from tests.test_loopx_turn_codex_cli import _fake_codex
+from tests.test_loopx_turn_driver import (
+ _completion_host_and_validation_scripts,
+ _turn_journal,
+ _write_live_fixture,
+)
+
+
+def _cli(registry: Path, runtime: Path, *args: str) -> tuple[int, dict]:
+ output = io.StringIO()
+ with contextlib.redirect_stdout(output):
+ code = main(
+ [
+ "--registry",
+ str(registry),
+ "--runtime-root",
+ str(runtime),
+ "--format",
+ "json",
+ *args,
+ ]
+ )
+ return code, json.loads(output.getvalue())
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize(
+ "scenario",
+ [
+ "completion",
+ "terminal",
+ "progress",
+ "independent_validation",
+ "declared_validation",
+ "stale_lease",
+ "stop_after_progress_validation",
+ "stop_after_completion_validation",
+ ],
+)
+def test_builtin_codex_completes_before_accountable_writeback(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ provider: str,
+ scenario: str,
+) -> None:
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ terminal = scenario == "terminal"
+ progress = scenario in {"progress", "stop_after_progress_validation"}
+ stopped_after_validation = scenario in {
+ "stop_after_progress_validation",
+ "stop_after_completion_validation",
+ }
+ project, runtime, registry = _write_live_fixture(
+ tmp_path,
+ provider=provider,
+ handoff_mode="hard_lease",
+ todo_metadata_extra="no_followup=true" if terminal else "",
+ )
+ added = (
+ {"todo_id": "todo_fixture0001"}
+ if terminal
+ else add_goal_todo(
+ registry_path=registry,
+ goal_id="loopx-turn-fixture",
+ role="agent",
+ text="Deliver the independently checked artifact.",
+ task_class="advancement_task",
+ action_kind="fixture",
+ claimed_by="codex-fixture",
+ agent_id="codex-fixture",
+ validation_command_json=None
+ if progress
+ else json.dumps(
+ [
+ sys.executable,
+ "-c",
+ "raise SystemExit(1)"
+ if scenario == "declared_validation"
+ else "raise SystemExit(0)",
+ ]
+ ),
+ )
+ )
+ todo_id = added["todo_id"]
+ claim_code, claim = _cli(
+ registry,
+ runtime,
+ "todo",
+ "claim",
+ "--goal-id",
+ "loopx-turn-fixture",
+ "--todo-id",
+ todo_id,
+ "--agent-id",
+ "codex-fixture",
+ "--claimed-by",
+ "codex-fixture",
+ )
+ assert claim_code == 0, claim
+ if terminal:
+ code, current = _cli(
+ registry, runtime, "todo", "list", "--goal-id", "loopx-turn-fixture"
+ )
+ assert code == 0, current
+ code, declaration = _cli(
+ registry,
+ runtime,
+ "todo",
+ "update",
+ "--goal-id",
+ "loopx-turn-fixture",
+ "--todo-id",
+ todo_id,
+ "--agent-id",
+ "codex-fixture",
+ "--claim-operation-id",
+ claim["claim_operation_id"],
+ "--validation-command-json",
+ json.dumps([sys.executable, "-c", "raise SystemExit(0)"]),
+ "--update-operation-id",
+ "declare-terminal-validation",
+ "--update-expected-provider-revision",
+ current["authority_read"]["provider_revision"],
+ )
+ assert code == 0, declaration
+ binary, host_log = _fake_codex(tmp_path)
+ codex_home = tmp_path / "codex-home"
+ codex_home.mkdir()
+ monkeypatch.setenv("CODEX_HOME", str(codex_home))
+ monkeypatch.setenv("LOOPX_RELEASE_ROOT", str(Path(__file__).resolve().parents[1]))
+ monkeypatch.setenv("FAKE_CODEX_LOG", str(host_log))
+ monkeypatch.setenv(
+ "FAKE_CODEX_RESULT_FIELDS",
+ json.dumps(
+ {
+ "result_kind": "validated_progress" if progress else "validated_completion",
+ }
+ ),
+ )
+ if scenario == "stale_lease":
+ code, inspection = _cli(
+ registry,
+ runtime,
+ "task-lease",
+ "inspect",
+ "--goal-id",
+ "loopx-turn-fixture",
+ "--todo-id",
+ todo_id,
+ )
+ assert code == 0 and inspection["active"] is True, inspection
+ lease = inspection["lease"]
+ run_codex = turn_run_once.run_codex_cli_host
+
+ def host(request, **kwargs):
+ # Renew after launch capture. A newer generation of the same owner
+ # still cannot authorize this result.
+ code, renewed = _cli(
+ registry,
+ runtime,
+ "task-lease",
+ "renew",
+ "--goal-id",
+ "loopx-turn-fixture",
+ "--todo-id",
+ todo_id,
+ "--owner",
+ "codex-fixture",
+ "--idempotency-key",
+ lease["idempotency_key"],
+ "--expected-version",
+ str(lease["version"]),
+ )
+ assert code == 0, renewed
+ return run_codex(request, **kwargs)
+
+ monkeypatch.setattr(turn_run_once, "run_codex_cli_host", host)
+ if stopped_after_validation:
+ build_validator = turn_run_once.build_loopx_turn_command_validator
+
+ def validate_then_stop(*args, **kwargs):
+ validate = build_validator(*args, **kwargs)
+
+ def checked(plan, result):
+ observation = validate(plan, result)
+ assert observation["status"] == "passed", observation
+ lifecycle = ("goal-lifecycle", "--goal-id", "loopx-turn-fixture", "--operation", "stop")
+ code, preview = _cli(registry, runtime, *lifecycle)
+ assert code == 0 and not preview["written"], preview
+ code, stopped = _cli(
+ registry, runtime, *lifecycle, "--actor-kind", "owner",
+ "--expected-state-fingerprint", preview["observed_state_fingerprint"], "--execute",
+ )
+ assert code == 0 and stopped["readback"]["verified"], stopped
+ assert stopped["after_state"] == "stopped", stopped
+ return observation
+
+ return checked
+
+ monkeypatch.setattr(turn_run_once, "build_loopx_turn_command_validator", validate_then_stop)
+ argv = [
+ "turn",
+ "run-once",
+ "--goal-id",
+ "loopx-turn-fixture",
+ "--agent-id",
+ "codex-fixture",
+ "--todo-id",
+ todo_id,
+ "--host",
+ "codex-cli",
+ "--project",
+ str(project),
+ "--codex-bin",
+ str(binary),
+ "--codex-model",
+ "fixture-model",
+ "--codex-reasoning-effort",
+ "high",
+ "--codex-sandbox",
+ "read-only",
+ "--validation-command-json",
+ json.dumps(
+ [
+ sys.executable,
+ "-c",
+ "raise SystemExit(1)"
+ if scenario == "independent_validation"
+ else "raise SystemExit(0)",
+ ]
+ ),
+ "--no-global-sync",
+ "--execute",
+ ]
+ code, result = _cli(registry, runtime, *argv)
+ journals = list((runtime / "goals" / "loopx-turn-fixture" / "turns").glob("*.json"))
+ assert len(journals) == 1
+ journal = json.loads(journals[0].read_text())
+ assert len(host_log.read_text().splitlines()) == 1
+ if stopped_after_validation:
+ assert code == 1 and result["error_code"] == "goal_stopped", result
+ assert journal["completed_phases"] == ["host_execute", "typed_result", "validation"]
+ read_code, readback = _cli(
+ registry, runtime, "todo", "list", "--goal-id", "loopx-turn-fixture", "--todo-id", todo_id,
+ )
+ assert read_code == 0 and readback["todo"]["status"] == "open", readback
+ return
+ if scenario in {"independent_validation", "declared_validation", "stale_lease"}:
+ assert result["status"] != "committed", result
+ assert "quota_spend" not in journal["completed_phases"]
+ assert "durable_writeback" not in journal["completed_phases"]
+ if scenario == "stale_lease":
+ recovery_args = argv[:-1]
+ todo_option = recovery_args.index("--todo-id")
+ del recovery_args[todo_option : todo_option + 2]
+ code, retried = _cli(
+ registry,
+ runtime,
+ *recovery_args,
+ "--resume-turn-key",
+ journal["turn_key"],
+ "--execute",
+ )
+ assert retried.get("status") != "committed", retried
+ assert len(host_log.read_text().splitlines()) == 1
+ return
+ assert code == 0 and result["status"] == "committed", result
+ kinds = _effect_kinds(runtime, journal)
+ if progress:
+ assert "completion" not in journal["writeback"]
+ assert kinds == ["refresh_state", "quota_spend"]
+ read_code, readback = _cli(
+ registry, runtime, "todo", "list", "--goal-id", "loopx-turn-fixture"
+ )
+ assert read_code == 0, readback
+ assert (
+ next(todo for todo in readback["todos"] if todo["todo_id"] == todo_id)[
+ "status"
+ ]
+ == "open"
+ )
+ else:
+ completion = {
+ "todo_id": todo_id,
+ "continuation": "no_followup" if terminal else "active_goal",
+ }
+ assert journal["writeback"]["completion"] == completion
+ assert kinds == ["todo_complete", "refresh_state", "quota_spend"]
+ if terminal:
+ assert journal["terminal_closeout"]["completion"] == completion
+ replay_args = argv[:-1]
+ todo_option = replay_args.index("--todo-id")
+ del replay_args[todo_option : todo_option + 2]
+ code, replay = _cli(
+ registry,
+ runtime,
+ *replay_args,
+ "--resume-turn-key",
+ journal["turn_key"],
+ "--execute",
+ )
+ assert code == 0 and replay["replayed"] is True, replay
+ assert len(host_log.read_text().splitlines()) == 1
+ assert not any(replay["effects"].values())
+ assert _effect_kinds(runtime, journal) == kinds
+
+
+def _effect_kinds(runtime: Path, journal: dict) -> list[str]:
+ identity = journal["plan"]["transaction"]
+ run_id = identity.get("turn_instance_id", journal["turn_key"])
+ path = runtime / "goals" / "loopx-turn-fixture" / "rollout-event-log.jsonl"
+ rows = (json.loads(line) for line in path.read_text().splitlines())
+ return [
+ row["event_kind"]
+ for row in rows
+ if row.get("run_id") == run_id
+ and row["event_kind"] in {"refresh_state", "quota_spend", "todo_complete"}
+ ]
+
+
+@pytest.mark.parametrize("provider", ["file", "sqlite"])
+@pytest.mark.parametrize(
+ "interruption", [None, "after_debit", "lost_completion_receipt"]
+)
+def test_native_terminal_closeout_keeps_the_original_lease_and_turn(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ provider: str,
+ interruption: str | None,
+) -> None:
+ isolate_sqlite_runtime(tmp_path, monkeypatch)
+ project, runtime, registry = _write_live_fixture(
+ tmp_path,
+ provider=provider,
+ handoff_mode="hard_lease",
+ todo_metadata_extra="no_followup=true",
+ )
+ goal_id, agent_id, todo_id = (
+ "loopx-turn-fixture",
+ "codex-fixture",
+ "todo_fixture0001",
+ )
+ code, claim = _cli(
+ registry,
+ runtime,
+ "todo",
+ "claim",
+ "--goal-id",
+ goal_id,
+ "--todo-id",
+ todo_id,
+ "--agent-id",
+ agent_id,
+ "--claimed-by",
+ agent_id,
+ )
+ assert code == 0, claim
+ lease_argv = ("task-lease", "inspect", "--goal-id", goal_id, "--todo-id", todo_id)
+ code, inspection = _cli(registry, runtime, *lease_argv)
+ assert code == 0 and inspection["active"] is True, inspection
+ lease = inspection["lease"]
+ adapter = SimpleNamespace(
+ controller=SimpleNamespace(
+ registry_path=registry, coordination_runtime_root=runtime
+ )
+ )
+ host_calls, lease_reads = [], []
+
+ def resolve_lease():
+ lease_reads.append(lease["version"])
+ return StewardTurnHost._task_lease_proof(
+ adapter, {"actor": {"goal_id": goal_id}, "todo_id": todo_id}, lease
+ )
+
+ def host(request, launch_lifetime):
+ with launch_lifetime():
+ host_calls.append(request["turn_key"])
+ (project / "completion-artifact.txt").write_text(
+ "completed", encoding="utf-8"
+ )
+ return {
+ "schema_version": "loopx_turn_result_v0",
+ "turn_key": request["turn_key"],
+ "result_kind": "validated_completion",
+ "completed_phases": ["host_execute", "typed_result"],
+ "classification": "fixture_completion",
+ "recommended_action": "Refresh the active Goal.",
+ "next_action": "Read the fresh decision.",
+ "delivery_batch_scale": "implementation",
+ "delivery_outcome": "outcome_progress",
+ "vision_unchanged_reason": "The remaining Goal is unchanged.",
+ "work_evidence": ["artifact:completion-artifact"],
+ "validation_evidence": ["check:artifact-contents"],
+ }
+
+ _, validation = _completion_host_and_validation_scripts()
+ base = [
+ "turn",
+ "run-once",
+ "--host",
+ "generic-cli",
+ "--goal-id",
+ goal_id,
+ "--agent-id",
+ agent_id,
+ "--project",
+ str(project),
+ "--no-global-sync",
+ "--validation-command-json",
+ json.dumps([sys.executable, "-c", validation]),
+ "--execute",
+ ]
+
+ def invoke(*extra: str):
+ args = build_parser().parse_args([*base, *extra])
+ args.host, args.session_scope = "codex-app-server", "agent"
+ result: dict = {}
+ code = handle_turn_command(
+ args,
+ registry_path=registry,
+ runtime_root_arg=str(runtime),
+ output_format=lambda *_args, **_kwargs: "json",
+ print_payload=lambda value, *_args: result.update(value),
+ native_host_runner=host,
+ native_completion_lease_resolver=resolve_lease,
+ native_session_binding_resolver=lambda _: {
+ "schema_version": "loopx_turn_session_binding_v0",
+ "goal_id": goal_id,
+ "agent_id": agent_id,
+ },
+ )
+ return code, result
+
+ complete = turn_run_once.write_turn_validated_completion
+ if interruption is not None:
+
+ def lose_terminal_attempt(**kwargs):
+ assert _effect_kinds(runtime, _turn_journal(runtime)) == [
+ "refresh_state",
+ "quota_spend",
+ ]
+ if interruption == "lost_completion_receipt":
+ applied = complete(**kwargs)
+ assert applied["ok"] and applied["completed"], applied
+ raise OSError("injected terminal completion interruption")
+
+ monkeypatch.setattr(
+ turn_run_once, "write_turn_validated_completion", lose_terminal_attempt
+ )
+ code, result = invoke("--todo-id", todo_id)
+ journal = _turn_journal(runtime)
+ if interruption is not None:
+ assert code == 1 and journal["status"] == "in_progress", result
+ assert journal["completed_phases"][-1] == "quota_spend"
+ assert _effect_kinds(runtime, journal) == ["refresh_state", "quota_spend"]
+ assert _cli(registry, runtime, *lease_argv)[1]["active"] is (
+ interruption == "after_debit"
+ )
+ monkeypatch.setattr(turn_run_once, "write_turn_validated_completion", complete)
+ code, result = invoke(
+ "--resume-turn-key", journal["turn_key"], "--retry-failed-turn"
+ )
+ assert code == 0 and result["status"] == "committed", result.get(
+ "error"
+ ) or result.get("reason")
+ assert _turn_journal(runtime)["terminal_closeout"]["completion"] == {
+ "todo_id": todo_id,
+ "continuation": "no_followup",
+ }
+ assert len(lease_reads) == (2 if interruption == "after_debit" else 1)
+ assert _cli(registry, runtime, *lease_argv)[1]["active"] is False
+ assert _effect_kinds(runtime, journal) == [
+ "refresh_state",
+ "quota_spend",
+ "todo_complete",
+ ]
+ code, replay = invoke("--resume-turn-key", journal["turn_key"])
+ assert code == 0 and replay["replayed"] is True, replay
+ assert not any(replay["effects"].values())
+ assert host_calls == [journal["turn_key"]]
+ assert _effect_kinds(runtime, journal) == [
+ "refresh_state",
+ "quota_spend",
+ "todo_complete",
+ ]
+
+
+def test_builtin_codex_advertises_explicit_completion_without_promoting_progress() -> (
+ None
+):
+ kinds = codex_cli_result_schema()["properties"]["result_kind"]["enum"]
+ assert "validated_completion" in kinds and "validated_progress" in kinds
diff --git a/tests/test_global_todos.py b/tests/test_global_todos.py
index 1f2b578a63..a6d3c6bb6a 100644
--- a/tests/test_global_todos.py
+++ b/tests/test_global_todos.py
@@ -1,7 +1,13 @@
from pathlib import Path
from typing import Any
+import pytest
+
import loopx.global_todos as global_todos
+from loopx.control_plane.goals.contract_health import (
+ contract_error_diagnostic,
+ contract_error_views,
+)
def build_payload(
@@ -137,6 +143,32 @@ def test_global_todos_error_redacts_local_paths(tmp_path) -> None:
assert "" in payload["error"]
+@pytest.mark.parametrize("failure", ["global_contract", "unknown_goal", "registry"])
+def test_global_todos_keeps_unverified_scope_unavailable(monkeypatch, tmp_path, failure) -> None:
+ diagnostic = contract_error_diagnostic(code="canonical_authority_required",
+ message="Unavailable canonical source.", goal_id="unknown" if failure == "unknown_goal" else "cold")
+ diagnostics = [diagnostic]
+ if failure == "global_contract":
+ diagnostics.append(contract_error_diagnostic(code="registry_contract", message="Global contract failed."))
+ status = {
+ **status_for("ready"),
+ "ok": False,
+ "global_registry": {"available": True, "ok": failure != "registry"},
+ "contract": {"ok": False, **contract_error_views(diagnostics)},
+ "run_history": {"goals": [
+ {"id": "ready", "registry_member": True},
+ {"id": "cold", "registry_member": True},
+ ]},
+ }
+ calls = patch_manager_reads(monkeypatch, status=status, quotas={})
+
+ payload = build_payload(tmp_path)
+
+ assert payload["ok"] is False
+ assert "todos" not in payload
+ assert calls == {"status": 1, "quota": []}
+
+
def test_global_todos_error_survives_projection_runtime_failure(monkeypatch) -> None:
monkeypatch.setattr(
global_todos,
diff --git a/tests/test_lark_private_conversations.py b/tests/test_lark_private_conversations.py
index 393ee609af..bef4c20103 100644
--- a/tests/test_lark_private_conversations.py
+++ b/tests/test_lark_private_conversations.py
@@ -4040,6 +4040,108 @@ def test_app_projection_refuses_a_replaced_provider_identity(ordinary): # noqa:
runtime.close()
+@pytest.mark.parametrize("fault", ["revoked", "provider_changed", "body_changed"])
+def test_app_projection_checks_current_authority_after_reading_original_source(ordinary, monkeypatch, fault): # noqa: F811
+ store, runtime, provider, transport, original, turns, before = _app_projection_journey(ordinary)
+ sid = original["session_id"]
+ transcript = store.sessions_root / sid / "messages.jsonl"
+ request_path = transport.root / f"{original['request_ref']}.json"
+ source_id = json.loads(request_path.read_text())["event"]["message_id"]
+ call = Provider.__call__
+ previewed = changed = False
+
+ def change_after_source_read(self, args, *pos, **kwargs):
+ nonlocal previewed, changed
+ result = call(self, args, *pos, **kwargs)
+ if "+messages-send" in args and "--dry-run" in args:
+ previewed = True
+ elif (previewed and not changed and "+messages-mget" in args
+ and args[args.index("--message-ids") + 1] == source_id):
+ if fault == "revoked":
+ transport.bindings.disconnect(original["binding_id"], expected_revision=transport.bindings.read()["revision"])
+ elif fault == "provider_changed":
+ provider.profile_apps["notes-app"] = "cli_replaced_app"
+ else:
+ messages = store.messages(sid)
+ next(message for message in messages if message.get("turn_id") == turns[0])["text"] = "Changed during source read"
+ transcript.write_text("".join(json.dumps(message) + "\n" for message in messages))
+ changed = True
+ return result
+
+ try:
+ starts = ordinary[4].read_bytes()
+ monkeypatch.setattr(Provider, "__call__", change_after_source_read)
+ transport._web_projection_scan_at = 0
+ path, = transport._web_projection_paths()
+ assert transport.reconcile_request(path) == 0
+ assert changed and len(provider.writes) == before
+ assert ordinary[4].read_bytes() == starts
+ assert not any(phase.get("started") for phase in transport._read_web_projection_journal(path)["deliveries"].values())
+ finally:
+ runtime.close()
+
+
+@pytest.mark.parametrize("lock_at", ["read", "writeback"])
+def test_busy_app_body_does_not_delay_feedback_for_another_session(ordinary, monkeypatch, lock_at): # noqa: F811
+ from contextlib import ExitStack
+
+ from loopx.file_lock import exclusive_file_lock, lock_incident_path
+
+ _store, runtime, provider, transport = connect(ordinary)
+ try:
+ for profile in ("notes-app", "steward-app"):
+ event = provider.event(profile, f"feedback-source-{profile}", "Admit the original private conversation")
+ transport.admit(profile, event)
+ request = transport.core.read_request(identity_ref(transport._binding(profile)["provider_ref"], event["message_id"]))
+ sid = request["session_id"]
+ assert runtime.wait_for_turn(session_id=sid, turn_id=request["turn_id"], timeout_sec=10)["status"] == "completed"
+ transport.reconcile_request(transport.root / f"{request['request_ref']}.json")
+ status, turn = ordinary[3](f"/api/chat/sessions/{sid}/turns", {"message": "New App input", "client_turn_id": "feedback"})
+ assert status == 202
+ assert runtime.wait_for_turn(session_id=sid, turn_id=turn["turn_id"], timeout_sec=10)["status"] == "completed"
+
+ transport._web_projection_scan_at = 0
+ busy, ready = sorted(transport._web_projection_paths())
+ targets = {}
+ for path in (busy, ready):
+ assert transport.reconcile_request(path) == 1
+ row = transport._read_web_projection_journal(path)
+ phase, = row["deliveries"].values()
+ assert phase["verified"] and phase["feedback"] == {}
+ targets[path] = (row["profile"], phase["attempt"]["message_ref"], "Get")
+
+ with ExitStack() as body_worker, monkeypatch.context() as patch:
+ body_lock = exclusive_file_lock(busy, operation="deliver_web_conversation_projection")
+ if lock_at == "read":
+ body_worker.enter_context(body_lock)
+ else:
+ feedback = transport._web_projection_feedback
+ busy_session = transport._read_web_projection_journal(busy)["session_id"]
+
+ def hold_body_after_feedback(row, message):
+ feedback(row, message)
+ if row["session_id"] == busy_session:
+ assert targets[busy] in provider.reaction_creates
+ body_worker.enter_context(body_lock)
+
+ patch.setattr(transport, "_web_projection_feedback", hold_body_after_feedback)
+
+ transport.reconcile_app_feedback()
+ assert not lock_incident_path(busy).exists()
+ busy_phase, = transport._read_web_projection_journal(busy)["deliveries"].values()
+ assert busy_phase["feedback"] == {}
+ assert (targets[busy] in provider.reaction_creates) == (lock_at == "writeback")
+ assert targets[ready] in provider.reaction_creates
+ ready_phase, = transport._read_web_projection_journal(ready)["deliveries"].values()
+ assert ready_phase["feedback"]["ok"]
+ transport.reconcile_app_feedback()
+ assert all(provider.reaction_creates.count(target) == 1 for target in targets.values())
+ busy_phase, = transport._read_web_projection_journal(busy)["deliveries"].values()
+ assert busy_phase["feedback"]["ok"]
+ finally:
+ runtime.close()
+
+
@pytest.mark.parametrize("fault", ["revoked", "app", "source", "session", "turn", "context_recovery"])
def test_app_feedback_rechecks_exact_source_and_turn_after_mirror_delivery(ordinary, monkeypatch, fault): # noqa: F811
store, runtime, provider, transport, original, turns, before = _app_projection_journey(ordinary)
diff --git a/tests/test_loopx_turn_driver.py b/tests/test_loopx_turn_driver.py
index b5b0b3464d..65682ba1ff 100644
--- a/tests/test_loopx_turn_driver.py
+++ b/tests/test_loopx_turn_driver.py
@@ -1850,6 +1850,7 @@ def _write_live_fixture(
},
"quota": {"compute": 1.0, "window_hours": 24},
"coordination": {
+ **({"handoff_mode": handoff_mode} if handoff_mode != "soft_claim" else {}),
"agent_model": "peer_v1",
"registered_agents": ["codex-fixture"],
"agent_profiles": {
diff --git a/tests/test_manager_context_roundtrip.py b/tests/test_manager_context_roundtrip.py
index 2a396f4c1c..60ab6e7d72 100644
--- a/tests/test_manager_context_roundtrip.py
+++ b/tests/test_manager_context_roundtrip.py
@@ -136,6 +136,34 @@ def test_frozen_private_reply_projects_original_text_without_mutating_model_inpu
assert {str(p): p.read_bytes() for p in store.root.rglob("*") if p.is_file()} == before
+def test_saved_answer_reads_only_its_original_question_and_exact_answer(frozen_private_reply, private_snapshot):
+ store, session, turn, _, _, _, source_text, _ = frozen_private_reply
+ sid, tid = session["session_id"], turn["turn_id"]
+ answer = store.append_message(sid, role="agent", text="The saved answer", turn_id=tid)
+ store.append_message(sid, role="agent", text="Later answer from the same Turn", turn_id=tid)
+ no_turn = store.append_message(sid, role="agent", text="An older saved answer without a Turn")
+ other_session = store.create_session(goal_id="notes", agent_id="codex", adapter_kind="codex_app_server",
+ upstream_thread_id="another-conversation")
+ foreign = store.append_message(other_session["session_id"], role="agent", text="An answer from another Session")
+ journal = store.sessions_root / sid / "messages.jsonl"
+ before = journal.read_bytes()
+
+ response = private_snapshot(report_message_id=answer["message_id"])
+ assert response["session"]["session_id"] == sid
+ assert response["report_message_id"] == answer["message_id"]
+ assert response["active_turn"] is None
+ question, saved = response["messages"]
+ assert question["reply_context"]["source_text"] == source_text
+ assert saved == answer
+ assert private_snapshot(report_message_id=answer["message_id"], turn_id=tid) == response
+ assert private_snapshot(report_message_id=answer["message_id"], turn_id="unrelated-turn")["messages"] == []
+ assert private_snapshot(report_message_id=no_turn["message_id"])["messages"] == [no_turn]
+ for unavailable in (foreign["message_id"], question["message_id"]):
+ assert private_snapshot(report_message_id=unavailable)["messages"] == []
+ private_snapshot(report_message_id=answer["message_id"], message_limit=200, expected_status=400)
+ assert journal.read_bytes() == before
+
+
def test_history_pages_reuse_unchanged_journal_but_reread_provider_receipts(
frozen_private_reply, private_snapshot, monkeypatch):
store, session, turn, request, *_ = frozen_private_reply
diff --git a/tests/test_readme_presentation.py b/tests/test_readme_presentation.py
index a338c54009..bb2df59f4d 100644
--- a/tests/test_readme_presentation.py
+++ b/tests/test_readme_presentation.py
@@ -29,7 +29,7 @@ def handle_endtag(self, tag: str) -> None:
self.link = None
-@pytest.mark.parametrize("readme", ["README.md", "README.zh-CN.md"])
+@pytest.mark.parametrize("readme", ["README.md", "README.zh-CN.md", "README.ja.md"])
def test_trending_achievement_is_linked_once_in_readme_hero(readme: str) -> None:
text = (REPO_ROOT / readme).read_text(encoding="utf-8")
document = LinkedImages()