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
126 changes: 35 additions & 91 deletions loopx/control_plane/quota/cli_projection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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)
)
Expand Down
6 changes: 5 additions & 1 deletion loopx/control_plane/quota/turn_envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
122 changes: 110 additions & 12 deletions loopx/control_plane/quota/turn_envelope.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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<string | number, unknown> = 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<string | number, unknown>;
}
return target;
};
const owners = new Map<string, string>();
const relocated = new Map<string, string>();
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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading