diff --git a/loopx/control_plane/quota/cli_projection.py b/loopx/control_plane/quota/cli_projection.py index 1409e20028..e72626fd2f 100644 --- a/loopx/control_plane/quota/cli_projection.py +++ b/loopx/control_plane/quota/cli_projection.py @@ -489,105 +489,50 @@ def _promote_interaction_contract(payload: dict[str, Any]) -> dict[str, Any]: return promoted -def _reference_inline_goal_acceptance(payload: dict[str, Any]) -> dict[str, Any]: - """Share exact JSON copies in this display only; never trim the contract. - - Work context is the preferred full carrier, then the planning horizon. - This Python CLI adapter only changes serialization after owner decisions; - canonical state, captures and replan context construction remain untouched. - """ - paths: list[tuple[str | int, ...]] = [] - interaction = payload.get("interaction_contract") - channel = interaction.get("agent_channel") if isinstance(interaction, dict) else None - context = channel.get("work_context") if isinstance(channel, dict) else None - sources = context.get("sources") if isinstance(context, dict) else None - for index, source in enumerate(sources if isinstance(sources, list) else []): - if (isinstance(source, dict) and source.get("source") == "goal_acceptance" - and isinstance(source.get("content"), dict) - and source["content"].get("status", "loaded") == "loaded" - and isinstance(source["content"].get("goal_acceptance_contract"), dict) - and source["content"]["goal_acceptance_contract"]): - paths.append(("interaction_contract", "agent_channel", "work_context", - "sources", index, "content", "goal_acceptance_contract")) - break - paths.extend([ - ("planning_horizon", "core_goal", "acceptance_contract"), - ("autonomous_replan_obligation", "replan_context", "core_goal", "acceptance_contract"), - ("agent_todo_summary", "goal_acceptance_contract"), - ]) - carriers: dict[str, str] = {} - relocated: dict[str, str] = {} - references: list[tuple[tuple[str | int, ...], str]] = [] - result = payload - - def writable_parent(path: tuple[str | int, ...]) -> dict[str, Any]: - nonlocal result - # Copy only the affected spine; never mutate caller-owned facts. - result = dict(result) - target: Any = result - for part in path[:-1]: - child = target[part] - target[part] = list(child) if isinstance(child, list) else dict(child) - target = target[part] - return cast(dict[str, Any], target) - - for path in paths: - parent: Any = result - for part in path[:-1]: - if isinstance(parent, dict) and isinstance(part, str): - parent = parent.get(part) - elif isinstance(parent, list) and isinstance(part, int) and part < len(parent): - parent = parent[part] - else: - parent = None - break - field = str(path[-1]) - existing = parent.get(field + "_ref") if isinstance(parent, dict) else None - if isinstance(existing, str): - references.append((path, existing)) - value = parent.get(field) if isinstance(parent, dict) else None - if not isinstance(value, dict) or not value or field + "_ref" in parent: - continue - # Keep complete revision, scope, failures and sources in the identity. - encoded = _json_content_key(value) - reference = carriers.get(encoded) - own_ref = "$" + "".join( - f"[{part}]" if isinstance(part, int) else f".{part}" for part in path) - if reference is None: - carriers[encoded] = own_ref - continue - if len(encoded) <= len(reference) + 8: - continue - target = writable_parent(path) - del target[field] - target[field + "_ref"] = reference - relocated[own_ref] = reference - # Retarget only references to owners actually moved by this projection. - # A later owner can move after an earlier alias was visited; a second pass - # keeps both directions direct without following arbitrary input chains. - for path, reference in references: - if reference in relocated: - writable_parent(path)[str(path[-1]) + "_ref"] = relocated[reference] - return result - - def _reference_context( payload: dict[str, Any], *, task_title: bool = True, explore_guidance: bool = True, - diagnostics: dict[str, Any] | None = None, + goal_acceptance: bool = False, diagnostics: dict[str, Any] | None = None, ) -> dict[str, Any]: """One coarse transport call for the existing typed context owner.""" contract = payload.get("interaction_contract") agent = contract.get("agent_channel") if isinstance(contract, dict) else None context = agent.get("work_context") if isinstance(agent, dict) else None - # No source carrier means neither operation can act. Leave semantic matching - # and reference validation in TypeScript, rather than replicating its rules. - if diagnostics is None and (not (task_title or explore_guidance) or not isinstance(context, dict) or not context.get("sources")): - return payload + sources = context.get("sources") if isinstance(context, dict) else None + needs_context = bool(sources) and (task_title or explore_guidance) + if not needs_context and (diagnostics is None or ( + diagnostics.get("agent_detail") is True and diagnostics.get("user_detail") is True + )): + if not goal_acceptance: + return payload + # A reference can only be created or relocated when two literal owners + # are present. Check structural presence here, leave equality, schema + # and the choice of owner to TypeScript. + def contains_contract(value: Any, *path: str) -> bool: + for key in path: + value = value.get(key) if isinstance(value, dict) else None + return isinstance(value, dict) and bool(value) + + carriers = ( + any(contains_contract(row, "content", "goal_acceptance_contract") for row in sources) + if isinstance(sources, list) else False, + contains_contract(payload, "planning_horizon", "core_goal", "acceptance_contract"), + contains_contract(payload, "autonomous_replan_obligation", "replan_context", "core_goal", "acceptance_contract"), + contains_contract(payload, "agent_todo_summary", "goal_acceptance_contract"), + ) + if sum(carriers) < 2: + return payload from .turn_envelope import _turn_envelope_result - result = _turn_envelope_result("reference_context", payload=payload, + # The typed projection reads and edits these roots. Untouched capture + # facts stay local. Apply the returned paths against the original payload. + source = {key: payload[key] for key in ( + "mode", "groups", "next_automatic_turn", "agent_todo_summary", "user_todo_summary", + "todo_summary_projection", "planning_horizon", "autonomous_replan_obligation", + "interaction_contract", "agent_lane_next_action", "selected_todo", + ) if key in payload} + result = _turn_envelope_result("reference_context", payload=source, task_title=task_title, explore_guidance=explore_guidance, - **({"diagnostics": diagnostics} if diagnostics is not None else {})) + goal_acceptance=goal_acceptance, **({"diagnostics": diagnostics} if diagnostics is not None else {})) return _apply_context_projection_changes(payload, result) @@ -706,14 +651,13 @@ def compact_quota_should_run_cli_payload( agent_lane_next_action = dict(agent_lane_next_action) agent_lane_next_action.pop("content_revision", None) compact["agent_lane_next_action"] = agent_lane_next_action - compact = _reference_inline_goal_acceptance(compact) diagnostics = None if ((not include_todo_summary_detail and isinstance(payload.get("agent_todo_summary"), dict)) or (not include_user_todo_summary_detail and isinstance(payload.get("user_todo_summary"), dict))): diagnostics = {"agent_detail": include_todo_summary_detail, "user_detail": include_user_todo_summary_detail} compact = _reference_context(compact, task_title=not include_todo_summary_detail, - explore_guidance=not include_vision_detail, diagnostics=diagnostics) + explore_guidance=not include_vision_detail, goal_acceptance=True, diagnostics=diagnostics) return _promote_interaction_contract( _promote_runtime_capability_reentry(compact) ) diff --git a/loopx/control_plane/quota/turn_envelope.py b/loopx/control_plane/quota/turn_envelope.py index 7b1111fede..85e58fc392 100644 --- a/loopx/control_plane/quota/turn_envelope.py +++ b/loopx/control_plane/quota/turn_envelope.py @@ -56,7 +56,11 @@ def _turn_envelope_result( """Call the coarse TS owner and fail closed on transport shape drift.""" request = {"operation": operation, **params} - if operation in {"context_delivery", "context_recovery", "progressive_context_delivery", "context_read_sections"}: + if operation == "reference_context" and params.get("goal_acceptance"): + tokens = source_number_tokens(params["payload"]) + if tokens: + request["source_number_tokens"] = tokens + elif operation in {"context_delivery", "context_recovery", "progressive_context_delivery", "context_read_sections"}: tokens = source_number_tokens(params) if tokens: request["source_number_tokens"] = tokens diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 508e710673..98d66c5ab1 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -1,6 +1,6 @@ import {capturedContextSelection} from "./context_selection.ts"; import {contextReadSectionDigests, initialContextReadPointers, prepareProgressiveContext, prepareProgressiveContextDelivery} from "./progressive_context.ts"; -import {contextProjectionChanges, projectQuotaDiagnostics} from "./diagnostic_projection.ts"; +import {contextProjectionChanges, contextSourceIdentity, projectQuotaDiagnostics} from "./diagnostic_projection.ts"; import type { LoopXTurnRouteValue } from "../turn_driver/turn_contract_generated.ts"; import { EffectiveAction, type QuotaEffectiveActionValue } from "./effective_action.generated.ts"; import { createHash } from "node:crypto"; @@ -250,6 +250,111 @@ function resolveExploreGuidance(payload: JsonObject, context: JsonObject): JsonO })}; } +/** Existing acceptance carriers only: this is not a general JSON-path codec. + * The loaded work context is preferred, then the complete planning/replan facts. + */ +function acceptanceCarriers(payload: JsonObject) { + // Keep read-only carrier parents attached to their source. The general + // object() helper intentionally returns copies for projection callers. + const carrierObject = (value: unknown): JsonObject => + typeof value === "object" && value !== null && !Array.isArray(value) + ? value as JsonObject : {}; + const carriers: {parent: JsonObject; field: string; path: string; parentPath: (string | number)[]}[] = []; + const sources = carrierObject(carrierObject(carrierObject(payload.interaction_contract).agent_channel).work_context).sources; + if (Array.isArray(sources)) { + const index = sources.findIndex(value => { + const source = carrierObject(value), content = carrierObject(source.content); + return source.source === "goal_acceptance" && + (content.status === undefined || content.status === "loaded") && + Object.keys(carrierObject(content.goal_acceptance_contract)).length > 0; + }); + if (index >= 0) carriers.push({parent: carrierObject(carrierObject(sources[index]).content), + field: "goal_acceptance_contract", + parentPath: ["interaction_contract", "agent_channel", "work_context", "sources", index, "content"], + path: `$.interaction_contract.agent_channel.work_context.sources[${index}].content.goal_acceptance_contract`}); + } + carriers.push( + {parent: carrierObject(carrierObject(payload.planning_horizon).core_goal), field: "acceptance_contract", + parentPath: ["planning_horizon", "core_goal"], + path: "$.planning_horizon.core_goal.acceptance_contract"}, + {parent: carrierObject(carrierObject(carrierObject(payload.autonomous_replan_obligation).replan_context).core_goal), + field: "acceptance_contract", path: "$.autonomous_replan_obligation.replan_context.core_goal.acceptance_contract", + parentPath: ["autonomous_replan_obligation", "replan_context", "core_goal"]}, + {parent: carrierObject(payload.agent_todo_summary), field: "goal_acceptance_contract", + parentPath: ["agent_todo_summary"], + path: "$.agent_todo_summary.goal_acceptance_contract"}, + ); + return carriers; +} + +function inlineAcceptance(payload: JsonObject, reference: unknown): JsonObject { + // Older captures may name any loaded work-context carrier, not only the + // preferred first source chosen for new sharing. + const match = typeof reference === "string" + ? /^\$\.interaction_contract\.agent_channel\.work_context\.sources\[(0|[1-9]\d*)\]\.content\.goal_acceptance_contract$/.exec(reference) : null; + if (match) { + const sources = object(object(object(payload.interaction_contract).agent_channel).work_context).sources; + const source = object(Array.isArray(sources) ? sources[Number(match[1])] : null); + const content = object(source.content); + if (source.source === "goal_acceptance" && + (content.status == null || content.status === "loaded") && + !Object.hasOwn(content, "goal_acceptance_contract_ref") && + Object.keys(object(content.goal_acceptance_contract)).length) { + return object(content.goal_acceptance_contract); + } + } + const carrier = acceptanceCarriers(payload).find(item => item.path === reference); + const value = object(carrier?.parent[carrier.field]); + if (!carrier || Object.hasOwn(carrier.parent, `${carrier.field}_ref`) || !Object.keys(value).length) { + throw new EffectRuntimeRequestError("Goal acceptance reference must resolve to complete inline work context or planning facts"); + } + return value; +} + +function referenceGoalAcceptance(payload: JsonObject, + identity = contextSourceIdentity(payload)): JsonObject { + let result = payload; + // Copy only a changed registered carrier's spine. Retained source objects + // keep their identity for the display-edit transport and original numbers. + const writableParent = (path: (string | number)[]): JsonObject => { + result = {...result}; + let target: Record = result; + for (const key of path) { + const value = target[key]; + target[key] = Array.isArray(value) ? [...value] : {...requireJsonObject(value, "acceptance carrier")}; + target = target[key] as Record; + } + return target; + }; + const owners = new Map(); + const relocated = new Map(); + const carriers = acceptanceCarriers(payload); + for (const {parent, field, path, parentPath} of carriers) { + const value = object(parent[field]); + if (!Object.keys(value).length || Object.hasOwn(parent, `${field}_ref`)) continue; + // Complete canonical JSON distinguishes booleans/numbers, revisions, + // provenance and negative evidence. Never deduplicate a prose summary. + const encoded = identity(value, [...parentPath, field]); + const owner = owners.get(encoded); + if (!owner) owners.set(encoded, path); + else if (Buffer.byteLength(JSON.stringify(canonicalValue(value)), "utf8") > Buffer.byteLength(owner, "utf8") + 8) { + const target = writableParent(parentPath); + delete target[field]; + target[`${field}_ref`] = owner; + relocated.set(path, owner); + } + } + // A historical source can already reference a carrier that was just shared. + // Rebind that exact reference to the retained inline owner, never a chain. + for (const {parent, field, parentPath} of carriers) { + const reference = parent[`${field}_ref`]; + if (typeof reference === "string" && relocated.has(reference)) { + writableParent(parentPath)[`${field}_ref`] = relocated.get(reference); + } + } + return result; +} + function referenceExploreGuidance(payload: JsonObject): JsonObject { const interaction = object(payload.interaction_contract), agent = object(interaction.agent_channel); const context = object(agent.work_context); @@ -401,18 +506,9 @@ function replanGoalContext(payload: JsonObject, reads: JsonObject | null, coreRe function indexedGoal(value: unknown): JsonObject { const core = {...object(value)}; if (!("acceptance_contract" in core) && "acceptance_contract_ref" in core) { - const match = typeof core.acceptance_contract_ref === "string" - ? /^\$\.interaction_contract\.agent_channel\.work_context\.sources\[(0|[1-9]\d*)\]\.content\.goal_acceptance_contract$/.exec(core.acceptance_contract_ref) : null; - const sources = object(object(object(payload.interaction_contract).agent_channel).work_context).sources; - const source = object(match && Array.isArray(sources) ? sources[Number(match[1])] : null); - const content = object(source.content); - if (!match || source.source !== "goal_acceptance" - || content.status != null && content.status !== "loaded" - || !Object.keys(object(content.goal_acceptance_contract)).length) { - throw new EffectRuntimeRequestError("Goal acceptance reference must resolve to complete inline work context"); - } + const acceptance = inlineAcceptance(payload, core.acceptance_contract_ref); delete core.acceptance_contract_ref; - core.acceptance_contract = content.goal_acceptance_contract; + core.acceptance_contract = acceptance; } const acceptance = {...object(core.acceptance_contract)}; const requirements = object(acceptance.outcome_requirements); @@ -1486,6 +1582,8 @@ export function evaluateTurnEnvelope(value: unknown): JsonObject { const source = requireJsonObject(request.payload, "quota decision"); let payload = source; if (jsonObject(request.diagnostics)) payload = projectQuotaDiagnostics(payload, request.diagnostics as JsonObject); + if (request.goal_acceptance === true) payload = referenceGoalAcceptance(payload, + contextSourceIdentity(source, request.source_number_tokens)); if (request.task_title === true) payload = referenceCurrentTaskTitle(payload); if (request.explore_guidance === true) payload = referenceExploreGuidance(payload); if (request.refresh_result === true) payload = referenceExploreResultDelivery(payload, request.source_number_tokens); diff --git a/tests/control_plane/test_quota_acceptance_readback.py b/tests/control_plane/test_quota_acceptance_readback.py new file mode 100644 index 0000000000..0d9d45fcea --- /dev/null +++ b/tests/control_plane/test_quota_acceptance_readback.py @@ -0,0 +1,94 @@ +"""A staged review follows exactly the acceptance reference emitted by the quota writer.""" +from copy import deepcopy +import hashlib +import json +import shlex +import subprocess +import sys + +import pytest +from test_quota_acceptance_references import packet +from loopx.control_plane.quota.cli_projection import compact_quota_should_run_cli_payload +from loopx.control_plane.quota.turn_envelope import build_turn_envelope + + +def run(argv): + result = subprocess.run(argv, capture_output=True, text=True) + return result.returncode, json.loads(result.stdout) + + +def staged_capture(tmp_path): + original = packet(with_context=False) + core = original["planning_horizon"]["core_goal"] + outcome = {"id": "goal", "revision": 7, "requirements": [{"id": "recover", "text": "Recover before retry."}]} + core["acceptance_contract"]["outcome_requirements"] = {"outcomes": [outcome]} + original["autonomous_replan_obligation"]["replan_context"]["core_goal"] = deepcopy(core) + source = compact_quota_should_run_cli_payload(original) + ref = source["autonomous_replan_obligation"]["replan_context"]["core_goal"]["acceptance_contract_ref"] + assert ref == "$.planning_horizon.core_goal.acceptance_contract" + return source, tmp_path / "decision.json", outcome + + +def read_review(source, capture): + capture.write_text(json.dumps(source)) + digest = build_turn_envelope(source)["action_signature"]["source_decision_hash"] + return run([sys.executable, "-m", "loopx.entrypoint", "--format", "json", "quota", "replan-view", + "--decision-file", str(capture), "--source-hash", digest, "--replan-stage", "review"]) + + +def test_staged_review_reads_the_planning_owner_advertised_by_the_quota_writer(tmp_path): + source, capture, outcome = staged_capture(tmp_path) + code, review = read_review(source, capture) + assert code == 0, review + index = review["acceptance_index"] + entry, = [r for r in index["outcomes"] if r["id"] == outcome["id"]] + argv = shlex.split(index["read_action_template"].replace("{outcome_ref}", entry["outcome_ref"])) + code, detail = run(argv) + assert code == 0 and detail["outcome"] == outcome, detail + assert json.loads(capture.read_bytes()) == source + + +@pytest.mark.parametrize("fault", ["missing", "chain", "literal-and-reference", "unregistered"]) +def test_staged_review_rejects_invalid_capture_reference(tmp_path, fault): + source, capture, _ = staged_capture(tmp_path) + target = source["planning_horizon"]["core_goal"] + ref = source["autonomous_replan_obligation"]["replan_context"]["core_goal"] + if fault in ("missing", "chain"): + del target["acceptance_contract"] + if fault in ("chain", "literal-and-reference"): + target["acceptance_contract_ref"] = "$.agent_todo_summary.goal_acceptance_contract" + if fault == "unregistered": + ref["acceptance_contract_ref"] = "$.arbitrary.acceptance_contract" + # A signature over these exact contents isolates the read from any hash failure. + # The build path may also reject invalid planning facts, so use native JSON's + # number rendering when independently computing the synthetic source hash. + data = json.dumps(source, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + canonical = subprocess.check_output(["node", "-p", "JSON.stringify(JSON.parse(require('fs').readFileSync(0,'utf8')))"], + input=data).rstrip(b"\n") + digest = "sha256:" + hashlib.sha256(canonical).hexdigest() + capture.write_bytes(data) + code, error = run([sys.executable, "-m", "loopx.entrypoint", "--format", "json", "quota", "replan-view", + "--decision-file", str(capture), "--source-hash", digest, "--replan-stage", "review"]) + assert code != 0 and "Goal acceptance reference" in error["reason"], error + assert capture.read_bytes() == data + +def test_acceptance_sharing_keeps_unrelated_facts_outside_the_projection_request(monkeypatch): + from loopx.control_plane.quota import turn_envelope + + source = packet(with_context=False) + extra = {"negative_evidence": "Retain the full original observation. " * 128, + "exact_integer": 2**60 + 1} + source["future_observation"] = deepcopy(extra) + calls = [] + evaluate = turn_envelope.effect_runtime_projection_result + + def observe(method, params, **kwargs): + if params["operation"] == "reference_context": + calls.append(params["payload"]) + return evaluate(method, params, **kwargs) + + monkeypatch.setattr(turn_envelope, "effect_runtime_projection_result", observe) + result = compact_quota_should_run_cli_payload(source) + assert len(calls) == 1 and "future_observation" not in calls[0] + assert result["future_observation"] == source["future_observation"] == extra + assert result["agent_todo_summary"]["goal_acceptance_contract_ref"] == "$.planning_horizon.core_goal.acceptance_contract" diff --git a/tests/control_plane/test_quota_acceptance_references.py b/tests/control_plane/test_quota_acceptance_references.py index 79f718c0c4..cc5f7b8e7c 100644 --- a/tests/control_plane/test_quota_acceptance_references.py +++ b/tests/control_plane/test_quota_acceptance_references.py @@ -1,11 +1,12 @@ """Display sharing preserves the complete acceptance and executable decisions.""" from copy import deepcopy import json +from functools import partial import pytest from loopx.control_plane.quota.cli_projection import ( - _reference_inline_goal_acceptance, compact_quota_should_run_cli_payload, + _reference_context, compact_quota_should_run_cli_payload, ) from loopx.control_plane.quota.turn_envelope import ( build_turn_envelope, quota_action_signature_document, @@ -14,6 +15,9 @@ from test_replan_host_context_projection import _quota_payload +share_acceptance = partial(_reference_context, task_title=False, explore_guidance=False, goal_acceptance=True) + + def acceptance(): return {"revision": 3, "scope": {"kind": "all_advancement"}, "status": "failed", "requirements": [{"id": "original", "text": "Keep the complete original requirement. " * 20}, @@ -41,9 +45,9 @@ def packet(with_context=True): def test_exact_copies_share_one_complete_source_without_changing_signed_action(with_context): source = packet(with_context) original = deepcopy(source) - shared = _reference_inline_goal_acceptance(source) + shared = share_acceptance(source) assert source == original - assert _reference_inline_goal_acceptance(shared) == shared + assert share_acceptance(shared) == shared ref = ("$.interaction_contract.agent_channel.work_context.sources[0].content.goal_acceptance_contract" if with_context else "$.planning_horizon.core_goal.acceptance_contract") assert shared["agent_todo_summary"]["goal_acceptance_contract_ref"] == ref @@ -77,7 +81,7 @@ def test_different_contracts_are_retained_in_full(change): changed["verification"]["passed"] = 0 # False == 0 in Python if change == "source": changed["sources"][0]["ref"] = "message:corrected" - shared = _reference_inline_goal_acceptance(source) + shared = share_acceptance(source) assert shared["autonomous_replan_obligation"]["replan_context"]["core_goal"]["acceptance_contract"] == changed assert "acceptance_contract_ref" not in shared["autonomous_replan_obligation"]["replan_context"]["core_goal"] @@ -88,7 +92,7 @@ def test_missing_or_malformed_carriers_never_create_dangling_references(missing) source["interaction_contract"]["agent_channel"]["work_context"] = missing source["planning_horizon"] = missing source["autonomous_replan_obligation"] = missing - shared = _reference_inline_goal_acceptance(source) + shared = share_acceptance(source) assert shared["agent_todo_summary"]["goal_acceptance_contract"] == acceptance() assert "goal_acceptance_contract_ref" not in shared["agent_todo_summary"] @@ -97,13 +101,13 @@ def test_unavailable_context_is_not_used_even_if_it_retains_old_content(): source = packet() content = source["interaction_contract"]["agent_channel"]["work_context"]["sources"][0]["content"] content["status"] = "unavailable" - shared = _reference_inline_goal_acceptance(source) + shared = share_acceptance(source) assert shared["planning_horizon"]["core_goal"]["acceptance_contract"] == acceptance() assert shared["agent_todo_summary"]["goal_acceptance_contract_ref"] == "$.planning_horizon.core_goal.acceptance_contract" assert build_turn_envelope(shared)["action"]["planning_horizon"]["core_goal"]["acceptance_contract"] == acceptance() -@pytest.mark.parametrize("project", [_reference_inline_goal_acceptance, compact_quota_should_run_cli_payload]) +@pytest.mark.parametrize("project", [share_acceptance, compact_quota_should_run_cli_payload]) @pytest.mark.parametrize("left,right", [(1, 1.0), (False, 0), (-0.0, 0), (2**60, 2**60 + 1), (2**60, float(2**60))]) def test_reference_transport_keeps_distinct_original_numbers_and_later_exact_owner(left, right, project): @@ -134,7 +138,7 @@ def test_existing_reference_follows_its_relocated_complete_owner(existing_owner) owner = ("$.planning_horizon.core_goal.acceptance_contract" if existing_owner == "planning" else "$.autonomous_replan_obligation.replan_context.core_goal.acceptance_contract") source["agent_todo_summary"]["goal_acceptance_contract_ref"] = owner - shared = _reference_inline_goal_acceptance(source) + shared = share_acceptance(source) assert shared["agent_todo_summary"]["goal_acceptance_contract_ref"] == ( "$.interaction_contract.agent_channel.work_context.sources[0].content.goal_acceptance_contract") envelope = build_turn_envelope(shared) @@ -148,12 +152,12 @@ def test_reference_visited_before_its_owner_is_retargeted_after_sharing(): del core["acceptance_contract"] core["acceptance_contract_ref"] = "$.autonomous_replan_obligation.replan_context.core_goal.acceptance_contract" original = json.dumps(source) - shared = _reference_inline_goal_acceptance(source) + shared = share_acceptance(source) assert shared["planning_horizon"]["core_goal"]["acceptance_contract_ref"] == ( "$.interaction_contract.agent_channel.work_context.sources[0].content.goal_acceptance_contract") assert shared["interaction_contract"]["agent_channel"]["work_context"]["sources"][0]["content"]["goal_acceptance_contract"] == acceptance() assert json.dumps(source) == original - assert _reference_inline_goal_acceptance(shared) == shared + assert share_acceptance(shared) == shared @pytest.mark.parametrize("reference", ["$.planning_horizon.core_goal.acceptance_contract", @@ -162,7 +166,7 @@ def test_unmoved_or_unknown_reference_is_not_inferred_or_rewritten(reference): source = packet(False) del source["agent_todo_summary"]["goal_acceptance_contract"] source["agent_todo_summary"]["goal_acceptance_contract_ref"] = reference - shared = _reference_inline_goal_acceptance(source) + shared = share_acceptance(source) assert shared["agent_todo_summary"]["goal_acceptance_contract_ref"] == reference assert shared["planning_horizon"]["core_goal"]["acceptance_contract"] == acceptance() @@ -170,10 +174,10 @@ def test_unmoved_or_unknown_reference_is_not_inferred_or_rewritten(reference): def test_shared_acceptance_survives_delta_and_lost_baseline_recovery(): from loopx.control_plane.quota.turn_envelope import prepare_context_delivery, restore_context_delivery - initial = _reference_inline_goal_acceptance(packet()) + initial = share_acceptance(packet()) changed = packet() changed["reason"] = "New feedback retains original requirements and publication stops." - current = _reference_inline_goal_acceptance(changed) + current = share_acceptance(changed) scope = dict(goal_id="fixture", agent_id="worker", session_id="session", context_epoch="one") baseline = prepare_context_delivery(initial, scope=scope, capture_id="one", surface="quota_packet") full = prepare_context_delivery(current, scope=scope, capture_id="two", surface="quota_packet") @@ -183,7 +187,7 @@ def test_shared_acceptance_survives_delta_and_lost_baseline_recovery(): for retained in (baseline, None): restored = restore_context_delivery(delta, baseline=retained, current=full)["context"] assert restored == current - assert _reference_inline_goal_acceptance(restored) == current + assert share_acceptance(restored) == current assert restored["interaction_contract"]["agent_channel"]["work_context"]["sources"][0]["content"]["goal_acceptance_contract"] == acceptance() @@ -207,7 +211,7 @@ def test_real_cli_reuses_complete_acceptance_for_selection_and_replan(tmp_path, "--document", str(document), "--expected-provider-revision", before["provider_revision"], "--operation-id", "source-requirements", "--execute") expected = call("goal-acceptance", "inspect", "--goal-id", GOAL)["goal_acceptance_contract"] - guard = call("quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, + guard = call("quota", "should-run", "--codex-app", "--context-delivery", "off", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", "turn-acceptance-sharing") assert guard["effective_action"] == "autonomous_replan_required" ref = "$.interaction_contract.agent_channel.work_context.sources[0].content.goal_acceptance_contract" @@ -233,11 +237,11 @@ def test_real_cli_reuses_complete_acceptance_for_selection_and_replan(tmp_path, "--document", str(document), "--expected-provider-revision", revision, "--operation-id", "link-export", "--execute") expected = call("goal-acceptance", "inspect", "--goal-id", GOAL)["goal_acceptance_contract"] - planning = call("quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, + planning = call("quota", "should-run", "--codex-app", "--context-delivery", "off", "--goal-id", GOAL, "--agent-id", AGENT, "--turn-instance-id", "turn-export-planning") assert planning["planning_horizon"]["core_goal"]["acceptance_contract"] == expected assert planning["agent_todo_summary"]["goal_acceptance_contract_ref"] == "$.planning_horizon.core_goal.acceptance_contract" - selected = call("quota", "should-run", "--codex-app", "--goal-id", GOAL, "--agent-id", AGENT, + selected = call("quota", "should-run", "--codex-app", "--context-delivery", "off", "--goal-id", GOAL, "--agent-id", AGENT, "--todo-id", added["todo_id"], "--turn-instance-id", "turn-export-delivery") assert selected["normal_delivery_allowed"] is True sources = selected["interaction_contract"]["agent_channel"]["work_context"]["sources"]