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
14 changes: 10 additions & 4 deletions loopx/cli_commands/quota_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,11 +322,12 @@ def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespa
root=getattr(args, "codex_context_root", None), create=True)
except NativeContextSessionUnavailable:
directory = None # Current full input, no fabricated native journal.
detail_sections = quota_detail_sections_from_args(args)
decision_ref = (
_saved_decision_reference(capture_directory, expected_sha256=capture_id)
if progressive_enabled
and (directory is not None or not bool(getattr(args, "begin_turn", False)))
and "vision" not in quota_detail_sections_from_args(args)
and "vision" not in detail_sections
else None
)
prepared = prepare_codex_context(payload, directory=directory,
Expand All @@ -335,7 +336,9 @@ def project_native_quota_context(payload: dict[str, Any], args: argparse.Namespa
capture_id=capture_id, continuity_generation=getattr(args, "_context_delivery_generation", None),
progressive_enabled=progressive_enabled,
captured_decision=decision_ref,
max_page_output_bytes=getattr(args, "max_page_output_bytes", None))
max_page_output_bytes=getattr(args, "max_page_output_bytes", None),
include_goal_acceptance_detail="goal_acceptance" in detail_sections,
include_agent_todos_detail="agent-todos" in detail_sections)
recovery = prepared.delivery.get("recovery")
view = native_context_capture_view(prepared.delivery, capture_directory, context_directory=directory,
progressive_enabled=progressive_enabled, initial_read_plan=prepared.initial_read_plan,
Expand Down Expand Up @@ -376,8 +379,9 @@ def progressive_context_capture_view(payload: dict[str, Any], args: argparse.Nam

# Only a fresh stateless source can supply this route. Saved and explicitly
# captured decisions keep the reader chosen by their existing callers.
detail_sections = quota_detail_sections_from_args(args)
stage_from_projection = (directory is None and captured_decision is None
and "vision" not in quota_detail_sections_from_args(args))
and "vision" not in detail_sections)
if directory is None:
root = Path(_private_transport_root(runtime_root))
try:
Expand All @@ -393,7 +397,9 @@ def progressive_context_capture_view(payload: dict[str, Any], args: argparse.Nam
transport = _capture_selection_transport_template(payload, args, capture_root=directory.parent)
required, reference = capture_progressive_context(payload, directory=directory, surface=surface,
selection_command_args_template=transport, captured_decision=captured_decision,
replan_reader_argv=reader_argv if stage_from_projection else None)
replan_reader_argv=reader_argv if stage_from_projection else None,
include_goal_acceptance_detail="goal_acceptance" in detail_sections,
include_agent_todos_detail="agent-todos" in detail_sections)
view = native_context_capture_view(required, directory, captured_recovery=reference,
metadata={"context_delivery": native_context_activation(args),
**({"capture_sha256": args.capture_sha256} if getattr(args, "capture_sha256", None) else {})},
Expand Down
2 changes: 2 additions & 0 deletions loopx/cli_commands/quota_result_delivery.py
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,8 @@ def _publish_quota_result(
goal_id=decision_identity[0],
agent_id=decision_identity[1],
surface=quota_context_surface(captured_payload),
include_goal_acceptance_detail="goal_acceptance" in detail_sections,
include_agent_todos_detail="agent-todos" in detail_sections,
)
if (
not deferred_context
Expand Down
93 changes: 80 additions & 13 deletions loopx/control_plane/quota/progressive_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {quotaSummaryReferences, contextSourceIdentity, contextProjectionChanges,
type ProjectionSourceValues} from "./diagnostic_projection.ts";
import {encodeContextDelivery, fileNavigationPaths} from "./context_delivery.ts";
import {capturedContextSelection} from "./context_selection.ts";
import {SCOPED_OUTCOME_PROJECTION_MODE} from "./turn_envelope_scoping.ts";
import {SCOPED_OUTCOME_PROJECTION_MODE, SCOPED_OUTCOME_THRESHOLD} from "./turn_envelope_scoping.ts";
import {createHash} from "node:crypto";


Expand All @@ -32,6 +32,8 @@ const MAX_INLINE_WORK_OPENING_BYTES = 7000;
const SETTLEMENT_PLAN_PATH = ["interaction_contract", "cli_channel", "settlement_plan"];
const REPLAN_CONTEXT_PATH = ["autonomous_replan_obligation", "replan_context"];
const COMPLETE_REQUIREMENTS_CLAUSE = "This view retains complete requirements and current review/check states. ";
const PROGRESSIVE_COMPLETE_REQUIREMENTS_CLAUSE =
"Read the complete acceptance basis, cumulative outcome requirements, work links and current review/check states. ";
const pointer = (path: Path): string => path.length ? "/" + path.map(key =>
String(key).replaceAll("~", "~0").replaceAll("/", "~1")).join("/") : "";
const at = (root: unknown, path: Path): unknown => path.reduce<unknown>((row, key) =>
Expand Down Expand Up @@ -517,7 +519,13 @@ function inlineReadSections(request: JsonObject, required: JsonObject, exactBody
/** Return paths instead of round-tripping the caller's JSON numeric values
* through JS. The IO adapter performs only these typed-owner-selected edits. */
export function progressiveContextPlan(request: JsonObject,
scopes: readonly PreparationScopeDetail[] = []): JsonObject {
scopes: readonly PreparationScopeDetail[] = [],
extraReferences: readonly JsonObject[] = []): JsonObject {
const includeGoalAcceptanceDetail = request.include_goal_acceptance_detail === undefined ? false
: requireBoolean(request.include_goal_acceptance_detail, "include_goal_acceptance_detail");
if (request.include_agent_todos_detail !== undefined) {
requireBoolean(request.include_agent_todos_detail, "include_agent_todos_detail");
}
const payload = requireJsonObject(request.payload, "captured context");
const deferred: JsonObject[] = [], instructions: JsonObject[] = [];
const unchanged = {deferred, instructions};
Expand All @@ -526,25 +534,50 @@ export function progressiveContextPlan(request: JsonObject,
if (request.surface !== "quota_packet" || payload.ok !== true || payload.schema_version !== undefined
|| payload.contract_binding !== undefined || payload.context_details !== undefined
|| payload.context_reference_instruction !== undefined) return unchanged;
const references = quotaSummaryReferences(payload);
const carriers: Path[] = [
["planning_horizon", "core_goal", "acceptance_contract"],
["autonomous_replan_obligation", "replan_context", "core_goal", "acceptance_contract"],
["agent_todo_summary", "goal_acceptance_contract"],
const references = [...quotaSummaryReferences(payload), ...extraReferences];
const carriers: {path: Path; suggestedIds?: Set<string>}[] = [
{path: ["planning_horizon", "core_goal", "acceptance_contract"]},
{path: ["agent_todo_summary", "goal_acceptance_contract"]},
{path: ["autonomous_replan_obligation", "replan_context", "core_goal", "acceptance_contract"]},
];
const selectedTodo = jsonObject(payload.selected_todo);
const relevantTodoIds = new Set<string>(
[selectedTodo?.todo_id, selectedTodo?.unblocks_todo_id,
...(Array.isArray(selectedTodo?.dependency_todo_ids) ? selectedTodo.dependency_todo_ids : []),
...(Array.isArray(selectedTodo?.successor_todo_ids) ? selectedTodo.successor_todo_ids : [])]
.filter((id): id is string => typeof id === "string" && id.length > 0),
);
const gapOutcomeIds = new Set<string>(
(Array.isArray(jsonObject(payload.goal_frontier_projection)?.acceptance_gaps)
? jsonObject(payload.goal_frontier_projection)!.acceptance_gaps as unknown[] : [])
.map(gap => jsonObject(gap)?.outcome_id)
.filter((id): id is string => typeof id === "string" && id.length > 0),
);
const agent = ["interaction_contract", "agent_channel"];
const sourcePath = [...agent, "work_context", "sources"];
const sources = at(payload, sourcePath);
if (Array.isArray(sources)) sources.forEach((value, i) => {
const source = jsonObject(value), content = jsonObject(source?.content);
if (source?.source === "goal_acceptance" && content?.ok !== false && content?.read_complete !== false
&& (content?.status === undefined || content.status === "loaded")
&& (source.reason === undefined || typeof source.reason === "string" && source.reason.includes(FULL_OUTCOME_READ_GUIDANCE)))
carriers.push([...sourcePath, i, "content", "goal_acceptance_contract"]);
&& (source.reason === undefined || typeof source.reason === "string" && source.reason.includes(FULL_OUTCOME_READ_GUIDANCE))) {
const outcomeCtx = jsonObject(content?.outcome_context);
const suggested = Array.isArray(outcomeCtx?.suggested_outcome_ids)
? new Set(outcomeCtx.suggested_outcome_ids.filter((id): id is string => typeof id === "string" && id.length > 0))
: undefined;
carriers.push({path: [...sourcePath, i, "content", "goal_acceptance_contract"], suggestedIds: suggested});
}
});
for (const carrier of carriers) {
let deferredHistoricalRequirements = false;
for (const {path: carrier, suggestedIds} of carriers) {
const path = [...carrier, "outcome_requirements"], declaration = jsonObject(at(payload, path));
if (declaration?.schema_version !== GOAL_OUTCOMES_SCHEMA || !Array.isArray(declaration.outcomes)) continue;
const isReplanObligationCarrier = carrier[0] === "autonomous_replan_obligation"
&& payload.effective_action === EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED;
const deferLargeHistoricalOutcomes = !includeGoalAcceptanceDetail
&& !isReplanObligationCarrier
&& declaration.outcomes.length > SCOPED_OUTCOME_THRESHOLD
&& declaration.projection_mode !== SCOPED_OUTCOME_PROJECTION_MODE;
declaration.outcomes.forEach((value, i) => {
const row = jsonObject(value);
if (!row || !known(row, ["id", "owner_agent_id", "declaration_owner_agent_id", "objective", "revision", "requirements", "todo_ids", "sources", "basis_digest", "work"])
Expand All @@ -571,11 +604,28 @@ export function progressiveContextPlan(request: JsonObject,
}
const parent = [...path, "outcomes", i];
const index_key = "supporting_material_pointer";
const isActiveOutcome = suggestedIds?.has(row.id) === true
|| gapOutcomeIds.has(row.id)
|| (Array.isArray(row.todo_ids) && row.todo_ids.some(id => typeof id === "string" && relevantTodoIds.has(id)));
if (deferLargeHistoricalOutcomes && !isActiveOutcome) {
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
if (row.sources.length) deferred.push({path: [...parent, "sources"], parent, index_key});
if (row.requirements.length) {
deferred.push({path: [...parent, "requirements"], parent, index_key});
deferredHistoricalRequirements = true;
}
return;
}
if (row.sources.length) deferred.push({path: [...parent, "sources"], parent, index_key});
for (const j of reviews) for (const field of ["note", "evidence_refs"])
deferred.push({path: [...parent, "requirements", j, "agent_review", field], parent, index_key});
});
}
const progressiveOutcomeGuidance = deferredHistoricalRequirements
? PROGRESSIVE_OUTCOME_READ_GUIDANCE.replace(
PROGRESSIVE_COMPLETE_REQUIREMENTS_CLAUSE,
"Read the complete acceptance basis, work links and current review/check states. Active/suggested outcomes retain complete requirements here; historical non-selected outcome requirements remain in context_details (read via supporting_material_pointer before dependent work). ",
)
: PROGRESSIVE_OUTCOME_READ_GUIDANCE;
// Replace only the exact source-owned obligation. Other merged obligations,
// objective adoption, unknown provider prose and pending reads remain intact.
for (const listPath of deferred.length ? [sourcePath, [...agent, "required_reads"]] : []) {
Expand All @@ -586,7 +636,7 @@ export function progressiveContextPlan(request: JsonObject,
if (row?.source === "goal_acceptance" && typeof row.reason === "string"
&& row.reason.includes(FULL_OUTCOME_READ_GUIDANCE))
instructions.push({path: [...listPath, i, "reason"], value:
row.reason.replace(FULL_OUTCOME_READ_GUIDANCE, PROGRESSIVE_OUTCOME_READ_GUIDANCE)});
row.reason.replace(FULL_OUTCOME_READ_GUIDANCE, progressiveOutcomeGuidance)});
});
}
const deferredDetails = jsonObject(at(payload, ["deferred_settlement_details"]));
Expand Down Expand Up @@ -617,7 +667,12 @@ export function progressiveContextPlan(request: JsonObject,
const pathStartsWith = (path: Path, start: Path) => start.every((key, i) => path[i] === key);

function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSourceValues,
plan = progressiveContextPlan({payload: request.context, surface: request.surface})):
plan = progressiveContextPlan({
payload: request.context,
surface: request.surface,
...(request.include_goal_acceptance_detail === undefined ? {} : {include_goal_acceptance_detail: request.include_goal_acceptance_detail}),
...(request.include_agent_todos_detail === undefined ? {} : {include_agent_todos_detail: request.include_agent_todos_detail}),
})):
{context: JsonObject; tokens: [Path, string][]; projected: boolean} {
const original = requireJsonObject(request.context, "current projection");
const staged = jsonObject(plan.staged_context);
Expand Down Expand Up @@ -687,6 +742,12 @@ function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSour
});
const sourcePath: Path = ["interaction_contract", "agent_channel", "work_context", "sources"];
const sources = at(context, sourcePath);
const hasDeferredOutcomeRequirements = deferred.some(
edit => Array.isArray(edit.path) && edit.path.at(-1) === "requirements",
);
const requirementsClause = hasDeferredOutcomeRequirements
? "Active/suggested outcomes retain complete requirements and current review/check states here; historical non-selected outcome requirements are supporting material in this same capture (append /requirements alongside supporting_material_pointer or use unread_context_index.pointers). "
: COMPLETE_REQUIREMENTS_CLAUSE;
required.context_details = {path: details.path, sha256: details.sha256,
...(typeof details.command_template === "string" ? {command_template: details.command_template} : {}),
source_path: details.path,
Expand All @@ -702,7 +763,7 @@ function requiredNativeContext(request: JsonObject, sourceValues: ProjectionSour
}) : [],
},
instruction: deferred.map(edit => typeof edit.read_instruction === "string" ? edit.read_instruction : "").join("")
+ COMPLETE_REQUIREMENTS_CLAUSE
+ requirementsClause
+ "Source history, review reasoning and evidence references are supporting material. "
+ "Read them from this same immutable capture when a decision, verification or review depends on them. "
+ "Use the outcome's supporting_material_pointer when shown, or remove /id from its selected JSON pointer. "
Expand Down Expand Up @@ -1274,6 +1335,11 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
}
}
const outcomesPath = [...requirementsPath, "outcomes"];
const hasContainerOutcomeReadCommands = requirements?.projection_mode === SCOPED_OUTCOME_PROJECTION_MODE
&& typeof requirements.capture_read_command === "string"
&& typeof requirements.cold_read_command === "string"
&& typeof requirements.cold_read_instruction === "string"
&& Array.isArray(outcomes) && outcomes.length > SCOPED_OUTCOME_THRESHOLD;
const canDeferSuggested = openingBudget !== undefined && readyIdentity !== undefined && expanded.size > 0
&& inlineSupportingDetails && details?.outcome_support_from_id === true
&& details.path === supportingSource?.path && details.sha256 === supportingSource?.sha256
Expand All @@ -1292,6 +1358,7 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
const row = object(_outcome), outcomeId = row?.id;
const suggested = typeof outcomeId === "string" && expanded.has(outcomeId);
if (suggested && !deferSuggested) { include(...outcome); return; }
if (row?.summary_only === true && hasContainerOutcomeReadCommands) return;
include(...outcome, "id");
if (row?.summary_only === true) {
for (const key of ["owner_agent_id", "basis_digest", "revision", "todo_count", "summary_only", "capture_read_command", "read_modes", "cold_read_command"]) {
Expand Down
16 changes: 14 additions & 2 deletions loopx/control_plane/quota/turn_envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,8 @@ def prepare_context_delivery(
surface: str = "work_context", native_projection: Mapping[str, Any] | None = None,
consumed_pointers: Mapping[str, str] | None = None, observe_first_read: bool = False,
include_initial_read_plan: bool = False,
include_goal_acceptance_detail: bool = False,
include_agent_todos_detail: bool = False,
) -> dict[str, Any]:
"""Prepare under the Host's explicit continuity basis, not a model assertion.

Expand All @@ -479,6 +481,10 @@ def prepare_context_delivery(
source["native_projection"] = dict(native_projection)
if include_initial_read_plan:
source["include_initial_read_plan"] = True
if include_goal_acceptance_detail:
source["include_goal_acceptance_detail"] = True
if include_agent_todos_detail:
source["include_agent_todos_detail"] = True
if consumed_pointers is not None:
source["consumed_pointers"] = dict(consumed_pointers)
if consumed_pointers and observe_first_read:
Expand All @@ -494,9 +500,15 @@ def prepare_context_delivery(


def prepare_progressive_context(context: Mapping[str, Any], *, source_reference: Mapping[str, Any],
surface: str = "quota_packet") -> dict[str, Any]:
surface: str = "quota_packet",
include_goal_acceptance_detail: bool = False,
include_agent_todos_detail: bool = False) -> dict[str, Any]:
"""Stateless IO adapter to the same typed presentation owner; no Delta identity."""
source = dict(context=dict(context), native_projection=dict(source_reference), surface=surface)
source: dict[str, Any] = dict(
context=dict(context), native_projection=dict(source_reference), surface=surface,
**({"include_goal_acceptance_detail": True} if include_goal_acceptance_detail else {}),
**({"include_agent_todos_detail": True} if include_agent_todos_detail else {}),
)
return _apply_context_projection_changes(source,
_turn_envelope_result("progressive_context_delivery", **source, source_edits=True))

Expand Down
Loading
Loading