From 4cf9821679ec7c07df58039012ee5f1a2f10ba1b Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:30:58 +0800 Subject: [PATCH 1/2] perf(control-plane,heartbeat): slim interaction contract and isolate CLI output probes Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- .../cli-output-budget-regression-smoke.py | 8 +- .../control_plane/cli-output-probe-runner.py | 4 +- loopx/control_plane/heartbeat/builder.py | 15 +- .../quota/progressive_context.ts | 77 ++++++++- .../quota/turn_envelope_scoping.ts | 93 +++++++--- tests/control_plane/cli_output_fixture.py | 28 +++ tests/control_plane/test_cli_output_budget.py | 47 ++++++ .../progressive_context.test.ts | 159 ++++++++++++++++++ .../turn_envelope_scoping.test.ts | 55 ++++++ 9 files changed, 457 insertions(+), 29 deletions(-) diff --git a/examples/control_plane/cli-output-budget-regression-smoke.py b/examples/control_plane/cli-output-budget-regression-smoke.py index 7c4b41052c..d768c2d4b9 100644 --- a/examples/control_plane/cli-output-budget-regression-smoke.py +++ b/examples/control_plane/cli-output-budget-regression-smoke.py @@ -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, diff --git a/examples/control_plane/cli-output-probe-runner.py b/examples/control_plane/cli-output-probe-runner.py index 18a16fd3bf..7a1fbe5c7e 100644 --- a/examples/control_plane/cli-output-probe-runner.py +++ b/examples/control_plane/cli-output-probe-runner.py @@ -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, diff --git a/loopx/control_plane/heartbeat/builder.py b/loopx/control_plane/heartbeat/builder.py index e2f1e0f8cb..8106531f77 100644 --- a/loopx/control_plane/heartbeat/builder.py +++ b/loopx/control_plane/heartbeat/builder.py @@ -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 diff --git a/loopx/control_plane/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index 2b1c88173b..b01f1e09a7 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -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((row, key) => @@ -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); @@ -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) { @@ -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)) @@ -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})) : []; diff --git a/loopx/control_plane/quota/turn_envelope_scoping.ts b/loopx/control_plane/quota/turn_envelope_scoping.ts index 336cb7b4e2..972d7a3c55 100644 --- a/loopx/control_plane/quota/turn_envelope_scoping.ts +++ b/loopx/control_plane/quota/turn_envelope_scoping.ts @@ -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, @@ -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; @@ -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, @@ -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); } diff --git a/tests/control_plane/cli_output_fixture.py b/tests/control_plane/cli_output_fixture.py index 31e72de027..35d8f98120 100644 --- a/tests/control_plane/cli_output_fixture.py +++ b/tests/control_plane/cli_output_fixture.py @@ -46,6 +46,34 @@ def budget_fixture_path(root: Path) -> Path: return Path("/tmp") / f"loopx-cli-budget-{suffix}" +@contextlib.contextmanager +def isolated_probe_host_env(home: Path): + """Prevent host-level auth/context env (e.g. gh hosts) from mutating isolated public fixtures.""" + home.mkdir(parents=True, exist_ok=True) + previous = { + key: os.environ.get(key) + for key in ( + "HOME", + "USERPROFILE", + "CODEX_HOME", + "ANTIGRAVITY_CONVERSATION_ID", + "LOOPX_CHAT_CODEX_MODEL_PROVIDER", + ) + } + os.environ["HOME"] = str(home) + os.environ["USERPROFILE"] = str(home) + for key in ("CODEX_HOME", "ANTIGRAVITY_CONVERSATION_ID", "LOOPX_CHAT_CODEX_MODEL_PROVIDER"): + 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) diff --git a/tests/control_plane/test_cli_output_budget.py b/tests/control_plane/test_cli_output_budget.py index 407897146e..0df9479f78 100644 --- a/tests/control_plane/test_cli_output_budget.py +++ b/tests/control_plane/test_cli_output_budget.py @@ -2079,6 +2079,53 @@ def test_long_path_budget_is_independent_of_runner_temp_prefix( test_brief_budget_retains_full_commands_on_real_long_paths() +def test_brief_prunes_duplicate_non_command_metadata_and_smoke_isolates_host(tmp_path: Path) -> None: + from tests.control_plane.cli_output_fixture import isolated_probe_host_env + + payload = build_heartbeat_prompt( + goal_id=GOAL_ID, + active_state=tmp_path / "ACTIVE_GOAL_STATE.md", + brief=True, + agent_id="codex-alpha", + registered_agents=["codex-alpha"], + agent_scopes=["Public CLI output qualification."], + agent_profile={"schema_version": "agent_profile_v1", "profile_role": "fixture"}, + runtime_root=tmp_path / "runtime", + registry_path=tmp_path / "registry.json", + reward_memory_enabled=True, + ) + for removed in ( + "material_queue_rule", + "permission_rule", + "agent_profile", + "registered_agents", + "reward_memory_enabled", + ): + assert removed not in payload + for retained in ( + "agent_model", + "agent_role", + "agent_scopes", + "active_state_source", + "resolved_active_state", + "cli_preflight", + "brief_prompt_command", + "quota_guard_command", + "quota_spend_command", + "refresh_state_command", + "progress_refresh_state_command", + ): + assert retained in payload + + empty_home = tmp_path / "isolated-home" + with isolated_probe_host_env(empty_home): + assert os.environ["HOME"] == str(empty_home) + assert os.environ["USERPROFILE"] == str(empty_home) + assert "CODEX_HOME" not in os.environ + assert "ANTIGRAVITY_CONVERSATION_ID" not in os.environ + assert "LOOPX_CHAT_CODEX_MODEL_PROVIDER" not in os.environ + + @pytest.mark.parametrize("nested_temp", [False, True]) def test_long_path_budget_uses_native_temp_without_a_drive_root_directory( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, nested_temp: bool, diff --git a/tests/control_plane_ts/progressive_context.test.ts b/tests/control_plane_ts/progressive_context.test.ts index 52cb55198a..dbed295813 100644 --- a/tests/control_plane_ts/progressive_context.test.ts +++ b/tests/control_plane_ts/progressive_context.test.ts @@ -677,3 +677,162 @@ test("initial read omits redundant summary_only outcome rows when container read const smallPointers = initialContextReadPointers(smallContext, []); assert.ok(smallPointers.includes(prefix + "/1/capture_read_command")); }); + +test("progressiveContextPlan handles agent_review basis_digest, defers large manager agenda items and non-explore graph bloat", () => { + const mkOutcome = (id: string, todoId: string, owner: string, note: string) => ({ + id, objective: `Deliver ${id}.`, revision: 2, owner_agent_id: owner, todo_ids: [todoId], + sources: [{ref: `src:${id}`, summary: "Historical source provenance."}], + requirements: [{ + id: "req-1", + description: `Requirement for ${id}. ` + "Detailed criteria. ".repeat(12), + status: "unverified", + planning_satisfied: false, + agent_review: { + id: "req-1", conclusion: "unmet", note, evidence_refs: [`ev:${id}`], + basis_digest: "sha256:" + "b".repeat(64), basis_current: false, independently_verified: false, + }, + }], + }); + const outcomes = [ + mkOutcome("out-active", "todo-active", "agent-a", "Active agent review detail."), + mkOutcome("out-other", "todo-other", "peer-b", "Inactive peer review detail."), + ...Array.from({length: 7}, (_, idx) => mkOutcome(`out-hist-${idx}`, `todo-h-${idx}`, "peer-c", "Historical detail.")), + ]; + const longPurpose = "Coordinate cross-module review handoff without losing request scope. ".repeat(4); + const largeItems = Array.from({length: 8}, (_, idx) => ({ + request_id: String(idx).repeat(64).slice(0, 64), + direction: "incoming", + request_revision: 1, + agent_id: "agent-a", + purpose: longPurpose, + purpose_truncated: false, + receipt_state: "pending", + decision: null, + step: "assess_request", + })); + const managerRead = { + source: "turn_start_capability_hook", + kind: "operator_inbox", + capability_id: "manager-context", + hook_id: "manager.context_inbox", + ordering: "before_work", + command: "loopx manager-inbox read --goal-id g1 --agent-id agent-a", + }; + const managerSource = { + ...managerRead, + content: { + ok: true, + read_complete: false, + unfinished_delegations: { + count_unit: "request", + items: largeItems, + incoming_count: largeItems.length, + outgoing_count: 0, + omitted_count: 0, + return_attention: {count: 0, items: [], omitted_count: 0}, + scan_complete: true, + unavailable_count: 0, + observed_at: "2026-11-27T00:00:00Z", + read_command: managerRead.command, + instruction: "Reconcile unfinished requests before proceeding.", + }, + }, + }; + const largeGuidance = "Explore writeback guidance. ".repeat(60); + const largeResults = Array.from({length: 3}, (_, idx) => ({ + finding_id: `f-${idx}`, node_id: "n-1", finding: `Finding ${idx}`, status: "confirmed", + summary: "Detailed finding narrative. ".repeat(20), + })); + const largeFeedback = Array.from({length: 4}, (_, idx) => ({ + node_id: `n-${idx}`, metric: "latency", unit: "ms", higher_is_better: false, + comparison_scope: "s1", best: {value: 10 + idx}, latest: {value: 11 + idx, measurement: {evidence_ref: `ev-${idx}`}}, + note: "Comparable profile details. ".repeat(12), + })); + const exploreSource = { + source: "turn_start_capability_hook", + kind: "explore_turn_context", + capability_id: "explore", + hook_id: "explore.turn_context", + ordering: "before_work", + command: "loopx explore turn-context --goal-id g1 --agent-id agent-a", + content: { + ok: true, + goal_id: "g1", + agent_id: "agent-a", + graph_enabled: true, + graph: { + counts: {nodes: 3, findings: 3}, + guidance: "Check existing evidence.", + recent_nodes: [{node_id: "n-1", title: "Node 1", status: "exploring"}], + recent_findings: [{finding_id: "f-0", node_id: "n-1", title: "Finding 0", status: "confirmed"}], + writeback_results: largeResults, + result_page: {total: 3, offset: 0, limit: 3, remaining: 0, revision: "r1"}, + measurement_feedback: largeFeedback, + measurement_guidance: "Compare only matching scopes.", + measurement_feedback_page: {total: 4, offset: 0, limit: 3, remaining: 1, revision: "r1"}, + result_writeback_guidance: largeGuidance, + record_node_template: "loopx explore node --title ", + record_finding_template: "loopx explore finding --node <id>", + }, + }, + }; + const payload = { + ok: true, + goal_id: "g1", + agent_id: "agent-a", + effective_action: "unsettled_host_turn_recovery", + normal_delivery_allowed: false, + selected_todo: {todo_id: "todo-active", required_capabilities: []}, + planning_horizon: { + core_goal: { + acceptance_contract: { + outcome_requirements: {schema_version: "loopx_goal_outcomes_v0", current_lifetime: true, outcomes}, + }, + }, + }, + interaction_contract: { + schema_version: "loopx_interaction_contract_v0", + agent_channel: { + required_reads: [managerRead], + work_context: {sources: [managerSource, exploreSource]}, + }, + }, + }; + + const plan = progressiveContextPlan({payload, surface: "quota_packet"}); + const deferredPointers = (plan.deferred as {path: (string | number)[]}[]).map( + entry => "/" + entry.path.map(k => String(k)).join("/"), + ); + // Active outcome preserves requirements while deferring review note/evidence_refs; inactive outcomes defer requirements even with basis_digest. + assert.ok(deferredPointers.includes("/planning_horizon/core_goal/acceptance_contract/outcome_requirements/outcomes/0/requirements/0/agent_review/note")); + assert.ok(deferredPointers.includes("/planning_horizon/core_goal/acceptance_contract/outcome_requirements/outcomes/1/requirements")); + assert.ok(!deferredPointers.includes("/planning_horizon/core_goal/acceptance_contract/outcome_requirements/outcomes/0/requirements")); + // Manager unfinished_delegations.items deferred on recovery when in required_reads. + assert.ok(deferredPointers.includes("/interaction_contract/agent_channel/work_context/sources/0/content/unfinished_delegations/items")); + // Non-explore turn defers large graph writeback_results, measurement_feedback, and authoring boilerplate. + assert.ok(deferredPointers.includes("/interaction_contract/agent_channel/work_context/sources/1/content/graph/writeback_results")); + assert.ok(deferredPointers.includes("/interaction_contract/agent_channel/work_context/sources/1/content/graph/measurement_feedback")); + assert.ok(deferredPointers.includes("/interaction_contract/agent_channel/work_context/sources/1/content/graph/result_writeback_guidance")); + assert.ok(initialContextReadPointers(payload, ["ok", "goal_id"]).includes( + "/interaction_contract/agent_channel/work_context/sources/0/content/unfinished_delegations/incoming_count", + )); + + // When selected_todo explicitly requires explore, keep Explore graph history & templates inline. + const exploreTurn = structuredClone(payload); + exploreTurn.selected_todo = {todo_id: "todo-active", required_capabilities: ["explore"]}; + const explorePlan = progressiveContextPlan({payload: exploreTurn, surface: "quota_packet"}); + const exploreDeferred = (explorePlan.deferred as {path: (string | number)[]}[]).map( + entry => "/" + entry.path.map(k => String(k)).join("/"), + ); + assert.equal(exploreDeferred.some(ptr => ptr.includes("/content/graph/")), false); + + // Small manager agenda (< 2048 B) stays inline. + const smallPayload = structuredClone(payload); + smallPayload.interaction_contract.agent_channel.work_context.sources[0].content.unfinished_delegations.items = [largeItems[0]]; + smallPayload.interaction_contract.agent_channel.work_context.sources[0].content.unfinished_delegations.incoming_count = 1; + const smallPlan = progressiveContextPlan({payload: smallPayload, surface: "quota_packet"}); + const smallDeferred = (smallPlan.deferred as {path: (string | number)[]}[]).map( + entry => "/" + entry.path.map(k => String(k)).join("/"), + ); + assert.equal(smallDeferred.some(ptr => ptr.includes("unfinished_delegations")), false); +}); diff --git a/tests/control_plane_ts/turn_envelope_scoping.test.ts b/tests/control_plane_ts/turn_envelope_scoping.test.ts index 16aa67c8af..c4ba9d5196 100644 --- a/tests/control_plane_ts/turn_envelope_scoping.test.ts +++ b/tests/control_plane_ts/turn_envelope_scoping.test.ts @@ -884,3 +884,58 @@ test("scopeTurnGoalAcceptance scopes unsettled recovery planning_horizon and sta undefined, ); }); + +test("compactRoutineSettlementPlan trims non-explore graph boilerplate on unsettled recovery and VCA normal turns", () => { + const base = baseNormalPayload(4); + const boilerplateGraph = () => ({ + ...exploreResultWritebackAffordance(), + counts: {nodes: 1}, + guidance: "Check evidence first.", + result_writeback_option: exploreResultWritebackAffordance().option, + result_writeback_inline_option: exploreResultWritebackAffordance().inline_option, + result_writeback_inline_field: exploreResultWritebackAffordance().inline_field, + result_attachment_schema: exploreResultWritebackAffordance().attachment_schema, + path_delta_attachment_schema: exploreResultWritebackAffordance().path_delta_attachment_schema, + path_delta_attachment_template: exploreResultWritebackAffordance().path_delta_attachment_template, + linked_question_attachment_template: exploreResultWritebackAffordance().linked_question_attachment_template, + optional_question_evolution_example: exploreResultWritebackAffordance().optional_question_evolution_example, + optional_execution_observation_example: exploreResultWritebackAffordance().optional_execution_observation_example, + result_writeback_guidance: exploreResultWritebackAffordance().guidance, + result_attachment_template: exploreResultWritebackAffordance().attachment_template, + optional_measurement_example: exploreResultWritebackAffordance().optional_measurement_example, + }); + const exploreSource = { + source: "turn_start_capability_hook", + hook_id: "explore.turn_context", + capability_id: "explore", + content: {ok: true, graph_enabled: true, graph: boilerplateGraph()}, + }; + const unsettled = { + ...base, + effective_action: "unsettled_host_turn_recovery", + normal_delivery_allowed: false, + vision_continuation_audit: {required: true}, + interaction_contract: { + agent_channel: {work_context: {sources: [structuredClone(exploreSource)]}}, + cli_channel: {settlement_plan: {schema_version: "quota_settlement_plan_v2", identity: {goal_id: "g1", agent_id: "a1"}, ordered_steps: []}}, + }, + }; + const compacted = compactRoutineSettlementPlan(unsettled, {captureReferenceFile: "/tmp/ref.json", cliArgv: ["loopx"]}); + const compactedGraph = (((((compacted.interaction_contract as JsonObject).agent_channel as JsonObject) + .work_context as JsonObject).sources as JsonObject[])[0].content as JsonObject).graph as JsonObject; + assert.equal(compactedGraph.result_writeback_guidance, undefined); + assert.equal(compactedGraph.optional_question_evolution_example, undefined); + assert.equal(compactedGraph.result_writeback_guidance_summary_only, true); + assert.match(String(compactedGraph.result_writeback_guidance_cold_read_command), /explore turn-context/); + + // Explicit explore requirement preserves full graph boilerplate on recovery too. + const requiredExplore = structuredClone(unsettled); + (requiredExplore.selected_todo as JsonObject).required_capabilities = ["explore"]; + assert.equal(compactRoutineSettlementPlan(requiredExplore, {captureReferenceFile: "/tmp/ref.json", cliArgv: ["loopx"]}), requiredExplore); + + // Pure replan packets remain untouched by compactRoutineSettlementPlan. + const replan = structuredClone(unsettled); + replan.effective_action = "autonomous_replan_required"; + (replan as JsonObject).replan_action_packet = {schema_version: "replan_action_packet_v0"}; + assert.equal(compactRoutineSettlementPlan(replan, {captureReferenceFile: "/tmp/ref.json", cliArgv: ["loopx"]}), replan); +}); From 62d37be75bb3f4ee053276aee52d9027b142c911 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 27 Nov 2026 03:58:59 +0800 Subject: [PATCH 2/2] fix(tests): isolate GitHub capability probe env vars in CLI budget fixtures Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- tests/control_plane/cli_output_fixture.py | 38 +++++--- tests/control_plane/test_cli_output_budget.py | 87 ++++++++++++++++++- 2 files changed, 109 insertions(+), 16 deletions(-) diff --git a/tests/control_plane/cli_output_fixture.py b/tests/control_plane/cli_output_fixture.py index 35d8f98120..297fbb701f 100644 --- a/tests/control_plane/cli_output_fixture.py +++ b/tests/control_plane/cli_output_fixture.py @@ -46,23 +46,35 @@ 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): - """Prevent host-level auth/context env (e.g. gh hosts) from mutating isolated public fixtures.""" + """Prevent host-level auth/context env (e.g. gh hosts/tokens) from mutating isolated public fixtures.""" home.mkdir(parents=True, exist_ok=True) - previous = { - key: os.environ.get(key) - for key in ( - "HOME", - "USERPROFILE", - "CODEX_HOME", - "ANTIGRAVITY_CONVERSATION_ID", - "LOOPX_CHAT_CODEX_MODEL_PROVIDER", - ) + managed = { + "HOME": str(home), + "USERPROFILE": str(home), + "XDG_CONFIG_HOME": str(home / ".config"), + "APPDATA": str(home / "AppData" / "Roaming"), } - os.environ["HOME"] = str(home) - os.environ["USERPROFILE"] = str(home) - for key in ("CODEX_HOME", "ANTIGRAVITY_CONVERSATION_ID", "LOOPX_CHAT_CODEX_MODEL_PROVIDER"): + 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 diff --git a/tests/control_plane/test_cli_output_budget.py b/tests/control_plane/test_cli_output_budget.py index 0df9479f78..2c373bc67c 100644 --- a/tests/control_plane/test_cli_output_budget.py +++ b/tests/control_plane/test_cli_output_budget.py @@ -2121,9 +2121,90 @@ def test_brief_prunes_duplicate_non_command_metadata_and_smoke_isolates_host(tmp with isolated_probe_host_env(empty_home): assert os.environ["HOME"] == str(empty_home) assert os.environ["USERPROFILE"] == str(empty_home) - assert "CODEX_HOME" not in os.environ - assert "ANTIGRAVITY_CONVERSATION_ID" not in os.environ - assert "LOOPX_CHAT_CODEX_MODEL_PROVIDER" not in os.environ + assert os.environ["XDG_CONFIG_HOME"] == str(empty_home / ".config") + assert os.environ["APPDATA"] == str(empty_home / "AppData" / "Roaming") + for cleared in ( + "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", + ): + assert cleared not in os.environ + + +@pytest.mark.parametrize( + ("auth_kind", "env_key"), + [ + ("token", "GH_TOKEN"), + ("token", "GITHUB_TOKEN"), + ("token", "GITHUB_ENTERPRISE_TOKEN"), + ("token", "GH_ENTERPRISE_TOKEN"), + ("hosts_dir", "GH_CONFIG_DIR"), + ("xdg_hosts", "XDG_CONFIG_HOME"), + ("appdata_hosts", "APPDATA"), + ], +) +def test_isolated_probe_host_env_ignores_ambient_github_auth_and_keeps_brief_budget( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + auth_kind: str, + env_key: str, +) -> None: + from loopx.control_plane.agents.capability_probe import probe_host_runtime_capabilities + from tests.control_plane.cli_output_fixture import isolated_probe_host_env + + clean_home = tmp_path / "clean-home" + dirty_home = tmp_path / "dirty-home" + with isolated_probe_host_env(clean_home): + baseline_caps = probe_host_runtime_capabilities() + assert baseline_caps == [] + test_brief_budget_retains_full_commands_on_real_long_paths() + + for cleared in ( + "GH_TOKEN", + "GITHUB_TOKEN", + "GITHUB_ENTERPRISE_TOKEN", + "GH_ENTERPRISE_TOKEN", + "GH_CONFIG_DIR", + "XDG_CONFIG_HOME", + "APPDATA", + ): + monkeypatch.delenv(cleared, raising=False) + monkeypatch.delenv("CODEX_SANDBOX_NETWORK_DISABLED", raising=False) + monkeypatch.delenv("LOOPX_OFFLINE", raising=False) + monkeypatch.setenv("LOOPX_AUTO_CAPABILITY_PROBE", "1") + + if auth_kind == "token": + expected_value = "ghp_synthetic_probe_token_fixture" + else: + auth_root = tmp_path / "synthetic-auth" / env_key.lower() + if auth_kind == "hosts_dir": + hosts_path = auth_root / "hosts.yml" + elif auth_kind == "xdg_hosts": + hosts_path = auth_root / "gh" / "hosts.yml" + else: + hosts_path = auth_root / "GitHub CLI" / "hosts.yml" + hosts_path.parent.mkdir(parents=True, exist_ok=True) + hosts_path.write_text("github.com:\n user: synthetic-fixture\n", encoding="utf-8") + expected_value = str(auth_root) + monkeypatch.setenv(env_key, expected_value) + + with isolated_probe_host_env(dirty_home): + assert env_key not in os.environ or os.environ[env_key] in { + str(dirty_home / ".config"), + str(dirty_home / "AppData" / "Roaming"), + } + assert probe_host_runtime_capabilities() == baseline_caps + test_brief_budget_retains_full_commands_on_real_long_paths() + + assert os.environ.get(env_key) == expected_value @pytest.mark.parametrize("nested_temp", [False, True])