Skip to content
38 changes: 36 additions & 2 deletions loopx/cli_commands/quota_presentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,47 @@ def compose_quota_work_contract(payload: dict[str, object], args: argparse.Names
"""Compose Complete Turn sources before capture and display."""
if args.quota_command != "should-run" or not isinstance(payload.get("interaction_contract"), Mapping):
return payload
from ..command_invocation import current_loopx_cli_argv
from ..control_plane.effect_runtime import EffectRuntimeRemoteError, EffectRuntimeStartupError
from ..control_plane.quota.error_codes import QuotaDecisionTransportError
from ..control_plane.quota.turn_envelope import compose_turn_decision
from .quota_request import quota_detail_sections_from_args

detail_sections = quota_detail_sections_from_args(args)
capture_reference_file = (
str(capture_directory / "decision.reader.json")
if capture_directory is not None
else None
)

def _anchor_existing_path(value: object) -> str | None:
if not isinstance(value, str) or not value.strip():
return None
candidate = Path(value).expanduser()
if candidate.is_absolute() or not candidate.exists():
return None
return str(candidate.resolve())

cli_registry = _anchor_existing_path(payload.get("registry"))
cli_runtime_root = _anchor_existing_path(payload.get("runtime_root"))
try:
return compose_turn_decision(payload, scheduler_execution_context=scheduler_context,
composed_settlement=True)
return compose_turn_decision(
payload,
scheduler_execution_context=scheduler_context,
composed_settlement=True,
include_vision_detail=(
"vision" in detail_sections
or getattr(args, "context_delivery", None) == "off"
),
include_goal_acceptance_detail=(
"goal_acceptance" in detail_sections
or getattr(args, "context_delivery", None) == "off"
),
cli_argv=current_loopx_cli_argv(),
capture_reference_file=capture_reference_file,
cli_registry=cli_registry,
cli_runtime_root=cli_runtime_root,
)
except (EffectRuntimeRemoteError, EffectRuntimeStartupError) as exc:
from .quota_capture import capture_decision
from .quota_failure_report import quota_decision_transport_diagnostic
Expand Down
6 changes: 3 additions & 3 deletions loopx/cli_commands/quota_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ def register_quota_command(
help=(
"Include one command-specific cold-path detail section. Status/plan default "
"to bounded Todo summaries; use agent-todos or user-todos for full lists. For `quota "
"should-run`: scheduler, agent-todos, user-todos, goal-boundary, or "
"vision. For `quota monitor-poll`: decisions. Repeat for multiple "
"sections or use `all`."
"should-run`: scheduler, agent-todos, user-todos, goal-boundary, "
"goal_acceptance (expands current live Goal acceptance at invocation time, not historical capture replay; use quota context-read on the original capture for admission-time readback), or vision. "
"For `quota monitor-poll`: decisions. Repeat for multiple sections or use `all`."
),
)
quota_parser.add_argument(
Expand Down
1 change: 1 addition & 0 deletions loopx/cli_commands/quota_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"agent-todos",
"user-todos",
"goal-boundary",
"goal_acceptance",
"vision",
)
QUOTA_MONITOR_POLL_DETAIL_SECTIONS = ("decisions",)
Expand Down
32 changes: 31 additions & 1 deletion loopx/control_plane/quota/progressive_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +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 {createHash} from "node:crypto";


Expand Down Expand Up @@ -588,6 +589,19 @@ export function progressiveContextPlan(request: JsonObject,
row.reason.replace(FULL_OUTCOME_READ_GUIDANCE, PROGRESSIVE_OUTCOME_READ_GUIDANCE)});
});
}
const deferredDetails = jsonObject(at(payload, ["deferred_settlement_details"]));
if (deferredDetails !== null) {
const hasGoalAcceptance = Object.hasOwn(deferredDetails, "goal_acceptance");
const hasOptionalAttachments = Object.hasOwn(deferredDetails, "optional_attachments");
deferred.push({
path: ["deferred_settlement_details"],
read_instruction: hasGoalAcceptance
? (hasOptionalAttachments
? "Admission-time goal_acceptance outcomes and optional settlement attachment details stay in the original capture; use outcome_requirements.capture_read_command for immutable baseline readback, or cold_read_command / optional_attachments[].cold_read_command for live inspection."
: "Admission-time goal_acceptance outcomes stay in the original capture; use outcome_requirements.capture_read_command for immutable baseline readback, or cold_read_command for live inspection.")
: "Complete optional settlement attachment details stay in the original capture; use optional_attachments[].cold_read_command when needed.",
});
}
for (const scope of scopes) {
deferred.push({path: scope.path, read_instruction: scope.instruction});
if (scope.marker_path) instructions.push({path: scope.marker_path, value: pointer(scope.path)});
Expand Down Expand Up @@ -1248,7 +1262,18 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
&& suggested.every(id => typeof id === "string"
&& outcomes.filter(value => object(value)?.id === id).length === 1);
const expanded = new Set(expand ? suggested as string[] : []);
const outcomesPath = [...source, "content", "goal_acceptance_contract", "outcome_requirements", "outcomes"];
const requirementsPath = [...source, "content", "goal_acceptance_contract", "outcome_requirements"];
if (requirements?.projection_mode === SCOPED_OUTCOME_PROJECTION_MODE) {
for (const field of [
"schema_version", "revision", "outcome_revision", "current_lifetime",
"projection_mode", "full_outcome_count", "inline_outcome_count",
"compacted_outcome_count", "full_outcomes_sha256",
"capture_read_command", "cold_read_command", "cold_read_instruction",
]) {
if (Object.hasOwn(requirements, field)) include(...requirementsPath, field);
}
}
const outcomesPath = [...requirementsPath, "outcomes"];
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 @@ -1268,6 +1293,11 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
const suggested = typeof outcomeId === "string" && expanded.has(outcomeId);
if (suggested && !deferSuggested) { include(...outcome); 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"]) {
if (Object.hasOwn(row, key)) include(...outcome, key);
}
}
if (suggested) {
include(...outcome, "objective");
include(...outcome, "revision");
Expand Down
14 changes: 13 additions & 1 deletion loopx/control_plane/quota/turn_envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,14 +339,26 @@ def compose_turn_decision(
Mapping[str, Any] | SchedulerExecutionContextResolution | None
) = None,
composed_settlement: bool = False,
include_vision_detail: bool = False,
include_goal_acceptance_detail: bool = False,
cli_argv: tuple[str, ...] | list[str] | None = None,
capture_reference_file: str | None = None,
cli_registry: str | None = None,
cli_runtime_root: str | None = None,
) -> dict[str, Any]:
"""Transport complete source facts to the existing typed composition owner."""
resolution = resolve_scheduler_execution_context(scheduler_execution_context)
args = render_scheduler_execution_args(scheduler_execution_context=resolution) if resolution.ok and resolution.context is not None else ""
source = dict(payload)
result = _turn_envelope_result("compose_complete", payload=source,
scheduler_execution_args=args, source_edits=True,
**({"composed_settlement": composed_settlement} if composed_settlement is not False else {}))
**({"composed_settlement": composed_settlement} if composed_settlement is not False else {}),
**({"include_vision_detail": True} if include_vision_detail else {}),
**({"include_goal_acceptance_detail": True} if include_goal_acceptance_detail else {}),
**({"cli_argv": list(cli_argv)} if cli_argv is not None else {}),
**({"capture_reference_file": capture_reference_file} if capture_reference_file is not None else {}),
**({"cli_registry": cli_registry} if cli_registry is not None else {}),
**({"cli_runtime_root": cli_runtime_root} if cli_runtime_root is not None else {}))
return _apply_context_projection_changes(source, result)


Expand Down
31 changes: 31 additions & 0 deletions loopx/control_plane/quota/turn_envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
referenceQuotaSummaryLanes, resolveQuotaSummaryLanes,
} from "./diagnostic_projection.ts";
import { completeCliSettlementChannel } from "./settlement_plan.ts";
import { compactRoutineSettlementPlan, scopeTurnGoalAcceptance } from "./turn_envelope_scoping.ts";
import {
interpretQuotaShouldRunPacket, assertSupportedQuotaPacket,
settlementIdentityFromPlan, settlementIdentityPayload, type JsonObject,
Expand Down Expand Up @@ -1026,9 +1027,33 @@ export function composeCompleteTurnDecision(value: unknown): JsonObject {
const payload = requireJsonObject(request.payload, "complete Turn decision source");
const composedSettlement = request.composed_settlement === undefined ? false
: requireBoolean(request.composed_settlement, "composed_settlement");
const includeGoalAcceptanceDetail = request.include_goal_acceptance_detail === undefined ? false
: requireBoolean(request.include_goal_acceptance_detail, "include_goal_acceptance_detail");
const includeVisionDetail = request.include_vision_detail === undefined ? false
: requireBoolean(request.include_vision_detail, "include_vision_detail");
if (typeof request.scheduler_execution_args !== "string") {
throw new EffectRuntimeRequestError("Turn scheduler execution binding must be a string");
}
const cliArgv = request.cli_argv === undefined ? ["loopx"] : executableCliArgs(request.cli_argv);
if (request.cli_argv !== undefined && cliArgv.length === 0) {
throw new EffectRuntimeRequestError("Turn envelope cli_argv must be a non-empty list of strings");
}
const captureReferenceFile = request.capture_reference_file;
if (captureReferenceFile !== undefined && !isNonEmptyFilePath(captureReferenceFile)) {
throw new EffectRuntimeRequestError("Turn envelope capture_reference_file must be a non-empty file path");
}
if (request.cli_registry !== undefined && !isNonEmptyFilePath(request.cli_registry)) {
throw new EffectRuntimeRequestError("Turn envelope cli_registry must be a non-empty file path");
}
if (request.cli_runtime_root !== undefined && !isNonEmptyFilePath(request.cli_runtime_root)) {
throw new EffectRuntimeRequestError("Turn envelope cli_runtime_root must be a non-empty file path");
}
const coldReadOptions = {
cliArgv,
captureReferenceFile,
registry: request.cli_registry ?? payload.registry,
runtimeRoot: request.cli_runtime_root ?? payload.runtime_root,
};
if (payload.schema_version === COMPLETE_TURN_DECISION_VERSION) {
const prior = requireCompleteTurnDecision(payload, request.source_number_tokens);
if (object(prior.contract_binding).scheduler_execution_args !== request.scheduler_execution_args) {
Expand Down Expand Up @@ -1083,7 +1108,13 @@ export function composeCompleteTurnDecision(value: unknown): JsonObject {
})}}}};
}
}
if (!includeVisionDetail) {
source = compactRoutineSettlementPlan(source, coldReadOptions);
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
}
source = referenceGoalAcceptance(source, sourceIdentity);
if (!includeGoalAcceptanceDetail) {
source = scopeTurnGoalAcceptance(source, coldReadOptions);
}
source = referenceReplanAuthoring(source, sourceIdentity);
source = referenceExploreGuidance(source);
source = referenceCurrentTaskTitle(source);
Expand Down
24 changes: 20 additions & 4 deletions loopx/control_plane/quota/turn_envelope_references.ts
Original file line number Diff line number Diff line change
Expand Up @@ -322,11 +322,23 @@ function indexCapturedAcceptanceOutcomes(payload: JsonObject, indexOutcome: (val
}
}

function summaryOutcomeIndexRow(ref: string, outcome: JsonObject): JsonObject | null {
if (outcome.summary_only !== true) return null;
return {
outcome_ref: ref,
id: outcome.id,
...pickOwn(outcome, ["owner_agent_id", "basis_digest", "revision", "todo_count", "capture_read_command", "read_modes", "cold_read_command"]),
summary_only: true,
};
}

/** Expose existing facts, not another acceptance verdict. Missing values stay
* absent; an Agent's `met` review is not a current independent check.
*/
function capturedOutcomeIndex(outcomes: ReadonlyMap<string, JsonObject>, precision?: ReplanReadPrecision): JsonObject[] {
return [...outcomes].map(([ref, outcome]) => {
const compactRow = summaryOutcomeIndexRow(ref, outcome);
if (compactRow) return compactRow;
const states = new Map<string, JsonObject>();
if (Array.isArray(outcome.requirements)) for (const value of outcome.requirements) {
const requirement = requireJsonObject(value, "captured outcome requirement");
Expand Down Expand Up @@ -674,10 +686,14 @@ export function replanGoalContext(payload: JsonObject, reads: JsonObject | null,
}
const acceptanceIndex = outcomes.size ? {
read_action_template: `${reads!.acceptance} --outcome-ref {outcome_ref}`,
outcomes: complete ? capturedOutcomeIndex(outcomes, precision) : [...outcomes].map(([ref, outcome]) => retain({outcome_ref: ref, id: outcome.id,
objective: outcome.objective, revision: outcome.revision,
requirement_count: Array.isArray(outcome.requirements) ? outcome.requirements.length : null},
outcome, ["id", "objective", "revision"])),
outcomes: complete ? capturedOutcomeIndex(outcomes, precision) : [...outcomes].map(([ref, outcome]) => {
const compactRow = summaryOutcomeIndexRow(ref, outcome);
if (compactRow) return compactRow;
return retain({outcome_ref: ref, id: outcome.id,
objective: outcome.objective, revision: outcome.revision,
requirement_count: Array.isArray(outcome.requirements) ? outcome.requirements.length : null},
outcome, ["id", "objective", "revision"]);
}),
} : null;
return {core, horizon, outcomes, acceptanceIndex, ambiguous};
}
Expand Down
Loading
Loading