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
6 changes: 3 additions & 3 deletions benchmark/runtime/RUNTIME.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,9 @@ Darwin native-checkpoint refusal remains in force.

The host-side checkpoint preflight captures the complete original decision.
With context delivery enabled, its prompt supplies `quota context-project`
with that original path/hash for ordinary work. An admitted replan with staged
review and writeback commands uses the existing replan projection in a private
presentation. Its readers retain the original guard's path and hash. The
with that original path and hash. The shared presentation owner prepares the
initial review and writeback routes for an admitted replan from the verified
capture. Their readers retain the original guard's path and hash. The
projection command also carries the Goal, Agent, Turn and private cache location. The
native tool presents the saved decision using the same native lifecycle projector;
no guard, checkpoint, admission or debit is repeated. Cold delivery supplies the
Expand Down
10 changes: 0 additions & 10 deletions benchmark/runtime/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,16 +265,6 @@ def capture_before_replan(env: dict[str, str], receipt: dict[str, Any], body: st
from .context_delivery import preflight_context_instruction

assert guard_digest is not None
if guard.get("replan_read_path"):
from loopx.control_plane.quota.turn_envelope import _turn_envelope_result
from loopx.control_plane.turn_driver.decision_capture import write_decision_capture

# Replan's staged commands are derived from the original packet.
# Keep their source hash and path bound to that immutable capture.
view = _turn_envelope_result("replan_cli_view", payload=guard)
if view != guard:
source_path = capture_root / "checkpoint-start-view.json"
guard_digest = write_decision_capture(source_path, view)
reading = preflight_context_instruction(env, source_path, guard_digest,
receipt["turn_id"], guide_in_host=guide_in_host)
else:
Expand Down
20 changes: 18 additions & 2 deletions loopx/cli_commands/quota_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,12 +793,14 @@ def project_saved_context_capture(args: argparse.Namespace, *, hook_session: str
# Carry the now-active transport into its selection presentation, not
# into the immutable source or a second admission. Native lifecycle
# still owns when the following full/delta view can be published.
bind_capture_selection_transport(payload, args, capture_root=root)
transport = _capture_selection_transport_template(payload, args, capture_root=root)
prepared = prepare_codex_context(payload, directory=directory, capture_directory=cache,
goal_id=args.goal_id, agent_id=args.agent_id, surface="quota_packet",
capture_id=hashlib.sha256(raw).hexdigest(),
continuity_generation=getattr(args, "_context_delivery_generation", None),
progressive_enabled=activation["progressive_enabled"], hook_session=hook_session)
progressive_enabled=activation["progressive_enabled"], selection_command_args_template=transport,
captured_decision_path=str(path) if args.initial_read and activation["progressive_enabled"] else None,
hook_session=hook_session)
projected = prepared.delivery
native_prepared = True
if projected.get("schema_version") == "context_delivery_v1":
Expand Down Expand Up @@ -1033,6 +1035,20 @@ def fits(value: dict[str, object]) -> bool:
) from exc


def _capture_selection_transport_template(payload: dict[str, Any], args: argparse.Namespace, *,
capture_root: Path) -> str | None:
"""Derive display argv without editing the captured decision."""
interaction = payload.get("interaction_contract")
cli = interaction.get("cli_channel") if isinstance(interaction, dict) else None
selection = cli.get("selection_command") if isinstance(cli, dict) else None
if not isinstance(selection, dict):
return None
presentation = {**payload, "interaction_contract": {**interaction,
"cli_channel": {**cli, "selection_command": dict(selection)}}}
bind_capture_selection_transport(presentation, args, capture_root=capture_root)
return presentation["interaction_contract"]["cli_channel"]["selection_command"].get("command_args_template")


def bind_capture_selection_transport(payload: dict[str, Any], args: argparse.Namespace, *,
capture_root: Path | None = None) -> None:
"""Retain caller display/capture options in the existing selection command.
Expand Down
48 changes: 39 additions & 9 deletions loopx/control_plane/quota/progressive_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,14 +245,17 @@ export function progressiveContextPlan(request: JsonObject): JsonObject {

const pathStartsWith = (path: Path, start: Path) => start.every((key, i) => path[i] === key);

function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSourceValues):
function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSourceValues,
plan = progressiveContextPlan({payload: request.context, surface: request.surface})):
{context: JsonObject; tokens: [Path, string][]; projected: boolean} {
const context = requireJsonObject(request.context, "current projection");
const original = requireJsonObject(request.context, "current projection");
const staged = jsonObject(plan.staged_context);
const context = staged ?? original;
const details = requireJsonObject(request.native_projection, "supporting material reference");
const identity = contextSourceIdentity(request, request.source_number_tokens);
const plan = progressiveContextPlan({payload: context, surface: request.surface});
const deferred = plan.deferred as JsonObject[], references = (plan.references ?? []) as JsonObject[];
const instructions = plan.instructions as JsonObject[];
const edits = details.progressive_enabled === false ? {deferred: [], instructions: []} : plan;
const deferred = edits.deferred as JsonObject[], references = (edits.references ?? []) as JsonObject[];
const instructions = edits.instructions as JsonObject[];
const at = (root: unknown, path: Path): unknown => path.reduce<unknown>((row, key) =>
row !== null && typeof row === "object" && Object.hasOwn(row, key)
? (row as Record<string | number, unknown>)[key] : undefined, root);
Expand Down Expand Up @@ -310,7 +313,8 @@ function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSour
});
const sourcePath: Path = ["interaction_contract", "agent_channel", "work_context", "sources"];
const sources = at(context, sourcePath);
required.context_details = {...details, source_path: details.path,
required.context_details = {path: details.path, sha256: details.sha256,
command_template: details.command_template, source_path: details.path,
unread_context_index: {
source: {path: details.path, sha256: details.sha256},
coverage_confirmed: false,
Expand Down Expand Up @@ -342,7 +346,33 @@ function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSour
path[0] === "context" ? size + token.length - JSON.stringify(at(request, path)).length : size, 0);
const projected = required !== context && Buffer.byteLength(JSON.stringify(required))
- Buffer.byteLength(JSON.stringify(context)) + adjustment(remaining) - adjustment(tokens) < 0;
return {context: projected ? required : context, tokens: projected ? remaining : tokens, projected};
if (!projected) { required = context; copies.clear(); }
// The capture can predate the current native invocation. Only the view gets
// its current selection recipe. Replan commands still use the original hash.
const selectionPath = ["interaction_contract", "cli_channel", "selection_command", "command_args_template"];
const transport = details.selection_command_args_template;
const bindTransport = typeof transport === "string" && typeof at(context, selectionPath) === "string"
&& transport !== at(context, selectionPath);
if (bindTransport) parent(selectionPath)[selectionPath.at(-1)!] = transport;
if (staged) {
if (required.context_details === undefined) {
required = {...required, context_details: {path: details.path, sha256: details.sha256}};
}
// Staging can omit whole subtrees, but the retained numeric facts still
// refer to the same source fields, including in the encoded full/delta.
const retained = tokens.filter(([path]) => {
if (path[0] !== "context") return true;
const target = path.slice(1), value = at(required, target);
if (typeof value !== "number" || !Object.is(value, at(original, target))) return false;
const owner = at(required, target.slice(0, -1)) as object;
const fields = sourceValues.get(owner) ?? new Map<string, Path>();
fields.set(String(target.at(-1)), path);
sourceValues.set(owner, fields);
return true;
});
return {context: required, tokens: retained, projected: true};
}
return {context: required, tokens: projected ? remaining : tokens, projected: projected || bindTransport};
}

function nativeContextContinuity(codec: JsonObject): JsonObject {
Expand All @@ -364,11 +394,11 @@ function nativeContextContinuity(codec: JsonObject): JsonObject {
/** Plan and encode one native capture without sending its intermediate view
* back through Python. Capture publication and native locking remain Host IO. */
export function prepareProgressiveContextDelivery(request: JsonObject, legacyFields: readonly string[],
decisionFields: readonly string[]): JsonObject {
decisionFields: readonly string[], plan?: JsonObject): JsonObject {
if (request.include_initial_read_plan !== undefined)
requireBoolean(request.include_initial_read_plan, "include_initial_read_plan");
const sourceValues: ProjectionSourceValues = new WeakMap();
const required = requiredNativeContext(request, sourceValues);
const required = requiredNativeContext(request, sourceValues, plan);
const codec = nativeContextContinuity({...request, context: required.context,
...(request.source_number_tokens === undefined ? {} : {source_number_tokens: required.tokens})});
const delivery = encodeContextDelivery(codec, legacyFields, sourceValues, fileNavigationPaths(required.context));
Expand Down
Loading
Loading