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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion loopx/capabilities/manager_context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -936,7 +936,9 @@ coordination runtime; neither root is moved and path containment stays enforced.
When the provider returned a trustworthy message locator before readback failed,
the same background pump persists that private attempt and later performs a
read-only verification. A matching message advances the original delivery to
`delivered` without sending again. Provider outages retain
`delivered` without sending again. When the project registry cannot be read,
the pump retries without changing delivery receipts. A legacy transaction may
not modify a receipt bound to an exact Goal instance. Provider outages retain
`verification_required`; a missing legacy locator, changed intent, missing
message, or verified mismatch becomes `explicit_unverified`. CLI, Manager read,
and Chat expose the same public-safe state and reason without returning the
Expand Down
7 changes: 3 additions & 4 deletions loopx/capabilities/manager_context/roundtrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -794,10 +794,9 @@ def clock() -> datetime:
# Keep one eligibility instant for the scan. The per-return transaction
# observes its own time after acquiring the route and source guards.
scan_at = clock()
try:
exact = load_project_registry(registry).get("profile_id") == SOURCE_SESSION_PROFILE_ID
except (OSError, ValueError, TypeError):
exact = False
# An unreadable registry cannot authorize legacy delivery. Let the hosted
# worker retry the scan without advancing any of its receipts.
exact = load_project_registry(registry).get("profile_id") == SOURCE_SESSION_PROFILE_ID
processed = 0
host = {
"root": root, "registry": registry, "store": store,
Expand Down
10 changes: 9 additions & 1 deletion loopx/control_plane/collaboration/return_delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,13 @@ function unavailableRecord(error: unknown): boolean {
|| typeof (error as NodeJS.ErrnoException)?.code === "string";
}

function deliveryProfileMatches(command: ReturnCommand, state: JsonObject): boolean {
// A legacy transition cannot honor a persisted exact identity or admission.
return command.exact || (state.goal_ref == null && state.status !== "admitted" && state.admission == null);
}

function pendingDelivery(command: ReturnCommand, state: JsonObject): boolean {
if (TERMINAL.has(String(state.status))) return false;
if (TERMINAL.has(String(state.status)) || !deliveryProfileMatches(command, state)) return false;
if (!command.exact || state.status !== "admitted") {
if (state.retry_at && command.nowMicros < returnClockMicros(state.retry_at)) return false;
}
Expand Down Expand Up @@ -552,6 +557,9 @@ export async function transactManagerReturnDelivery(value: unknown): Promise<Jso
if (command.request.phase === "prepare" && unavailableRecord(error)) return returnResponse();
throw error;
}
if (!deliveryProfileMatches(command, state)) {
throw new EffectRuntimeRequestError("saved return requires the exact delivery profile");
}
return command.request.phase === "prepare" ? prepareReturn(command, state) : finishReturn(command, state);
});
}
21 changes: 21 additions & 0 deletions tests/control_plane_ts/manager_return_transaction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,27 @@ test("concurrent exact admission is single flight and stale settlement cannot ov
} finally { await f.close(); }
});

test("a legacy transaction cannot rewrite a saved exact attempt", async () => {
const f = await fixture(true, true);
try {
const plan = await f.run("prepare");
const saved = await f.run("attempt", { ...plan, attempt });
const before = await readFile(f.statePath);
const legacy = { exact: false, now: "2026-01-02T03:06:05.123456+00:00",
facts: { error: "return_source_unavailable" } };
const scanned = await f.run("scan", { ...legacy, candidates: [{ request_id: id, result_key: "conclusion" }] });
assert.deepEqual(scanned.candidates, []);
const skipped = await f.run("prepare", legacy);
assert.equal(skipped.action, "skip");
assert.equal(skipped.processed, 0);
await assert.rejects(f.run("attempt", { ...saved, ...legacy, attempt }), /exact delivery profile/);
assert.deepEqual(await readFile(f.statePath), before);
const recovery = await f.run("prepare", { now: legacy.now });
assert.equal(recovery.action, "verify");
assert.deepEqual(recovery.attempt, attempt);
} finally { await f.close(); }
});

test("an ambiguous expired external admission never dispatches another send", async () => {
const f = await fixture(true, true);
try {
Expand Down
63 changes: 63 additions & 0 deletions tests/test_collaboration_goal_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -967,6 +967,69 @@ def verify(self, *_args):
assert observations == ['verified']


@pytest.mark.parametrize("exact", [False, True], ids=["legacy", "exact"])
@pytest.mark.parametrize("corrupt", [False, True], ids=["missing-registry", "malformed-registry"])
def test_unreadable_return_registry_preserves_the_original_attempt(tmp_path, monkeypatch, exact, corrupt):
monkeypatch.setattr("loopx.usage_ping.observe_verified_return", lambda: None)
registry = _create_source_registry(tmp_path)
if not exact:
registry.write_text(json.dumps({"goals": _source_payload(tmp_path, INSTANCE_A)["goals"]}))
store, session, receipt = _external_manager_request(tmp_path, registry)
state_path = _root(tmp_path) / "replies" / receipt["request_id"] / "conclusion.delivery.json"
attempt = {
"schema_version": "manager_return_delivery_attempt_v0", "provider": "lark",
"message_ref": "om_original_result", "intent_digest": "sha256:" + "a" * 64,
"provider_receipt": "sha256:" + "b" * 64,
}
calls = []

class Transport:
def send_with_attempt(self, route, _session, _turn, _text, record_attempt):
assert not calls, "the original provider write must not be repeated"
calls.append(("send", route["return_message_id"]))
record_attempt(attempt)
raise SystemExit("stopped after provider attempt")

def verify(self, route, current_session, _turn, _text, saved_attempt):
calls.append(("verify", route["return_message_id"]))
assert current_session["session_id"] == session["session_id"]
assert saved_attempt == attempt
return {"verification_performed": True, "reply_verified": True}

transport = Transport()
started = datetime(2026, 9, 28, tzinfo=timezone.utc)
with pytest.raises(SystemExit, match="stopped after provider attempt"):
drain(tmp_path, registry, store, transport, now=started)
original_state = state_path.read_bytes()
original_messages = store.messages(session["session_id"])
assert json.loads(original_state)["attempt"] == attempt
(send,) = calls

saved_registry = registry.with_suffix(".offline")
registry.rename(saved_registry)
later = started + timedelta(minutes=2)
try:
if corrupt:
registry.write_text("[")
with pytest.raises(ValueError if corrupt else FileNotFoundError):
drain(tmp_path, registry, ChatSessionStore(tmp_path), transport, now=later)
assert state_path.read_bytes() == original_state
assert store.messages(session["session_id"]) == original_messages
assert calls == [send]
finally:
saved_registry.replace(registry)

restored = later + timedelta(minutes=1)
assert drain(tmp_path, registry, ChatSessionStore(tmp_path), transport, now=restored) == 1
assert drain(tmp_path, registry, ChatSessionStore(tmp_path), transport, now=restored) == 0
assert calls == [("send", send[1]), ("verify", send[1])]
snapshot = _http_snapshot(tmp_path, registry, session["session_id"])
messages = [row for row in snapshot["messages"] if row.get("origin") == "manager_followup"]
assert len(messages) == 1
assert messages[0]["return_delivery"]["status"] == "delivered"
assert attempt["message_ref"] not in json.dumps(messages)


def test_long_lived_mcp_keeps_its_captured_instance_after_recreation(
tmp_path: Path,
) -> None:
Expand Down
Loading