Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,13 @@ def main() -> int:
raise RuntimeError(
f"missing CLI output budget test: {TEST_PATH.relative_to(REPO_ROOT)}"
)
_run_budget_checks()
import tempfile

from tests.control_plane.cli_output_fixture import isolated_probe_host_env

with tempfile.TemporaryDirectory(prefix="loopx-budget-smoke-home-") as temp_home:
with isolated_probe_host_env(Path(temp_home) / "home"):
_run_budget_checks()
completed = subprocess.run(
[sys.executable, str(DIFFERENTIAL_SMOKE.relative_to(REPO_ROOT))],
cwd=REPO_ROOT,
Expand Down
4 changes: 3 additions & 1 deletion examples/control_plane/cli-output-probe-runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -719,7 +719,9 @@ def main() -> int:
args.fixture_root.mkdir(parents=True)
# Use one current root owner for both revisions. A historical test source
# may still assume /tmp exists on every Windows drive.
with fixture_support.stable_budget_fixture_root(args.fixture_root) as stable_root:
with fixture_support.stable_budget_fixture_root(args.fixture_root) as stable_root, fixture_support.isolated_probe_host_env(
stable_root / "isolated-home"
):
rows = [
*_default_rows(
probe, semantics, stable_root,
Expand Down
15 changes: 11 additions & 4 deletions loopx/control_plane/heartbeat/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,13 +726,20 @@ def _prune_prompt_metadata(
if not payload.get(key):
payload.pop(key, None)
elif brief:
# The brief task body already embeds its compact-detail command. Keep
# only the selected brief command as top-level regeneration metadata;
# repeating the other mode commands can exceed the registered output
# budget when the CLI/runtime paths are long.
# The brief task body already embeds its compact-detail command and
# rule/profile prose. Keep regeneration metadata and markdown-rendered
# diagnostic fields while omitting duplicate non-command copies.
payload.pop("expanded_prompt_command", None)
payload.pop("compact_prompt_command", None)
payload.pop("thin_prompt_command", None)
for key in (
"material_queue_rule",
"permission_rule",
"agent_profile",
"registered_agents",
"reward_memory_enabled",
):
payload.pop(key, None)
if payload.get("pr_review_pre_quota_command") is None:
payload.pop("pr_review_pre_quota_command", None)
return payload
Expand Down
77 changes: 74 additions & 3 deletions loopx/control_plane/quota/progressive_context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,22 @@ 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 EXPLORE_GRAPH_BOILERPLATE_KEYS = [
"result_writeback_option",
"result_writeback_inline_option",
"result_writeback_inline_field",
"result_attachment_schema",
"path_delta_attachment_schema",
"path_delta_attachment_template",
"linked_question_attachment_template",
"optional_question_evolution_example",
"optional_execution_observation_example",
"result_writeback_guidance",
"result_attachment_template",
"optional_measurement_example",
"record_node_template",
"record_finding_template",
] as const;
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 @@ -558,6 +574,16 @@ export function progressiveContextPlan(request: JsonObject,
);
const agent = ["interaction_contract", "agent_channel"];
const sourcePath = [...agent, "work_context", "sources"];
const agentChannel = jsonObject(at(payload, agent));
const agentRequiredReads = Array.isArray(agentChannel?.required_reads) ? agentChannel.required_reads : [];
const requiredCapabilities = new Set(
(Array.isArray(selectedTodo?.required_capabilities) ? selectedTodo.required_capabilities : [])
.filter((cap): cap is string => typeof cap === "string" && cap.length > 0),
);
const allowExploreGraphDeferral = !includeGoalAcceptanceDetail
&& !requiredCapabilities.has("explore")
&& payload.effective_action !== EffectiveAction.AUTONOMOUS_REPLAN_REQUIRED
&& payload.replan_action_packet == null;
const sources = at(payload, sourcePath);
if (Array.isArray(sources)) sources.forEach((value, i) => {
const source = jsonObject(value), content = jsonObject(source?.content);
Expand All @@ -570,6 +596,48 @@ export function progressiveContextPlan(request: JsonObject,
: undefined;
carriers.push({path: [...sourcePath, i, "content", "goal_acceptance_contract"], suggestedIds: suggested});
}
const agenda = requiredManagerAgenda(value, agentRequiredReads);
if (agenda && Buffer.byteLength(JSON.stringify(agenda.items), "utf8") >= 2048) {
const agendaPath = [...sourcePath, i, "content", "unfinished_delegations"];
deferred.push({
path: [...agendaPath, "items"],
parent: agendaPath,
index_key: "supporting_material_pointer",
read_instruction: "Full unfinished delegation request rows remain in the required manager-inbox read and at unfinished_delegations/items via context_details. ",
});
}
const graph = jsonObject(content?.graph);
if (allowExploreGraphDeferral && source?.kind === "explore_turn_context" && content?.ok === true
&& content?.graph_enabled === true && graph) {
const graphPath = [...sourcePath, i, "content", "graph"];
let graphDeferred = false;
if (Array.isArray(graph.writeback_results) && graph.writeback_results.length > 0
&& Buffer.byteLength(JSON.stringify(graph.writeback_results), "utf8") >= 1024) {
deferred.push({path: [...graphPath, "writeback_results"], parent: graphPath, index_key: "supporting_material_pointer"});
graphDeferred = true;
}
if (Array.isArray(graph.measurement_feedback) && graph.measurement_feedback.length > 0
&& (!Array.isArray(graph.work_yardsticks) || graph.work_yardsticks.length === 0)
&& Buffer.byteLength(JSON.stringify(graph.measurement_feedback), "utf8") >= 1024) {
deferred.push({path: [...graphPath, "measurement_feedback"], parent: graphPath, index_key: "supporting_material_pointer"});
if (typeof graph.measurement_guidance === "string") {
deferred.push({path: [...graphPath, "measurement_guidance"], parent: graphPath, index_key: "supporting_material_pointer"});
}
graphDeferred = true;
}
if (typeof graph.result_writeback_guidance === "string"
&& Buffer.byteLength(graph.result_writeback_guidance, "utf8") >= 1024) {
for (const key of EXPLORE_GRAPH_BOILERPLATE_KEYS) {
if (Object.hasOwn(graph, key)) {
deferred.push({path: [...graphPath, key], parent: graphPath, index_key: "supporting_material_pointer"});
}
}
graphDeferred = true;
}
if (graphDeferred) {
deferred.at(-1)!.read_instruction = "Deferred Explore history and authoring templates remain readable at graph.supporting_material_pointer children or via explore turn-context. ";
}
}
});
let deferredHistoricalRequirements = false;
for (const {path: carrier, suggestedIds} of carriers) {
Expand Down Expand Up @@ -597,8 +665,9 @@ export function progressiveContextPlan(request: JsonObject,
|| typeof requirement.id !== "string" || typeof requirement.description !== "string") return;
if (requirement.agent_review === undefined) continue;
const review = jsonObject(requirement.agent_review);
if (!review || !known(review, ["id", "recorded_for_agent_id", "conclusion", "note", "evidence_refs", "basis_current", "independently_verified"])
if (!review || !known(review, ["id", "recorded_for_agent_id", "conclusion", "note", "evidence_refs", "basis_digest", "basis_current", "independently_verified"])
|| (review.recorded_for_agent_id !== undefined && !isGoalOutcomeIdentifier(review.recorded_for_agent_id))
|| (review.basis_digest !== undefined && typeof review.basis_digest !== "string")
|| typeof review.note !== "string" || !Array.isArray(review.evidence_refs)
|| review.evidence_refs.some(ref => typeof ref !== "string")
|| !["met", "unmet", "uncertain"].includes(String(review.conclusion))
Expand Down Expand Up @@ -1204,8 +1273,10 @@ function initialContextReadGroups(context: JsonObject, decisionFields: readonly
// remains disabled while that review is being settled.
const replanningBeforeWork = replanRequired && context.ok === true && context.should_run === true
&& cli?.spend_allowed_now === false;
const requiredInboxReads = (normalWork || replanningBeforeWork) && channel?.must_attempt === true
&& Array.isArray(channel.required_reads)
const recoveryReads = context.effective_action === EffectiveAction.UNSETTLED_HOST_TURN_RECOVERY
&& context.ok === true && Array.isArray(channel?.required_reads);
const requiredInboxReads = ((normalWork || replanningBeforeWork) && channel?.must_attempt === true || recoveryReads)
&& Array.isArray(channel?.required_reads)
? channel.required_reads : [];
const sources = object(channel?.work_context)?.sources;
const sourceRows = Array.isArray(sources) ? sources.map((source, index) => ({source, index})) : [];
Expand Down
93 changes: 73 additions & 20 deletions loopx/control_plane/quota/turn_envelope_scoping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -522,34 +522,58 @@ function compactExploreGraphBoilerplate(
return {sources: next, changed};
}

function compactExploreBoilerplateForNonExploreTurn(
payload: JsonObject,
options: CompactSettlementOptions,
exploreEnabled: boolean,
exploreColdRead: string,
): JsonObject {
if (exploreEnabled) return payload;
const action = payload.effective_action;
const isNormal = action === EffectiveAction.NORMAL_RUN && payload.normal_delivery_allowed === true;
if (!isNormal && action !== EffectiveAction.UNSETTLED_HOST_TURN_RECOVERY) return payload;
if (payload.replan_action_packet != null || payload.autonomous_replan_obligation != null) return payload;
const interaction = jsonObject(payload.interaction_contract);
const agent = jsonObject(interaction?.agent_channel);
const workContext = jsonObject(agent?.work_context);
if (!interaction || !agent || !workContext || !Array.isArray(workContext.sources)) return payload;
const knownExplore = exploreResultWritebackAffordance();
const updated = compactExploreGraphBoilerplate(workContext.sources, knownExplore, exploreColdRead);
if (!updated.changed) return payload;
return {
...payload,
interaction_contract: {
...interaction,
agent_channel: {
...agent,
work_context: {
...workContext,
sources: updated.sources,
},
},
},
};
}

export function compactRoutineSettlementPlan(
payload: JsonObject,
options: CompactSettlementOptions = {},
): JsonObject {
if (!isRoutineNormalRun(payload)) return payload;
const captureReferenceFile = nonEmptyString(options.captureReferenceFile);
if (!captureReferenceFile) return payload;
const frontier = object(payload.goal_frontier_projection);
if (Array.isArray(frontier.acceptance_gaps) && frontier.acceptance_gaps.length > 0) return payload;

const interaction = jsonObject(payload.interaction_contract);
const cli = jsonObject(interaction?.cli_channel);
const plan = jsonObject(cli?.settlement_plan);
if (!interaction || !cli || !plan || !Array.isArray(plan.ordered_steps)) return payload;

const identity = object(plan.identity);
const isTodoBound = identity.binding_kind === "todo"
|| (identity.binding_kind === undefined && nonEmptyString(identity.todo_id) !== null && identity.replan_obligation_id == null);
if (!isTodoBound) return payload;
const goalId = nonEmptyString(payload.goal_id ?? identity.goal_id);
const agentId = nonEmptyString(object(payload.agent_identity).agent_id ?? payload.agent_id ?? identity.agent_id);
const todoId = nonEmptyString(object(payload.selected_todo).todo_id ?? identity.todo_id);
const planIdentity = object(object(object(payload.interaction_contract).cli_channel).settlement_plan).identity;
const identityObj = object(planIdentity);
const goalId = nonEmptyString(payload.goal_id ?? identityObj.goal_id);
const agentId = nonEmptyString(
object(payload.agent_identity).agent_id
?? payload.agent_id
?? identityObj.agent_id,
);
if (!goalId || !agentId) return payload;

const requiredCaps = new Set(stringList(object(payload.selected_todo).required_capabilities));
const exploreEnabled = requiredCaps.has("explore");
const knownExplore = exploreResultWritebackAffordance();
const cliArgv = options.cliArgv ?? ["loopx"];
const todoId = nonEmptyString(object(payload.selected_todo).todo_id ?? identityObj.todo_id);
const exploreColdRead = exploreColdReadCommand({
cliArgv,
registry: options.registry ?? payload.registry,
Expand All @@ -558,6 +582,30 @@ export function compactRoutineSettlementPlan(
agentId,
todoId,
});

if (!isRoutineNormalRun(payload)) {
return compactExploreBoilerplateForNonExploreTurn(payload, options, exploreEnabled, exploreColdRead);
}
const frontier = object(payload.goal_frontier_projection);
if (Array.isArray(frontier.acceptance_gaps) && frontier.acceptance_gaps.length > 0) {
return compactExploreBoilerplateForNonExploreTurn(payload, options, exploreEnabled, exploreColdRead);
}

const interaction = jsonObject(payload.interaction_contract);
const cli = jsonObject(interaction?.cli_channel);
const plan = jsonObject(cli?.settlement_plan);
if (!interaction || !cli || !plan || !Array.isArray(plan.ordered_steps)) {
return compactExploreBoilerplateForNonExploreTurn(payload, options, exploreEnabled, exploreColdRead);
}

const identity = object(plan.identity);
const isTodoBound = identity.binding_kind === "todo"
|| (identity.binding_kind === undefined && nonEmptyString(identity.todo_id) !== null && identity.replan_obligation_id == null);
if (!isTodoBound) {
return compactExploreBoilerplateForNonExploreTurn(payload, options, exploreEnabled, exploreColdRead);
}

const knownExplore = exploreResultWritebackAffordance();
let deferredOptionalAttachments: unknown[] | null = null;

let planChanged = false;
Expand Down Expand Up @@ -602,7 +650,9 @@ export function compactRoutineSettlementPlan(
return rawStep;
});

if (!planChanged) return payload;
if (!planChanged) {
return compactExploreBoilerplateForNonExploreTurn(payload, options, exploreEnabled, exploreColdRead);
}

let nextInteraction: JsonObject = {
...interaction,
Expand Down Expand Up @@ -635,11 +685,14 @@ export function compactRoutineSettlementPlan(
}
}

return {
const nextPayload: JsonObject = {
...payload,
interaction_contract: nextInteraction,
...(deferredOptionalAttachments !== null
? {deferred_settlement_details: {optional_attachments: deferredOptionalAttachments}}
: {}),
};
return compactedExploreAttachment
? nextPayload
: compactExploreBoilerplateForNonExploreTurn(nextPayload, options, exploreEnabled, exploreColdRead);
}
40 changes: 40 additions & 0 deletions tests/control_plane/cli_output_fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,46 @@ def budget_fixture_path(root: Path) -> Path:
return Path("/tmp") / f"loopx-cli-budget-{suffix}"


_ISOLATED_HOST_CLEARED_ENV_KEYS = (
"CODEX_HOME",
"ANTIGRAVITY_CONVERSATION_ID",
"LOOPX_CHAT_CODEX_MODEL_PROVIDER",
"GH_CONFIG_DIR",
"GH_TOKEN",
"GITHUB_TOKEN",
"GITHUB_ENTERPRISE_TOKEN",
"GH_ENTERPRISE_TOKEN",
"CODEX_SANDBOX_NETWORK_DISABLED",
"LOOPX_OFFLINE",
"LOOPX_AUTO_CAPABILITY_PROBE",
)


@contextlib.contextmanager
def isolated_probe_host_env(home: Path):
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
"""Prevent host-level auth/context env (e.g. gh hosts/tokens) from mutating isolated public fixtures."""
home.mkdir(parents=True, exist_ok=True)
managed = {
"HOME": str(home),
"USERPROFILE": str(home),
"XDG_CONFIG_HOME": str(home / ".config"),
"APPDATA": str(home / "AppData" / "Roaming"),
}
tracked_keys = (*managed.keys(), *_ISOLATED_HOST_CLEARED_ENV_KEYS)
previous = {key: os.environ.get(key) for key in tracked_keys}
os.environ.update(managed)
for key in _ISOLATED_HOST_CLEARED_ENV_KEYS:
os.environ.pop(key, None)
try:
yield
finally:
for key, value in previous.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value


@contextlib.contextmanager
def stable_budget_fixture_root(root: Path):
fixture = budget_fixture_path(root)
Expand Down
Loading
Loading